@smartcrab/next 0.8.0 → 0.9.0-next-20261203092527
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/handlers.d.ts +2 -3
- package/dist/handlers.js +1 -2
- package/dist/middleware.d.ts +2 -2
- package/dist/middleware.js +8 -1
- package/package.json +4 -3
- package/src/handlers.ts +2 -4
- package/src/middleware.ts +11 -3
- package/src/index.test.ts +0 -425
- package/src/no-next-import.test.ts +0 -47
package/dist/handlers.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ import type { ServerAuth } from "@smartcrab/server";
|
|
|
21
21
|
*
|
|
22
22
|
* ```ts
|
|
23
23
|
* // app/auth/logout/route.ts
|
|
24
|
-
* export const {
|
|
24
|
+
* export const { POST } = createLogoutRouteHandler(auth);
|
|
25
25
|
* ```
|
|
26
26
|
*
|
|
27
27
|
* Origin/Referer and `state` validation happen inside the sdk-server
|
|
@@ -38,9 +38,8 @@ export declare const createLoginRouteHandler: (auth: ServerAuth) => {
|
|
|
38
38
|
};
|
|
39
39
|
/** OAuth callback: GET only — the authorization response is always a redirect. */
|
|
40
40
|
export declare const createCallbackRouteHandler: (auth: ServerAuth) => RouteHandler;
|
|
41
|
-
/** Logout:
|
|
41
|
+
/** Logout: POST only; the server validates Origin or a same-origin Referer. */
|
|
42
42
|
export declare const createLogoutRouteHandler: (auth: ServerAuth) => {
|
|
43
|
-
readonly GET: (request: Request) => Promise<Response>;
|
|
44
43
|
readonly POST: (request: Request) => Promise<Response>;
|
|
45
44
|
};
|
|
46
45
|
export interface AuthRouteHandlers {
|
package/dist/handlers.js
CHANGED
|
@@ -7,9 +7,8 @@ export const createLoginRouteHandler = (auth) => ({
|
|
|
7
7
|
export const createCallbackRouteHandler = (auth) => ({
|
|
8
8
|
GET: (request) => auth.callbackHandler(request),
|
|
9
9
|
});
|
|
10
|
-
/** Logout:
|
|
10
|
+
/** Logout: POST only; the server validates Origin or a same-origin Referer. */
|
|
11
11
|
export const createLogoutRouteHandler = (auth) => ({
|
|
12
|
-
GET: (request) => auth.logoutHandler(request),
|
|
13
12
|
POST: (request) => auth.logoutHandler(request),
|
|
14
13
|
});
|
|
15
14
|
/** All three factories in one call, for colocated route files. */
|
package/dist/middleware.d.ts
CHANGED
|
@@ -28,9 +28,9 @@ import type { ServerAuth } from "@smartcrab/server";
|
|
|
28
28
|
* rather than a login loop (design.md §21.7).
|
|
29
29
|
*/
|
|
30
30
|
export interface AuthMiddlewareOptions {
|
|
31
|
-
/** Custom matcher —
|
|
31
|
+
/** Custom matcher — receives the raw pathname and owns its matching rules. */
|
|
32
32
|
readonly protect?: (pathname: string) => boolean;
|
|
33
|
-
/**
|
|
33
|
+
/** Segment-aware path prefixes that require a session (e.g. `["/dashboard", "/api"]`). */
|
|
34
34
|
readonly protectedPrefixes?: readonly string[];
|
|
35
35
|
}
|
|
36
36
|
export type AuthMiddlewareResult = {
|
package/dist/middleware.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
export const createAuthMiddleware = (auth, options = {}) => {
|
|
2
|
+
const matchesPrefix = (pathname, prefix) => {
|
|
3
|
+
if (prefix === "/")
|
|
4
|
+
return true;
|
|
5
|
+
const normalizedPrefix = prefix.replace(/\/+$/, "");
|
|
6
|
+
return (normalizedPrefix.length > 0 &&
|
|
7
|
+
(pathname === normalizedPrefix || pathname.startsWith(`${normalizedPrefix}/`)));
|
|
8
|
+
};
|
|
2
9
|
const isProtected = (pathname) => {
|
|
3
10
|
if (options.protect !== undefined)
|
|
4
11
|
return options.protect(pathname);
|
|
5
|
-
return (options.protectedPrefixes ?? []).some((prefix) => pathname
|
|
12
|
+
return (options.protectedPrefixes ?? []).some((prefix) => matchesPrefix(pathname, prefix));
|
|
6
13
|
};
|
|
7
14
|
return async (request) => {
|
|
8
15
|
const pathname = new URL(request.url).pathname;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smartcrab/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0-next-20261203092527",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -21,13 +21,14 @@
|
|
|
21
21
|
},
|
|
22
22
|
"files": [
|
|
23
23
|
"dist",
|
|
24
|
-
"src"
|
|
24
|
+
"src",
|
|
25
|
+
"!src/**/*.test.ts"
|
|
25
26
|
],
|
|
26
27
|
"publishConfig": {
|
|
27
28
|
"access": "public"
|
|
28
29
|
},
|
|
29
30
|
"dependencies": {
|
|
30
|
-
"@smartcrab/server": "0.
|
|
31
|
+
"@smartcrab/server": "0.9.0-next-20261203092527"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"typescript": "5.9.3",
|
package/src/handlers.ts
CHANGED
|
@@ -22,7 +22,7 @@ import type { ServerAuth } from "@smartcrab/server";
|
|
|
22
22
|
*
|
|
23
23
|
* ```ts
|
|
24
24
|
* // app/auth/logout/route.ts
|
|
25
|
-
* export const {
|
|
25
|
+
* export const { POST } = createLogoutRouteHandler(auth);
|
|
26
26
|
* ```
|
|
27
27
|
*
|
|
28
28
|
* Origin/Referer and `state` validation happen inside the sdk-server
|
|
@@ -50,14 +50,12 @@ export const createCallbackRouteHandler = (auth: ServerAuth): RouteHandler => ({
|
|
|
50
50
|
GET: (request) => auth.callbackHandler(request),
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
-
/** Logout:
|
|
53
|
+
/** Logout: POST only; the server validates Origin or a same-origin Referer. */
|
|
54
54
|
export const createLogoutRouteHandler = (
|
|
55
55
|
auth: ServerAuth,
|
|
56
56
|
): {
|
|
57
|
-
readonly GET: (request: Request) => Promise<Response>;
|
|
58
57
|
readonly POST: (request: Request) => Promise<Response>;
|
|
59
58
|
} => ({
|
|
60
|
-
GET: (request) => auth.logoutHandler(request),
|
|
61
59
|
POST: (request) => auth.logoutHandler(request),
|
|
62
60
|
});
|
|
63
61
|
|
package/src/middleware.ts
CHANGED
|
@@ -30,9 +30,9 @@ import type { ServerAuth } from "@smartcrab/server";
|
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
32
|
export interface AuthMiddlewareOptions {
|
|
33
|
-
/** Custom matcher —
|
|
33
|
+
/** Custom matcher — receives the raw pathname and owns its matching rules. */
|
|
34
34
|
readonly protect?: (pathname: string) => boolean;
|
|
35
|
-
/**
|
|
35
|
+
/** Segment-aware path prefixes that require a session (e.g. `["/dashboard", "/api"]`). */
|
|
36
36
|
readonly protectedPrefixes?: readonly string[];
|
|
37
37
|
}
|
|
38
38
|
|
|
@@ -52,9 +52,17 @@ export const createAuthMiddleware = (
|
|
|
52
52
|
auth: ServerAuth,
|
|
53
53
|
options: AuthMiddlewareOptions = {},
|
|
54
54
|
): ((request: Request) => Promise<AuthMiddlewareResult>) => {
|
|
55
|
+
const matchesPrefix = (pathname: string, prefix: string): boolean => {
|
|
56
|
+
if (prefix === "/") return true;
|
|
57
|
+
const normalizedPrefix = prefix.replace(/\/+$/, "");
|
|
58
|
+
return (
|
|
59
|
+
normalizedPrefix.length > 0 &&
|
|
60
|
+
(pathname === normalizedPrefix || pathname.startsWith(`${normalizedPrefix}/`))
|
|
61
|
+
);
|
|
62
|
+
};
|
|
55
63
|
const isProtected = (pathname: string): boolean => {
|
|
56
64
|
if (options.protect !== undefined) return options.protect(pathname);
|
|
57
|
-
return (options.protectedPrefixes ?? []).some((prefix) => pathname
|
|
65
|
+
return (options.protectedPrefixes ?? []).some((prefix) => matchesPrefix(pathname, prefix));
|
|
58
66
|
};
|
|
59
67
|
|
|
60
68
|
return async (request) => {
|
package/src/index.test.ts
DELETED
|
@@ -1,425 +0,0 @@
|
|
|
1
|
-
import { createServerAuth } from "@smartcrab/server";
|
|
2
|
-
import type { FetchLike, ServerAuth } from "@smartcrab/server";
|
|
3
|
-
import { describe, expect, test } from "vitest";
|
|
4
|
-
import {
|
|
5
|
-
createAuthRouteHandlers,
|
|
6
|
-
createCallbackRouteHandler,
|
|
7
|
-
createLoginRouteHandler,
|
|
8
|
-
createLogoutRouteHandler,
|
|
9
|
-
} from "./handlers.js";
|
|
10
|
-
import { getSession, requireSession } from "./helpers.js";
|
|
11
|
-
import { createAuthMiddleware } from "./middleware.js";
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Verifies the Next.js helpers against Web-standard Request/Response only —
|
|
15
|
-
* no `next` import anywhere (proven by construction: `next` is not installed
|
|
16
|
-
* for this package, and the import-scan test at the bottom asserts no source
|
|
17
|
-
* file references it). The Authorization Server is stubbed behind an
|
|
18
|
-
* injected fetch; ID tokens are real ES256 JWS signed via WebCrypto.
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
const ISSUER = "https://id.example.com/e/env_test";
|
|
22
|
-
const CLIENT_ID = "cli_testclient";
|
|
23
|
-
const CLIENT_SECRET = "test_client_secret";
|
|
24
|
-
const COOKIE_SECRET = "0123456789abcdef0123456789abcdef";
|
|
25
|
-
const REDIRECT_URI = "https://app.example.com/auth/callback";
|
|
26
|
-
const APP_ORIGIN = "https://app.example.com";
|
|
27
|
-
const KID = "test-signing-key-1";
|
|
28
|
-
const USER_SUB = "usr_testuser";
|
|
29
|
-
|
|
30
|
-
// ---------------------------------------------------------------------------
|
|
31
|
-
// WebCrypto-only test helpers (no extra dependencies in this package)
|
|
32
|
-
// ---------------------------------------------------------------------------
|
|
33
|
-
|
|
34
|
-
const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
35
|
-
|
|
36
|
-
const base64UrlEncode = (bytes: Uint8Array): string => {
|
|
37
|
-
let out = "";
|
|
38
|
-
for (let i = 0; i < bytes.length; i += 3) {
|
|
39
|
-
const b0 = bytes[i] ?? 0;
|
|
40
|
-
const b1 = bytes[i + 1];
|
|
41
|
-
const b2 = bytes[i + 2];
|
|
42
|
-
out += BASE64URL_ALPHABET[b0 >> 2] ?? "";
|
|
43
|
-
out += BASE64URL_ALPHABET[((b0 & 0x03) << 4) | ((b1 ?? 0) >> 4)] ?? "";
|
|
44
|
-
if (b1 !== undefined) out += BASE64URL_ALPHABET[((b1 & 0x0f) << 2) | ((b2 ?? 0) >> 6)] ?? "";
|
|
45
|
-
if (b2 !== undefined) out += BASE64URL_ALPHABET[b2 & 0x3f] ?? "";
|
|
46
|
-
}
|
|
47
|
-
return out;
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
const textEncoder = new TextEncoder();
|
|
51
|
-
|
|
52
|
-
const signJwt = async (
|
|
53
|
-
header: Record<string, unknown>,
|
|
54
|
-
payload: Record<string, unknown>,
|
|
55
|
-
key: CryptoKey,
|
|
56
|
-
): Promise<string> => {
|
|
57
|
-
const data = `${base64UrlEncode(textEncoder.encode(JSON.stringify(header)))}.${base64UrlEncode(textEncoder.encode(JSON.stringify(payload)))}`;
|
|
58
|
-
const signature = await crypto.subtle.sign(
|
|
59
|
-
{ name: "ECDSA", hash: "SHA-256" },
|
|
60
|
-
key,
|
|
61
|
-
textEncoder.encode(data),
|
|
62
|
-
);
|
|
63
|
-
return `${data}.${base64UrlEncode(new Uint8Array(signature))}`;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
const cookieFragment = (setCookieHeader: string): string => setCookieHeader.split(";")[0] ?? "";
|
|
67
|
-
|
|
68
|
-
const generatedKeyPair = await crypto.subtle.generateKey(
|
|
69
|
-
{ name: "ECDSA", namedCurve: "P-256" },
|
|
70
|
-
true,
|
|
71
|
-
["sign", "verify"],
|
|
72
|
-
);
|
|
73
|
-
if (!("publicKey" in generatedKeyPair) || !("privateKey" in generatedKeyPair)) {
|
|
74
|
-
throw new Error("expected an ECDSA key pair");
|
|
75
|
-
}
|
|
76
|
-
const signingKeyPair: CryptoKeyPair = generatedKeyPair;
|
|
77
|
-
const exportedPublicJwk = await crypto.subtle.exportKey("jwk", signingKeyPair.publicKey);
|
|
78
|
-
if (exportedPublicJwk instanceof ArrayBuffer) {
|
|
79
|
-
throw new Error("expected a JWK export");
|
|
80
|
-
}
|
|
81
|
-
const publicJwk = {
|
|
82
|
-
kty: exportedPublicJwk.kty,
|
|
83
|
-
crv: exportedPublicJwk.crv,
|
|
84
|
-
x: exportedPublicJwk.x,
|
|
85
|
-
y: exportedPublicJwk.y,
|
|
86
|
-
kid: KID,
|
|
87
|
-
alg: "ES256",
|
|
88
|
-
use: "sig",
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
const nowSeconds = (): number => Math.floor(Date.now() / 1000);
|
|
92
|
-
|
|
93
|
-
const signIdToken = async (nonce: string): Promise<string> =>
|
|
94
|
-
signJwt(
|
|
95
|
-
{ alg: "ES256", typ: "JWT", kid: KID },
|
|
96
|
-
{
|
|
97
|
-
iss: ISSUER,
|
|
98
|
-
sub: USER_SUB,
|
|
99
|
-
aud: CLIENT_ID,
|
|
100
|
-
iat: nowSeconds(),
|
|
101
|
-
exp: nowSeconds() + 300,
|
|
102
|
-
nonce,
|
|
103
|
-
email: "test@example.com",
|
|
104
|
-
},
|
|
105
|
-
signingKeyPair.privateKey,
|
|
106
|
-
);
|
|
107
|
-
|
|
108
|
-
interface StubState {
|
|
109
|
-
currentNonce: string | null;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const jsonResponse = (body: unknown, status = 200): Response =>
|
|
113
|
-
new Response(JSON.stringify(body), {
|
|
114
|
-
status,
|
|
115
|
-
headers: { "content-type": "application/json" },
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
const createStubFetch = (state: StubState): FetchLike => {
|
|
119
|
-
return async (input, init) => {
|
|
120
|
-
const url =
|
|
121
|
-
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
122
|
-
if (url === `${ISSUER}/.well-known/openid-configuration`) {
|
|
123
|
-
return jsonResponse({
|
|
124
|
-
issuer: ISSUER,
|
|
125
|
-
authorization_endpoint: `${ISSUER}/oauth2/authorize`,
|
|
126
|
-
token_endpoint: `${ISSUER}/oauth2/token`,
|
|
127
|
-
userinfo_endpoint: `${ISSUER}/oauth2/userinfo`,
|
|
128
|
-
jwks_uri: `${ISSUER}/oauth2/jwks`,
|
|
129
|
-
revocation_endpoint: `${ISSUER}/oauth2/revoke`,
|
|
130
|
-
introspection_endpoint: `${ISSUER}/oauth2/introspect`,
|
|
131
|
-
end_session_endpoint: `${ISSUER}/oauth2/logout`,
|
|
132
|
-
response_types_supported: ["code"],
|
|
133
|
-
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
134
|
-
code_challenge_methods_supported: ["S256"],
|
|
135
|
-
token_endpoint_auth_methods_supported: ["client_secret_basic"],
|
|
136
|
-
scopes_supported: ["openid", "profile", "email", "offline_access"],
|
|
137
|
-
subject_types_supported: ["public"],
|
|
138
|
-
id_token_signing_alg_values_supported: ["ES256"],
|
|
139
|
-
claims_supported: ["sub", "nonce", "email"],
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
if (url === `${ISSUER}/oauth2/jwks`) {
|
|
143
|
-
return jsonResponse({ keys: [publicJwk] });
|
|
144
|
-
}
|
|
145
|
-
if (url === `${ISSUER}/oauth2/token`) {
|
|
146
|
-
const body = typeof init?.body === "string" ? init.body : "";
|
|
147
|
-
const params = new URLSearchParams(body);
|
|
148
|
-
if (params.get("grant_type") === "authorization_code") {
|
|
149
|
-
return jsonResponse({
|
|
150
|
-
access_token: "atk_initial",
|
|
151
|
-
token_type: "Bearer",
|
|
152
|
-
expires_in: 300,
|
|
153
|
-
refresh_token: "rt_1",
|
|
154
|
-
id_token: await signIdToken(state.currentNonce ?? ""),
|
|
155
|
-
scope: "openid profile email offline_access",
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
return jsonResponse({
|
|
159
|
-
access_token: "atk_refreshed",
|
|
160
|
-
token_type: "Bearer",
|
|
161
|
-
expires_in: 300,
|
|
162
|
-
refresh_token: "rt_2",
|
|
163
|
-
scope: "openid profile email offline_access",
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
if (url === `${ISSUER}/oauth2/revoke`) {
|
|
167
|
-
return new Response(null, { status: 200 });
|
|
168
|
-
}
|
|
169
|
-
return new Response("not found", { status: 404 });
|
|
170
|
-
};
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
const createAuth = (
|
|
174
|
-
state: StubState,
|
|
175
|
-
overrides: { readonly refreshLeewaySeconds?: number } = {},
|
|
176
|
-
): ServerAuth =>
|
|
177
|
-
createServerAuth({
|
|
178
|
-
issuer: ISSUER,
|
|
179
|
-
clientId: CLIENT_ID,
|
|
180
|
-
clientSecret: CLIENT_SECRET,
|
|
181
|
-
redirectUri: REDIRECT_URI,
|
|
182
|
-
cookieSecret: COOKIE_SECRET,
|
|
183
|
-
fetch: createStubFetch(state),
|
|
184
|
-
...(overrides.refreshLeewaySeconds !== undefined
|
|
185
|
-
? { refreshLeewaySeconds: overrides.refreshLeewaySeconds }
|
|
186
|
-
: {}),
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
/** Runs the login flow through the route-handler factories. */
|
|
190
|
-
const completeLogin = async (auth: ServerAuth, state: StubState): Promise<string> => {
|
|
191
|
-
const login = createLoginRouteHandler(auth);
|
|
192
|
-
const callback = createCallbackRouteHandler(auth);
|
|
193
|
-
const loginResponse = await login.GET(new Request(`${APP_ORIGIN}/auth/login`));
|
|
194
|
-
expect(loginResponse.status).toBe(302);
|
|
195
|
-
const location = new URL(loginResponse.headers.get("location") ?? "");
|
|
196
|
-
expect(location.origin + location.pathname).toBe(`${ISSUER}/oauth2/authorize`);
|
|
197
|
-
state.currentNonce = location.searchParams.get("nonce");
|
|
198
|
-
const pkce = cookieFragment(loginResponse.headers.getSetCookie()[0] ?? "");
|
|
199
|
-
const callbackResponse = await callback.GET(
|
|
200
|
-
new Request(
|
|
201
|
-
`${APP_ORIGIN}/auth/callback?code=ac_${"a".repeat(32)}&state=${location.searchParams.get("state") ?? ""}`,
|
|
202
|
-
{ headers: { cookie: pkce } },
|
|
203
|
-
),
|
|
204
|
-
);
|
|
205
|
-
expect(callbackResponse.status).toBe(302);
|
|
206
|
-
const sessionSet = callbackResponse.headers
|
|
207
|
-
.getSetCookie()
|
|
208
|
-
.find((value) => value.startsWith("__Host-auth-session="));
|
|
209
|
-
expect(sessionSet).toBeDefined();
|
|
210
|
-
return cookieFragment(sessionSet ?? "");
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
// ---------------------------------------------------------------------------
|
|
214
|
-
// Route-handler factories
|
|
215
|
-
// ---------------------------------------------------------------------------
|
|
216
|
-
|
|
217
|
-
describe("route handler factories", () => {
|
|
218
|
-
test("login GET redirects to the authorize endpoint", async () => {
|
|
219
|
-
const state: StubState = { currentNonce: null };
|
|
220
|
-
const auth = createAuth(state);
|
|
221
|
-
const handler = createLoginRouteHandler(auth);
|
|
222
|
-
const response = await handler.GET(new Request(`${APP_ORIGIN}/auth/login`));
|
|
223
|
-
expect(response.status).toBe(302);
|
|
224
|
-
const location = new URL(response.headers.get("location") ?? "");
|
|
225
|
-
expect(location.searchParams.get("response_type")).toBe("code");
|
|
226
|
-
expect(location.searchParams.get("code_challenge_method")).toBe("S256");
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
test("login POST validates the Origin (CSRF)", async () => {
|
|
230
|
-
const state: StubState = { currentNonce: null };
|
|
231
|
-
const auth = createAuth(state);
|
|
232
|
-
const handler = createLoginRouteHandler(auth);
|
|
233
|
-
const evil = await handler.POST(
|
|
234
|
-
new Request(`${APP_ORIGIN}/auth/login`, {
|
|
235
|
-
method: "POST",
|
|
236
|
-
headers: { origin: "https://evil.example.com" },
|
|
237
|
-
}),
|
|
238
|
-
);
|
|
239
|
-
expect(evil.status).toBe(403);
|
|
240
|
-
const good = await handler.POST(
|
|
241
|
-
new Request(`${APP_ORIGIN}/auth/login`, {
|
|
242
|
-
method: "POST",
|
|
243
|
-
headers: { origin: APP_ORIGIN },
|
|
244
|
-
}),
|
|
245
|
-
);
|
|
246
|
-
expect(good.status).toBe(302);
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
test("callback validates state and issues the session cookie", async () => {
|
|
250
|
-
const state: StubState = { currentNonce: null };
|
|
251
|
-
const auth = createAuth(state);
|
|
252
|
-
const cookie = await completeLogin(auth, state);
|
|
253
|
-
expect(cookie.startsWith("__Host-auth-session=v1.")).toBe(true);
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
test("callback rejects a state mismatch", async () => {
|
|
257
|
-
const state: StubState = { currentNonce: null };
|
|
258
|
-
const auth = createAuth(state);
|
|
259
|
-
const login = createLoginRouteHandler(auth);
|
|
260
|
-
const callback = createCallbackRouteHandler(auth);
|
|
261
|
-
const loginResponse = await login.GET(new Request(`${APP_ORIGIN}/auth/login`));
|
|
262
|
-
const pkce = cookieFragment(loginResponse.headers.getSetCookie()[0] ?? "");
|
|
263
|
-
const response = await callback.GET(
|
|
264
|
-
new Request(`${APP_ORIGIN}/auth/callback?code=ac_${"a".repeat(32)}&state=wrong-state`, {
|
|
265
|
-
headers: { cookie: pkce },
|
|
266
|
-
}),
|
|
267
|
-
);
|
|
268
|
-
expect(response.status).toBe(400);
|
|
269
|
-
});
|
|
270
|
-
|
|
271
|
-
test("logout GET clears the session; logout POST validates Origin", async () => {
|
|
272
|
-
const state: StubState = { currentNonce: null };
|
|
273
|
-
const auth = createAuth(state);
|
|
274
|
-
const cookie = await completeLogin(auth, state);
|
|
275
|
-
const logout = createLogoutRouteHandler(auth);
|
|
276
|
-
|
|
277
|
-
const evil = await logout.POST(
|
|
278
|
-
new Request(`${APP_ORIGIN}/auth/logout`, {
|
|
279
|
-
method: "POST",
|
|
280
|
-
headers: { origin: "https://evil.example.com", cookie },
|
|
281
|
-
}),
|
|
282
|
-
);
|
|
283
|
-
expect(evil.status).toBe(403);
|
|
284
|
-
|
|
285
|
-
const response = await logout.GET(
|
|
286
|
-
new Request(`${APP_ORIGIN}/auth/logout`, { headers: { cookie } }),
|
|
287
|
-
);
|
|
288
|
-
expect(response.status).toBe(302);
|
|
289
|
-
const cleared = response.headers
|
|
290
|
-
.getSetCookie()
|
|
291
|
-
.find((value) => value.startsWith("__Host-auth-session="));
|
|
292
|
-
expect(cleared).toBeDefined();
|
|
293
|
-
expect(cleared ?? "").toContain("Max-Age=0");
|
|
294
|
-
});
|
|
295
|
-
|
|
296
|
-
test("createAuthRouteHandlers bundles all three", async () => {
|
|
297
|
-
const state: StubState = { currentNonce: null };
|
|
298
|
-
const auth = createAuth(state);
|
|
299
|
-
const handlers = createAuthRouteHandlers(auth);
|
|
300
|
-
expect(typeof handlers.login.GET).toBe("function");
|
|
301
|
-
expect(typeof handlers.login.POST).toBe("function");
|
|
302
|
-
expect(typeof handlers.callback.GET).toBe("function");
|
|
303
|
-
expect(typeof handlers.logout.GET).toBe("function");
|
|
304
|
-
expect(typeof handlers.logout.POST).toBe("function");
|
|
305
|
-
});
|
|
306
|
-
});
|
|
307
|
-
|
|
308
|
-
// ---------------------------------------------------------------------------
|
|
309
|
-
// middleware helper
|
|
310
|
-
// ---------------------------------------------------------------------------
|
|
311
|
-
|
|
312
|
-
describe("createAuthMiddleware", () => {
|
|
313
|
-
test("passes unprotected paths without touching the session", async () => {
|
|
314
|
-
const state: StubState = { currentNonce: null };
|
|
315
|
-
const auth = createAuth(state);
|
|
316
|
-
const middleware = createAuthMiddleware(auth, { protectedPrefixes: ["/app"] });
|
|
317
|
-
const result = await middleware(new Request(`${APP_ORIGIN}/`));
|
|
318
|
-
expect(result.action).toBe("next");
|
|
319
|
-
if (result.action === "next") {
|
|
320
|
-
expect(result.setCookie).toBeUndefined();
|
|
321
|
-
}
|
|
322
|
-
});
|
|
323
|
-
|
|
324
|
-
test("redirects unauthenticated requests to protected paths", async () => {
|
|
325
|
-
const state: StubState = { currentNonce: null };
|
|
326
|
-
const auth = createAuth(state);
|
|
327
|
-
const middleware = createAuthMiddleware(auth, { protectedPrefixes: ["/app"] });
|
|
328
|
-
const result = await middleware(new Request(`${APP_ORIGIN}/app/dashboard`));
|
|
329
|
-
expect(result.action).toBe("respond");
|
|
330
|
-
if (result.action !== "respond") return;
|
|
331
|
-
expect(result.response.status).toBe(302);
|
|
332
|
-
expect(result.response.headers.get("location")).toBe(
|
|
333
|
-
"/auth/login?return_to=%2Fapp%2Fdashboard",
|
|
334
|
-
);
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
test("passes authenticated requests through", async () => {
|
|
338
|
-
const state: StubState = { currentNonce: null };
|
|
339
|
-
const auth = createAuth(state);
|
|
340
|
-
const cookie = await completeLogin(auth, state);
|
|
341
|
-
const middleware = createAuthMiddleware(auth, { protectedPrefixes: ["/app"] });
|
|
342
|
-
const result = await middleware(
|
|
343
|
-
new Request(`${APP_ORIGIN}/app/dashboard`, { headers: { cookie } }),
|
|
344
|
-
);
|
|
345
|
-
expect(result.action).toBe("next");
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
test("surfaces the rotated session cookie after a refresh", async () => {
|
|
349
|
-
const state: StubState = { currentNonce: null };
|
|
350
|
-
const auth = createAuth(state, { refreshLeewaySeconds: 10_000 });
|
|
351
|
-
const cookie = await completeLogin(auth, state);
|
|
352
|
-
const middleware = createAuthMiddleware(auth, {
|
|
353
|
-
protect: (pathname) => pathname.startsWith("/app"),
|
|
354
|
-
});
|
|
355
|
-
const result = await middleware(
|
|
356
|
-
new Request(`${APP_ORIGIN}/app/dashboard`, { headers: { cookie } }),
|
|
357
|
-
);
|
|
358
|
-
expect(result.action).toBe("next");
|
|
359
|
-
if (result.action !== "next") return;
|
|
360
|
-
expect(result.setCookie).toBeDefined();
|
|
361
|
-
expect(result.setCookie ?? "").toContain("__Host-auth-session=");
|
|
362
|
-
expect(result.setCookie ?? "").toContain("HttpOnly");
|
|
363
|
-
});
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
// ---------------------------------------------------------------------------
|
|
367
|
-
// server helpers (Request / Headers / { headers })
|
|
368
|
-
// ---------------------------------------------------------------------------
|
|
369
|
-
|
|
370
|
-
describe("getSession / requireSession helpers", () => {
|
|
371
|
-
test("getSession accepts a Request", async () => {
|
|
372
|
-
const state: StubState = { currentNonce: null };
|
|
373
|
-
const auth = createAuth(state);
|
|
374
|
-
const cookie = await completeLogin(auth, state);
|
|
375
|
-
const outcome = await getSession(auth, new Request(`${APP_ORIGIN}/x`, { headers: { cookie } }));
|
|
376
|
-
expect(outcome.status).toBe("authenticated");
|
|
377
|
-
});
|
|
378
|
-
|
|
379
|
-
test("getSession accepts plain Headers and { headers } sources", async () => {
|
|
380
|
-
const state: StubState = { currentNonce: null };
|
|
381
|
-
const auth = createAuth(state);
|
|
382
|
-
const cookie = await completeLogin(auth, state);
|
|
383
|
-
|
|
384
|
-
const fromHeaders = await getSession(auth, new Headers({ cookie }));
|
|
385
|
-
expect(fromHeaders.status).toBe("authenticated");
|
|
386
|
-
if (fromHeaders.status === "authenticated") {
|
|
387
|
-
expect(fromHeaders.session.user.sub).toBe(USER_SUB);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// Structurally what `headers()` from next/headers looks like in RSC.
|
|
391
|
-
const fromHeadersLike = await getSession(auth, { headers: new Headers({ cookie }) });
|
|
392
|
-
expect(fromHeadersLike.status).toBe("authenticated");
|
|
393
|
-
});
|
|
394
|
-
|
|
395
|
-
test("getSession without a cookie is unauthenticated", async () => {
|
|
396
|
-
const state: StubState = { currentNonce: null };
|
|
397
|
-
const auth = createAuth(state);
|
|
398
|
-
const outcome = await getSession(auth, new Headers());
|
|
399
|
-
expect(outcome.status).toBe("unauthenticated");
|
|
400
|
-
});
|
|
401
|
-
|
|
402
|
-
test("requireSession redirects header-only sources with a sanitized return_to", async () => {
|
|
403
|
-
const state: StubState = { currentNonce: null };
|
|
404
|
-
const auth = createAuth(state);
|
|
405
|
-
const outcome = await requireSession(auth, new Headers(), { returnTo: "/app/settings" });
|
|
406
|
-
expect(outcome.ok).toBe(false);
|
|
407
|
-
if (outcome.ok) return;
|
|
408
|
-
expect(outcome.response.status).toBe(302);
|
|
409
|
-
expect(outcome.response.headers.get("location")).toBe(
|
|
410
|
-
"/auth/login?return_to=%2Fapp%2Fsettings",
|
|
411
|
-
);
|
|
412
|
-
});
|
|
413
|
-
|
|
414
|
-
test("requireSession never builds an open redirect from returnTo", async () => {
|
|
415
|
-
const state: StubState = { currentNonce: null };
|
|
416
|
-
const auth = createAuth(state);
|
|
417
|
-
const outcome = await requireSession(auth, new Headers(), {
|
|
418
|
-
returnTo: "https://evil.example.com",
|
|
419
|
-
});
|
|
420
|
-
expect(outcome.ok).toBe(false);
|
|
421
|
-
if (outcome.ok) return;
|
|
422
|
-
// Sanitized to "/" — never to the attacker-supplied absolute URL.
|
|
423
|
-
expect(outcome.response.headers.get("location")).toBe("/auth/login?return_to=%2F");
|
|
424
|
-
});
|
|
425
|
-
});
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { describe, expect, test } from "vitest";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Dependency-boundary guarantee: @smartcrab/next must never import
|
|
5
|
-
* `next` (or `next/*`) — the helpers are designed against Web-standard
|
|
6
|
-
* Request/Response structurally, so the package works with any Next version
|
|
7
|
-
* and none of its types leak into our API. This scans every source file
|
|
8
|
-
* (including this test) for a forbidden import.
|
|
9
|
-
*
|
|
10
|
-
* The scan uses vite's `import.meta.glob` (vitest implements it) because
|
|
11
|
-
* this package intentionally carries no `@types/node` — indeed, a stray
|
|
12
|
-
* `import "next"` would also fail `tsc --noEmit` outright, since `next` is
|
|
13
|
-
* not installed for this package (proof by construction).
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
declare global {
|
|
17
|
-
interface ImportMeta {
|
|
18
|
-
/** Subset of vite's glob import used for the raw-source scan. */
|
|
19
|
-
readonly glob: (
|
|
20
|
-
pattern: string,
|
|
21
|
-
options: { readonly eager: true; readonly query: "?raw"; readonly import: "default" },
|
|
22
|
-
) => Record<string, unknown>;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// Line-anchored so doc-comment examples (which start with ` * `) never match.
|
|
27
|
-
const NEXT_IMPORT_PATTERN = /^(?:import|export)\s[^;\n]*?from\s*["']next(?:\/[^"']*)?["']/m;
|
|
28
|
-
const NEXT_DYNAMIC_IMPORT_PATTERN = /^import\s*\(\s*["']next(?:\/[^"']*)?["']/m;
|
|
29
|
-
|
|
30
|
-
describe("no next dependency", () => {
|
|
31
|
-
test("no source file imports next or next/*", () => {
|
|
32
|
-
const sources = import.meta.glob("./*.ts", { eager: true, query: "?raw", import: "default" });
|
|
33
|
-
const offenders = Object.entries(sources)
|
|
34
|
-
.filter(
|
|
35
|
-
([, content]) =>
|
|
36
|
-
typeof content === "string" &&
|
|
37
|
-
(NEXT_IMPORT_PATTERN.test(content) || NEXT_DYNAMIC_IMPORT_PATTERN.test(content)),
|
|
38
|
-
)
|
|
39
|
-
.map(([path]) => path);
|
|
40
|
-
expect(offenders).toEqual([]);
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
test("the glob scan actually sees the source files", () => {
|
|
44
|
-
const sources = import.meta.glob("./*.ts", { eager: true, query: "?raw", import: "default" });
|
|
45
|
-
expect(Object.keys(sources).length).toBeGreaterThanOrEqual(4);
|
|
46
|
-
});
|
|
47
|
-
});
|