@bymax-one/nest-auth 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/CHANGELOG.md +369 -0
- package/LICENSE +21 -0
- package/README.md +886 -0
- package/dist/client/index.cjs +347 -0
- package/dist/client/index.d.cts +301 -0
- package/dist/client/index.d.ts +301 -0
- package/dist/client/index.mjs +341 -0
- package/dist/nextjs/index.cjs +1103 -0
- package/dist/nextjs/index.d.cts +1025 -0
- package/dist/nextjs/index.d.ts +1025 -0
- package/dist/nextjs/index.mjs +1083 -0
- package/dist/react/index.cjs +304 -0
- package/dist/react/index.d.cts +342 -0
- package/dist/react/index.d.ts +342 -0
- package/dist/react/index.mjs +295 -0
- package/dist/server/index.cjs +8039 -0
- package/dist/server/index.d.cts +5092 -0
- package/dist/server/index.d.ts +5092 -0
- package/dist/server/index.mjs +7996 -0
- package/dist/shared/index.cjs +240 -0
- package/dist/shared/index.d.cts +736 -0
- package/dist/shared/index.d.ts +736 -0
- package/dist/shared/index.mjs +223 -0
- package/package.json +195 -0
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Background-request detection for the Next.js App Router.
|
|
5
|
+
*
|
|
6
|
+
* Next.js 13+ issues several classes of "background" HTTP requests that
|
|
7
|
+
* look like ordinary navigations to the proxy but must NOT be treated
|
|
8
|
+
* as user-initiated traffic:
|
|
9
|
+
*
|
|
10
|
+
* - `RSC: 1` — a React Server Component fetch triggered by client-side
|
|
11
|
+
* navigation. The browser is still showing the previous page; returning
|
|
12
|
+
* a redirect here causes the client router to follow the redirect and
|
|
13
|
+
* then perform a second navigation, producing visible flicker or a
|
|
14
|
+
* redirect loop.
|
|
15
|
+
* - `Next-Router-Prefetch: 1` — a speculative prefetch for a `<Link>`
|
|
16
|
+
* that the user has not yet clicked. A redirect response is useless
|
|
17
|
+
* (there is no page to navigate) and noisy in logs.
|
|
18
|
+
* - `Next-Router-State-Tree` — the router's state-tree fetch during
|
|
19
|
+
* partial rendering. Same concern as RSC: the main document is
|
|
20
|
+
* already rendered, so redirects misbehave.
|
|
21
|
+
*
|
|
22
|
+
* When the proxy detects an unauthenticated background request it must
|
|
23
|
+
* respond with `401` instead of a redirect. The client router interprets
|
|
24
|
+
* the 401 as "this navigation is not authorized" and falls through to a
|
|
25
|
+
* normal full-page navigation, where a redirect IS appropriate.
|
|
26
|
+
*
|
|
27
|
+
* This helper is pure, synchronous, and Edge-Runtime-safe (no Node-only
|
|
28
|
+
* APIs).
|
|
29
|
+
*/
|
|
30
|
+
/**
|
|
31
|
+
* Minimal structural type accepted by {@link isBackgroundRequest}.
|
|
32
|
+
*
|
|
33
|
+
* Both `Request` (Web Fetch API) and `NextRequest` expose `.headers` with
|
|
34
|
+
* a `get(name)` method that performs a case-insensitive lookup. This
|
|
35
|
+
* helper relies on that contract — any custom implementation passed in
|
|
36
|
+
* unit tests or consumer code MUST normalise header names the same way,
|
|
37
|
+
* otherwise background-request detection silently fails and the proxy
|
|
38
|
+
* reintroduces the redirect loop this helper was built to prevent.
|
|
39
|
+
*
|
|
40
|
+
* Accepting a structural type keeps the helper trivially mockable and
|
|
41
|
+
* avoids a hard import of `next/server`.
|
|
42
|
+
*/
|
|
43
|
+
interface RequestWithHeaders {
|
|
44
|
+
readonly headers: {
|
|
45
|
+
/**
|
|
46
|
+
* Case-insensitive header lookup. Must return `null` when the
|
|
47
|
+
* header is absent and the raw value (possibly empty string) when
|
|
48
|
+
* it is present.
|
|
49
|
+
*/
|
|
50
|
+
get(name: string): string | null;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Returns `true` when the request is a Next.js background request
|
|
55
|
+
* (RSC fetch, router prefetch, or router state-tree fetch).
|
|
56
|
+
*
|
|
57
|
+
* Callers in the proxy use the result to choose between `401` (for
|
|
58
|
+
* background requests) and a redirect (for top-level navigations) when
|
|
59
|
+
* the user is not authenticated. See the module JSDoc for the rationale.
|
|
60
|
+
*
|
|
61
|
+
* Header names are passed lowercased so the guard remains robust against
|
|
62
|
+
* non-standard `Headers` implementations that skip the RFC-mandated
|
|
63
|
+
* case-insensitive comparison.
|
|
64
|
+
*
|
|
65
|
+
* @param request - Any value whose `headers.get(name)` returns the header
|
|
66
|
+
* value or `null`. `NextRequest` and the standard
|
|
67
|
+
* `Request` both satisfy this contract.
|
|
68
|
+
* @returns `true` if at least one of `RSC`, `Next-Router-Prefetch`, or
|
|
69
|
+
* `Next-Router-State-Tree` headers is present with a non-empty
|
|
70
|
+
* value on the request.
|
|
71
|
+
*/
|
|
72
|
+
declare function isBackgroundRequest(request: RequestWithHeaders): boolean;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Silent-refresh URL builder for the Next.js auth proxy.
|
|
76
|
+
*
|
|
77
|
+
* When the proxy decides to attempt a transparent token refresh (either
|
|
78
|
+
* on a public route with a stale `has_session` cookie or on a protected
|
|
79
|
+
* route with an expired access token), it redirects the browser to
|
|
80
|
+
* `/api/auth/silent-refresh?redirect=<destination>`. The silent-refresh
|
|
81
|
+
* handler then exchanges the refresh cookie for a new access/refresh
|
|
82
|
+
* pair and redirects the user back to `destination`.
|
|
83
|
+
*
|
|
84
|
+
* This helper builds that URL consistently across the proxy codebase so
|
|
85
|
+
* the query-parameter encoding, leading-slash discipline, and default
|
|
86
|
+
* destination (current pathname) are all centralised in one place.
|
|
87
|
+
*
|
|
88
|
+
* Edge-Runtime-safe: only relies on the standard `URL` constructor.
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* This builder deliberately does NOT validate whether `redirectTo`
|
|
92
|
+
* points to the same origin. The canonical open-redirect check lives
|
|
93
|
+
* in {@link createSilentRefreshHandler} (NEST-177) where the destination
|
|
94
|
+
* is actually consumed. Callers of `buildSilentRefreshUrl` should only
|
|
95
|
+
* pass relative paths (starting with `/`, not `//`) — passing an
|
|
96
|
+
* absolute URL is not blocked here, but it will be rejected by the
|
|
97
|
+
* handler.
|
|
98
|
+
*/
|
|
99
|
+
/**
|
|
100
|
+
* Minimal structural type accepted by {@link buildSilentRefreshUrl}.
|
|
101
|
+
*
|
|
102
|
+
* Matches both `NextRequest` and the standard web `Request` — we only
|
|
103
|
+
* read `url` and `nextUrl.pathname` for the default fallback. The
|
|
104
|
+
* optional `nextUrl` mirrors Next.js' request object; if absent we
|
|
105
|
+
* fall back to parsing `url`.
|
|
106
|
+
*/
|
|
107
|
+
interface RequestWithUrl {
|
|
108
|
+
readonly url: string;
|
|
109
|
+
readonly nextUrl?: {
|
|
110
|
+
readonly pathname: string;
|
|
111
|
+
readonly search?: string;
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Builds the absolute silent-refresh URL for the given request.
|
|
116
|
+
*
|
|
117
|
+
* - The `redirect` query parameter is always set so the handler knows
|
|
118
|
+
* where to return the user after the refresh round-trip.
|
|
119
|
+
* - When `redirectTo` is omitted or empty, the function falls back to
|
|
120
|
+
* the current pathname (plus search, if available). This preserves
|
|
121
|
+
* deep-link context when the proxy needs to refresh mid-navigation.
|
|
122
|
+
* - `redirectTo` is always URL-encoded via `URLSearchParams`, so
|
|
123
|
+
* callers do NOT pre-encode it.
|
|
124
|
+
* - The returned URL is absolute (same origin as the request) because
|
|
125
|
+
* `NextResponse.redirect` prefers absolute URLs for cross-middleware
|
|
126
|
+
* consistency.
|
|
127
|
+
*
|
|
128
|
+
* @param request - Request whose origin and pathname are used.
|
|
129
|
+
* @param redirectTo - Destination path/URL after refresh. Optional; falls
|
|
130
|
+
* back to the current pathname (+ search).
|
|
131
|
+
* @returns An absolute URL string pointing to
|
|
132
|
+
* `{origin}/api/auth/silent-refresh?redirect={encoded-destination}`.
|
|
133
|
+
* @throws {TypeError} When `request.url` is not a valid HTTP(S) URL.
|
|
134
|
+
*/
|
|
135
|
+
declare function buildSilentRefreshUrl(request: RequestWithUrl, redirectTo?: string): string;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Set-Cookie parsing and deduplication utilities for the Next.js auth
|
|
139
|
+
* proxy.
|
|
140
|
+
*
|
|
141
|
+
* In multi-domain white-label deployments the upstream API may emit
|
|
142
|
+
* multiple `Set-Cookie` headers for different domains during a single
|
|
143
|
+
* response (e.g., one for the tenant sub-domain and one for the
|
|
144
|
+
* marketing apex). When the proxy forwards these headers to the browser
|
|
145
|
+
* it can accidentally duplicate the same `(name, domain)` pair if the
|
|
146
|
+
* backend retries a cookie write or if the framework's cookie jar
|
|
147
|
+
* flushes twice. Browsers then persist whichever cookie happened to
|
|
148
|
+
* arrive last, producing hard-to-reproduce session bugs.
|
|
149
|
+
*
|
|
150
|
+
* {@link dedupeSetCookieHeaders} collapses that array down to a single
|
|
151
|
+
* entry per `(name + domain)` pair — *last writer wins* — so the
|
|
152
|
+
* forwarded response is deterministic regardless of how many writes
|
|
153
|
+
* the backend performed.
|
|
154
|
+
*
|
|
155
|
+
* {@link parseSetCookieHeader} breaks a single `Set-Cookie` string into
|
|
156
|
+
* its structured attributes so dedup logic (and any future cookie
|
|
157
|
+
* inspection) can work against a typed object instead of raw strings.
|
|
158
|
+
*
|
|
159
|
+
* {@link getSetCookieHeaders} is a fallback that extracts the list of
|
|
160
|
+
* raw Set-Cookie strings from either a modern `Headers.getSetCookie()`
|
|
161
|
+
* (Node 18.14+ / undici 5.19+) or the legacy `get('set-cookie')` (which
|
|
162
|
+
* concatenates cookies with commas — only safe when the values don't
|
|
163
|
+
* themselves contain unquoted commas).
|
|
164
|
+
*
|
|
165
|
+
* Edge-Runtime-safe: pure string manipulation, no Node-only APIs.
|
|
166
|
+
*
|
|
167
|
+
* Security & correctness notes:
|
|
168
|
+
*
|
|
169
|
+
* - Inputs containing CR (`\r`) or LF (`\n`) are rejected: RFC 6265
|
|
170
|
+
* forbids them in Set-Cookie values, and passing such a string
|
|
171
|
+
* straight through to `response.headers.append('set-cookie', …)`
|
|
172
|
+
* would enable response-header smuggling.
|
|
173
|
+
* - The dedup key is `(name, domain)` — NOT `(name, domain, path)`.
|
|
174
|
+
* This is intentional: the upstream NestJS API never emits two
|
|
175
|
+
* cookies with the same name and domain but different paths, so
|
|
176
|
+
* collapsing by `(name, domain)` is sufficient and preserves the
|
|
177
|
+
* *most-recent-writer-wins* invariant users rely on. If that
|
|
178
|
+
* upstream behaviour ever changes, widen the key.
|
|
179
|
+
* - `parseSetCookieHeader` intentionally does NOT trim the cookie
|
|
180
|
+
* *value* — RFC 6265 §5.2 step 2 says the value is everything
|
|
181
|
+
* after the first `=` up to the first `;`. Attribute *values*
|
|
182
|
+
* (e.g., `Path=/x `) are trimmed because the spec explicitly
|
|
183
|
+
* permits surrounding OWS there.
|
|
184
|
+
* - Unknown `SameSite` values (e.g., a future spec value we do not
|
|
185
|
+
* recognise) leave the typed `sameSite` field as `undefined`;
|
|
186
|
+
* the raw attribute is still preserved in {@link rawAttributes}
|
|
187
|
+
* for faithful pass-through.
|
|
188
|
+
*/
|
|
189
|
+
/**
|
|
190
|
+
* Structured representation of a parsed `Set-Cookie` header.
|
|
191
|
+
*
|
|
192
|
+
* Only the attributes we actually reason about are modelled. Unknown
|
|
193
|
+
* attributes are preserved inside {@link rawAttributes} so callers can
|
|
194
|
+
* round-trip a cookie without losing fields we do not yet understand.
|
|
195
|
+
*/
|
|
196
|
+
interface ParsedSetCookie {
|
|
197
|
+
/** Cookie name (the part before the first `=`). Case-sensitive. */
|
|
198
|
+
readonly name: string;
|
|
199
|
+
/** Cookie value (the part between the first `=` and the first `;`). Not trimmed. */
|
|
200
|
+
readonly value: string;
|
|
201
|
+
/** `HttpOnly` attribute flag. */
|
|
202
|
+
readonly httpOnly: boolean;
|
|
203
|
+
/** `Secure` attribute flag. */
|
|
204
|
+
readonly secure: boolean;
|
|
205
|
+
/**
|
|
206
|
+
* `SameSite` attribute value (lowercased) or `undefined` if absent OR
|
|
207
|
+
* if present with an unrecognised value. The original raw attribute
|
|
208
|
+
* is preserved in {@link rawAttributes}.
|
|
209
|
+
*/
|
|
210
|
+
readonly sameSite: 'strict' | 'lax' | 'none' | undefined;
|
|
211
|
+
/** `Path` attribute value or `undefined` if absent. */
|
|
212
|
+
readonly path: string | undefined;
|
|
213
|
+
/** `Domain` attribute value (lowercased) or `undefined` if absent. */
|
|
214
|
+
readonly domain: string | undefined;
|
|
215
|
+
/** `Max-Age` attribute as a number, or `undefined` if absent / unparsable. */
|
|
216
|
+
readonly maxAge: number | undefined;
|
|
217
|
+
/** `Expires` attribute as the raw string, or `undefined` if absent. */
|
|
218
|
+
readonly expires: string | undefined;
|
|
219
|
+
/**
|
|
220
|
+
* All attribute pairs in their original order and casing. Used when
|
|
221
|
+
* the caller wants to re-serialise the cookie without losing unknown
|
|
222
|
+
* attributes. Does not include the `name=value` prefix.
|
|
223
|
+
*/
|
|
224
|
+
readonly rawAttributes: readonly string[];
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Minimal structural type accepted by {@link getSetCookieHeaders}.
|
|
228
|
+
*
|
|
229
|
+
* Both the native `Headers` object and a plain `{ get, getSetCookie? }`
|
|
230
|
+
* mock satisfy this contract.
|
|
231
|
+
*/
|
|
232
|
+
interface HeadersLike {
|
|
233
|
+
get(name: string): string | null;
|
|
234
|
+
getSetCookie?: () => string[];
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Parse a single `Set-Cookie` header into a {@link ParsedSetCookie}.
|
|
238
|
+
*
|
|
239
|
+
* Attribute names are matched case-insensitively per RFC 6265. Values
|
|
240
|
+
* with attribute semantics (`SameSite`, `Domain`) are lowercased to
|
|
241
|
+
* keep the dedup key stable. The `name` and `value` of the cookie
|
|
242
|
+
* itself are preserved as-is — including any internal whitespace, per
|
|
243
|
+
* RFC 6265 §5.2 step 2.
|
|
244
|
+
*
|
|
245
|
+
* Rejects inputs containing CR or LF characters (header smuggling
|
|
246
|
+
* defence): the returned record has an empty `name`, which the dedup
|
|
247
|
+
* step filters out.
|
|
248
|
+
*
|
|
249
|
+
* Malformed input (no `=` in the first segment) similarly returns an
|
|
250
|
+
* empty parsed record.
|
|
251
|
+
*
|
|
252
|
+
* @param raw - A single `Set-Cookie` header value.
|
|
253
|
+
* @returns The parsed structured representation.
|
|
254
|
+
*/
|
|
255
|
+
declare function parseSetCookieHeader(raw: string): ParsedSetCookie;
|
|
256
|
+
/**
|
|
257
|
+
* Deduplicate an array of raw `Set-Cookie` header strings by
|
|
258
|
+
* `(name, domain)` — last writer wins.
|
|
259
|
+
*
|
|
260
|
+
* The ordering of the returned array matches the ordering of the
|
|
261
|
+
* *last* occurrence of each unique key in the input, which preserves
|
|
262
|
+
* the relative order of the cookies the browser will ultimately see
|
|
263
|
+
* and keeps logs diff-able when the upstream API's cookie ordering
|
|
264
|
+
* changes.
|
|
265
|
+
*
|
|
266
|
+
* Entries that fail to parse (no cookie name, or containing header
|
|
267
|
+
* smuggling bytes) are dropped.
|
|
268
|
+
*
|
|
269
|
+
* @param cookies - Raw `Set-Cookie` header strings.
|
|
270
|
+
* @returns Deduplicated list, preserving each winner's original string.
|
|
271
|
+
*/
|
|
272
|
+
declare function dedupeSetCookieHeaders(cookies: readonly string[]): string[];
|
|
273
|
+
/**
|
|
274
|
+
* Return the array of raw `Set-Cookie` header strings from a
|
|
275
|
+
* {@link HeadersLike}.
|
|
276
|
+
*
|
|
277
|
+
* Prefers the modern `Headers.getSetCookie()` API (Node 18.14+,
|
|
278
|
+
* undici 5.19+) which correctly separates multiple Set-Cookie headers.
|
|
279
|
+
* Falls back to splitting the single comma-joined value returned by
|
|
280
|
+
* `get('set-cookie')` on older runtimes — this split is aware that
|
|
281
|
+
* commas inside `Expires` attribute values (e.g.,
|
|
282
|
+
* `Expires=Wed, 09 Jun 2021 10:18:14 GMT`) must NOT be treated as
|
|
283
|
+
* separators.
|
|
284
|
+
*
|
|
285
|
+
* @param headers - Any object with `get()` and optionally `getSetCookie()`.
|
|
286
|
+
* @returns An array of raw `Set-Cookie` header strings (possibly empty).
|
|
287
|
+
*/
|
|
288
|
+
declare function getSetCookieHeaders(headers: HeadersLike): string[];
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* JWT helpers for the Next.js auth proxy (Edge Runtime).
|
|
292
|
+
*
|
|
293
|
+
* The proxy runs under Next.js Edge middleware, where Node's `crypto`
|
|
294
|
+
* module is unavailable. These helpers therefore use the Web Crypto
|
|
295
|
+
* API (`globalThis.crypto.subtle`) for signature verification and
|
|
296
|
+
* never import from `node:crypto` or `@nestjs/jwt`.
|
|
297
|
+
*
|
|
298
|
+
* Two modes are supported:
|
|
299
|
+
*
|
|
300
|
+
* - **Verify mode**: when a `JWT_SECRET` is provided we call
|
|
301
|
+
* {@link verifyJwtToken} which performs HS256 signature
|
|
302
|
+
* verification and expiry validation. This is the production path.
|
|
303
|
+
*
|
|
304
|
+
* - **Decode-only mode**: when no secret is available (e.g., during
|
|
305
|
+
* local development or in a proxy that delegates signature
|
|
306
|
+
* verification to the upstream API) we fall back to
|
|
307
|
+
* {@link decodeJwtToken} which parses the payload without
|
|
308
|
+
* verifying the signature. Decode-only mode is explicit — the
|
|
309
|
+
* caller must pass `undefined`/`null` as the secret.
|
|
310
|
+
*
|
|
311
|
+
* SECURITY — algorithm pinning:
|
|
312
|
+
*
|
|
313
|
+
* {@link verifyJwtToken} hard-pins `alg: 'HS256'`. Any token whose
|
|
314
|
+
* header advertises a different algorithm (including `none`, `HS384`,
|
|
315
|
+
* `HS512`, `RS256`, `ES256`, etc.) is rejected without key import.
|
|
316
|
+
* This defends against two classic attacks:
|
|
317
|
+
*
|
|
318
|
+
* - `alg: none` — the attacker removes the signature. Without
|
|
319
|
+
* algorithm pinning a naive verifier treats the token as valid.
|
|
320
|
+
* - `RS256 → HS256 confusion` — the attacker signs an HS256 token
|
|
321
|
+
* using the server's RS256 PUBLIC key as the HMAC secret. Without
|
|
322
|
+
* algorithm pinning the verifier imports the public key bytes as
|
|
323
|
+
* an HMAC secret and accepts the forgery.
|
|
324
|
+
*
|
|
325
|
+
* Pinning the algorithm at verification time eliminates both vectors.
|
|
326
|
+
*/
|
|
327
|
+
/**
|
|
328
|
+
* Header of a JWT as carried in the first base64url segment.
|
|
329
|
+
*
|
|
330
|
+
* Only the fields we branch on are typed; anything else is permitted
|
|
331
|
+
* but ignored. Exported so consumers of `DecodedToken` can name the
|
|
332
|
+
* type of `DecodedToken.header`.
|
|
333
|
+
*/
|
|
334
|
+
interface JwtHeader {
|
|
335
|
+
alg?: string;
|
|
336
|
+
typ?: string;
|
|
337
|
+
kid?: string;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Decoded representation of a JWT.
|
|
341
|
+
*
|
|
342
|
+
* `isValid` reflects **expiry only** — the signature is NOT checked by
|
|
343
|
+
* {@link decodeJwtToken}. Use {@link verifyJwtToken} when the caller
|
|
344
|
+
* needs cryptographic assurance that the token was issued by the
|
|
345
|
+
* backend.
|
|
346
|
+
*
|
|
347
|
+
* All optional claim accessors (`sub`, `role`, `tenantId`, …) return
|
|
348
|
+
* `undefined` when the claim is absent from the payload. They are
|
|
349
|
+
* exposed as plain properties so helpers like {@link getUserRole} can
|
|
350
|
+
* extract them without re-parsing.
|
|
351
|
+
*/
|
|
352
|
+
interface DecodedToken {
|
|
353
|
+
/**
|
|
354
|
+
* `true` when the payload parses AND `exp` is in the future.
|
|
355
|
+
*
|
|
356
|
+
* WARNING: this flag does NOT on its own imply signature
|
|
357
|
+
* verification. {@link decodeJwtToken} sets it from expiry only,
|
|
358
|
+
* while {@link verifyJwtToken} sets it after BOTH signature
|
|
359
|
+
* verification and expiry validation. Callers must therefore track
|
|
360
|
+
* which function they called and treat `isValid` as authoritative
|
|
361
|
+
* only when `verifyJwtToken` was invoked with a non-null secret.
|
|
362
|
+
*/
|
|
363
|
+
readonly isValid: boolean;
|
|
364
|
+
/** Raw header object, or `undefined` if the header failed to parse. */
|
|
365
|
+
readonly header: JwtHeader | undefined;
|
|
366
|
+
/**
|
|
367
|
+
* Raw payload record. Empty object when the payload failed to parse
|
|
368
|
+
* — callers should check `isValid` before reading individual claims.
|
|
369
|
+
*/
|
|
370
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
371
|
+
/** Standard `sub` claim if present and a string. */
|
|
372
|
+
readonly sub: string | undefined;
|
|
373
|
+
/** Role claim (`role`) if present and a string. */
|
|
374
|
+
readonly role: string | undefined;
|
|
375
|
+
/** Tenant claim (`tenantId`) if present and a string. */
|
|
376
|
+
readonly tenantId: string | undefined;
|
|
377
|
+
/** Expiry as a Unix timestamp (seconds), or `undefined`. */
|
|
378
|
+
readonly exp: number | undefined;
|
|
379
|
+
/** Issued-at as a Unix timestamp (seconds), or `undefined`. */
|
|
380
|
+
readonly iat: number | undefined;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Decode a JWT without verifying the signature.
|
|
384
|
+
*
|
|
385
|
+
* Returns a {@link DecodedToken} with `isValid` computed from the
|
|
386
|
+
* `exp` claim — `true` only when the token parses AND `exp` is in the
|
|
387
|
+
* future. Malformed tokens (not three base64url segments, invalid
|
|
388
|
+
* JSON, non-object payload) return `{ isValid: false }` with empty
|
|
389
|
+
* fields.
|
|
390
|
+
*
|
|
391
|
+
* Do NOT use this function for authorisation decisions. Signature
|
|
392
|
+
* verification must happen either via {@link verifyJwtToken} in the
|
|
393
|
+
* proxy or by delegating to the upstream API. This function is safe
|
|
394
|
+
* for inspecting non-authoritative claims like `role` for UI hints
|
|
395
|
+
* that are re-checked on the server.
|
|
396
|
+
*
|
|
397
|
+
* @param token - JWS compact serialisation (`header.payload.signature`).
|
|
398
|
+
*/
|
|
399
|
+
declare function decodeJwtToken(token: string): DecodedToken;
|
|
400
|
+
/**
|
|
401
|
+
* Verify a JWT using HS256 via Web Crypto API.
|
|
402
|
+
*
|
|
403
|
+
* Steps:
|
|
404
|
+
* 1. Structural validation: three base64url segments.
|
|
405
|
+
* 2. Decode + parse the header.
|
|
406
|
+
* 3. **Pin `alg === 'HS256'`** — reject every other algorithm,
|
|
407
|
+
* including `none`, `HS384`, `HS512`, `RS256`, and `ES256`.
|
|
408
|
+
* 4. Decode + parse the payload.
|
|
409
|
+
* 5. Import the secret as an HMAC-SHA-256 key.
|
|
410
|
+
* 6. Verify the signature over `<header>.<payload>` (ASCII bytes).
|
|
411
|
+
* 7. Validate `exp` is in the future.
|
|
412
|
+
*
|
|
413
|
+
* When `secret` is `undefined` or `null` this falls back to
|
|
414
|
+
* {@link decodeJwtToken} (decode-only mode) — the caller has
|
|
415
|
+
* explicitly opted out of signature verification. This is useful in
|
|
416
|
+
* proxy deployments that delegate verification to the upstream API;
|
|
417
|
+
* it is NOT safe when the proxy is the authorisation boundary.
|
|
418
|
+
*
|
|
419
|
+
* When `secret` is the EMPTY STRING this function fails closed and
|
|
420
|
+
* returns `emptyDecoded()`. An empty HMAC key is technically valid
|
|
421
|
+
* from the Web Crypto API's perspective and would verify a token
|
|
422
|
+
* signed with the same empty key — a common misconfiguration (e.g.,
|
|
423
|
+
* `JWT_SECRET=""` in an environment file) that we refuse rather
|
|
424
|
+
* than silently downgrade to a no-op.
|
|
425
|
+
*
|
|
426
|
+
* @param token - JWS compact serialisation.
|
|
427
|
+
* @param secret - HS256 shared secret, or `undefined`/`null` for
|
|
428
|
+
* decode-only mode.
|
|
429
|
+
* @returns A {@link DecodedToken} where `isValid` reflects BOTH the
|
|
430
|
+
* signature verification AND the expiry check.
|
|
431
|
+
*/
|
|
432
|
+
declare function verifyJwtToken(token: string, secret?: string | null): Promise<DecodedToken>;
|
|
433
|
+
/**
|
|
434
|
+
* Returns `true` when the decoded token has no `exp` claim OR the
|
|
435
|
+
* `exp` claim has already passed relative to the system clock.
|
|
436
|
+
*
|
|
437
|
+
* Separate from `DecodedToken.isValid` because `isValid` folds expiry
|
|
438
|
+
* and signature-verification together; callers sometimes want to know
|
|
439
|
+
* whether a signature-valid token has merely expired (so they can
|
|
440
|
+
* trigger a silent refresh) as opposed to being forged.
|
|
441
|
+
*
|
|
442
|
+
* @param token - A {@link DecodedToken} produced by
|
|
443
|
+
* {@link decodeJwtToken} or {@link verifyJwtToken}.
|
|
444
|
+
* @returns `true` when `exp` is absent or has already elapsed.
|
|
445
|
+
*/
|
|
446
|
+
declare function isTokenExpired(token: DecodedToken): boolean;
|
|
447
|
+
/**
|
|
448
|
+
* Extract the user's role from a decoded token. Returns an empty
|
|
449
|
+
* string when the claim is absent — the empty string is guaranteed
|
|
450
|
+
* NOT to match any configured role, so RBAC checks fail safely.
|
|
451
|
+
*
|
|
452
|
+
* Uses `''` rather than `undefined` on purpose: callers typically
|
|
453
|
+
* feed the result into a string equality or `.includes(...)` check
|
|
454
|
+
* where a sentinel is more ergonomic. Compare with
|
|
455
|
+
* {@link getTenantId} which deliberately keeps `undefined` as its
|
|
456
|
+
* sentinel to preserve the platform-vs-tenant distinction.
|
|
457
|
+
*
|
|
458
|
+
* @param token - The decoded token.
|
|
459
|
+
*/
|
|
460
|
+
declare function getUserRole(token: DecodedToken): string;
|
|
461
|
+
/**
|
|
462
|
+
* Extract the user's subject identifier (`sub`) from a decoded token.
|
|
463
|
+
* Returns an empty string when the claim is absent. See
|
|
464
|
+
* {@link getUserRole} for the rationale on empty-string vs.
|
|
465
|
+
* `undefined` sentinels.
|
|
466
|
+
*
|
|
467
|
+
* @param token - The decoded token.
|
|
468
|
+
*/
|
|
469
|
+
declare function getUserId(token: DecodedToken): string;
|
|
470
|
+
/**
|
|
471
|
+
* Extract the tenant identifier from a decoded token. Returns
|
|
472
|
+
* `undefined` — not an empty string — so callers can distinguish
|
|
473
|
+
* "platform token without tenant" (legitimate) from "tenant token
|
|
474
|
+
* with an empty tenantId" (a server bug worth surfacing). This is
|
|
475
|
+
* intentionally ASYMMETRIC with {@link getUserRole} and
|
|
476
|
+
* {@link getUserId}, which use `''` as their sentinel.
|
|
477
|
+
*
|
|
478
|
+
* @param token - The decoded token.
|
|
479
|
+
*/
|
|
480
|
+
declare function getTenantId(token: DecodedToken): string | undefined;
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* `createAuthProxy` — factory that produces a Next.js 16 proxy
|
|
484
|
+
* function.
|
|
485
|
+
*
|
|
486
|
+
* The Next.js App Router looks for a `proxy.ts` file at the project
|
|
487
|
+
* root that exports a `proxy` function. This factory makes it
|
|
488
|
+
* straightforward to configure authentication, route guards, RBAC,
|
|
489
|
+
* and the anti-redirect-loop invariant in one place:
|
|
490
|
+
*
|
|
491
|
+
* ```ts
|
|
492
|
+
* // proxy.ts
|
|
493
|
+
* import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
|
|
494
|
+
*
|
|
495
|
+
* export const { proxy } = createAuthProxy({
|
|
496
|
+
* publicRoutes: ['/', '/auth/login'],
|
|
497
|
+
* publicRoutesRedirectIfAuthenticated: ['/auth/login'],
|
|
498
|
+
* protectedRoutes: [
|
|
499
|
+
* { pattern: '/dashboard/:path*', allowedRoles: ['admin', 'member'] }
|
|
500
|
+
* ],
|
|
501
|
+
* loginPath: '/auth/login',
|
|
502
|
+
* getDefaultDashboard: (role) => role === 'admin' ? '/dashboard/admin' : '/dashboard',
|
|
503
|
+
* apiBase: process.env.API_BASE_URL ?? 'http://localhost:3001',
|
|
504
|
+
* jwtSecret: process.env.JWT_SECRET,
|
|
505
|
+
* cookieNames: { access: 'access_token', refresh: 'refresh_token', hasSession: 'has_session' },
|
|
506
|
+
* userHeaders: { userId: 'x-user-id', role: 'x-user-role', tenantId: 'x-tenant-id', tenantDomain: 'x-tenant-domain' },
|
|
507
|
+
* blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
|
|
508
|
+
* })
|
|
509
|
+
*
|
|
510
|
+
* export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }
|
|
511
|
+
* ```
|
|
512
|
+
*
|
|
513
|
+
* The returned `proxy` runs under the Next.js Edge Runtime, so this
|
|
514
|
+
* module MUST stay Web-API-only. Internal pipeline modules live
|
|
515
|
+
* under `src/nextjs/internal/`; this file is the public surface
|
|
516
|
+
* (types + factory) only.
|
|
517
|
+
*/
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Pattern specification for a protected route.
|
|
521
|
+
*
|
|
522
|
+
* - `pattern` matches the request pathname. Use a leading `/` for
|
|
523
|
+
* absolute matches. Three forms are supported: an exact path
|
|
524
|
+
* (`/dashboard`), a trailing wildcard (`/dashboard/*` or
|
|
525
|
+
* `/dashboard/:path*`) that matches the base path AND any subpath,
|
|
526
|
+
* and single-segment `:name` placeholders (`/tenants/:id/users`)
|
|
527
|
+
* that match exactly one path segment.
|
|
528
|
+
* - `allowedRoles` is consulted by the protected-route handler.
|
|
529
|
+
* Roles are compared case-sensitively against the token's `role`
|
|
530
|
+
* claim.
|
|
531
|
+
* - `redirectPath` is the destination when the route matches but
|
|
532
|
+
* the user lacks the required role. When omitted the proxy falls
|
|
533
|
+
* back to `config.getDefaultDashboard(role)`.
|
|
534
|
+
*
|
|
535
|
+
* Wildcards are only permitted as the LAST segment of the pattern.
|
|
536
|
+
* The factory throws at configuration time if a wildcard appears
|
|
537
|
+
* elsewhere — this avoids ambiguous middle-of-path globs that
|
|
538
|
+
* would otherwise silently widen the protected surface.
|
|
539
|
+
*/
|
|
540
|
+
interface ProtectedRoutePattern {
|
|
541
|
+
readonly pattern: string;
|
|
542
|
+
readonly allowedRoles: readonly string[];
|
|
543
|
+
readonly redirectPath?: string;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Configuration contract for {@link createAuthProxy}.
|
|
547
|
+
*
|
|
548
|
+
* Every field is required unless marked optional. The authors of
|
|
549
|
+
* each downstream app are expected to populate this object from
|
|
550
|
+
* their own environment; the library intentionally ships no
|
|
551
|
+
* defaults that would hide a misconfiguration.
|
|
552
|
+
*/
|
|
553
|
+
interface AuthProxyConfig {
|
|
554
|
+
/**
|
|
555
|
+
* Pathnames that can be accessed without authentication. Match
|
|
556
|
+
* is an exact equality or a prefix check with a trailing `/`.
|
|
557
|
+
*/
|
|
558
|
+
readonly publicRoutes: readonly string[];
|
|
559
|
+
/**
|
|
560
|
+
* Subset of {@link publicRoutes} that must redirect AUTHENTICATED
|
|
561
|
+
* users away (e.g., a signed-in user visiting `/auth/login` gets
|
|
562
|
+
* redirected to their dashboard via {@link getDefaultDashboard}).
|
|
563
|
+
*/
|
|
564
|
+
readonly publicRoutesRedirectIfAuthenticated: readonly string[];
|
|
565
|
+
/**
|
|
566
|
+
* Pattern-based protected route specifications. The first
|
|
567
|
+
* matching pattern wins, so order them from most-specific to
|
|
568
|
+
* least-specific. Catch-all patterns (`*` / `:name*`) at segment
|
|
569
|
+
* 0 are rejected at factory time.
|
|
570
|
+
*/
|
|
571
|
+
readonly protectedRoutes: readonly ProtectedRoutePattern[];
|
|
572
|
+
/**
|
|
573
|
+
* Pathname of the login page. MUST be a same-origin path
|
|
574
|
+
* starting with `/` and MUST NOT contain CR / LF / NUL /
|
|
575
|
+
* backslash characters.
|
|
576
|
+
*/
|
|
577
|
+
readonly loginPath: string;
|
|
578
|
+
/**
|
|
579
|
+
* Function that resolves the default dashboard path for a given
|
|
580
|
+
* role. MUST return a same-origin path starting with `/` (not
|
|
581
|
+
* `//`). Call sites guard the return value against open-redirect
|
|
582
|
+
* attempts.
|
|
583
|
+
*/
|
|
584
|
+
readonly getDefaultDashboard: (role: string) => string;
|
|
585
|
+
/**
|
|
586
|
+
* Absolute base URL of the upstream NestJS API (e.g.,
|
|
587
|
+
* `https://api.example.com`). Used by the silent-refresh and
|
|
588
|
+
* logout handlers; not used directly by the proxy.
|
|
589
|
+
*/
|
|
590
|
+
readonly apiBase: string;
|
|
591
|
+
/**
|
|
592
|
+
* HS256 secret used to verify access tokens inside the Edge
|
|
593
|
+
* proxy. When omitted the proxy falls back to decode-only mode
|
|
594
|
+
* and logs a `console.warn` at factory time — in decode-only
|
|
595
|
+
* mode signature verification MUST be performed upstream.
|
|
596
|
+
*/
|
|
597
|
+
readonly jwtSecret?: string;
|
|
598
|
+
/**
|
|
599
|
+
* Maximum number of consecutive silent-refresh redirects the
|
|
600
|
+
* proxy will chain before giving up and rendering the page
|
|
601
|
+
* as-is. Two is the documented default.
|
|
602
|
+
*/
|
|
603
|
+
readonly maxRefreshAttempts?: number;
|
|
604
|
+
/**
|
|
605
|
+
* Cookie names the proxy reads and clears. These must match the
|
|
606
|
+
* names configured in the upstream NestJS auth module.
|
|
607
|
+
*/
|
|
608
|
+
readonly cookieNames: {
|
|
609
|
+
readonly access: string;
|
|
610
|
+
readonly refresh: string;
|
|
611
|
+
readonly hasSession: string;
|
|
612
|
+
};
|
|
613
|
+
/**
|
|
614
|
+
* Header names used to propagate decoded JWT claims to
|
|
615
|
+
* downstream server components and route handlers after
|
|
616
|
+
* successful authentication.
|
|
617
|
+
*/
|
|
618
|
+
readonly userHeaders: {
|
|
619
|
+
readonly userId: string;
|
|
620
|
+
readonly role: string;
|
|
621
|
+
readonly tenantId: string;
|
|
622
|
+
readonly tenantDomain: string;
|
|
623
|
+
};
|
|
624
|
+
/**
|
|
625
|
+
* Token `status` claim values that should BLOCK a user even if
|
|
626
|
+
* their token is cryptographically valid (e.g., BANNED,
|
|
627
|
+
* INACTIVE, EXPIRED). Comparison is case-insensitive: both the
|
|
628
|
+
* incoming claim value and the configured entries are lowercased
|
|
629
|
+
* before equality is tested.
|
|
630
|
+
*/
|
|
631
|
+
readonly blockedUserStatuses: readonly string[];
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Return shape of {@link createAuthProxy}.
|
|
635
|
+
*/
|
|
636
|
+
interface AuthProxyInstance {
|
|
637
|
+
/**
|
|
638
|
+
* The Next.js 16 proxy function. Destructure and re-export:
|
|
639
|
+
*
|
|
640
|
+
* ```ts
|
|
641
|
+
* export const { proxy } = createAuthProxy({ ... })
|
|
642
|
+
* ```
|
|
643
|
+
*/
|
|
644
|
+
readonly proxy: (request: NextRequest) => Promise<NextResponse>;
|
|
645
|
+
/**
|
|
646
|
+
* The resolved configuration — exposed for debugging and tests.
|
|
647
|
+
*/
|
|
648
|
+
readonly config: ResolvedAuthProxyConfig;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Config after defaulting. Exposed separately so downstream
|
|
652
|
+
* helpers (silent-refresh, logout) can depend on the defaulted
|
|
653
|
+
* values without every caller having to re-apply the defaults.
|
|
654
|
+
*/
|
|
655
|
+
interface ResolvedAuthProxyConfig extends AuthProxyConfig {
|
|
656
|
+
readonly maxRefreshAttempts: number;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Create a Next.js proxy function wired to the given configuration.
|
|
660
|
+
*
|
|
661
|
+
* The returned `proxy` is async because signature verification via
|
|
662
|
+
* Web Crypto returns a promise.
|
|
663
|
+
*
|
|
664
|
+
* @throws {Error} When the configuration contains an invalid
|
|
665
|
+
* protected-route pattern (mid-pattern wildcard or
|
|
666
|
+
* catch-all at segment 0), or when `loginPath` /
|
|
667
|
+
* `redirectPath` are not same-origin pathnames.
|
|
668
|
+
*/
|
|
669
|
+
declare function createAuthProxy(config: AuthProxyConfig): AuthProxyInstance;
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* `createSilentRefreshHandler` — factory for the GET
|
|
673
|
+
* `/api/auth/silent-refresh` route handler.
|
|
674
|
+
*
|
|
675
|
+
* The proxy sends the browser here when it detects a missing or
|
|
676
|
+
* expired access token but a surviving `has_session` cookie. The
|
|
677
|
+
* handler forwards the incoming cookies to the upstream NestJS
|
|
678
|
+
* `POST /auth/refresh` endpoint and, on success, redirects the
|
|
679
|
+
* browser back to the original destination with the refreshed
|
|
680
|
+
* `Set-Cookie` headers attached. On failure it redirects to the
|
|
681
|
+
* configured `loginPath` with `reason=expired` and clears the three
|
|
682
|
+
* auth cookies so the proxy's next pass sees a fully logged-out
|
|
683
|
+
* state.
|
|
684
|
+
*
|
|
685
|
+
* Critical concerns handled here:
|
|
686
|
+
*
|
|
687
|
+
* - **Open-redirect defence.** The `redirect` query parameter is
|
|
688
|
+
* attacker-controlled (it arrives from a URL the browser was
|
|
689
|
+
* pointed at). The handler rejects values that do not start with
|
|
690
|
+
* `/`, that begin with `//` (protocol-relative URLs), or that
|
|
691
|
+
* embed CR/LF/NUL/backslash; it then resolves the value against
|
|
692
|
+
* the request's origin and rejects anything whose origin drifts.
|
|
693
|
+
* Everything suspicious falls back to `loginPath`.
|
|
694
|
+
* - **`Set-Cookie` deduplication.** Multi-domain white-label
|
|
695
|
+
* deployments may receive multiple `Set-Cookie` headers for the
|
|
696
|
+
* same cookie name. `dedupeSetCookieHeaders` collapses them by
|
|
697
|
+
* `(name, domain)` — last writer wins.
|
|
698
|
+
* - **Legacy runtime support.** `getSetCookieHeaders` transparently
|
|
699
|
+
* falls back to parsing a single comma-joined `Set-Cookie`
|
|
700
|
+
* header on Node < 18.14.
|
|
701
|
+
* - **CDN cache poisoning.** Every response sets
|
|
702
|
+
* `Cache-Control: no-store, no-cache` so intermediate caches
|
|
703
|
+
* cannot replay a stale redirect.
|
|
704
|
+
* - **Empty refresh response.** A 2xx response with no `Set-Cookie`
|
|
705
|
+
* header is treated as a failure; otherwise the proxy would
|
|
706
|
+
* redirect back into an identical refresh attempt, producing a
|
|
707
|
+
* silent retry loop.
|
|
708
|
+
*
|
|
709
|
+
* Consumer obligations documented in the factory JSDoc below:
|
|
710
|
+
*
|
|
711
|
+
* - **Rate limiting.** The handler makes one upstream `POST` per
|
|
712
|
+
* inbound `GET`. Apply route-level rate limiting in the consumer
|
|
713
|
+
* app to prevent DoS amplification.
|
|
714
|
+
* - **Host-header trust.** `origin` is derived from the request's
|
|
715
|
+
* `Host`. Self-hosted Next.js deployments must configure the
|
|
716
|
+
* reverse proxy to forward only trusted `Host` values.
|
|
717
|
+
* - **`apiBase`.** Always points to your OWN NestJS backend — all
|
|
718
|
+
* incoming cookies are forwarded there.
|
|
719
|
+
*
|
|
720
|
+
* Edge-Runtime-safe: uses only `fetch`, `URL`, and the standard
|
|
721
|
+
* Headers API.
|
|
722
|
+
*/
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Configuration contract for {@link createSilentRefreshHandler}.
|
|
726
|
+
*/
|
|
727
|
+
interface SilentRefreshHandlerConfig {
|
|
728
|
+
/**
|
|
729
|
+
* Absolute base URL of the upstream NestJS API (e.g.,
|
|
730
|
+
* `https://api.example.com`). Must NOT include a trailing slash.
|
|
731
|
+
*
|
|
732
|
+
* SECURITY — all cookies on the incoming request are forwarded to
|
|
733
|
+
* this URL. Ensure `apiBase` always points to your OWN NestJS
|
|
734
|
+
* backend; never set it to a third-party host.
|
|
735
|
+
*/
|
|
736
|
+
readonly apiBase: string;
|
|
737
|
+
/**
|
|
738
|
+
* Pathname of the login page. Used as the fallback destination on
|
|
739
|
+
* refresh failure and on open-redirect rejection. MUST be a
|
|
740
|
+
* same-origin path starting with `/` (not `//`) and MUST NOT
|
|
741
|
+
* contain CR, LF, NUL, or backslash characters.
|
|
742
|
+
*/
|
|
743
|
+
readonly loginPath: string;
|
|
744
|
+
/**
|
|
745
|
+
* Pathname of the refresh endpoint on the upstream API. Defaults
|
|
746
|
+
* to `/auth/refresh`.
|
|
747
|
+
*/
|
|
748
|
+
readonly refreshPath?: string;
|
|
749
|
+
/**
|
|
750
|
+
* Cookie names the handler clears on refresh failure. These must
|
|
751
|
+
* match the upstream NestJS auth module's configuration. On
|
|
752
|
+
* failure the handler clears:
|
|
753
|
+
* - `access` at path `/`
|
|
754
|
+
* - `refresh` at `refreshCookiePath` (default `/api/auth`)
|
|
755
|
+
* - `hasSession` at path `/`
|
|
756
|
+
*/
|
|
757
|
+
readonly cookieNames: {
|
|
758
|
+
readonly access: string;
|
|
759
|
+
readonly refresh: string;
|
|
760
|
+
readonly hasSession: string;
|
|
761
|
+
};
|
|
762
|
+
/**
|
|
763
|
+
* Path attribute for the refresh cookie clear. Defaults to
|
|
764
|
+
* `/api/auth` — matches the default scope of the NestJS auth
|
|
765
|
+
* module's refresh cookie.
|
|
766
|
+
*/
|
|
767
|
+
readonly refreshCookiePath?: string;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Type of the Next.js App Router GET handler returned by the
|
|
771
|
+
* factory. Exported for convenience in tests.
|
|
772
|
+
*/
|
|
773
|
+
type SilentRefreshHandler = (request: NextRequest) => Promise<NextResponse>;
|
|
774
|
+
/**
|
|
775
|
+
* Create a GET handler for `/api/auth/silent-refresh`.
|
|
776
|
+
*
|
|
777
|
+
* The returned handler:
|
|
778
|
+
* 1. Resolves a safe `redirect` destination (see open-redirect
|
|
779
|
+
* defence above).
|
|
780
|
+
* 2. Forwards the incoming cookies to the upstream refresh endpoint.
|
|
781
|
+
* 3. On 2xx with a non-empty `Set-Cookie` payload: emits a 302 to
|
|
782
|
+
* the destination and propagates the deduplicated cookies.
|
|
783
|
+
* 4. On non-2xx, fetch failure, or a 2xx with no cookies: emits a
|
|
784
|
+
* 302 to `loginPath?reason=expired` with all three auth cookies
|
|
785
|
+
* cleared (`Max-Age=0`).
|
|
786
|
+
*
|
|
787
|
+
* @remarks
|
|
788
|
+
* RATE LIMITING — this factory does not rate-limit. Every invocation
|
|
789
|
+
* makes an outbound `POST` to `apiBase`. Apply rate limiting at the
|
|
790
|
+
* Next.js middleware or CDN layer in the consumer app to prevent
|
|
791
|
+
* DoS amplification against the upstream service.
|
|
792
|
+
*
|
|
793
|
+
* @remarks
|
|
794
|
+
* HOST-HEADER TRUST — `request.nextUrl.origin` is derived from the
|
|
795
|
+
* `Host` header. On Vercel this is safe; self-hosted deployments
|
|
796
|
+
* behind a reverse proxy MUST configure `trustHost` / forward only
|
|
797
|
+
* vetted `Host` values, or the open-redirect defence can be bypassed
|
|
798
|
+
* by an attacker who controls the `Host` header.
|
|
799
|
+
*
|
|
800
|
+
* @throws {Error} When `loginPath` is not a same-origin pathname.
|
|
801
|
+
*/
|
|
802
|
+
declare function createSilentRefreshHandler(config: SilentRefreshHandlerConfig): SilentRefreshHandler;
|
|
803
|
+
/**
|
|
804
|
+
* Resolve the attacker-controlled `redirect` parameter to a safe
|
|
805
|
+
* same-origin pathname. The function is exported so unit tests can
|
|
806
|
+
* exercise it directly — its correctness is the main defence against
|
|
807
|
+
* open-redirect attacks on this handler.
|
|
808
|
+
*
|
|
809
|
+
* Rules:
|
|
810
|
+
* 1. Missing or empty value → `loginPath`.
|
|
811
|
+
* 2. Does not start with `/` → `loginPath` (would be an absolute
|
|
812
|
+
* URL or a scheme-relative reference).
|
|
813
|
+
* 3. Starts with `//` → `loginPath` (protocol-relative URL that
|
|
814
|
+
* would escape the origin).
|
|
815
|
+
* 4. Contains `\\` / `\r` / `\n` / NUL → `loginPath` (defence in
|
|
816
|
+
* depth against runtime-specific normalisation quirks).
|
|
817
|
+
* 5. After `new URL(candidate, origin)` resolution, the resulting
|
|
818
|
+
* origin MUST equal the request origin → otherwise `loginPath`.
|
|
819
|
+
*
|
|
820
|
+
* @example
|
|
821
|
+
* ```ts
|
|
822
|
+
* resolveSafeDestination('/dashboard', 'https://app.com', '/login')
|
|
823
|
+
* // → '/dashboard'
|
|
824
|
+
*
|
|
825
|
+
* resolveSafeDestination('//evil.com', 'https://app.com', '/login')
|
|
826
|
+
* // → '/login'
|
|
827
|
+
*
|
|
828
|
+
* resolveSafeDestination(null, 'https://app.com', '/login')
|
|
829
|
+
* // → '/login'
|
|
830
|
+
* ```
|
|
831
|
+
*/
|
|
832
|
+
declare function resolveSafeDestination(raw: string | null, origin: string, loginPath: string): string;
|
|
833
|
+
/**
|
|
834
|
+
* Re-exports the canonical path for the silent-refresh endpoint so
|
|
835
|
+
* consumers who mount this factory can use the same constant the
|
|
836
|
+
* proxy does, keeping the two aligned.
|
|
837
|
+
*/
|
|
838
|
+
declare const SILENT_REFRESH_ROUTE: "/api/auth/silent-refresh";
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* `createClientRefreshHandler` — factory for the POST
|
|
842
|
+
* `/api/auth/client-refresh` route handler.
|
|
843
|
+
*
|
|
844
|
+
* While `createSilentRefreshHandler` (NEST-177) is invoked by the
|
|
845
|
+
* proxy during server-side navigation, this handler is the
|
|
846
|
+
* same-origin bridge the browser uses when a client-side `fetch`
|
|
847
|
+
* receives a 401 and wants to refresh its access token without a
|
|
848
|
+
* full-page redirect. Because it is invoked from JavaScript via
|
|
849
|
+
* `fetch(..., { credentials: 'include' })`, the browser sends the
|
|
850
|
+
* auth cookies automatically and the handler simply forwards them
|
|
851
|
+
* to the upstream NestJS `POST /auth/refresh`, translating the
|
|
852
|
+
* response into a bare 200/401 the calling code can branch on.
|
|
853
|
+
*
|
|
854
|
+
* Concretely the handler contract is:
|
|
855
|
+
*
|
|
856
|
+
* - `fetch('/api/auth/client-refresh', { method: 'POST', credentials: 'include' })`
|
|
857
|
+
* - 200 OK + new `Set-Cookie` headers on success — the browser
|
|
858
|
+
* installs the new cookies before the caller retries the
|
|
859
|
+
* original request.
|
|
860
|
+
* - 401 Unauthorized with an empty body on failure — the caller
|
|
861
|
+
* should transition to logged-out UI.
|
|
862
|
+
* - 405 Method Not Allowed for non-POST methods. Keeps the handler
|
|
863
|
+
* robust against misconfigured Next.js route files that would
|
|
864
|
+
* otherwise let a `GET <img src>` cross-origin attack forward
|
|
865
|
+
* cookies to the backend.
|
|
866
|
+
*
|
|
867
|
+
* Every response carries `Cache-Control: no-store, no-cache` so
|
|
868
|
+
* intermediate caches cannot replay old 200s (which would install
|
|
869
|
+
* someone else's cookies on a different user) or 401s (which would
|
|
870
|
+
* break legitimate sign-ins after a CDN flush).
|
|
871
|
+
*
|
|
872
|
+
* CSRF posture: same-origin cookie policy (`SameSite=Lax`/`Strict`)
|
|
873
|
+
* on the upstream NestJS auth module is the primary defence. The
|
|
874
|
+
* method guard here provides a second line against verb-confusion
|
|
875
|
+
* variants. Consumers deploying on a separate domain from the API
|
|
876
|
+
* MUST additionally ensure CORS is configured on the upstream to
|
|
877
|
+
* reject cross-origin browser requests.
|
|
878
|
+
*
|
|
879
|
+
* Edge-Runtime-safe: uses only `fetch`, `Response`, and the Headers
|
|
880
|
+
* API.
|
|
881
|
+
*/
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Configuration contract for {@link createClientRefreshHandler}.
|
|
885
|
+
*/
|
|
886
|
+
interface ClientRefreshHandlerConfig {
|
|
887
|
+
/**
|
|
888
|
+
* Absolute base URL of the upstream NestJS API (e.g.,
|
|
889
|
+
* `https://api.example.com`). Must start with `http://` or
|
|
890
|
+
* `https://`. Trailing slashes are trimmed.
|
|
891
|
+
*
|
|
892
|
+
* SECURITY — all cookies on the incoming request are forwarded to
|
|
893
|
+
* this URL. Ensure `apiBase` always points to your OWN NestJS
|
|
894
|
+
* backend.
|
|
895
|
+
*/
|
|
896
|
+
readonly apiBase: string;
|
|
897
|
+
/**
|
|
898
|
+
* Pathname of the refresh endpoint on the upstream API. Defaults
|
|
899
|
+
* to `/auth/refresh`.
|
|
900
|
+
*/
|
|
901
|
+
readonly refreshPath?: string;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Signature of the POST handler returned by the factory.
|
|
905
|
+
*/
|
|
906
|
+
type ClientRefreshHandler = (request: NextRequest) => Promise<Response>;
|
|
907
|
+
/**
|
|
908
|
+
* Create a POST handler for `/api/auth/client-refresh`.
|
|
909
|
+
*
|
|
910
|
+
* The handler:
|
|
911
|
+
* 1. Rejects any non-POST request with `405 Method Not Allowed`.
|
|
912
|
+
* 2. Forwards incoming cookies to the upstream refresh endpoint.
|
|
913
|
+
* 3. Returns `200` with the refreshed `Set-Cookie` headers on
|
|
914
|
+
* success. Cookies are deduplicated via
|
|
915
|
+
* `dedupeSetCookieHeaders` to guard multi-domain white-label
|
|
916
|
+
* deployments.
|
|
917
|
+
* 4. Returns `401` with an empty body on ANY failure mode (fetch
|
|
918
|
+
* error, non-2xx upstream, a 2xx upstream that failed to emit
|
|
919
|
+
* cookies, or an upstream 3xx that `fetch` exposed as an
|
|
920
|
+
* opaque redirect). Never leaks upstream error bodies to the
|
|
921
|
+
* browser.
|
|
922
|
+
*
|
|
923
|
+
* @remarks
|
|
924
|
+
* RATE LIMITING — this factory does not rate-limit. Every invocation
|
|
925
|
+
* makes one outbound `POST` to `apiBase`. Apply rate limiting at the
|
|
926
|
+
* Next.js middleware or CDN layer in the consumer app.
|
|
927
|
+
*
|
|
928
|
+
* @throws {Error} When `apiBase` is not an absolute HTTP(S) URL.
|
|
929
|
+
*/
|
|
930
|
+
declare function createClientRefreshHandler(config: ClientRefreshHandlerConfig): ClientRefreshHandler;
|
|
931
|
+
/**
|
|
932
|
+
* Canonical Next.js proxy-side path this handler is expected to be
|
|
933
|
+
* mounted at. Exported so consumers can keep the route registration
|
|
934
|
+
* and the factory in sync.
|
|
935
|
+
*/
|
|
936
|
+
declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* `createLogoutHandler` — factory for the POST
|
|
940
|
+
* `/api/auth/logout` route handler.
|
|
941
|
+
*
|
|
942
|
+
* The handler forwards the incoming cookies to the upstream NestJS
|
|
943
|
+
* `POST /auth/logout` endpoint (which revokes the refresh token
|
|
944
|
+
* server-side) and, regardless of whether the upstream responds with
|
|
945
|
+
* success or failure, clears the three auth cookies on the browser.
|
|
946
|
+
* A user who pressed "logout" MUST end up logged out of the browser
|
|
947
|
+
* session even if the upstream is unreachable — otherwise a network
|
|
948
|
+
* glitch leaves them with cookies they thought they had invalidated.
|
|
949
|
+
*
|
|
950
|
+
* Two response modes are supported, expressed as a discriminated
|
|
951
|
+
* union on {@link LogoutHandlerConfig}:
|
|
952
|
+
*
|
|
953
|
+
* - `mode: 'redirect'`: 302 to `loginPath`. Appropriate when the
|
|
954
|
+
* handler is invoked from a full-page form POST.
|
|
955
|
+
* - `mode: 'status'` (default): 200 empty body. Appropriate when
|
|
956
|
+
* the handler is invoked from client-side JavaScript that
|
|
957
|
+
* manages its own navigation.
|
|
958
|
+
*
|
|
959
|
+
* @remarks
|
|
960
|
+
* HOST-HEADER TRUST — in `'redirect'` mode the destination URL is
|
|
961
|
+
* built with `new URL(loginPath, request.nextUrl.origin)`. Self-
|
|
962
|
+
* hosted Next.js deployments behind a reverse proxy MUST ensure the
|
|
963
|
+
* proxy forwards only vetted `Host` values; otherwise an attacker
|
|
964
|
+
* who controls the `Host` header can redirect the browser to an
|
|
965
|
+
* off-site origin after logout.
|
|
966
|
+
*
|
|
967
|
+
* Edge-Runtime-safe.
|
|
968
|
+
*/
|
|
969
|
+
|
|
970
|
+
/**
|
|
971
|
+
* Cookie names + path used by every logout response to clear the
|
|
972
|
+
* browser's auth state. Shared by both config variants of the
|
|
973
|
+
* discriminated union.
|
|
974
|
+
*/
|
|
975
|
+
interface LogoutCookieConfig {
|
|
976
|
+
readonly cookieNames: {
|
|
977
|
+
readonly access: string;
|
|
978
|
+
readonly refresh: string;
|
|
979
|
+
readonly hasSession: string;
|
|
980
|
+
};
|
|
981
|
+
/** Path attribute for the refresh-cookie clear. Defaults to `/api/auth`. */
|
|
982
|
+
readonly refreshCookiePath?: string;
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Logout response mode = `'redirect'`. `loginPath` is required and
|
|
986
|
+
* MUST be a same-origin pathname.
|
|
987
|
+
*/
|
|
988
|
+
interface LogoutHandlerRedirectConfig extends LogoutCookieConfig {
|
|
989
|
+
readonly mode: 'redirect';
|
|
990
|
+
readonly loginPath: string;
|
|
991
|
+
readonly apiBase: string;
|
|
992
|
+
readonly logoutPath?: string;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Logout response mode = `'status'` (default). Emits a 200 with
|
|
996
|
+
* cookies cleared; no redirect destination needed.
|
|
997
|
+
*/
|
|
998
|
+
interface LogoutHandlerStatusConfig extends LogoutCookieConfig {
|
|
999
|
+
readonly mode?: 'status';
|
|
1000
|
+
readonly apiBase: string;
|
|
1001
|
+
readonly logoutPath?: string;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Configuration contract for {@link createLogoutHandler}. A
|
|
1005
|
+
* discriminated union on `mode` so the compiler enforces that
|
|
1006
|
+
* `loginPath` is present whenever redirect mode is selected.
|
|
1007
|
+
*/
|
|
1008
|
+
type LogoutHandlerConfig = LogoutHandlerRedirectConfig | LogoutHandlerStatusConfig;
|
|
1009
|
+
/** Signature of the POST handler returned by the factory. */
|
|
1010
|
+
type LogoutHandler = (request: NextRequest) => Promise<Response>;
|
|
1011
|
+
/**
|
|
1012
|
+
* Create a POST handler for `/api/auth/logout`.
|
|
1013
|
+
*
|
|
1014
|
+
* @throws {Error} When `apiBase` is not absolute HTTP(S), or when
|
|
1015
|
+
* `loginPath`/`logoutPath` / cookie names / cookie
|
|
1016
|
+
* paths fail their validation checks.
|
|
1017
|
+
*/
|
|
1018
|
+
declare function createLogoutHandler(config: LogoutHandlerConfig): LogoutHandler;
|
|
1019
|
+
/**
|
|
1020
|
+
* Canonical Next.js proxy-side path this handler is expected to be
|
|
1021
|
+
* mounted at.
|
|
1022
|
+
*/
|
|
1023
|
+
declare const LOGOUT_ROUTE: "/api/auth/logout";
|
|
1024
|
+
|
|
1025
|
+
export { type AuthProxyConfig, type AuthProxyInstance, CLIENT_REFRESH_ROUTE, type ClientRefreshHandler, type ClientRefreshHandlerConfig, type DecodedToken, type HeadersLike, type JwtHeader, LOGOUT_ROUTE, type LogoutHandler, type LogoutHandlerConfig, type LogoutHandlerRedirectConfig, type LogoutHandlerStatusConfig, type ParsedSetCookie, type ProtectedRoutePattern, type RequestWithHeaders, type RequestWithUrl, type ResolvedAuthProxyConfig, SILENT_REFRESH_ROUTE, type SilentRefreshHandler, type SilentRefreshHandlerConfig, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
|