@smartcrab/next 0.1.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/LICENSE +202 -0
- package/dist/handlers.d.ts +52 -0
- package/dist/handlers.js +20 -0
- package/dist/helpers.d.ts +33 -0
- package/dist/helpers.js +24 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +10 -0
- package/dist/middleware.d.ts +45 -0
- package/dist/middleware.js +21 -0
- package/package.json +42 -0
- package/src/handlers.ts +75 -0
- package/src/helpers.ts +64 -0
- package/src/index.test.ts +425 -0
- package/src/index.ts +27 -0
- package/src/middleware.ts +74 -0
- package/src/no-next-import.test.ts +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
2
|
+
/**
|
|
3
|
+
* Route-handler factories for Next.js App Router (design.md §3.1: "Next.js
|
|
4
|
+
* サーバー — Route Handler、Middleware、Server helper").
|
|
5
|
+
*
|
|
6
|
+
* Structural typing, no `next` dependency: Next's Route Handlers (the
|
|
7
|
+
* `route.ts` files under `app/`) receive a Web-standard `Request` and must
|
|
8
|
+
* return a Web-standard `Response`, which is exactly the surface
|
|
9
|
+
* @smartcrab/server already speaks. Wire them up like:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* // app/auth/login/route.ts
|
|
13
|
+
* import { auth } from "@/lib/auth"; // createServerAuth(...)
|
|
14
|
+
* export const { GET, POST } = createLoginRouteHandler(auth);
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* // app/auth/callback/route.ts
|
|
19
|
+
* export const { GET } = createCallbackRouteHandler(auth);
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* // app/auth/logout/route.ts
|
|
24
|
+
* export const { GET, POST } = createLogoutRouteHandler(auth);
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* Origin/Referer and `state` validation happen inside the sdk-server
|
|
28
|
+
* handlers exactly as for any other runtime (design.md §32.2).
|
|
29
|
+
*/
|
|
30
|
+
export interface RouteHandler {
|
|
31
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
32
|
+
readonly POST?: (request: Request) => Promise<Response>;
|
|
33
|
+
}
|
|
34
|
+
/** Login start: GET (browser navigation) and POST (fetch-based clients, CSRF-checked). */
|
|
35
|
+
export declare const createLoginRouteHandler: (auth: ServerAuth) => {
|
|
36
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
37
|
+
readonly POST: (request: Request) => Promise<Response>;
|
|
38
|
+
};
|
|
39
|
+
/** OAuth callback: GET only — the authorization response is always a redirect. */
|
|
40
|
+
export declare const createCallbackRouteHandler: (auth: ServerAuth) => RouteHandler;
|
|
41
|
+
/** Logout: GET (navigation) and POST (CSRF-checked). */
|
|
42
|
+
export declare const createLogoutRouteHandler: (auth: ServerAuth) => {
|
|
43
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
44
|
+
readonly POST: (request: Request) => Promise<Response>;
|
|
45
|
+
};
|
|
46
|
+
export interface AuthRouteHandlers {
|
|
47
|
+
readonly login: ReturnType<typeof createLoginRouteHandler>;
|
|
48
|
+
readonly callback: ReturnType<typeof createCallbackRouteHandler>;
|
|
49
|
+
readonly logout: ReturnType<typeof createLogoutRouteHandler>;
|
|
50
|
+
}
|
|
51
|
+
/** All three factories in one call, for colocated route files. */
|
|
52
|
+
export declare const createAuthRouteHandlers: (auth: ServerAuth) => AuthRouteHandlers;
|
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Login start: GET (browser navigation) and POST (fetch-based clients, CSRF-checked). */
|
|
2
|
+
export const createLoginRouteHandler = (auth) => ({
|
|
3
|
+
GET: (request) => auth.loginHandler(request),
|
|
4
|
+
POST: (request) => auth.loginHandler(request),
|
|
5
|
+
});
|
|
6
|
+
/** OAuth callback: GET only — the authorization response is always a redirect. */
|
|
7
|
+
export const createCallbackRouteHandler = (auth) => ({
|
|
8
|
+
GET: (request) => auth.callbackHandler(request),
|
|
9
|
+
});
|
|
10
|
+
/** Logout: GET (navigation) and POST (CSRF-checked). */
|
|
11
|
+
export const createLogoutRouteHandler = (auth) => ({
|
|
12
|
+
GET: (request) => auth.logoutHandler(request),
|
|
13
|
+
POST: (request) => auth.logoutHandler(request),
|
|
14
|
+
});
|
|
15
|
+
/** All three factories in one call, for colocated route files. */
|
|
16
|
+
export const createAuthRouteHandlers = (auth) => ({
|
|
17
|
+
login: createLoginRouteHandler(auth),
|
|
18
|
+
callback: createCallbackRouteHandler(auth),
|
|
19
|
+
logout: createLogoutRouteHandler(auth),
|
|
20
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { GetSessionOutcome, RequireSessionOptions, RequireSessionOutcome, ServerAuth } from "@smartcrab/server";
|
|
2
|
+
/**
|
|
3
|
+
* Server-component / route helpers (design.md §3.1 "Server helper").
|
|
4
|
+
*
|
|
5
|
+
* They accept the incoming `Request` (route handlers, middleware), a plain
|
|
6
|
+
* `Headers` instance, or any object carrying `headers: Headers` — which is
|
|
7
|
+
* what `headers()` from `next/headers` structurally looks like in React
|
|
8
|
+
* Server Components, again without importing `next`.
|
|
9
|
+
*
|
|
10
|
+
* RSC caveat: when only headers are available there is no outgoing response
|
|
11
|
+
* to attach a refreshed session cookie to; the outcome still reports
|
|
12
|
+
* `setCookie`/`clearCookie` and callers that CAN write cookies (route
|
|
13
|
+
* handlers, Server Actions) should apply them. In RSC the middleware helper
|
|
14
|
+
* is the right place to perform refreshes.
|
|
15
|
+
*/
|
|
16
|
+
export type HeaderSource = Request | Headers | {
|
|
17
|
+
readonly headers: Headers;
|
|
18
|
+
};
|
|
19
|
+
/** Resolves the current session from a Request, Headers, or `{ headers }` source. */
|
|
20
|
+
export declare const getSession: (auth: ServerAuth, source: HeaderSource) => Promise<GetSessionOutcome>;
|
|
21
|
+
export interface NextRequireSessionOptions extends RequireSessionOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Where the login redirect should return to, for header-only sources (RSC)
|
|
24
|
+
* that carry no URL. Sanitized like any other redirect target (relative
|
|
25
|
+
* paths or allowlisted URLs only); default `"/"`.
|
|
26
|
+
*/
|
|
27
|
+
readonly returnTo?: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Like `getSession`, but produces the typed failure/redirect response for
|
|
31
|
+
* unauthenticated requests (see `ServerAuth.requireSession`).
|
|
32
|
+
*/
|
|
33
|
+
export declare const requireSession: (auth: ServerAuth, source: HeaderSource, options?: NextRequireSessionOptions) => Promise<RequireSessionOutcome>;
|
package/dist/helpers.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { sanitizeRedirectTarget } from "@smartcrab/server";
|
|
2
|
+
/** Synthetic origin for header-only sources; getSession never inspects it. */
|
|
3
|
+
const HEADER_SOURCE_ORIGIN = "https://localhost";
|
|
4
|
+
const toRequest = (source, path) => {
|
|
5
|
+
if (source instanceof Request)
|
|
6
|
+
return source;
|
|
7
|
+
const headers = source instanceof Headers ? source : source.headers;
|
|
8
|
+
return new Request(`${HEADER_SOURCE_ORIGIN}${path}`, { headers });
|
|
9
|
+
};
|
|
10
|
+
/** Resolves the current session from a Request, Headers, or `{ headers }` source. */
|
|
11
|
+
export const getSession = (auth, source) => auth.getSession(toRequest(source, "/"));
|
|
12
|
+
/**
|
|
13
|
+
* Like `getSession`, but produces the typed failure/redirect response for
|
|
14
|
+
* unauthenticated requests (see `ServerAuth.requireSession`).
|
|
15
|
+
*/
|
|
16
|
+
export const requireSession = (auth, source, options) => {
|
|
17
|
+
if (source instanceof Request) {
|
|
18
|
+
return auth.requireSession(source, options);
|
|
19
|
+
}
|
|
20
|
+
// Header-only source: build a synthetic request whose path is the sanitized
|
|
21
|
+
// return_to so the login redirect points back at a safe location.
|
|
22
|
+
const returnTo = sanitizeRedirectTarget(options?.returnTo ?? "/", [], "/");
|
|
23
|
+
return auth.requireSession(toRequest(source, returnTo), options);
|
|
24
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/next — Next.js helpers for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1), built purely on Web-standard `Request`/`Response` so no
|
|
4
|
+
* `next` dependency is required. Next's Route Handlers accept/return Web
|
|
5
|
+
* `Request`/`Response` and `middleware.ts` may return any Web `Response`;
|
|
6
|
+
* this package is designed against those structural contracts.
|
|
7
|
+
*/
|
|
8
|
+
export { createAuthRouteHandlers, createCallbackRouteHandler, createLoginRouteHandler, createLogoutRouteHandler, } from "./handlers.js";
|
|
9
|
+
export type { AuthRouteHandlers, RouteHandler } from "./handlers.js";
|
|
10
|
+
export { createAuthMiddleware } from "./middleware.js";
|
|
11
|
+
export type { AuthMiddlewareOptions, AuthMiddlewareResult } from "./middleware.js";
|
|
12
|
+
export { getSession, requireSession } from "./helpers.js";
|
|
13
|
+
export type { HeaderSource, NextRequireSessionOptions } from "./helpers.js";
|
|
14
|
+
export type { GetSessionOutcome, RequireSessionOutcome, ServerAuth, ServerAuthConfig, Session, SessionUser, UnauthenticatedReason, } from "@smartcrab/server";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/next — Next.js helpers for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1), built purely on Web-standard `Request`/`Response` so no
|
|
4
|
+
* `next` dependency is required. Next's Route Handlers accept/return Web
|
|
5
|
+
* `Request`/`Response` and `middleware.ts` may return any Web `Response`;
|
|
6
|
+
* this package is designed against those structural contracts.
|
|
7
|
+
*/
|
|
8
|
+
export { createAuthRouteHandlers, createCallbackRouteHandler, createLoginRouteHandler, createLogoutRouteHandler, } from "./handlers.js";
|
|
9
|
+
export { createAuthMiddleware } from "./middleware.js";
|
|
10
|
+
export { getSession, requireSession } from "./helpers.js";
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
2
|
+
/**
|
|
3
|
+
* Session-enforcement helper for Next.js `middleware.ts` (design.md §3.1) —
|
|
4
|
+
* built on Web-standard Request/Response only, so this package needs no
|
|
5
|
+
* `next` dependency. Next's middleware receives a `NextRequest` (a Web
|
|
6
|
+
* `Request` subclass) and may return any Web `Response`; the result contract
|
|
7
|
+
* here maps onto that model without importing Next:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* // middleware.ts
|
|
11
|
+
* import { NextResponse } from "next/server";
|
|
12
|
+
* import { authMiddleware } from "@/lib/auth-middleware"; // createAuthMiddleware(...)
|
|
13
|
+
*
|
|
14
|
+
* export default async function middleware(request: NextRequest) {
|
|
15
|
+
* const result = await authMiddleware(request);
|
|
16
|
+
* if (result.action === "respond") return result.response; // redirect / 503
|
|
17
|
+
* const response = NextResponse.next();
|
|
18
|
+
* if (result.setCookie !== undefined) {
|
|
19
|
+
* response.headers.append("set-cookie", result.setCookie); // rotated session
|
|
20
|
+
* }
|
|
21
|
+
* return response;
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* Unauthenticated requests to protected paths get the sdk-server
|
|
26
|
+
* `requireSession` redirect response (302 to the login handler with a safe
|
|
27
|
+
* `return_to`); a transient refresh failure yields a 503 problem response
|
|
28
|
+
* rather than a login loop (design.md §21.7).
|
|
29
|
+
*/
|
|
30
|
+
export interface AuthMiddlewareOptions {
|
|
31
|
+
/** Custom matcher — highest precedence. */
|
|
32
|
+
readonly protect?: (pathname: string) => boolean;
|
|
33
|
+
/** Path prefixes that require a session (e.g. `["/dashboard", "/api"]`). */
|
|
34
|
+
readonly protectedPrefixes?: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
export type AuthMiddlewareResult = {
|
|
37
|
+
readonly action: "next";
|
|
38
|
+
/** Present when the session was refreshed — apply to the outgoing response. */
|
|
39
|
+
readonly setCookie?: string;
|
|
40
|
+
} | {
|
|
41
|
+
/** Return this response to the client (302 login redirect or 503 problem). */
|
|
42
|
+
readonly action: "respond";
|
|
43
|
+
readonly response: Response;
|
|
44
|
+
};
|
|
45
|
+
export declare const createAuthMiddleware: (auth: ServerAuth, options?: AuthMiddlewareOptions) => ((request: Request) => Promise<AuthMiddlewareResult>);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const createAuthMiddleware = (auth, options = {}) => {
|
|
2
|
+
const isProtected = (pathname) => {
|
|
3
|
+
if (options.protect !== undefined)
|
|
4
|
+
return options.protect(pathname);
|
|
5
|
+
return (options.protectedPrefixes ?? []).some((prefix) => pathname.startsWith(prefix));
|
|
6
|
+
};
|
|
7
|
+
return async (request) => {
|
|
8
|
+
const pathname = new URL(request.url).pathname;
|
|
9
|
+
if (!isProtected(pathname)) {
|
|
10
|
+
return { action: "next" };
|
|
11
|
+
}
|
|
12
|
+
const outcome = await auth.requireSession(request);
|
|
13
|
+
if (outcome.ok) {
|
|
14
|
+
return {
|
|
15
|
+
action: "next",
|
|
16
|
+
...(outcome.setCookie !== undefined ? { setCookie: outcome.setCookie } : {}),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
return { action: "respond", response: outcome.response };
|
|
20
|
+
};
|
|
21
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@smartcrab/next",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"development": "./src/index.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./*": {
|
|
16
|
+
"types": "./src/*.ts",
|
|
17
|
+
"development": "./src/*.ts",
|
|
18
|
+
"import": "./dist/*.js",
|
|
19
|
+
"default": "./dist/*.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@smartcrab/server": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"typescript": "5.9.3",
|
|
34
|
+
"vitest": "4.1.11",
|
|
35
|
+
"@cloudflare/workers-types": "5.20260804.1"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"typecheck": "tsc --noEmit",
|
|
39
|
+
"test": "vitest run --passWithNoTests",
|
|
40
|
+
"build": "tsc -p tsconfig.build.json"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/handlers.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Route-handler factories for Next.js App Router (design.md §3.1: "Next.js
|
|
5
|
+
* サーバー — Route Handler、Middleware、Server helper").
|
|
6
|
+
*
|
|
7
|
+
* Structural typing, no `next` dependency: Next's Route Handlers (the
|
|
8
|
+
* `route.ts` files under `app/`) receive a Web-standard `Request` and must
|
|
9
|
+
* return a Web-standard `Response`, which is exactly the surface
|
|
10
|
+
* @smartcrab/server already speaks. Wire them up like:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* // app/auth/login/route.ts
|
|
14
|
+
* import { auth } from "@/lib/auth"; // createServerAuth(...)
|
|
15
|
+
* export const { GET, POST } = createLoginRouteHandler(auth);
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* // app/auth/callback/route.ts
|
|
20
|
+
* export const { GET } = createCallbackRouteHandler(auth);
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* // app/auth/logout/route.ts
|
|
25
|
+
* export const { GET, POST } = createLogoutRouteHandler(auth);
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Origin/Referer and `state` validation happen inside the sdk-server
|
|
29
|
+
* handlers exactly as for any other runtime (design.md §32.2).
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export interface RouteHandler {
|
|
33
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
34
|
+
readonly POST?: (request: Request) => Promise<Response>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Login start: GET (browser navigation) and POST (fetch-based clients, CSRF-checked). */
|
|
38
|
+
export const createLoginRouteHandler = (
|
|
39
|
+
auth: ServerAuth,
|
|
40
|
+
): {
|
|
41
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
42
|
+
readonly POST: (request: Request) => Promise<Response>;
|
|
43
|
+
} => ({
|
|
44
|
+
GET: (request) => auth.loginHandler(request),
|
|
45
|
+
POST: (request) => auth.loginHandler(request),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** OAuth callback: GET only — the authorization response is always a redirect. */
|
|
49
|
+
export const createCallbackRouteHandler = (auth: ServerAuth): RouteHandler => ({
|
|
50
|
+
GET: (request) => auth.callbackHandler(request),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/** Logout: GET (navigation) and POST (CSRF-checked). */
|
|
54
|
+
export const createLogoutRouteHandler = (
|
|
55
|
+
auth: ServerAuth,
|
|
56
|
+
): {
|
|
57
|
+
readonly GET: (request: Request) => Promise<Response>;
|
|
58
|
+
readonly POST: (request: Request) => Promise<Response>;
|
|
59
|
+
} => ({
|
|
60
|
+
GET: (request) => auth.logoutHandler(request),
|
|
61
|
+
POST: (request) => auth.logoutHandler(request),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
export interface AuthRouteHandlers {
|
|
65
|
+
readonly login: ReturnType<typeof createLoginRouteHandler>;
|
|
66
|
+
readonly callback: ReturnType<typeof createCallbackRouteHandler>;
|
|
67
|
+
readonly logout: ReturnType<typeof createLogoutRouteHandler>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** All three factories in one call, for colocated route files. */
|
|
71
|
+
export const createAuthRouteHandlers = (auth: ServerAuth): AuthRouteHandlers => ({
|
|
72
|
+
login: createLoginRouteHandler(auth),
|
|
73
|
+
callback: createCallbackRouteHandler(auth),
|
|
74
|
+
logout: createLogoutRouteHandler(auth),
|
|
75
|
+
});
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { sanitizeRedirectTarget } from "@smartcrab/server";
|
|
2
|
+
import type {
|
|
3
|
+
GetSessionOutcome,
|
|
4
|
+
RequireSessionOptions,
|
|
5
|
+
RequireSessionOutcome,
|
|
6
|
+
ServerAuth,
|
|
7
|
+
} from "@smartcrab/server";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Server-component / route helpers (design.md §3.1 "Server helper").
|
|
11
|
+
*
|
|
12
|
+
* They accept the incoming `Request` (route handlers, middleware), a plain
|
|
13
|
+
* `Headers` instance, or any object carrying `headers: Headers` — which is
|
|
14
|
+
* what `headers()` from `next/headers` structurally looks like in React
|
|
15
|
+
* Server Components, again without importing `next`.
|
|
16
|
+
*
|
|
17
|
+
* RSC caveat: when only headers are available there is no outgoing response
|
|
18
|
+
* to attach a refreshed session cookie to; the outcome still reports
|
|
19
|
+
* `setCookie`/`clearCookie` and callers that CAN write cookies (route
|
|
20
|
+
* handlers, Server Actions) should apply them. In RSC the middleware helper
|
|
21
|
+
* is the right place to perform refreshes.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export type HeaderSource = Request | Headers | { readonly headers: Headers };
|
|
25
|
+
|
|
26
|
+
/** Synthetic origin for header-only sources; getSession never inspects it. */
|
|
27
|
+
const HEADER_SOURCE_ORIGIN = "https://localhost";
|
|
28
|
+
|
|
29
|
+
const toRequest = (source: HeaderSource, path: string): Request => {
|
|
30
|
+
if (source instanceof Request) return source;
|
|
31
|
+
const headers = source instanceof Headers ? source : source.headers;
|
|
32
|
+
return new Request(`${HEADER_SOURCE_ORIGIN}${path}`, { headers });
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Resolves the current session from a Request, Headers, or `{ headers }` source. */
|
|
36
|
+
export const getSession = (auth: ServerAuth, source: HeaderSource): Promise<GetSessionOutcome> =>
|
|
37
|
+
auth.getSession(toRequest(source, "/"));
|
|
38
|
+
|
|
39
|
+
export interface NextRequireSessionOptions extends RequireSessionOptions {
|
|
40
|
+
/**
|
|
41
|
+
* Where the login redirect should return to, for header-only sources (RSC)
|
|
42
|
+
* that carry no URL. Sanitized like any other redirect target (relative
|
|
43
|
+
* paths or allowlisted URLs only); default `"/"`.
|
|
44
|
+
*/
|
|
45
|
+
readonly returnTo?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Like `getSession`, but produces the typed failure/redirect response for
|
|
50
|
+
* unauthenticated requests (see `ServerAuth.requireSession`).
|
|
51
|
+
*/
|
|
52
|
+
export const requireSession = (
|
|
53
|
+
auth: ServerAuth,
|
|
54
|
+
source: HeaderSource,
|
|
55
|
+
options?: NextRequireSessionOptions,
|
|
56
|
+
): Promise<RequireSessionOutcome> => {
|
|
57
|
+
if (source instanceof Request) {
|
|
58
|
+
return auth.requireSession(source, options);
|
|
59
|
+
}
|
|
60
|
+
// Header-only source: build a synthetic request whose path is the sanitized
|
|
61
|
+
// return_to so the login redirect points back at a safe location.
|
|
62
|
+
const returnTo = sanitizeRedirectTarget(options?.returnTo ?? "/", [], "/");
|
|
63
|
+
return auth.requireSession(toRequest(source, returnTo), options);
|
|
64
|
+
};
|
|
@@ -0,0 +1,425 @@
|
|
|
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
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/next — Next.js helpers for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1), built purely on Web-standard `Request`/`Response` so no
|
|
4
|
+
* `next` dependency is required. Next's Route Handlers accept/return Web
|
|
5
|
+
* `Request`/`Response` and `middleware.ts` may return any Web `Response`;
|
|
6
|
+
* this package is designed against those structural contracts.
|
|
7
|
+
*/
|
|
8
|
+
export {
|
|
9
|
+
createAuthRouteHandlers,
|
|
10
|
+
createCallbackRouteHandler,
|
|
11
|
+
createLoginRouteHandler,
|
|
12
|
+
createLogoutRouteHandler,
|
|
13
|
+
} from "./handlers.js";
|
|
14
|
+
export type { AuthRouteHandlers, RouteHandler } from "./handlers.js";
|
|
15
|
+
export { createAuthMiddleware } from "./middleware.js";
|
|
16
|
+
export type { AuthMiddlewareOptions, AuthMiddlewareResult } from "./middleware.js";
|
|
17
|
+
export { getSession, requireSession } from "./helpers.js";
|
|
18
|
+
export type { HeaderSource, NextRequireSessionOptions } from "./helpers.js";
|
|
19
|
+
export type {
|
|
20
|
+
GetSessionOutcome,
|
|
21
|
+
RequireSessionOutcome,
|
|
22
|
+
ServerAuth,
|
|
23
|
+
ServerAuthConfig,
|
|
24
|
+
Session,
|
|
25
|
+
SessionUser,
|
|
26
|
+
UnauthenticatedReason,
|
|
27
|
+
} from "@smartcrab/server";
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Session-enforcement helper for Next.js `middleware.ts` (design.md §3.1) —
|
|
5
|
+
* built on Web-standard Request/Response only, so this package needs no
|
|
6
|
+
* `next` dependency. Next's middleware receives a `NextRequest` (a Web
|
|
7
|
+
* `Request` subclass) and may return any Web `Response`; the result contract
|
|
8
|
+
* here maps onto that model without importing Next:
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* // middleware.ts
|
|
12
|
+
* import { NextResponse } from "next/server";
|
|
13
|
+
* import { authMiddleware } from "@/lib/auth-middleware"; // createAuthMiddleware(...)
|
|
14
|
+
*
|
|
15
|
+
* export default async function middleware(request: NextRequest) {
|
|
16
|
+
* const result = await authMiddleware(request);
|
|
17
|
+
* if (result.action === "respond") return result.response; // redirect / 503
|
|
18
|
+
* const response = NextResponse.next();
|
|
19
|
+
* if (result.setCookie !== undefined) {
|
|
20
|
+
* response.headers.append("set-cookie", result.setCookie); // rotated session
|
|
21
|
+
* }
|
|
22
|
+
* return response;
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Unauthenticated requests to protected paths get the sdk-server
|
|
27
|
+
* `requireSession` redirect response (302 to the login handler with a safe
|
|
28
|
+
* `return_to`); a transient refresh failure yields a 503 problem response
|
|
29
|
+
* rather than a login loop (design.md §21.7).
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export interface AuthMiddlewareOptions {
|
|
33
|
+
/** Custom matcher — highest precedence. */
|
|
34
|
+
readonly protect?: (pathname: string) => boolean;
|
|
35
|
+
/** Path prefixes that require a session (e.g. `["/dashboard", "/api"]`). */
|
|
36
|
+
readonly protectedPrefixes?: readonly string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type AuthMiddlewareResult =
|
|
40
|
+
| {
|
|
41
|
+
readonly action: "next";
|
|
42
|
+
/** Present when the session was refreshed — apply to the outgoing response. */
|
|
43
|
+
readonly setCookie?: string;
|
|
44
|
+
}
|
|
45
|
+
| {
|
|
46
|
+
/** Return this response to the client (302 login redirect or 503 problem). */
|
|
47
|
+
readonly action: "respond";
|
|
48
|
+
readonly response: Response;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const createAuthMiddleware = (
|
|
52
|
+
auth: ServerAuth,
|
|
53
|
+
options: AuthMiddlewareOptions = {},
|
|
54
|
+
): ((request: Request) => Promise<AuthMiddlewareResult>) => {
|
|
55
|
+
const isProtected = (pathname: string): boolean => {
|
|
56
|
+
if (options.protect !== undefined) return options.protect(pathname);
|
|
57
|
+
return (options.protectedPrefixes ?? []).some((prefix) => pathname.startsWith(prefix));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
return async (request) => {
|
|
61
|
+
const pathname = new URL(request.url).pathname;
|
|
62
|
+
if (!isProtected(pathname)) {
|
|
63
|
+
return { action: "next" };
|
|
64
|
+
}
|
|
65
|
+
const outcome = await auth.requireSession(request);
|
|
66
|
+
if (outcome.ok) {
|
|
67
|
+
return {
|
|
68
|
+
action: "next",
|
|
69
|
+
...(outcome.setCookie !== undefined ? { setCookie: outcome.setCookie } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
return { action: "respond", response: outcome.response };
|
|
73
|
+
};
|
|
74
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
});
|