@kohaku-ui/authz-jwt 0.0.0-bootstrap.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/LICENSE +201 -0
- package/README.md +64 -1
- package/dist/authz-port.d.ts +33 -0
- package/dist/authz-port.d.ts.map +1 -0
- package/dist/authz-port.js +23 -0
- package/dist/authz-port.js.map +1 -0
- package/dist/bearer.d.ts +3 -0
- package/dist/bearer.d.ts.map +1 -0
- package/dist/bearer.js +8 -0
- package/dist/bearer.js.map +1 -0
- package/dist/identity.d.ts +64 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +123 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# @kohaku-ui/authz-jwt
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#32](https://github.com/yosuque/kohaku/pull/32) [`244136c`](https://github.com/yosuque/kohaku/commit/244136c70cb1875c084589c7640ee3fbb3880f4c) Thanks [@yosuque](https://github.com/yosuque)! - Hardens capability revocation and JWT identity resolution, and closes a fail-open gap where a revocation-store
|
|
8
|
+
outage surfaced as an unhandled raw failure instead of a client-safe, observed one.
|
|
9
|
+
|
|
10
|
+
`@kohaku-ui/authz-hmac`'s `verify` now evaluates the requested scope before consulting the revocation store
|
|
11
|
+
(an out-of-scope request no longer pays for a store round trip), and a store rejection propagates as a thrown
|
|
12
|
+
error rather than being silently swallowed — per `AuthzPort.verify`'s doc comment (`@kohaku-ui/spec-core`'s
|
|
13
|
+
`ports.ts`): verify throws only on infrastructure failure, and a thrown verify is fail-closed, mapped by the
|
|
14
|
+
host to a 5xx. `revokeCapability` now returns `{ ok: true, alreadyExpired: true }` for an already-expired
|
|
15
|
+
token (idempotent success, not a failure) and a coded `"STORE_ERROR"` (instead of throwing) when the
|
|
16
|
+
revocation store itself fails. Expiry is now `exp <= now` consistently across `verify`, `revokeCapability`,
|
|
17
|
+
and the memory store's own sweep (previously `verify`/`revokeCapability` used `exp < now`, off by one second
|
|
18
|
+
at the boundary from the memory store). New `HmacAuthzOptions.requireJti` (default `false`) rejects a
|
|
19
|
+
capability token with no `jti` claim once a fleet has fully rolled onto a `jti`-issuing version.
|
|
20
|
+
|
|
21
|
+
`@kohaku-ui/authz-jwt`'s `createJwtIdentityResolver` (and `createJwtAuthzPort`, which constructs one) now
|
|
22
|
+
validates its configuration at construction: `audience` is required when `key` is `jwks` or `jwksUrl` (stays
|
|
23
|
+
optional for `secret`); an HS256 `key.secret` must be at least 32 bytes; a `jwksUrl` must use `https:` unless
|
|
24
|
+
the host is `localhost` / `127.0.0.1` / `::1`. New `requireTenant` option (default `false`) rejects a token
|
|
25
|
+
with no (or an empty) tenant claim as `JwtIdentityError({ code: "MISSING_TENANT" })` instead of silently
|
|
26
|
+
widening scope to "no tenant" (only applies to the default claim mapping).
|
|
27
|
+
|
|
28
|
+
`@kohaku-ui/host-core` adds `verifyCapabilitySafely(authz, token, req, onFailure)` (alongside the existing
|
|
29
|
+
`issueSpecCapabilitySafely`): calls `authz.verify` and returns a discriminated
|
|
30
|
+
`{ kind: "verdict"; verdict } | { kind: "unavailable"; error }` instead of letting a thrown `verify`
|
|
31
|
+
propagate, plus the shared `CAPABILITY_VERIFICATION_UNAVAILABLE_MESSAGE` client-safe text constant.
|
|
32
|
+
`@kohaku-ui/host-rest`'s `/binding/resolve` and `/binding/action`, and `@kohaku-ui/host-mcp-apps`'s
|
|
33
|
+
`kohaku_resolve_binding` / `kohaku_action` tools, now call it and map `"unavailable"` to a client-safe,
|
|
34
|
+
observed failure (REST: 503 `INTERNAL` with `"capability verification unavailable"`, reported to `onError`;
|
|
35
|
+
MCP: a structured tool error with the same message, reported to `onError`) instead of letting a thrown
|
|
36
|
+
`authz.verify` surface as a raw 500 or an unhandled rejection.
|
|
37
|
+
|
|
38
|
+
- [#28](https://github.com/yosuque/kohaku/pull/28) [`a26f9be`](https://github.com/yosuque/kohaku/commit/a26f9be35f5702287e79f67f13bd3298bfb73bc5) Thanks [@yosuque](https://github.com/yosuque)! - Capability tokens can now be revoked before they expire. `@kohaku-ui/spec-core` adds the
|
|
39
|
+
`CapabilityRevocationStore` port type (`ports.ts`, alongside `AuthzPort`, which itself is unchanged).
|
|
40
|
+
`@kohaku-ui/authz-hmac`'s tokens now carry a `jti`, `createHmacAuthzPort`'s `HmacAuthzOptions` accepts a
|
|
41
|
+
`revocations` store, and the returned `HmacAuthzPort` exposes `revokeCapability(token)` (signature
|
|
42
|
+
verified first, so a caller cannot revoke a `jti` it merely guessed) alongside the reference
|
|
43
|
+
`createMemoryRevocationStore`. A token minted before this change carries no `jti` and verifies as
|
|
44
|
+
before; it simply cannot be revoked and is left to expire on its own, so a rolling deploy does not break
|
|
45
|
+
an older instance's already-issued tokens. `@kohaku-ui/authz-jwt`'s `createJwtAuthzPort` passes
|
|
46
|
+
`revocations` through to the underlying `@kohaku-ui/authz-hmac` port and exposes the same
|
|
47
|
+
`revokeCapability(token)`, delegating entirely; the JWT identity path is unaffected.
|
|
48
|
+
|
|
49
|
+
`@kohaku-ui/storage-redis` adds `createRedisRevocationStore({ url | client, keyPrefix, connectTimeoutMs,
|
|
50
|
+
maxRetriesPerRequest })`: a revoked `jti` is a plain key carrying its own `SET … EX` expiry derived from
|
|
51
|
+
the token's `exp`, so Redis drops it once the token would have expired anyway (`revoke()` is a no-op when
|
|
52
|
+
that remaining lifetime is already zero or negative); `isRevoked` is an `EXISTS` check. Same fail-fast
|
|
53
|
+
construction and memoized-and-discarded-on-failure `ready()` gate as `createRedisStoragePort`, awaited by
|
|
54
|
+
every method. `@kohaku-ui/storage-postgres` adds `createPostgresRevocationStore({ connectionString | pool,
|
|
55
|
+
schema, migrate })` and a fifth table, `kohaku_capability_revocation` (`jti` primary key, `expires_at`),
|
|
56
|
+
in the shared idempotent `postgresSchemaSql`; `revoke()` upserts, `isRevoked` filters by `expires_at >
|
|
57
|
+
now()`, and `sweepExpiredRevocations()` deletes expired rows for a cron, the same treatment as the
|
|
58
|
+
existing `sweepExpiredSpecCache()`. Both stores are exercised against a real backend via
|
|
59
|
+
`describeRevocationStoreContract` (`@kohaku-ui/port-contracts`), skipping without Docker.
|
|
60
|
+
|
|
61
|
+
- [#28](https://github.com/yosuque/kohaku/pull/28) [`50cbb8a`](https://github.com/yosuque/kohaku/commit/50cbb8adec9e01fc7d906ea53528e4cf598e52ea) Thanks [@yosuque](https://github.com/yosuque)! - Production adapters: `@kohaku-ui/storage-redis` and `@kohaku-ui/storage-postgres` implement the whole `StoragePort` (Spec cache, lineage, promotion state, fixation, tenant scoping) so several host instances share one Spec cache and serve the same Intent as `cache: "hit"`; `@kohaku-ui/authz-jwt` resolves principal / roles / tenant from JWT / OIDC claims (shared secret or JWKS) and delegates capability tokens to `@kohaku-ui/authz-hmac`. All three are reference adapters over the unchanged `ports.ts` contract; the sample host selects them via `KOHAKU_STORAGE` / `KOHAKU_AUTHZ`.
|
|
62
|
+
|
|
63
|
+
### Patch Changes
|
|
64
|
+
|
|
65
|
+
- Updated dependencies [[`244136c`](https://github.com/yosuque/kohaku/commit/244136c70cb1875c084589c7640ee3fbb3880f4c), [`a26f9be`](https://github.com/yosuque/kohaku/commit/a26f9be35f5702287e79f67f13bd3298bfb73bc5), [`ad51284`](https://github.com/yosuque/kohaku/commit/ad5128464169d389e0c462c59184d411ba359d8e), [`cffc1aa`](https://github.com/yosuque/kohaku/commit/cffc1aac259bfdc8f22c48ae57427a809853924e), [`76103a6`](https://github.com/yosuque/kohaku/commit/76103a60caf2bdac87fec1d4241e3e62cf317b5c)]:
|
|
66
|
+
- @kohaku-ui/authz-hmac@0.3.0
|
|
67
|
+
- @kohaku-ui/spec-core@0.3.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
1
|
# @kohaku-ui/authz-jwt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
JWT / OIDC identity resolution for kohaku hosts — verifies a bearer JWT with [`jose`](https://github.com/panva/jose) and maps its claims to kohaku's `Principal` plus a tenant, while delegating capability tokens unchanged to [`@kohaku-ui/authz-hmac`](https://github.com/yosuque/kohaku/tree/main/packages/authz-hmac). The contract stays `@kohaku-ui/spec-core`'s `ports.ts`.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createJwtAuthzPort } from "@kohaku-ui/authz-jwt";
|
|
7
|
+
|
|
8
|
+
const authz = createJwtAuthzPort({
|
|
9
|
+
key: { jwksUrl: "https://issuer.example.com/.well-known/jwks.json" },
|
|
10
|
+
issuer: "https://issuer.example.com",
|
|
11
|
+
audience: "kohaku",
|
|
12
|
+
capabilitySecret: process.env.KOHAKU_CAPABILITY_SECRET!,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// Resolve the caller from the request's Authorization header (a host's principal/tenant hooks):
|
|
16
|
+
const { principal, tenant } = await authz.identity.fromAuthorizationHeader(req.headers.authorization);
|
|
17
|
+
|
|
18
|
+
// Capability issuance/verification is the unchanged @kohaku-ui/authz-hmac scheme:
|
|
19
|
+
const token = await authz.issueCapability(principal, [{ kind: "read", ref: "query://sales/summary" }]);
|
|
20
|
+
await authz.verify(token, { kind: "read", ref: "query://sales/summary" });
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Identity resolution
|
|
24
|
+
|
|
25
|
+
`createJwtIdentityResolver` verifies signature, `exp`/`nbf`, and optionally `iss`, then maps claims to a `Principal` (`id`, optional `name`, optional `roles`) and an optional `tenant`. The default claim names are `sub` / `name` / `roles` / `tenant`; override them with `claims` for issuers that namespace custom claims (Auth0-style URLs), or bypass the mapping entirely with `mapClaims`. The `roles` claim accepts either a `string[]` or a whitespace-separated `string` (OIDC `scope`-style).
|
|
26
|
+
|
|
27
|
+
The key source (`{ secret }`, `{ jwks }`, or `{ jwksUrl }`) also fixes the default algorithm allow-list — `["HS256"]` for a shared secret, `["RS256", "ES256", "EdDSA"]` for a JWK set — which a caller can narrow or replace with `algorithms`. This allow-list is a security boundary: a JWKS-configured resolver rejects an HS256-signed token even if it happens to verify against some key in the set.
|
|
28
|
+
|
|
29
|
+
**Construction-time validation** (throws synchronously, before any token is ever verified):
|
|
30
|
+
- **`audience` is required** when `key` is `jwks` or `jwksUrl` — a JWKS-configured resolver typically talks to a third-party issuer that mints tokens for other audiences too, so skipping the `aud` check would accept a token never meant for this service. `audience` stays optional in `secret` mode. **`issuer` is not similarly required, but is recommended alongside it** with a third-party JWKS: a JWKS URL is already per-issuer, so the risk is low, but setting `issuer` too makes the `iss` check an explicit, verified assertion rather than an implicit one left to the URL alone.
|
|
31
|
+
- **`key.secret` must be at least 32 bytes** (UTF-8) — a shorter HS256 shared secret is brute-forceable well before the hash itself becomes the weak link.
|
|
32
|
+
- **`jwksUrl` must use `https:`**, unless the host is `localhost` / `127.0.0.1` / `::1` (local development or tests only) — fetching a JWKS over plain HTTP to a real issuer would let a network attacker substitute their own keys and forge tokens this resolver would then accept.
|
|
33
|
+
|
|
34
|
+
**`requireTenant`** (default `false`): when true, a token with no (or an empty) tenant claim rejects with `JwtIdentityError({ code: "MISSING_TENANT" })` instead of resolving with `{ principal }` (no tenant). Only applies to the default claim mapping — a caller supplying `mapClaims` is responsible for its own tenant requirement, if any.
|
|
35
|
+
|
|
36
|
+
Failures throw `JwtIdentityError` with a `code` (`MISSING_TOKEN` / `INVALID_TOKEN` / `MISSING_SUBJECT` / `MISSING_TENANT`) and, for `INVALID_TOKEN`, the underlying `jose` error as `cause`, so a host can log the real reason while returning an opaque message to the caller.
|
|
37
|
+
|
|
38
|
+
## Capability tokens are unchanged, including revocation
|
|
39
|
+
|
|
40
|
+
`createJwtAuthzPort` delegates `issueCapability` / `verify` to `@kohaku-ui/authz-hmac` untouched — a JWT is never a capability and a capability is never a JWT. This means capability revocation is also the unchanged `@kohaku-ui/authz-hmac` scheme: pass `revocations` (a `CapabilityRevocationStore`, e.g. from `@kohaku-ui/storage-redis` or `@kohaku-ui/storage-postgres`) and the returned port's `revokeCapability(token)` delegates straight through.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { createRedisRevocationStore } from "@kohaku-ui/storage-redis";
|
|
44
|
+
// storage-redis's ioredis peer dependency must be installed alongside it.
|
|
45
|
+
|
|
46
|
+
const authz = createJwtAuthzPort({
|
|
47
|
+
key: { jwksUrl: "https://issuer.example.com/.well-known/jwks.json" },
|
|
48
|
+
audience: "kohaku",
|
|
49
|
+
capabilitySecret: process.env.KOHAKU_CAPABILITY_SECRET!,
|
|
50
|
+
revocations: createRedisRevocationStore({ url: process.env.KOHAKU_REDIS_URL! }),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
await authz.revokeCapability(token); // signature verified first; a tampered or foreign token is rejected
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**A token minted before this change carries no `jti` and therefore still cannot be revoked**: it verifies exactly as before and is left to expire on its own. This is the one thing worth watching operationally, because it is silent — nothing logs a jti-less token being accepted, so the only signal an operator has is knowing when a fleet finished rolling onto a `jti`-issuing version.
|
|
57
|
+
|
|
58
|
+
Part of [kohaku](https://github.com/yosuque/kohaku), a reference implementation of the
|
|
59
|
+
[Kohaku Protocol](https://github.com/yosuque/kohaku/blob/main/spec/SPEC.md).
|
|
60
|
+
|
|
61
|
+
The packages in this scope share a single version and are designed to be installed together.
|
|
62
|
+
|
|
63
|
+
- Documentation: https://github.com/yosuque/kohaku#readme
|
|
64
|
+
- Source: https://github.com/yosuque/kohaku/tree/main/packages/authz-jwt
|
|
65
|
+
|
|
66
|
+
Licensed under the Apache License, Version 2.0.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type RevokeCapabilityResult } from "@kohaku-ui/authz-hmac";
|
|
2
|
+
import type { AuthzPort, CapabilityRevocationStore } from "@kohaku-ui/spec-core";
|
|
3
|
+
import { type JwtIdentityOptions, type JwtIdentityResolver } from "./identity.js";
|
|
4
|
+
export interface JwtAuthzOptions extends JwtIdentityOptions {
|
|
5
|
+
/** Secret for the capability tokens kohaku issues per Spec (HMAC-SHA256, from @kohaku-ui/authz-hmac). */
|
|
6
|
+
capabilitySecret: string;
|
|
7
|
+
/** Default capability TTL in seconds (the host may override per issuance). Default 600. */
|
|
8
|
+
capabilityTtlSeconds?: number;
|
|
9
|
+
/**
|
|
10
|
+
* The store consulted for pre-expiry capability revocation, passed straight through to the underlying
|
|
11
|
+
* HMAC port (see `@kohaku-ui/authz-hmac`'s `HmacAuthzOptions.revocations`). Defaults to a private
|
|
12
|
+
* in-memory store; a multi-instance deployment should inject a shared store instead.
|
|
13
|
+
*/
|
|
14
|
+
revocations?: CapabilityRevocationStore;
|
|
15
|
+
}
|
|
16
|
+
export interface JwtAuthzPort extends AuthzPort {
|
|
17
|
+
/** The resolver a host wires into its principal/tenant hooks (host-rest `auth` / `tenant`, MCP `resolvePrincipal`). */
|
|
18
|
+
readonly identity: JwtIdentityResolver;
|
|
19
|
+
/**
|
|
20
|
+
* Revokes a capability before its `exp`, delegating entirely to the underlying HMAC port
|
|
21
|
+
* (`@kohaku-ui/authz-hmac`'s `revokeCapability`). Revocation applies only to the capability token; it
|
|
22
|
+
* has no effect on the bearer JWT the identity resolver handles.
|
|
23
|
+
*/
|
|
24
|
+
revokeCapability(token: string): Promise<RevokeCapabilityResult>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* AuthzPort for JWT / OIDC deployments. The two halves of the contract are deliberately separate:
|
|
28
|
+
* capability tokens (issue / verify) are the existing HMAC scheme, unchanged; the identity resolver only
|
|
29
|
+
* turns the caller's bearer JWT into a Principal + tenant for the host's own hooks. A capability is never a
|
|
30
|
+
* JWT and a JWT is never a capability.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createJwtAuthzPort(options: JwtAuthzOptions): JwtAuthzPort;
|
|
33
|
+
//# sourceMappingURL=authz-port.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authz-port.d.ts","sourceRoot":"","sources":["../src/authz-port.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACzF,OAAO,KAAK,EAAE,SAAS,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AACjF,OAAO,EAA6B,KAAK,kBAAkB,EAAE,KAAK,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAE7G,MAAM,WAAW,eAAgB,SAAQ,kBAAkB;IACzD,yGAAyG;IACzG,gBAAgB,EAAE,MAAM,CAAC;IACzB,2FAA2F;IAC3F,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;;OAIG;IACH,WAAW,CAAC,EAAE,yBAAyB,CAAC;CACzC;AAED,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC7C,uHAAuH;IACvH,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC;;;;OAIG;IACH,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC;CAClE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,eAAe,GAAG,YAAY,CAazE"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createHmacAuthzPort } from "@kohaku-ui/authz-hmac";
|
|
2
|
+
import { createJwtIdentityResolver } from "./identity.js";
|
|
3
|
+
/**
|
|
4
|
+
* AuthzPort for JWT / OIDC deployments. The two halves of the contract are deliberately separate:
|
|
5
|
+
* capability tokens (issue / verify) are the existing HMAC scheme, unchanged; the identity resolver only
|
|
6
|
+
* turns the caller's bearer JWT into a Principal + tenant for the host's own hooks. A capability is never a
|
|
7
|
+
* JWT and a JWT is never a capability.
|
|
8
|
+
*/
|
|
9
|
+
export function createJwtAuthzPort(options) {
|
|
10
|
+
const { capabilitySecret, capabilityTtlSeconds, revocations, ...identityOptions } = options;
|
|
11
|
+
const capabilities = createHmacAuthzPort(capabilitySecret, {
|
|
12
|
+
...(capabilityTtlSeconds != null ? { ttlSeconds: capabilityTtlSeconds } : {}),
|
|
13
|
+
...(revocations != null ? { revocations } : {}),
|
|
14
|
+
});
|
|
15
|
+
const identity = createJwtIdentityResolver(identityOptions);
|
|
16
|
+
return {
|
|
17
|
+
identity,
|
|
18
|
+
issueCapability: (principal, scopes, opts) => capabilities.issueCapability(principal, scopes, opts),
|
|
19
|
+
verify: (token, req) => capabilities.verify(token, req),
|
|
20
|
+
revokeCapability: (token) => capabilities.revokeCapability(token),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=authz-port.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authz-port.js","sourceRoot":"","sources":["../src/authz-port.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAA+B,MAAM,uBAAuB,CAAC;AAEzF,OAAO,EAAE,yBAAyB,EAAqD,MAAM,eAAe,CAAC;AA0B7G;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAwB;IACzD,MAAM,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,WAAW,EAAE,GAAG,eAAe,EAAE,GAAG,OAAO,CAAC;IAC5F,MAAM,YAAY,GAAG,mBAAmB,CAAC,gBAAgB,EAAE;QACzD,GAAG,CAAC,oBAAoB,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,oBAAoB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7E,GAAG,CAAC,WAAW,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAChD,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,yBAAyB,CAAC,eAAe,CAAC,CAAC;IAC5D,OAAO;QACL,QAAQ;QACR,eAAe,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC;QACnG,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC;QACvD,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,gBAAgB,CAAC,KAAK,CAAC;KAClE,CAAC;AACJ,CAAC"}
|
package/dist/bearer.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bearer.d.ts","sourceRoot":"","sources":["../src/bearer.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAI5E"}
|
package/dist/bearer.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The token of an `Authorization: Bearer <token>` header (scheme matched case-insensitively), or null. */
|
|
2
|
+
export function bearerToken(header) {
|
|
3
|
+
if (header == null)
|
|
4
|
+
return null;
|
|
5
|
+
const match = /^\s*bearer\s+(\S+)\s*$/i.exec(header);
|
|
6
|
+
return match?.[1] ?? null;
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=bearer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bearer.js","sourceRoot":"","sources":["../src/bearer.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,MAAM,UAAU,WAAW,CAAC,MAAiC;IAC3D,IAAI,MAAM,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,KAAK,GAAG,yBAAyB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACrD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AAC5B,CAAC"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Principal } from "@kohaku-ui/spec-core";
|
|
2
|
+
import { type JSONWebKeySet, type JWTPayload } from "jose";
|
|
3
|
+
export type JwtKeySource = {
|
|
4
|
+
secret: string;
|
|
5
|
+
} | {
|
|
6
|
+
jwks: JSONWebKeySet;
|
|
7
|
+
} | {
|
|
8
|
+
jwksUrl: string | URL;
|
|
9
|
+
};
|
|
10
|
+
/** Claim names the default mapping reads. Override for issuers that namespace custom claims (Auth0-style URLs). */
|
|
11
|
+
export interface JwtClaimNames {
|
|
12
|
+
subject?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
roles?: string;
|
|
15
|
+
tenant?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ResolvedIdentity {
|
|
18
|
+
principal: Principal;
|
|
19
|
+
tenant?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface JwtIdentityOptions {
|
|
22
|
+
key: JwtKeySource;
|
|
23
|
+
issuer?: string | string[];
|
|
24
|
+
/**
|
|
25
|
+
* The expected `aud` claim. REQUIRED when `key` is `jwksUrl` or `jwks` (a JWKS-configured resolver
|
|
26
|
+
* typically talks to a third-party issuer that mints tokens for other audiences too, so skipping the
|
|
27
|
+
* `aud` check there would accept a token never meant for this service) -- the constructor throws if
|
|
28
|
+
* omitted in either mode. Optional in `secret` mode (a single shared secret is usually already
|
|
29
|
+
* service-specific, so there is no comparable cross-audience risk).
|
|
30
|
+
*/
|
|
31
|
+
audience?: string | string[];
|
|
32
|
+
/** Seconds of leeway on exp / nbf. Default 0. */
|
|
33
|
+
clockToleranceSeconds?: number;
|
|
34
|
+
/** Allowed `alg` values. Default: ["HS256"] for a secret, ["RS256", "ES256", "EdDSA"] for a JWK set. */
|
|
35
|
+
algorithms?: string[];
|
|
36
|
+
claims?: JwtClaimNames;
|
|
37
|
+
/** Full override of the claims → identity mapping (the verified payload is passed in). Bypasses the
|
|
38
|
+
* default mapping entirely, including `requireTenant` below -- a caller supplying `mapClaims` is
|
|
39
|
+
* responsible for its own tenant requirement, if any. */
|
|
40
|
+
mapClaims?: (payload: JWTPayload) => ResolvedIdentity;
|
|
41
|
+
/**
|
|
42
|
+
* When true, a token with no (or an empty) tenant claim resolves to a `JwtIdentityError` with code
|
|
43
|
+
* `MISSING_TENANT`, instead of the default `{ principal }` (no tenant). Default false. Only applies to
|
|
44
|
+
* the default claim mapping (ignored when `mapClaims` is supplied — see its doc comment).
|
|
45
|
+
*/
|
|
46
|
+
requireTenant?: boolean;
|
|
47
|
+
}
|
|
48
|
+
export type JwtIdentityErrorCode = "MISSING_TOKEN" | "INVALID_TOKEN" | "MISSING_SUBJECT" | "MISSING_TENANT";
|
|
49
|
+
export declare class JwtIdentityError extends Error {
|
|
50
|
+
readonly code: JwtIdentityErrorCode;
|
|
51
|
+
constructor(code: JwtIdentityErrorCode, message: string, options?: {
|
|
52
|
+
cause?: unknown;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
export interface JwtIdentityResolver {
|
|
56
|
+
resolve(token: string): Promise<ResolvedIdentity>;
|
|
57
|
+
fromAuthorizationHeader(header: string | null | undefined): Promise<ResolvedIdentity>;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Verifies a JWT (signature, exp/nbf, optional iss/aud) with jose and maps its claims to kohaku's
|
|
61
|
+
* `Principal` (+ tenant). Nothing here touches capability tokens — that stays with the AuthzPort.
|
|
62
|
+
*/
|
|
63
|
+
export declare function createJwtIdentityResolver(options: JwtIdentityOptions): JwtIdentityResolver;
|
|
64
|
+
//# sourceMappingURL=identity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,UAAU,EAGhB,MAAM,MAAM,CAAC;AAGd,MAAM,MAAM,YAAY,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,CAAC;AAEpG,mHAAmH;AACnH,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,SAAS,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,YAAY,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC3B;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC7B,iDAAiD;IACjD,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,wGAAwG;IACxG,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB;;6DAEyD;IACzD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,gBAAgB,CAAC;IACtD;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,MAAM,oBAAoB,GAAG,eAAe,GAAG,eAAe,GAAG,iBAAiB,GAAG,gBAAgB,CAAC;AAW5G,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,YAAY,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIrF;CACF;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAClD,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACvF;AA2DD;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,kBAAkB,GAAG,mBAAmB,CA6C1F"}
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createLocalJWKSet, createRemoteJWKSet, jwtVerify, } from "jose";
|
|
2
|
+
import { bearerToken } from "./bearer.js";
|
|
3
|
+
/** Minimum HS256 shared-secret length (bytes, UTF-8), enforced at construction in `secret` mode. 32 bytes
|
|
4
|
+
* (256 bits) matches HS256's own hash output size -- a shorter secret is brute-forceable well before the
|
|
5
|
+
* hash itself becomes the weak link. */
|
|
6
|
+
const MIN_HMAC_SECRET_BYTES = 32;
|
|
7
|
+
/** Hostnames `jwksUrl` may use over plain `http:` (never in production; local development / tests only).
|
|
8
|
+
* `URL.hostname` renders an IPv6 literal with brackets (`new URL("http://[::1]/").hostname === "[::1]"`). */
|
|
9
|
+
const LOCAL_JWKS_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
10
|
+
export class JwtIdentityError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.name = "JwtIdentityError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const DEFAULT_CLAIMS = {
|
|
19
|
+
subject: "sub",
|
|
20
|
+
name: "name",
|
|
21
|
+
roles: "roles",
|
|
22
|
+
tenant: "tenant",
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Rejects an `http:` `jwksUrl` unless it targets a local host (`localhost` / `127.0.0.1` / `::1`) --
|
|
26
|
+
* fetching a JWKS over plain HTTP to a real issuer would let a network attacker substitute their own keys
|
|
27
|
+
* and forge tokens this resolver would then accept. `https:` is always allowed. Thrown at construction, so
|
|
28
|
+
* a misconfiguration is caught before the first token is ever verified.
|
|
29
|
+
*/
|
|
30
|
+
function assertJwksUrlAllowed(jwksUrl) {
|
|
31
|
+
const url = jwksUrl instanceof URL ? jwksUrl : new URL(jwksUrl);
|
|
32
|
+
if (url.protocol === "https:")
|
|
33
|
+
return;
|
|
34
|
+
if (url.protocol === "http:" && LOCAL_JWKS_HOSTS.has(url.hostname))
|
|
35
|
+
return;
|
|
36
|
+
throw new Error(`jwksUrl must use https: (http: is only allowed for localhost/127.0.0.1/::1), got "${url.protocol}//${url.hostname}"`);
|
|
37
|
+
}
|
|
38
|
+
function keyOf(source) {
|
|
39
|
+
if ("secret" in source)
|
|
40
|
+
return { key: new TextEncoder().encode(source.secret), defaultAlgorithms: ["HS256"] };
|
|
41
|
+
const asymmetric = ["RS256", "ES256", "EdDSA"];
|
|
42
|
+
if ("jwks" in source)
|
|
43
|
+
return { key: createLocalJWKSet(source.jwks), defaultAlgorithms: asymmetric };
|
|
44
|
+
assertJwksUrlAllowed(source.jwksUrl);
|
|
45
|
+
return { key: createRemoteJWKSet(new URL(source.jwksUrl)), defaultAlgorithms: asymmetric };
|
|
46
|
+
}
|
|
47
|
+
function rolesOf(value) {
|
|
48
|
+
if (Array.isArray(value))
|
|
49
|
+
return value.filter((v) => typeof v === "string");
|
|
50
|
+
if (typeof value === "string")
|
|
51
|
+
return value.split(/\s+/).filter((v) => v !== "");
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
function defaultMap(names, requireTenant) {
|
|
55
|
+
return (payload) => {
|
|
56
|
+
const subject = payload[names.subject];
|
|
57
|
+
if (typeof subject !== "string" || subject === "") {
|
|
58
|
+
throw new JwtIdentityError("MISSING_SUBJECT", `token has no "${names.subject}" claim`);
|
|
59
|
+
}
|
|
60
|
+
const principal = { id: subject };
|
|
61
|
+
const name = payload[names.name];
|
|
62
|
+
if (typeof name === "string")
|
|
63
|
+
principal.name = name;
|
|
64
|
+
const roles = rolesOf(payload[names.roles]);
|
|
65
|
+
if (roles != null)
|
|
66
|
+
principal.roles = roles;
|
|
67
|
+
const tenant = payload[names.tenant];
|
|
68
|
+
if (typeof tenant === "string" && tenant !== "")
|
|
69
|
+
return { principal, tenant };
|
|
70
|
+
if (requireTenant) {
|
|
71
|
+
throw new JwtIdentityError("MISSING_TENANT", `token has no "${names.tenant}" claim`);
|
|
72
|
+
}
|
|
73
|
+
return { principal };
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Verifies a JWT (signature, exp/nbf, optional iss/aud) with jose and maps its claims to kohaku's
|
|
78
|
+
* `Principal` (+ tenant). Nothing here touches capability tokens — that stays with the AuthzPort.
|
|
79
|
+
*/
|
|
80
|
+
export function createJwtIdentityResolver(options) {
|
|
81
|
+
if ("secret" in options.key) {
|
|
82
|
+
if (Buffer.byteLength(options.key.secret, "utf8") < MIN_HMAC_SECRET_BYTES) {
|
|
83
|
+
throw new Error(`key.secret must be at least ${MIN_HMAC_SECRET_BYTES} bytes (HS256 requires a strong shared secret)`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
else if (options.audience == null) {
|
|
87
|
+
// jwks / jwksUrl mode: a JWKS-configured resolver typically talks to a third-party issuer that mints
|
|
88
|
+
// tokens for other audiences too, so an unset `audience` here would accept a token never meant for
|
|
89
|
+
// this service.
|
|
90
|
+
throw new Error("audience is required when key is jwksUrl or jwks");
|
|
91
|
+
}
|
|
92
|
+
const { key, defaultAlgorithms } = keyOf(options.key);
|
|
93
|
+
const algorithms = options.algorithms ?? defaultAlgorithms;
|
|
94
|
+
const requireTenant = options.requireTenant ?? false;
|
|
95
|
+
const map = options.mapClaims ?? defaultMap({ ...DEFAULT_CLAIMS, ...options.claims }, requireTenant);
|
|
96
|
+
const resolve = async (token) => {
|
|
97
|
+
let payload;
|
|
98
|
+
try {
|
|
99
|
+
const verifyOptions = {
|
|
100
|
+
algorithms,
|
|
101
|
+
...(options.issuer != null ? { issuer: options.issuer } : {}),
|
|
102
|
+
...(options.audience != null ? { audience: options.audience } : {}),
|
|
103
|
+
clockTolerance: options.clockToleranceSeconds ?? 0,
|
|
104
|
+
};
|
|
105
|
+
const result = await jwtVerify(token, key, verifyOptions);
|
|
106
|
+
payload = result.payload;
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
throw new JwtIdentityError("INVALID_TOKEN", "token verification failed", { cause: e });
|
|
110
|
+
}
|
|
111
|
+
return map(payload);
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
resolve,
|
|
115
|
+
async fromAuthorizationHeader(header) {
|
|
116
|
+
const token = bearerToken(header);
|
|
117
|
+
if (token == null)
|
|
118
|
+
throw new JwtIdentityError("MISSING_TOKEN", "no Bearer token in the Authorization header");
|
|
119
|
+
return resolve(token);
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=identity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAIlB,SAAS,GACV,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA+C1C;;wCAEwC;AACxC,MAAM,qBAAqB,GAAG,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B,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createJwtAuthzPort, type JwtAuthzOptions, type JwtAuthzPort } from "./authz-port.js";
|
|
2
|
+
export { bearerToken } from "./bearer.js";
|
|
3
|
+
export { createJwtIdentityResolver, type JwtClaimNames, JwtIdentityError, type JwtIdentityErrorCode, type JwtIdentityOptions, type JwtIdentityResolver, type JwtKeySource, type ResolvedIdentity, } from "./identity.js";
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,KAAK,eAAe,EAAE,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,yBAAyB,EACzB,KAAK,aAAa,EAClB,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,YAAY,EACjB,KAAK,gBAAgB,GACtB,MAAM,eAAe,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAA2C,MAAM,iBAAiB,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,yBAAyB,EAEzB,gBAAgB,GAMjB,MAAM,eAAe,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,11 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kohaku-ui/authz-jwt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "JWT / OIDC identity resolution for kohaku hosts (principal, roles, tenant from claims) with capability tokens delegated to @kohaku-ui/authz-hmac — a reference adapter; the contract stays @kohaku-ui/spec-core's ports.ts.",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"license": "Apache-2.0",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@kohaku-ui/spec-core": "^0.3.0",
|
|
16
|
+
"@kohaku-ui/authz-hmac": "^0.3.0",
|
|
17
|
+
"jose": "^6.2.12"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@kohaku-ui/port-contracts": "^0.2.0",
|
|
21
|
+
"@types/node": "^26.6.2",
|
|
22
|
+
"typescript": "7.0.2",
|
|
23
|
+
"vitest": "^5.0.1"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/yosuque/kohaku/tree/main/packages/authz-jwt#readme",
|
|
26
|
+
"bugs": {
|
|
27
|
+
"url": "https://github.com/yosuque/kohaku/issues"
|
|
28
|
+
},
|
|
6
29
|
"repository": {
|
|
7
30
|
"type": "git",
|
|
8
31
|
"url": "git+https://github.com/yosuque/kohaku.git",
|
|
9
32
|
"directory": "packages/authz-jwt"
|
|
10
|
-
}
|
|
11
|
-
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=22"
|
|
36
|
+
},
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"LICENSE",
|
|
41
|
+
"README.md",
|
|
42
|
+
"CHANGELOG.md"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"typecheck": "tsc --noEmit",
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json"
|
|
50
|
+
},
|
|
51
|
+
"main": "./dist/index.js",
|
|
52
|
+
"types": "./dist/index.d.ts"
|
|
53
|
+
}
|