@smartcrab/hono 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/bearer.d.ts +26 -0
- package/dist/bearer.js +49 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +8 -0
- package/dist/middleware.d.ts +43 -0
- package/dist/middleware.js +41 -0
- package/dist/routes.d.ts +18 -0
- package/dist/routes.js +9 -0
- package/package.json +46 -0
- package/src/bearer.ts +88 -0
- package/src/index.test.ts +422 -0
- package/src/index.ts +26 -0
- package/src/middleware.ts +91 -0
- package/src/routes.ts +32 -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.
|
package/dist/bearer.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import type { AccessTokenVerifierOptions, VerifiedAccessToken } from "@smartcrab/server";
|
|
3
|
+
/**
|
|
4
|
+
* Resource-server middleware for Hono APIs (design.md §3.1: "その他の
|
|
5
|
+
* バックエンドは OIDC/JWKS で統合"). Verifies `Authorization: Bearer`
|
|
6
|
+
* access tokens against the issuer's JWKS via
|
|
7
|
+
* `createAccessTokenVerifier` (ES256 only, mandatory `kid`,
|
|
8
|
+
* iss/aud/exp/`typ: at+jwt` checked — design.md §15.6, §15.8).
|
|
9
|
+
*
|
|
10
|
+
* Failures answer with an RFC 6750 `WWW-Authenticate` challenge and a
|
|
11
|
+
* problem JSON body: 401 for invalid/absent tokens, 503 for transient
|
|
12
|
+
* upstream failures (discovery/JWKS unreachable).
|
|
13
|
+
*/
|
|
14
|
+
export interface BearerVariables {
|
|
15
|
+
readonly accessTokenClaims: VerifiedAccessToken;
|
|
16
|
+
readonly accessTokenSubject: string;
|
|
17
|
+
readonly accessTokenScope: string;
|
|
18
|
+
}
|
|
19
|
+
export interface BearerEnv {
|
|
20
|
+
readonly Variables: BearerVariables;
|
|
21
|
+
}
|
|
22
|
+
export interface BearerTokenMiddlewareOptions extends AccessTokenVerifierOptions {
|
|
23
|
+
/** RFC 6750 realm reported in challenges. Default `"api"`. */
|
|
24
|
+
readonly realm?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare const bearerTokenMiddleware: (options: BearerTokenMiddlewareOptions) => MiddlewareHandler<BearerEnv>;
|
package/dist/bearer.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Result, createAccessTokenVerifier, isRetryableError } from "@smartcrab/server";
|
|
2
|
+
const BEARER_PATTERN = /^Bearer ([A-Za-z0-9\-._~+/]+=*)$/;
|
|
3
|
+
const parseBearerToken = (header) => {
|
|
4
|
+
if (header === undefined)
|
|
5
|
+
return null;
|
|
6
|
+
const match = BEARER_PATTERN.exec(header);
|
|
7
|
+
return match?.[1] ?? null;
|
|
8
|
+
};
|
|
9
|
+
const challengeResponse = (status, realm, error, code) => {
|
|
10
|
+
const body = {
|
|
11
|
+
type: `https://docs.example-auth.com/errors/${code.replaceAll("_", "-")}`,
|
|
12
|
+
title: status === 401 ? "Unauthorized" : "Service Unavailable",
|
|
13
|
+
status,
|
|
14
|
+
code,
|
|
15
|
+
};
|
|
16
|
+
return new Response(JSON.stringify(body), {
|
|
17
|
+
status,
|
|
18
|
+
headers: {
|
|
19
|
+
"content-type": "application/problem+json",
|
|
20
|
+
"cache-control": "no-store",
|
|
21
|
+
"www-authenticate": `Bearer realm="${realm}", error="${error}", error_description="${code}"`,
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
export const bearerTokenMiddleware = (options) => {
|
|
26
|
+
const verifier = createAccessTokenVerifier({
|
|
27
|
+
issuer: options.issuer,
|
|
28
|
+
...(options.audience !== undefined ? { audience: options.audience } : {}),
|
|
29
|
+
...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
|
|
30
|
+
});
|
|
31
|
+
const realm = options.realm ?? "api";
|
|
32
|
+
return async (c, next) => {
|
|
33
|
+
const token = parseBearerToken(c.req.header("authorization"));
|
|
34
|
+
if (token === null) {
|
|
35
|
+
return challengeResponse(401, realm, "invalid_request", "missing_bearer_token");
|
|
36
|
+
}
|
|
37
|
+
const verified = await verifier(token);
|
|
38
|
+
if (Result.isFailure(verified)) {
|
|
39
|
+
if (isRetryableError(verified.error)) {
|
|
40
|
+
return challengeResponse(503, realm, "temporarily_unavailable", verified.error.type);
|
|
41
|
+
}
|
|
42
|
+
return challengeResponse(401, realm, "invalid_token", verified.error.type);
|
|
43
|
+
}
|
|
44
|
+
c.set("accessTokenClaims", verified.value);
|
|
45
|
+
c.set("accessTokenSubject", verified.value.sub);
|
|
46
|
+
c.set("accessTokenScope", verified.value.scope);
|
|
47
|
+
await next();
|
|
48
|
+
};
|
|
49
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/hono — Hono bindings for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1): session middleware, route mounting, and a JWKS
|
|
4
|
+
* resource-server middleware, all on top of @smartcrab/server.
|
|
5
|
+
*/
|
|
6
|
+
export { authMiddleware, requireSession } from "./middleware.js";
|
|
7
|
+
export type { AuthEnv, AuthVariables, OptionalAuthEnv, OptionalAuthVariables, RequireSessionMiddlewareOptions, } from "./middleware.js";
|
|
8
|
+
export { mountAuthRoutes } from "./routes.js";
|
|
9
|
+
export type { MountAuthRoutesOptions } from "./routes.js";
|
|
10
|
+
export { bearerTokenMiddleware } from "./bearer.js";
|
|
11
|
+
export type { BearerEnv, BearerTokenMiddlewareOptions, BearerVariables } from "./bearer.js";
|
|
12
|
+
export type { GetSessionOutcome, RequireSessionOutcome, ServerAuth, ServerAuthConfig, Session, SessionUser, VerifiedAccessToken, } from "@smartcrab/server";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/hono — Hono bindings for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1): session middleware, route mounting, and a JWKS
|
|
4
|
+
* resource-server middleware, all on top of @smartcrab/server.
|
|
5
|
+
*/
|
|
6
|
+
export { authMiddleware, requireSession } from "./middleware.js";
|
|
7
|
+
export { mountAuthRoutes } from "./routes.js";
|
|
8
|
+
export { bearerTokenMiddleware } from "./bearer.js";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import type { ServerAuth, Session, SessionUser } from "@smartcrab/server";
|
|
3
|
+
/**
|
|
4
|
+
* Hono session middleware (design.md §3.1: "Honoサーバー — Middleware、
|
|
5
|
+
* session/token検証") on top of @smartcrab/server's BFF core.
|
|
6
|
+
*
|
|
7
|
+
* - `requireSession` **blocks** unauthenticated requests: the documented
|
|
8
|
+
* response is the one produced by `ServerAuth.requireSession` — a 401
|
|
9
|
+
* problem JSON in `"json"` mode (default, API-safe), a 302 redirect to the
|
|
10
|
+
* login handler in `"redirect"` mode (browser pages), and a 503 problem
|
|
11
|
+
* JSON when a transient refresh failure occurs (design.md §21.7: the
|
|
12
|
+
* session is preserved, the client retries). When the session was
|
|
13
|
+
* refreshed or destroyed, the corresponding `Set-Cookie` is appended to the
|
|
14
|
+
* response.
|
|
15
|
+
* - `authMiddleware` is the optional variant: it populates the context when a
|
|
16
|
+
* valid session exists and never blocks (variables read as `undefined`).
|
|
17
|
+
*
|
|
18
|
+
* Both populate the context with `authSession`, `authUser` and `accessToken`.
|
|
19
|
+
*/
|
|
20
|
+
export interface AuthVariables {
|
|
21
|
+
readonly authSession: Session;
|
|
22
|
+
readonly authUser: SessionUser;
|
|
23
|
+
readonly accessToken: string;
|
|
24
|
+
}
|
|
25
|
+
export interface AuthEnv {
|
|
26
|
+
readonly Variables: AuthVariables;
|
|
27
|
+
}
|
|
28
|
+
export interface OptionalAuthVariables {
|
|
29
|
+
readonly authSession: Session | undefined;
|
|
30
|
+
readonly authUser: SessionUser | undefined;
|
|
31
|
+
readonly accessToken: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
export interface OptionalAuthEnv {
|
|
34
|
+
readonly Variables: OptionalAuthVariables;
|
|
35
|
+
}
|
|
36
|
+
export interface RequireSessionMiddlewareOptions {
|
|
37
|
+
/** `"json"` (default) answers 401/503 problem JSON; `"redirect"` 302s to the login handler. */
|
|
38
|
+
readonly onUnauthenticated?: "json" | "redirect";
|
|
39
|
+
}
|
|
40
|
+
/** Blocking middleware — unauthenticated requests get the documented response above. */
|
|
41
|
+
export declare const requireSession: (auth: ServerAuth, options?: RequireSessionMiddlewareOptions) => MiddlewareHandler<AuthEnv>;
|
|
42
|
+
/** Non-blocking middleware — populates the context when a valid session exists. */
|
|
43
|
+
export declare const authMiddleware: (auth: ServerAuth) => MiddlewareHandler<OptionalAuthEnv>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Blocking middleware — unauthenticated requests get the documented response above. */
|
|
2
|
+
export const requireSession = (auth, options) => {
|
|
3
|
+
return async (c, next) => {
|
|
4
|
+
const outcome = await auth.requireSession(c.req.raw, {
|
|
5
|
+
onUnauthenticated: options?.onUnauthenticated ?? "json",
|
|
6
|
+
});
|
|
7
|
+
if (!outcome.ok) {
|
|
8
|
+
return outcome.response;
|
|
9
|
+
}
|
|
10
|
+
c.set("authSession", outcome.session);
|
|
11
|
+
c.set("authUser", outcome.session.user);
|
|
12
|
+
c.set("accessToken", outcome.session.accessToken);
|
|
13
|
+
await next();
|
|
14
|
+
if (outcome.setCookie !== undefined) {
|
|
15
|
+
c.res.headers.append("set-cookie", outcome.setCookie);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/** Non-blocking middleware — populates the context when a valid session exists. */
|
|
20
|
+
export const authMiddleware = (auth) => {
|
|
21
|
+
return async (c, next) => {
|
|
22
|
+
const outcome = await auth.getSession(c.req.raw);
|
|
23
|
+
if (outcome.status === "authenticated") {
|
|
24
|
+
c.set("authSession", outcome.session);
|
|
25
|
+
c.set("authUser", outcome.session.user);
|
|
26
|
+
c.set("accessToken", outcome.session.accessToken);
|
|
27
|
+
await next();
|
|
28
|
+
if (outcome.setCookie !== undefined) {
|
|
29
|
+
c.res.headers.append("set-cookie", outcome.setCookie);
|
|
30
|
+
}
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
c.set("authSession", undefined);
|
|
34
|
+
c.set("authUser", undefined);
|
|
35
|
+
c.set("accessToken", undefined);
|
|
36
|
+
await next();
|
|
37
|
+
if (outcome.status === "unauthenticated" && outcome.clearCookie !== undefined) {
|
|
38
|
+
c.res.headers.append("set-cookie", outcome.clearCookie);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
};
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Env, Hono } from "hono";
|
|
2
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
3
|
+
/**
|
|
4
|
+
* Wires the BFF login/callback/logout handlers from @smartcrab/server
|
|
5
|
+
* into a Hono app (design.md §3.1, §22.2). Paths are configurable via
|
|
6
|
+
* `basePath`; keep it aligned with the `basePath` given to
|
|
7
|
+
* `createServerAuth`, which uses it when building login redirects.
|
|
8
|
+
*
|
|
9
|
+
* Mounted routes (GET+POST where the BFF flow needs both):
|
|
10
|
+
* - `${basePath}/login`
|
|
11
|
+
* - `${basePath}/callback` (GET only — the authorization response is a redirect)
|
|
12
|
+
* - `${basePath}/logout`
|
|
13
|
+
*/
|
|
14
|
+
export interface MountAuthRoutesOptions {
|
|
15
|
+
/** Default `"/auth"`. Absolute path without a trailing slash. */
|
|
16
|
+
readonly basePath?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare const mountAuthRoutes: <E extends Env>(app: Hono<E>, auth: ServerAuth, options?: MountAuthRoutesOptions) => Hono<E>;
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const mountAuthRoutes = (app, auth, options) => {
|
|
2
|
+
const basePath = options?.basePath ?? auth.basePath;
|
|
3
|
+
app.get(`${basePath}/login`, (c) => auth.loginHandler(c.req.raw));
|
|
4
|
+
app.post(`${basePath}/login`, (c) => auth.loginHandler(c.req.raw));
|
|
5
|
+
app.get(`${basePath}/callback`, (c) => auth.callbackHandler(c.req.raw));
|
|
6
|
+
app.get(`${basePath}/logout`, (c) => auth.logoutHandler(c.req.raw));
|
|
7
|
+
app.post(`${basePath}/logout`, (c) => auth.logoutHandler(c.req.raw));
|
|
8
|
+
return app;
|
|
9
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@smartcrab/hono",
|
|
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
|
+
"peerDependencies": {
|
|
33
|
+
"hono": ">=4"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"typescript": "5.9.3",
|
|
37
|
+
"vitest": "4.1.11",
|
|
38
|
+
"@cloudflare/workers-types": "5.20260804.1",
|
|
39
|
+
"hono": "4.13.8"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"test": "vitest run --passWithNoTests",
|
|
44
|
+
"build": "tsc -p tsconfig.build.json"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/bearer.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import { Result, createAccessTokenVerifier, isRetryableError } from "@smartcrab/server";
|
|
3
|
+
import type { AccessTokenVerifierOptions, VerifiedAccessToken } from "@smartcrab/server";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resource-server middleware for Hono APIs (design.md §3.1: "その他の
|
|
7
|
+
* バックエンドは OIDC/JWKS で統合"). Verifies `Authorization: Bearer`
|
|
8
|
+
* access tokens against the issuer's JWKS via
|
|
9
|
+
* `createAccessTokenVerifier` (ES256 only, mandatory `kid`,
|
|
10
|
+
* iss/aud/exp/`typ: at+jwt` checked — design.md §15.6, §15.8).
|
|
11
|
+
*
|
|
12
|
+
* Failures answer with an RFC 6750 `WWW-Authenticate` challenge and a
|
|
13
|
+
* problem JSON body: 401 for invalid/absent tokens, 503 for transient
|
|
14
|
+
* upstream failures (discovery/JWKS unreachable).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface BearerVariables {
|
|
18
|
+
readonly accessTokenClaims: VerifiedAccessToken;
|
|
19
|
+
readonly accessTokenSubject: string;
|
|
20
|
+
readonly accessTokenScope: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface BearerEnv {
|
|
24
|
+
readonly Variables: BearerVariables;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface BearerTokenMiddlewareOptions extends AccessTokenVerifierOptions {
|
|
28
|
+
/** RFC 6750 realm reported in challenges. Default `"api"`. */
|
|
29
|
+
readonly realm?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const BEARER_PATTERN = /^Bearer ([A-Za-z0-9\-._~+/]+=*)$/;
|
|
33
|
+
|
|
34
|
+
const parseBearerToken = (header: string | undefined): string | null => {
|
|
35
|
+
if (header === undefined) return null;
|
|
36
|
+
const match = BEARER_PATTERN.exec(header);
|
|
37
|
+
return match?.[1] ?? null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const challengeResponse = (
|
|
41
|
+
status: number,
|
|
42
|
+
realm: string,
|
|
43
|
+
error: string,
|
|
44
|
+
code: string,
|
|
45
|
+
): Response => {
|
|
46
|
+
const body = {
|
|
47
|
+
type: `https://docs.example-auth.com/errors/${code.replaceAll("_", "-")}`,
|
|
48
|
+
title: status === 401 ? "Unauthorized" : "Service Unavailable",
|
|
49
|
+
status,
|
|
50
|
+
code,
|
|
51
|
+
};
|
|
52
|
+
return new Response(JSON.stringify(body), {
|
|
53
|
+
status,
|
|
54
|
+
headers: {
|
|
55
|
+
"content-type": "application/problem+json",
|
|
56
|
+
"cache-control": "no-store",
|
|
57
|
+
"www-authenticate": `Bearer realm="${realm}", error="${error}", error_description="${code}"`,
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const bearerTokenMiddleware = (
|
|
63
|
+
options: BearerTokenMiddlewareOptions,
|
|
64
|
+
): MiddlewareHandler<BearerEnv> => {
|
|
65
|
+
const verifier = createAccessTokenVerifier({
|
|
66
|
+
issuer: options.issuer,
|
|
67
|
+
...(options.audience !== undefined ? { audience: options.audience } : {}),
|
|
68
|
+
...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
|
|
69
|
+
});
|
|
70
|
+
const realm = options.realm ?? "api";
|
|
71
|
+
return async (c, next) => {
|
|
72
|
+
const token = parseBearerToken(c.req.header("authorization"));
|
|
73
|
+
if (token === null) {
|
|
74
|
+
return challengeResponse(401, realm, "invalid_request", "missing_bearer_token");
|
|
75
|
+
}
|
|
76
|
+
const verified = await verifier(token);
|
|
77
|
+
if (Result.isFailure(verified)) {
|
|
78
|
+
if (isRetryableError(verified.error)) {
|
|
79
|
+
return challengeResponse(503, realm, "temporarily_unavailable", verified.error.type);
|
|
80
|
+
}
|
|
81
|
+
return challengeResponse(401, realm, "invalid_token", verified.error.type);
|
|
82
|
+
}
|
|
83
|
+
c.set("accessTokenClaims", verified.value);
|
|
84
|
+
c.set("accessTokenSubject", verified.value.sub);
|
|
85
|
+
c.set("accessTokenScope", verified.value.scope);
|
|
86
|
+
await next();
|
|
87
|
+
};
|
|
88
|
+
};
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { createServerAuth } from "@smartcrab/server";
|
|
2
|
+
import type { FetchLike, ServerAuth } from "@smartcrab/server";
|
|
3
|
+
import { Hono } from "hono";
|
|
4
|
+
import { describe, expect, test } from "vitest";
|
|
5
|
+
import { bearerTokenMiddleware } from "./bearer.js";
|
|
6
|
+
import type { BearerEnv } from "./bearer.js";
|
|
7
|
+
import { authMiddleware, requireSession } from "./middleware.js";
|
|
8
|
+
import type { AuthEnv, OptionalAuthEnv } from "./middleware.js";
|
|
9
|
+
import { mountAuthRoutes } from "./routes.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Exercises the Hono bindings against a real Hono app instance, with the
|
|
13
|
+
* Authorization Server stubbed behind an injected fetch (discovery, JWKS,
|
|
14
|
+
* token, revocation). ID/access tokens are real ES256 JWS compact
|
|
15
|
+
* serializations signed through WebCrypto (this package deliberately has no
|
|
16
|
+
* `jose`/`cookie` dependency — only @smartcrab/server + hono).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const ISSUER = "https://id.example.com/e/env_test";
|
|
20
|
+
const CLIENT_ID = "cli_testclient";
|
|
21
|
+
const CLIENT_SECRET = "test_client_secret";
|
|
22
|
+
const COOKIE_SECRET = "0123456789abcdef0123456789abcdef";
|
|
23
|
+
const REDIRECT_URI = "https://app.example.com/auth/callback";
|
|
24
|
+
const APP_ORIGIN = "https://app.example.com";
|
|
25
|
+
const KID = "test-signing-key-1";
|
|
26
|
+
const USER_SUB = "usr_testuser";
|
|
27
|
+
const API_AUDIENCE = "https://api.example.com";
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Minimal WebCrypto-only test helpers (no extra dependencies)
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
34
|
+
|
|
35
|
+
const base64UrlEncode = (bytes: Uint8Array): string => {
|
|
36
|
+
let out = "";
|
|
37
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
38
|
+
const b0 = bytes[i] ?? 0;
|
|
39
|
+
const b1 = bytes[i + 1];
|
|
40
|
+
const b2 = bytes[i + 2];
|
|
41
|
+
out += BASE64URL_ALPHABET[b0 >> 2] ?? "";
|
|
42
|
+
out += BASE64URL_ALPHABET[((b0 & 0x03) << 4) | ((b1 ?? 0) >> 4)] ?? "";
|
|
43
|
+
if (b1 !== undefined) out += BASE64URL_ALPHABET[((b1 & 0x0f) << 2) | ((b2 ?? 0) >> 6)] ?? "";
|
|
44
|
+
if (b2 !== undefined) out += BASE64URL_ALPHABET[b2 & 0x3f] ?? "";
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const textEncoder = new TextEncoder();
|
|
50
|
+
|
|
51
|
+
const signJwt = async (
|
|
52
|
+
header: Record<string, unknown>,
|
|
53
|
+
payload: Record<string, unknown>,
|
|
54
|
+
key: CryptoKey,
|
|
55
|
+
): Promise<string> => {
|
|
56
|
+
const data = `${base64UrlEncode(textEncoder.encode(JSON.stringify(header)))}.${base64UrlEncode(textEncoder.encode(JSON.stringify(payload)))}`;
|
|
57
|
+
const signature = await crypto.subtle.sign(
|
|
58
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
59
|
+
key,
|
|
60
|
+
textEncoder.encode(data),
|
|
61
|
+
);
|
|
62
|
+
return `${data}.${base64UrlEncode(new Uint8Array(signature))}`;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Extracts the `name=value` fragment from a Set-Cookie header. */
|
|
66
|
+
const cookieFragment = (setCookieHeader: string): string => setCookieHeader.split(";")[0] ?? "";
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// Signing key + stubbed Authorization Server
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
const generatedKeyPair = await crypto.subtle.generateKey(
|
|
73
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
74
|
+
true,
|
|
75
|
+
["sign", "verify"],
|
|
76
|
+
);
|
|
77
|
+
if (!("publicKey" in generatedKeyPair) || !("privateKey" in generatedKeyPair)) {
|
|
78
|
+
throw new Error("expected an ECDSA key pair");
|
|
79
|
+
}
|
|
80
|
+
const signingKeyPair: CryptoKeyPair = generatedKeyPair;
|
|
81
|
+
const exportedPublicJwk = await crypto.subtle.exportKey("jwk", signingKeyPair.publicKey);
|
|
82
|
+
if (exportedPublicJwk instanceof ArrayBuffer) {
|
|
83
|
+
throw new Error("expected a JWK export");
|
|
84
|
+
}
|
|
85
|
+
// Keep exactly the fields of the platform JWKS contract (strict schema).
|
|
86
|
+
const publicJwk = {
|
|
87
|
+
kty: exportedPublicJwk.kty,
|
|
88
|
+
crv: exportedPublicJwk.crv,
|
|
89
|
+
x: exportedPublicJwk.x,
|
|
90
|
+
y: exportedPublicJwk.y,
|
|
91
|
+
kid: KID,
|
|
92
|
+
alg: "ES256",
|
|
93
|
+
use: "sig",
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const nowSeconds = (): number => Math.floor(Date.now() / 1000);
|
|
97
|
+
|
|
98
|
+
const signIdToken = async (nonce: string): Promise<string> =>
|
|
99
|
+
signJwt(
|
|
100
|
+
{ alg: "ES256", typ: "JWT", kid: KID },
|
|
101
|
+
{
|
|
102
|
+
iss: ISSUER,
|
|
103
|
+
sub: USER_SUB,
|
|
104
|
+
aud: CLIENT_ID,
|
|
105
|
+
iat: nowSeconds(),
|
|
106
|
+
exp: nowSeconds() + 300,
|
|
107
|
+
nonce,
|
|
108
|
+
name: "Test User",
|
|
109
|
+
email: "test@example.com",
|
|
110
|
+
},
|
|
111
|
+
signingKeyPair.privateKey,
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
const signAccessToken = async (audience: string = API_AUDIENCE): Promise<string> =>
|
|
115
|
+
signJwt(
|
|
116
|
+
{ alg: "ES256", typ: "at+jwt", kid: KID },
|
|
117
|
+
{
|
|
118
|
+
iss: ISSUER,
|
|
119
|
+
sub: USER_SUB,
|
|
120
|
+
aud: audience,
|
|
121
|
+
iat: nowSeconds(),
|
|
122
|
+
exp: nowSeconds() + 300,
|
|
123
|
+
client_id: CLIENT_ID,
|
|
124
|
+
scope: "openid profile",
|
|
125
|
+
},
|
|
126
|
+
signingKeyPair.privateKey,
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
interface StubState {
|
|
130
|
+
currentNonce: string | null;
|
|
131
|
+
readonly tokenCalls: URLSearchParams[];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const jsonResponse = (body: unknown, status = 200): Response =>
|
|
135
|
+
new Response(JSON.stringify(body), {
|
|
136
|
+
status,
|
|
137
|
+
headers: { "content-type": "application/json" },
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const createStubFetch = (state: StubState): FetchLike => {
|
|
141
|
+
return async (input, init) => {
|
|
142
|
+
const url =
|
|
143
|
+
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
144
|
+
if (url === `${ISSUER}/.well-known/openid-configuration`) {
|
|
145
|
+
return jsonResponse({
|
|
146
|
+
issuer: ISSUER,
|
|
147
|
+
authorization_endpoint: `${ISSUER}/oauth2/authorize`,
|
|
148
|
+
token_endpoint: `${ISSUER}/oauth2/token`,
|
|
149
|
+
userinfo_endpoint: `${ISSUER}/oauth2/userinfo`,
|
|
150
|
+
jwks_uri: `${ISSUER}/oauth2/jwks`,
|
|
151
|
+
revocation_endpoint: `${ISSUER}/oauth2/revoke`,
|
|
152
|
+
introspection_endpoint: `${ISSUER}/oauth2/introspect`,
|
|
153
|
+
end_session_endpoint: `${ISSUER}/oauth2/logout`,
|
|
154
|
+
response_types_supported: ["code"],
|
|
155
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
156
|
+
code_challenge_methods_supported: ["S256"],
|
|
157
|
+
token_endpoint_auth_methods_supported: ["client_secret_basic"],
|
|
158
|
+
scopes_supported: ["openid", "profile", "email", "offline_access"],
|
|
159
|
+
subject_types_supported: ["public"],
|
|
160
|
+
id_token_signing_alg_values_supported: ["ES256"],
|
|
161
|
+
claims_supported: ["sub", "nonce", "name", "email"],
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (url === `${ISSUER}/oauth2/jwks`) {
|
|
165
|
+
return jsonResponse({ keys: [publicJwk] });
|
|
166
|
+
}
|
|
167
|
+
if (url === `${ISSUER}/oauth2/token`) {
|
|
168
|
+
const body = typeof init?.body === "string" ? init.body : "";
|
|
169
|
+
const params = new URLSearchParams(body);
|
|
170
|
+
state.tokenCalls.push(params);
|
|
171
|
+
if (params.get("grant_type") === "authorization_code") {
|
|
172
|
+
return jsonResponse({
|
|
173
|
+
access_token: "atk_initial",
|
|
174
|
+
token_type: "Bearer",
|
|
175
|
+
expires_in: 300,
|
|
176
|
+
refresh_token: "rt_1",
|
|
177
|
+
id_token: await signIdToken(state.currentNonce ?? ""),
|
|
178
|
+
scope: "openid profile email offline_access",
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return jsonResponse({
|
|
182
|
+
access_token: "atk_refreshed",
|
|
183
|
+
token_type: "Bearer",
|
|
184
|
+
expires_in: 300,
|
|
185
|
+
refresh_token: "rt_2",
|
|
186
|
+
scope: "openid profile email offline_access",
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
if (url === `${ISSUER}/oauth2/revoke`) {
|
|
190
|
+
return new Response(null, { status: 200 });
|
|
191
|
+
}
|
|
192
|
+
return new Response("not found", { status: 404 });
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const createAuth = (
|
|
197
|
+
state: StubState,
|
|
198
|
+
overrides: { readonly refreshLeewaySeconds?: number } = {},
|
|
199
|
+
): ServerAuth =>
|
|
200
|
+
createServerAuth({
|
|
201
|
+
issuer: ISSUER,
|
|
202
|
+
clientId: CLIENT_ID,
|
|
203
|
+
clientSecret: CLIENT_SECRET,
|
|
204
|
+
redirectUri: REDIRECT_URI,
|
|
205
|
+
cookieSecret: COOKIE_SECRET,
|
|
206
|
+
fetch: createStubFetch(state),
|
|
207
|
+
...(overrides.refreshLeewaySeconds !== undefined
|
|
208
|
+
? { refreshLeewaySeconds: overrides.refreshLeewaySeconds }
|
|
209
|
+
: {}),
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
/** Drives the full login flow through the mounted Hono routes. */
|
|
213
|
+
const completeLogin = async (app: Hono<AuthEnv>, state: StubState): Promise<string> => {
|
|
214
|
+
const loginResponse = await app.request(`${APP_ORIGIN}/auth/login`);
|
|
215
|
+
expect(loginResponse.status).toBe(302);
|
|
216
|
+
const location = new URL(loginResponse.headers.get("location") ?? "");
|
|
217
|
+
expect(location.origin + location.pathname).toBe(`${ISSUER}/oauth2/authorize`);
|
|
218
|
+
const pkceSetCookie = loginResponse.headers.getSetCookie()[0] ?? "";
|
|
219
|
+
state.currentNonce = location.searchParams.get("nonce");
|
|
220
|
+
const callbackResponse = await app.request(
|
|
221
|
+
`${APP_ORIGIN}/auth/callback?code=ac_${"a".repeat(32)}&state=${location.searchParams.get("state") ?? ""}`,
|
|
222
|
+
{ headers: { cookie: cookieFragment(pkceSetCookie) } },
|
|
223
|
+
);
|
|
224
|
+
expect(callbackResponse.status).toBe(302);
|
|
225
|
+
const sessionSet = callbackResponse.headers
|
|
226
|
+
.getSetCookie()
|
|
227
|
+
.find((value) => value.startsWith("__Host-auth-session="));
|
|
228
|
+
expect(sessionSet).toBeDefined();
|
|
229
|
+
return cookieFragment(sessionSet ?? "");
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
describe("mountAuthRoutes", () => {
|
|
233
|
+
test("mounts login/callback/logout at the configured base path", async () => {
|
|
234
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
235
|
+
const auth = createAuth(state);
|
|
236
|
+
const app = new Hono<AuthEnv>();
|
|
237
|
+
mountAuthRoutes(app, auth, { basePath: "/auth" });
|
|
238
|
+
|
|
239
|
+
const loginResponse = await app.request(`${APP_ORIGIN}/auth/login`);
|
|
240
|
+
expect(loginResponse.status).toBe(302);
|
|
241
|
+
|
|
242
|
+
const logoutResponse = await app.request(`${APP_ORIGIN}/auth/logout`);
|
|
243
|
+
expect(logoutResponse.status).toBe(302);
|
|
244
|
+
|
|
245
|
+
// Unmounted paths fall through to Hono's 404.
|
|
246
|
+
const missing = await app.request(`${APP_ORIGIN}/other/login`);
|
|
247
|
+
expect(missing.status).toBe(404);
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("requireSession middleware", () => {
|
|
252
|
+
const buildApp = (auth: ServerAuth): Hono<AuthEnv> => {
|
|
253
|
+
const app = new Hono<AuthEnv>();
|
|
254
|
+
mountAuthRoutes(app, auth);
|
|
255
|
+
app.get("/api/me", requireSession(auth), (c) =>
|
|
256
|
+
c.json({ sub: c.get("authUser").sub, accessToken: c.get("accessToken") }),
|
|
257
|
+
);
|
|
258
|
+
return app;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
test("populates the context for an authenticated request", async () => {
|
|
262
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
263
|
+
const auth = createAuth(state);
|
|
264
|
+
const app = buildApp(auth);
|
|
265
|
+
const cookie = await completeLogin(app, state);
|
|
266
|
+
|
|
267
|
+
const response = await app.request(`${APP_ORIGIN}/api/me`, { headers: { cookie } });
|
|
268
|
+
expect(response.status).toBe(200);
|
|
269
|
+
const body: unknown = await response.json();
|
|
270
|
+
expect(body).toEqual({ sub: USER_SUB, accessToken: "atk_initial" });
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
test("unauthenticated requests get the documented 401 problem response", async () => {
|
|
274
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
275
|
+
const auth = createAuth(state);
|
|
276
|
+
const app = buildApp(auth);
|
|
277
|
+
|
|
278
|
+
const response = await app.request(`${APP_ORIGIN}/api/me`);
|
|
279
|
+
expect(response.status).toBe(401);
|
|
280
|
+
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
|
281
|
+
const body: unknown = await response.json();
|
|
282
|
+
expect(body).toMatchObject({ code: "no_session", status: 401 });
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
test("redirect mode sends browsers to the login handler", async () => {
|
|
286
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
287
|
+
const auth = createAuth(state);
|
|
288
|
+
const app = new Hono<AuthEnv>();
|
|
289
|
+
mountAuthRoutes(app, auth);
|
|
290
|
+
app.get("/dashboard", requireSession(auth, { onUnauthenticated: "redirect" }), (c) =>
|
|
291
|
+
c.text("secret"),
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
const response = await app.request(`${APP_ORIGIN}/dashboard`);
|
|
295
|
+
expect(response.status).toBe(302);
|
|
296
|
+
expect(response.headers.get("location")).toBe("/auth/login?return_to=%2Fdashboard");
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
test("appends the rotated session cookie after a transparent refresh", async () => {
|
|
300
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
301
|
+
const auth = createAuth(state, { refreshLeewaySeconds: 10_000 });
|
|
302
|
+
const app = buildApp(auth);
|
|
303
|
+
const cookie = await completeLogin(app, state);
|
|
304
|
+
|
|
305
|
+
const response = await app.request(`${APP_ORIGIN}/api/me`, { headers: { cookie } });
|
|
306
|
+
expect(response.status).toBe(200);
|
|
307
|
+
const body: unknown = await response.json();
|
|
308
|
+
expect(body).toEqual({ sub: USER_SUB, accessToken: "atk_refreshed" });
|
|
309
|
+
const setCookies = response.headers.getSetCookie();
|
|
310
|
+
const rotated = setCookies.find((value) => value.startsWith("__Host-auth-session="));
|
|
311
|
+
expect(rotated).toBeDefined();
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
describe("authMiddleware (optional session)", () => {
|
|
316
|
+
const buildOptionalApp = (auth: ServerAuth): Hono<OptionalAuthEnv> => {
|
|
317
|
+
const app = new Hono<OptionalAuthEnv>();
|
|
318
|
+
mountAuthRoutes(app, auth);
|
|
319
|
+
app.get("/public", authMiddleware(auth), (c) =>
|
|
320
|
+
c.json({ sub: c.get("authUser")?.sub ?? null }),
|
|
321
|
+
);
|
|
322
|
+
return app;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
test("passes unauthenticated requests with an empty context", async () => {
|
|
326
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
327
|
+
const auth = createAuth(state);
|
|
328
|
+
const app = buildOptionalApp(auth);
|
|
329
|
+
|
|
330
|
+
const response = await app.request(`${APP_ORIGIN}/public`);
|
|
331
|
+
expect(response.status).toBe(200);
|
|
332
|
+
const body: unknown = await response.json();
|
|
333
|
+
expect(body).toEqual({ sub: null });
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
test("populates the context when a session exists", async () => {
|
|
337
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
338
|
+
const auth = createAuth(state);
|
|
339
|
+
const app = buildOptionalApp(auth);
|
|
340
|
+
|
|
341
|
+
const loginResponse = await app.request(`${APP_ORIGIN}/auth/login`);
|
|
342
|
+
const location = new URL(loginResponse.headers.get("location") ?? "");
|
|
343
|
+
const pkceSetCookie = loginResponse.headers.getSetCookie()[0] ?? "";
|
|
344
|
+
state.currentNonce = location.searchParams.get("nonce");
|
|
345
|
+
const callbackResponse = await app.request(
|
|
346
|
+
`${APP_ORIGIN}/auth/callback?code=ac_${"a".repeat(32)}&state=${location.searchParams.get("state") ?? ""}`,
|
|
347
|
+
{ headers: { cookie: cookieFragment(pkceSetCookie) } },
|
|
348
|
+
);
|
|
349
|
+
const sessionSet = callbackResponse.headers
|
|
350
|
+
.getSetCookie()
|
|
351
|
+
.find((value) => value.startsWith("__Host-auth-session="));
|
|
352
|
+
const cookie = cookieFragment(sessionSet ?? "");
|
|
353
|
+
|
|
354
|
+
const response = await app.request(`${APP_ORIGIN}/public`, { headers: { cookie } });
|
|
355
|
+
expect(response.status).toBe(200);
|
|
356
|
+
const body: unknown = await response.json();
|
|
357
|
+
expect(body).toEqual({ sub: USER_SUB });
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
describe("bearerTokenMiddleware", () => {
|
|
362
|
+
const buildResourceApp = (state: StubState): Hono<BearerEnv> => {
|
|
363
|
+
const app = new Hono<BearerEnv>();
|
|
364
|
+
app.get(
|
|
365
|
+
"/resource",
|
|
366
|
+
bearerTokenMiddleware({
|
|
367
|
+
issuer: ISSUER,
|
|
368
|
+
audience: API_AUDIENCE,
|
|
369
|
+
fetch: createStubFetch(state),
|
|
370
|
+
}),
|
|
371
|
+
(c) => c.json({ sub: c.get("accessTokenSubject"), scope: c.get("accessTokenScope") }),
|
|
372
|
+
);
|
|
373
|
+
return app;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
test("accepts a valid at+jwt access token and exposes its claims", async () => {
|
|
377
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
378
|
+
const app = buildResourceApp(state);
|
|
379
|
+
const token = await signAccessToken();
|
|
380
|
+
|
|
381
|
+
const response = await app.request(`${APP_ORIGIN}/resource`, {
|
|
382
|
+
headers: { authorization: `Bearer ${token}` },
|
|
383
|
+
});
|
|
384
|
+
expect(response.status).toBe(200);
|
|
385
|
+
const body: unknown = await response.json();
|
|
386
|
+
expect(body).toEqual({ sub: USER_SUB, scope: "openid profile" });
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
test("rejects a missing Authorization header with an RFC 6750 challenge", async () => {
|
|
390
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
391
|
+
const app = buildResourceApp(state);
|
|
392
|
+
|
|
393
|
+
const response = await app.request(`${APP_ORIGIN}/resource`);
|
|
394
|
+
expect(response.status).toBe(401);
|
|
395
|
+
expect(response.headers.get("www-authenticate")).toContain('Bearer realm="api"');
|
|
396
|
+
const body: unknown = await response.json();
|
|
397
|
+
expect(body).toMatchObject({ code: "missing_bearer_token" });
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
test("rejects a malformed bearer token", async () => {
|
|
401
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
402
|
+
const app = buildResourceApp(state);
|
|
403
|
+
|
|
404
|
+
const response = await app.request(`${APP_ORIGIN}/resource`, {
|
|
405
|
+
headers: { authorization: "Bearer not-a-jwt" },
|
|
406
|
+
});
|
|
407
|
+
expect(response.status).toBe(401);
|
|
408
|
+
const body: unknown = await response.json();
|
|
409
|
+
expect(body).toMatchObject({ code: "access_token_invalid" });
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
test("rejects a token for another audience", async () => {
|
|
413
|
+
const state: StubState = { currentNonce: null, tokenCalls: [] };
|
|
414
|
+
const app = buildResourceApp(state);
|
|
415
|
+
const token = await signAccessToken("https://other-api.example.com");
|
|
416
|
+
|
|
417
|
+
const response = await app.request(`${APP_ORIGIN}/resource`, {
|
|
418
|
+
headers: { authorization: `Bearer ${token}` },
|
|
419
|
+
});
|
|
420
|
+
expect(response.status).toBe(401);
|
|
421
|
+
});
|
|
422
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @smartcrab/hono — Hono bindings for the Web BFF auth SDK
|
|
3
|
+
* (design.md §3.1): session middleware, route mounting, and a JWKS
|
|
4
|
+
* resource-server middleware, all on top of @smartcrab/server.
|
|
5
|
+
*/
|
|
6
|
+
export { authMiddleware, requireSession } from "./middleware.js";
|
|
7
|
+
export type {
|
|
8
|
+
AuthEnv,
|
|
9
|
+
AuthVariables,
|
|
10
|
+
OptionalAuthEnv,
|
|
11
|
+
OptionalAuthVariables,
|
|
12
|
+
RequireSessionMiddlewareOptions,
|
|
13
|
+
} from "./middleware.js";
|
|
14
|
+
export { mountAuthRoutes } from "./routes.js";
|
|
15
|
+
export type { MountAuthRoutesOptions } from "./routes.js";
|
|
16
|
+
export { bearerTokenMiddleware } from "./bearer.js";
|
|
17
|
+
export type { BearerEnv, BearerTokenMiddlewareOptions, BearerVariables } from "./bearer.js";
|
|
18
|
+
export type {
|
|
19
|
+
GetSessionOutcome,
|
|
20
|
+
RequireSessionOutcome,
|
|
21
|
+
ServerAuth,
|
|
22
|
+
ServerAuthConfig,
|
|
23
|
+
Session,
|
|
24
|
+
SessionUser,
|
|
25
|
+
VerifiedAccessToken,
|
|
26
|
+
} from "@smartcrab/server";
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import type { ServerAuth, Session, SessionUser } from "@smartcrab/server";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Hono session middleware (design.md §3.1: "Honoサーバー — Middleware、
|
|
6
|
+
* session/token検証") on top of @smartcrab/server's BFF core.
|
|
7
|
+
*
|
|
8
|
+
* - `requireSession` **blocks** unauthenticated requests: the documented
|
|
9
|
+
* response is the one produced by `ServerAuth.requireSession` — a 401
|
|
10
|
+
* problem JSON in `"json"` mode (default, API-safe), a 302 redirect to the
|
|
11
|
+
* login handler in `"redirect"` mode (browser pages), and a 503 problem
|
|
12
|
+
* JSON when a transient refresh failure occurs (design.md §21.7: the
|
|
13
|
+
* session is preserved, the client retries). When the session was
|
|
14
|
+
* refreshed or destroyed, the corresponding `Set-Cookie` is appended to the
|
|
15
|
+
* response.
|
|
16
|
+
* - `authMiddleware` is the optional variant: it populates the context when a
|
|
17
|
+
* valid session exists and never blocks (variables read as `undefined`).
|
|
18
|
+
*
|
|
19
|
+
* Both populate the context with `authSession`, `authUser` and `accessToken`.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface AuthVariables {
|
|
23
|
+
readonly authSession: Session;
|
|
24
|
+
readonly authUser: SessionUser;
|
|
25
|
+
readonly accessToken: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface AuthEnv {
|
|
29
|
+
readonly Variables: AuthVariables;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface OptionalAuthVariables {
|
|
33
|
+
readonly authSession: Session | undefined;
|
|
34
|
+
readonly authUser: SessionUser | undefined;
|
|
35
|
+
readonly accessToken: string | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface OptionalAuthEnv {
|
|
39
|
+
readonly Variables: OptionalAuthVariables;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface RequireSessionMiddlewareOptions {
|
|
43
|
+
/** `"json"` (default) answers 401/503 problem JSON; `"redirect"` 302s to the login handler. */
|
|
44
|
+
readonly onUnauthenticated?: "json" | "redirect";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Blocking middleware — unauthenticated requests get the documented response above. */
|
|
48
|
+
export const requireSession = (
|
|
49
|
+
auth: ServerAuth,
|
|
50
|
+
options?: RequireSessionMiddlewareOptions,
|
|
51
|
+
): MiddlewareHandler<AuthEnv> => {
|
|
52
|
+
return async (c, next) => {
|
|
53
|
+
const outcome = await auth.requireSession(c.req.raw, {
|
|
54
|
+
onUnauthenticated: options?.onUnauthenticated ?? "json",
|
|
55
|
+
});
|
|
56
|
+
if (!outcome.ok) {
|
|
57
|
+
return outcome.response;
|
|
58
|
+
}
|
|
59
|
+
c.set("authSession", outcome.session);
|
|
60
|
+
c.set("authUser", outcome.session.user);
|
|
61
|
+
c.set("accessToken", outcome.session.accessToken);
|
|
62
|
+
await next();
|
|
63
|
+
if (outcome.setCookie !== undefined) {
|
|
64
|
+
c.res.headers.append("set-cookie", outcome.setCookie);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Non-blocking middleware — populates the context when a valid session exists. */
|
|
70
|
+
export const authMiddleware = (auth: ServerAuth): MiddlewareHandler<OptionalAuthEnv> => {
|
|
71
|
+
return async (c, next) => {
|
|
72
|
+
const outcome = await auth.getSession(c.req.raw);
|
|
73
|
+
if (outcome.status === "authenticated") {
|
|
74
|
+
c.set("authSession", outcome.session);
|
|
75
|
+
c.set("authUser", outcome.session.user);
|
|
76
|
+
c.set("accessToken", outcome.session.accessToken);
|
|
77
|
+
await next();
|
|
78
|
+
if (outcome.setCookie !== undefined) {
|
|
79
|
+
c.res.headers.append("set-cookie", outcome.setCookie);
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
c.set("authSession", undefined);
|
|
84
|
+
c.set("authUser", undefined);
|
|
85
|
+
c.set("accessToken", undefined);
|
|
86
|
+
await next();
|
|
87
|
+
if (outcome.status === "unauthenticated" && outcome.clearCookie !== undefined) {
|
|
88
|
+
c.res.headers.append("set-cookie", outcome.clearCookie);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
};
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Env, Hono } from "hono";
|
|
2
|
+
import type { ServerAuth } from "@smartcrab/server";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Wires the BFF login/callback/logout handlers from @smartcrab/server
|
|
6
|
+
* into a Hono app (design.md §3.1, §22.2). Paths are configurable via
|
|
7
|
+
* `basePath`; keep it aligned with the `basePath` given to
|
|
8
|
+
* `createServerAuth`, which uses it when building login redirects.
|
|
9
|
+
*
|
|
10
|
+
* Mounted routes (GET+POST where the BFF flow needs both):
|
|
11
|
+
* - `${basePath}/login`
|
|
12
|
+
* - `${basePath}/callback` (GET only — the authorization response is a redirect)
|
|
13
|
+
* - `${basePath}/logout`
|
|
14
|
+
*/
|
|
15
|
+
export interface MountAuthRoutesOptions {
|
|
16
|
+
/** Default `"/auth"`. Absolute path without a trailing slash. */
|
|
17
|
+
readonly basePath?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const mountAuthRoutes = <E extends Env>(
|
|
21
|
+
app: Hono<E>,
|
|
22
|
+
auth: ServerAuth,
|
|
23
|
+
options?: MountAuthRoutesOptions,
|
|
24
|
+
): Hono<E> => {
|
|
25
|
+
const basePath = options?.basePath ?? auth.basePath;
|
|
26
|
+
app.get(`${basePath}/login`, (c) => auth.loginHandler(c.req.raw));
|
|
27
|
+
app.post(`${basePath}/login`, (c) => auth.loginHandler(c.req.raw));
|
|
28
|
+
app.get(`${basePath}/callback`, (c) => auth.callbackHandler(c.req.raw));
|
|
29
|
+
app.get(`${basePath}/logout`, (c) => auth.logoutHandler(c.req.raw));
|
|
30
|
+
app.post(`${basePath}/logout`, (c) => auth.logoutHandler(c.req.raw));
|
|
31
|
+
return app;
|
|
32
|
+
};
|