@cardonjs/auth 0.0.0-stage → 0.2.7
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 +21 -0
- package/README.md +302 -2
- package/dist/contract.d.ts +21 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/contract.js +210 -0
- package/dist/contract.js.map +1 -0
- package/dist/helpers.d.ts +15 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/helpers.js +39 -0
- package/dist/helpers.js.map +1 -0
- package/dist/identity.d.ts +31 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +29 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/policies.d.ts +27 -0
- package/dist/policies.d.ts.map +1 -0
- package/dist/policies.js +37 -0
- package/dist/policies.js.map +1 -0
- package/dist/require-auth.d.ts +72 -0
- package/dist/require-auth.d.ts.map +1 -0
- package/dist/require-auth.js +214 -0
- package/dist/require-auth.js.map +1 -0
- package/dist/testing.d.ts +16 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +66 -0
- package/dist/testing.js.map +1 -0
- package/llms.txt +158 -0
- package/package.json +61 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matias Terradas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,303 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cardonjs/auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The authentication and authorization interface of Cardón. It separates **who** is calling (an
|
|
4
|
+
`Identity`, produced by an `Authenticator` adapter such as `@cardonjs/auth-cf-access`) from **what
|
|
5
|
+
they may do** (roles and policies, checked in the service). It provides a secure-by-default
|
|
6
|
+
guard, `requireAuth`, under which every route requires authentication unless listed as public,
|
|
7
|
+
plus `getIdentity`, `requireRole`, `definePolicies`, the shared contract suite adapters must
|
|
8
|
+
pass (`@cardonjs/auth/contract`) and a test-only authenticator (`@cardonjs/auth/testing`).
|
|
9
|
+
Standard web APIs only (Workers, Node, Bun, Deno).
|
|
10
|
+
|
|
11
|
+
Peer dependencies: `@cardonjs/core`, `hono`. `@cardonjs/testing` is an optional peer, only needed by
|
|
12
|
+
`@cardonjs/auth/contract` (in adapter tests).
|
|
13
|
+
|
|
14
|
+
For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { type CardonEnv, createApp } from "@cardonjs/core";
|
|
20
|
+
import { definePolicies, getIdentity, requireAuth, requireRole } from "@cardonjs/auth";
|
|
21
|
+
import { cfAccess } from "@cardonjs/auth-cf-access";
|
|
22
|
+
|
|
23
|
+
type Bindings = { ACCESS_AUD: string };
|
|
24
|
+
const adapters = (env: Bindings) => ({
|
|
25
|
+
auth: cfAccess({ teamDomain: "myteam", audience: env.ACCESS_AUD }),
|
|
26
|
+
});
|
|
27
|
+
type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
|
|
28
|
+
|
|
29
|
+
interface Order {
|
|
30
|
+
readonly id: string;
|
|
31
|
+
readonly ownerId: string;
|
|
32
|
+
}
|
|
33
|
+
const policies = definePolicies({
|
|
34
|
+
"order.read": (actor, order: Order) =>
|
|
35
|
+
order.ownerId === actor.id || actor.roles.includes("support"),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const app = createApp(adapters, {
|
|
39
|
+
// Every route the app registers requires authentication...
|
|
40
|
+
guard: requireAuth<AppEnv>({
|
|
41
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
42
|
+
// ...except these, exactly as registered (method + Hono pattern, prefixes included).
|
|
43
|
+
public: ["GET /v1/catalog", "GET /v1/catalog/:id"],
|
|
44
|
+
}),
|
|
45
|
+
docs: { access: "auth" }, // the docs use the same guard
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
app.get("/v1/catalog", (c) => c.json({ data: [] }));
|
|
49
|
+
app.get("/v1/orders/:id", async (c) => {
|
|
50
|
+
const order = { id: c.req.param("id"), ownerId: "user-1" }; // from a repository
|
|
51
|
+
policies.authorize(getIdentity(c), "order.read", order); // 403 unless allowed
|
|
52
|
+
return c.json({ data: order });
|
|
53
|
+
});
|
|
54
|
+
app.post("/v1/admin/reindex", requireRole("admin"), (c) => c.json({ data: { queued: true } }));
|
|
55
|
+
|
|
56
|
+
export default app;
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`requireAuth` needs the app env as its type argument (`requireAuth<AppEnv>`) so the
|
|
60
|
+
`authenticator` callback sees `c.var.adapters`. In practice, routes live in modules:
|
|
61
|
+
`createApp(adapters, { guard, ... }).register(orders).register(admin)` guards them all, in any
|
|
62
|
+
order.
|
|
63
|
+
|
|
64
|
+
## API
|
|
65
|
+
|
|
66
|
+
### `Identity`, `AuthResult`, `Authenticator`
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
interface Identity {
|
|
70
|
+
readonly id: string; // stable subject id from the credential
|
|
71
|
+
readonly kind: "user" | "service";
|
|
72
|
+
readonly email?: string;
|
|
73
|
+
readonly roles: readonly string[]; // only from the authenticator, never from the client
|
|
74
|
+
}
|
|
75
|
+
type AuthFailure = "missing" | "invalid" | "expired";
|
|
76
|
+
type AuthResult =
|
|
77
|
+
| { readonly ok: true; readonly identity: Identity }
|
|
78
|
+
| { readonly ok: false; readonly reason: AuthFailure };
|
|
79
|
+
interface Authenticator {
|
|
80
|
+
/** Never throws for any request content; infrastructure errors (e.g. key fetch) may reject. */
|
|
81
|
+
authenticate(request: Request): Promise<AuthResult>;
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### `requireAuth(options)`
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
interface RequireAuthOptions<E extends Env> {
|
|
89
|
+
authenticator: (c: Context<E>) => Authenticator; // chosen per request
|
|
90
|
+
public?: readonly string[]; // "METHOD /pattern"
|
|
91
|
+
optional?: readonly string[]; // "METHOD /pattern"
|
|
92
|
+
securitySchemes?: Readonly<Record<string, SecuritySchemeObject>>; // for the OpenAPI spec
|
|
93
|
+
securityRequirements?: readonly (readonly string[])[]; // schemes presented together
|
|
94
|
+
}
|
|
95
|
+
function requireAuth<E extends Env>(
|
|
96
|
+
options: RequireAuthOptions<E>,
|
|
97
|
+
): MiddlewareHandler<E & { Variables: { identity: Identity | undefined } }>;
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Pass it to `createApp` as the **`guard` option**. Core mounts it before every route the app
|
|
101
|
+
registers (whenever it is registered) and for unknown paths; `/health`, `/ready` and
|
|
102
|
+
`/version` stay outside it, and docs with `docs: { access: "auth" }` use it (below).
|
|
103
|
+
|
|
104
|
+
**Advanced escape hatch: `app.use(requireAuth(...))`.** It works, but Hono runs handlers in
|
|
105
|
+
registration order, so it only protects routes registered **after** that call: a module
|
|
106
|
+
registered before it (e.g. `createApp(...).register(a)` followed by `app.use(...)`) is public.
|
|
107
|
+
Use it only for a guard scoped to part of the app (e.g. a second authenticator under a prefix),
|
|
108
|
+
and register it before the routes it must cover.
|
|
109
|
+
|
|
110
|
+
- **Public routes**: the request is public when Hono matched at least one route for it and
|
|
111
|
+
every matched method route is listed in `public`. The check uses the matched route patterns
|
|
112
|
+
(`matchedRoutes(c)`), never the raw URL, so an encoded, upper-case, double-slash or
|
|
113
|
+
trailing-slash spelling can only reach the route Hono itself dispatches to. No
|
|
114
|
+
authentication is attempted and `c.var.identity` is `undefined`.
|
|
115
|
+
- Entries are `"METHOD /pattern"` with the full pattern as registered: a module registered
|
|
116
|
+
with prefix `/v1/shop` and a route `/products` is `"GET /v1/shop/products"`; an OpenAPI
|
|
117
|
+
route with path `/{id}` is registered by Hono as `/:id`.
|
|
118
|
+
- Methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (uppercase). A public `GET`
|
|
119
|
+
also covers `HEAD` (Hono answers `HEAD` with the `GET` route); `HEAD` itself is rejected.
|
|
120
|
+
- When several method routes match a request (e.g. a public `GET /items/:id` and a protected
|
|
121
|
+
`GET /items/admin` for `/items/admin`), all of them must be public.
|
|
122
|
+
- `all()` endpoints and `use()` middleware are `ALL` entries. They never make a request
|
|
123
|
+
public, and one registered on an exact path (`app.all("/v1/graphql")`,
|
|
124
|
+
`app.use("/v1/files/internal", ...)`) makes every request it matches **protected**, since it
|
|
125
|
+
may answer by itself. `ALL` entries whose path ends in `*` (core's own middleware, module
|
|
126
|
+
`use()` scopes, `app.use("/v1/*", ...)`) and the guard's own entry are ignored.
|
|
127
|
+
- **Avoid public catch-alls** (`"GET /*"`, `"GET /v1/:rest{.+}"`): they make public whatever
|
|
128
|
+
the pattern matches. A `use()` middleware that answers by itself (a proxy, static files)
|
|
129
|
+
under a wildcard scope is never public-safe: if a public route matches the same request,
|
|
130
|
+
the middleware answers it without authentication.
|
|
131
|
+
- Core's CORS middleware answers `OPTIONS` preflights itself, before the guard.
|
|
132
|
+
- **Optional routes** (listed in `optional`, same format and rules as `public`): for routes
|
|
133
|
+
that serve signed-in and anonymous callers alike. The authenticator runs:
|
|
134
|
+
- success: `c.var.identity` is set, as on a protected route;
|
|
135
|
+
- `missing` (no credential at all): the request continues with `c.var.identity` `undefined`;
|
|
136
|
+
- `invalid` or `expired`: `401`, as on a protected route. **A credential that was presented
|
|
137
|
+
and failed is never downgraded to anonymous**: an expired or invalid session cookie answers
|
|
138
|
+
`401` there, not the anonymous view. Clients should treat a `401` as "sign in again" (drop
|
|
139
|
+
the stale credential, e.g. through the sign-out route for an `HttpOnly` cookie, then retry
|
|
140
|
+
anonymously or send the user to sign in);
|
|
141
|
+
- an authenticator that rejects: `503`, as on a protected route.
|
|
142
|
+
|
|
143
|
+
Read the identity with `getOptionalIdentity(c)`. A request is optional only when every
|
|
144
|
+
method route it matches is listed in `public` or `optional` and at least one in `optional`
|
|
145
|
+
(the same per-route matching as `public`); an entry cannot be in both lists (`requireAuth`
|
|
146
|
+
throws). What `missing` means is the authenticator's call: one that reads
|
|
147
|
+
`Authorization: Bearer` answers `missing` only when there is no `Authorization` header, so
|
|
148
|
+
any other credential in that header (an access token, for instance) is a `401` there.
|
|
149
|
+
- **Protected routes and unknown paths**: authenticates. On success `c.var.identity` is set (a
|
|
150
|
+
frozen copy) and the request continues; an unknown path then answers `404`. On failure it
|
|
151
|
+
answers `401 UNAUTHORIZED` with a generic message and logs `authentication failed` at `info`
|
|
152
|
+
with the reason (never the credential).
|
|
153
|
+
- An authenticator that rejects (e.g. its keys cannot be fetched) answers a generic `503
|
|
154
|
+
SERVICE_UNAVAILABLE`, and `requireAuth` logs `authenticator failed` at `error` with the
|
|
155
|
+
cause's name and message (the message is withheld for Hono JWT errors, which embed the token,
|
|
156
|
+
and for non-`Error` values). The `cause` of that `503` is a new `AuthenticatorError` holding
|
|
157
|
+
only the same name and message, never the authenticator's error itself (its stack, fields or
|
|
158
|
+
own cause could carry the credential), because core's error handler logs the cause chain. One
|
|
159
|
+
that returns a malformed result is a generic `500`. Neither ever lets the request through.
|
|
160
|
+
- Throws at creation on a malformed `public` or `optional` entry (`"GET/x"`, `"get /x"`,
|
|
161
|
+
`"FETCH /x"`, `"GET x"`, extra spaces), an entry in both lists, or a missing `authenticator`.
|
|
162
|
+
|
|
163
|
+
### In the OpenAPI spec
|
|
164
|
+
|
|
165
|
+
`requireAuth` describes itself to core's generated spec (see "API reference" in
|
|
166
|
+
`@cardonjs/core`). `securitySchemes` says how clients authenticate: OpenAPI security schemes by
|
|
167
|
+
name. `securityRequirements` says which of them are presented together (each list is one way
|
|
168
|
+
to authenticate and needs all its schemes; default: each scheme alone; every name must be in
|
|
169
|
+
`securitySchemes`, or `requireAuth` throws a `TypeError`). Both are documentation only (the
|
|
170
|
+
authenticator decides at runtime), so pass the ones of the adapter in use:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { cfAccessSecurityRequirements, cfAccessSecuritySchemes } from "@cardonjs/auth-cf-access";
|
|
174
|
+
|
|
175
|
+
const guard = requireAuth<AppEnv>({
|
|
176
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
177
|
+
public: ["GET /v1/catalog"],
|
|
178
|
+
securitySchemes: cfAccessSecuritySchemes, // or { bearer: { type: "http", scheme: "bearer" } }
|
|
179
|
+
securityRequirements: cfAccessSecurityRequirements, // which schemes go together
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- Protected operations list the requirements in `security` and document `401`, `403` and
|
|
184
|
+
`503`.
|
|
185
|
+
- Optional operations list the same requirements plus the empty one (`{}`: no credential is
|
|
186
|
+
accepted too) and document `401` and `503`, not `403`. They are matched like public ones.
|
|
187
|
+
- Public routes get none of those responses, and `security: []` once a scheme is registered.
|
|
188
|
+
They are matched exactly as at runtime: the same `public` list, against the route patterns a
|
|
189
|
+
request for the operation matches (so an overlapping protected route, or an `all()`/`use()`
|
|
190
|
+
entry on an exact path, keeps it protected in the spec too). A guard mounted inside a module
|
|
191
|
+
(`use()`, with or without the module's own `onError`) is documented the same way.
|
|
192
|
+
- **Each registered route is documented on its own.** A public parameterised route does not make
|
|
193
|
+
a later, more specific literal route public: with `public: ["GET /items/:id"]` and a route
|
|
194
|
+
`GET /items/special` that is not listed, `/items/{id}` is documented public and
|
|
195
|
+
`/items/special` protected, and a request for `/items/special` needs authentication (both
|
|
196
|
+
routes match it, and one is not public).
|
|
197
|
+
- When it cannot be decided whether the guard runs for an operation (its scope may cover some
|
|
198
|
+
of the operation's requests, or a regular expression in the path), the operation is
|
|
199
|
+
documented protected. The spec never documents as public an operation the guard protects.
|
|
200
|
+
- **Without `securitySchemes`**, protected operations still document `401`, `403` and `503`,
|
|
201
|
+
but no `security` is written anywhere, public routes included: protected and public
|
|
202
|
+
operations are told apart only by those responses. Pass `securitySchemes` to document
|
|
203
|
+
`security`. An invalid scheme throws a `TypeError` at creation.
|
|
204
|
+
|
|
205
|
+
Read the identity with `getIdentity(c)` (or `getOptionalIdentity(c)` on optional routes);
|
|
206
|
+
`c.var.identity` is not part of `CardonEnv`.
|
|
207
|
+
|
|
208
|
+
### Docs behind authentication
|
|
209
|
+
|
|
210
|
+
With `docs: { access: "auth" }`, the docs (`/openapi.json` and the UI) use the app's `guard`
|
|
211
|
+
in every environment. Pass `docs.guard` to protect them with a different guard.
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
const app = createApp(adapters, {
|
|
215
|
+
environment: (env) => env.ENVIRONMENT,
|
|
216
|
+
guard: requireAuth<AppEnv>({ authenticator: (c) => c.var.adapters.auth }),
|
|
217
|
+
docs: { access: "auth" },
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**Never list the docs routes as public.** `requireAuth` does not know where the docs are: a
|
|
222
|
+
`public` entry naming them (`"GET /openapi.json"`, `"GET /docs"`, or a catch-all that matches
|
|
223
|
+
them) serves them without authentication, **in production too**.
|
|
224
|
+
|
|
225
|
+
### `getIdentity(c)` and `requireRole(...roles)`
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
function getIdentity(c: Context): Identity; // UnauthorizedError (401) when there is none
|
|
229
|
+
function getOptionalIdentity(c: Context): Identity | undefined; // never throws
|
|
230
|
+
function requireRole(...roles: [string, ...string[]]): MiddlewareHandler;
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
`requireRole` answers `403 FORBIDDEN` unless the identity has at least one of the roles, and `401`
|
|
234
|
+
when the request is not authenticated (e.g. on a public route). Roles come only from the
|
|
235
|
+
authenticator.
|
|
236
|
+
|
|
237
|
+
### `definePolicies(policies)`
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
type Policy<R> = (actor: Identity, resource: R) => boolean;
|
|
241
|
+
function definePolicies<P extends Record<string, Policy<never>>>(policies: P): Policies<P>;
|
|
242
|
+
interface Policies<P> {
|
|
243
|
+
can(actor: Identity, action: keyof P, resource: ResourceOf<P[action]>): boolean;
|
|
244
|
+
authorize(actor: Identity, action: keyof P, resource: ResourceOf<P[action]>): void;
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Checks belong in the service, with the loaded resource. `can` is true only when the policy for the
|
|
249
|
+
action exists and returns exactly `true`; `authorize` throws `ForbiddenError` (403, generic
|
|
250
|
+
message, never revealing whether the resource exists) otherwise. An unknown action (from JS)
|
|
251
|
+
denies. A policy that throws is a programming error: the error propagates (a generic 500), it is
|
|
252
|
+
never an allow.
|
|
253
|
+
|
|
254
|
+
## Testing (`@cardonjs/auth/testing`)
|
|
255
|
+
|
|
256
|
+
`staticAuthenticator` is **test-only**: it maps fixed bearer tokens to identities.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { staticAuthenticator } from "@cardonjs/auth/testing";
|
|
260
|
+
|
|
261
|
+
const auth = staticAuthenticator({
|
|
262
|
+
tokens: { "test-admin": { id: "u-1", kind: "user", roles: ["admin"] } },
|
|
263
|
+
// header: "authorization" (default)
|
|
264
|
+
});
|
|
265
|
+
// Authorization: Bearer test-admin → { ok: true, identity }; no header → "missing"; else "invalid"
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
Tokens are compared as SHA-256 digests in constant time (core's `timingSafeEqual`), against every
|
|
269
|
+
configured token. There is no expiry.
|
|
270
|
+
|
|
271
|
+
## Contract suite (`@cardonjs/auth/contract`)
|
|
272
|
+
|
|
273
|
+
Every authenticator adapter runs `authenticatorContract` in its tests:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
interface AuthenticatorContractHarness {
|
|
277
|
+
create(): Authenticator | Promise<Authenticator>;
|
|
278
|
+
/** A request carrying a valid credential, and the identity it must produce. */
|
|
279
|
+
validRequest(): Promise<{ request: Request; identity: Identity }>;
|
|
280
|
+
/** Requests for each failure; each list may be empty when the adapter cannot produce it. */
|
|
281
|
+
missingRequests(): Promise<Request[]>;
|
|
282
|
+
invalidRequests(): Promise<Request[]>;
|
|
283
|
+
expiredRequests(): Promise<Request[]>;
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
The cases, each failing with an `AssertionError` that says which rule broke:
|
|
288
|
+
|
|
289
|
+
1. A valid credential authenticates with the exact identity (`id`, `kind`, `email`, `roles`).
|
|
290
|
+
2. Each request without a credential fails with `missing`.
|
|
291
|
+
3. Each invalid credential fails with `invalid`.
|
|
292
|
+
4. Each expired credential fails with `expired`.
|
|
293
|
+
5. Garbage requests (huge, binary, unicode and JWT-like values in every credential-like header,
|
|
294
|
+
many headers, a unicode URL) never throw and never authenticate.
|
|
295
|
+
6. Results are not cached: a request without headers, and every failing request of the harness,
|
|
296
|
+
still fail right after a valid one.
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { authenticatorContract } from "@cardonjs/auth/contract";
|
|
300
|
+
import { it } from "vitest";
|
|
301
|
+
|
|
302
|
+
it.each(authenticatorContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness));
|
|
303
|
+
```
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared contract every `Authenticator` adapter must pass. Import it from
|
|
3
|
+
* `@cardonjs/auth/contract` in the adapter's tests (it needs `@cardonjs/testing`) and run each case
|
|
4
|
+
* with the adapter's own runner.
|
|
5
|
+
*/
|
|
6
|
+
import { type ContractCase } from "@cardonjs/testing";
|
|
7
|
+
import { type Authenticator, type Identity } from "./identity.js";
|
|
8
|
+
export interface AuthenticatorContractHarness {
|
|
9
|
+
create(): Authenticator | Promise<Authenticator>;
|
|
10
|
+
/** A request carrying a valid credential, and the identity it must produce. */
|
|
11
|
+
validRequest(): Promise<{
|
|
12
|
+
request: Request;
|
|
13
|
+
identity: Identity;
|
|
14
|
+
}>;
|
|
15
|
+
/** Requests for each failure; each list may be empty when the adapter cannot produce it. */
|
|
16
|
+
missingRequests(): Promise<Request[]>;
|
|
17
|
+
invalidRequests(): Promise<Request[]>;
|
|
18
|
+
expiredRequests(): Promise<Request[]>;
|
|
19
|
+
}
|
|
20
|
+
export declare const authenticatorContract: readonly ContractCase<AuthenticatorContractHarness>[];
|
|
21
|
+
//# sourceMappingURL=contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,YAAY,EAAwB,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,KAAK,aAAa,EAAoB,KAAK,QAAQ,EAAiB,MAAM,eAAe,CAAC;AAEnG,MAAM,WAAW,4BAA4B;IAC3C,MAAM,IAAI,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACjD,+EAA+E;IAC/E,YAAY,IAAI,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAA;KAAE,CAAC,CAAC;IAClE,4FAA4F;IAC5F,eAAe,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACtC,eAAe,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACtC,eAAe,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;CACvC;AA2HD,eAAO,MAAM,qBAAqB,EAAE,SAAS,YAAY,CAAC,4BAA4B,CAAC,EA+GnF,CAAC"}
|
package/dist/contract.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared contract every `Authenticator` adapter must pass. Import it from
|
|
3
|
+
* `@cardonjs/auth/contract` in the adapter's tests (it needs `@cardonjs/testing`) and run each case
|
|
4
|
+
* with the adapter's own runner.
|
|
5
|
+
*/
|
|
6
|
+
import { defineContract, fail } from "@cardonjs/testing";
|
|
7
|
+
import { isAuthFailure } from "./identity.js";
|
|
8
|
+
/** Runs `authenticate` and classifies the result; a synchronous throw counts as a rejection. */
|
|
9
|
+
async function outcomeOf(authenticator, request) {
|
|
10
|
+
let value;
|
|
11
|
+
try {
|
|
12
|
+
value = await authenticator.authenticate(request);
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return { kind: "threw", error };
|
|
16
|
+
}
|
|
17
|
+
if (typeof value === "object" && value !== null && "ok" in value) {
|
|
18
|
+
if (value.ok === true && "identity" in value)
|
|
19
|
+
return { kind: "ok", identity: value.identity };
|
|
20
|
+
if (value.ok === false && "reason" in value && isAuthFailure(value.reason)) {
|
|
21
|
+
return { kind: "failed", reason: value.reason };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return { kind: "malformed", value };
|
|
25
|
+
}
|
|
26
|
+
function describe(outcome) {
|
|
27
|
+
switch (outcome.kind) {
|
|
28
|
+
case "threw": {
|
|
29
|
+
const { error } = outcome;
|
|
30
|
+
return `it threw ${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}`;
|
|
31
|
+
}
|
|
32
|
+
case "malformed":
|
|
33
|
+
return `it returned a malformed AuthResult: ${safeJson(outcome.value)}`;
|
|
34
|
+
case "ok":
|
|
35
|
+
return `it succeeded with ${safeJson(outcome.identity)}`;
|
|
36
|
+
case "failed":
|
|
37
|
+
return `it failed with reason "${outcome.reason}"`;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function safeJson(value) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.stringify(value) ?? String(value);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return String(value);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** The four identity fields, in a fixed key order, for comparison. */
|
|
49
|
+
function normalizeIdentity(value) {
|
|
50
|
+
if (typeof value !== "object" || value === null)
|
|
51
|
+
return safeJson(value);
|
|
52
|
+
const { id, kind, email, roles } = value;
|
|
53
|
+
return safeJson({ id, kind, email: email ?? null, roles });
|
|
54
|
+
}
|
|
55
|
+
function describeRequest(request, index) {
|
|
56
|
+
return `request #${index + 1} (${request.method} ${request.url})`;
|
|
57
|
+
}
|
|
58
|
+
async function expectFailures(authenticator, requests, reason, title) {
|
|
59
|
+
const problems = [];
|
|
60
|
+
for (const [index, request] of requests.entries()) {
|
|
61
|
+
const outcome = await outcomeOf(authenticator, request);
|
|
62
|
+
if (outcome.kind !== "failed" || outcome.reason !== reason) {
|
|
63
|
+
problems.push(`${describeRequest(request, index)}: ${describe(outcome)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (problems.length > 0)
|
|
67
|
+
fail(title, problems);
|
|
68
|
+
}
|
|
69
|
+
/** Credential-like header names every garbage request fills, besides the valid request's own. */
|
|
70
|
+
const CREDENTIAL_HEADERS = [
|
|
71
|
+
"authorization",
|
|
72
|
+
"cookie",
|
|
73
|
+
"cf-access-jwt-assertion",
|
|
74
|
+
"x-api-key",
|
|
75
|
+
"proxy-authorization",
|
|
76
|
+
];
|
|
77
|
+
/** Garbage values, each a valid header value (Latin-1, no CR/LF/NUL). */
|
|
78
|
+
function garbageValues() {
|
|
79
|
+
const binary = Array.from({ length: 254 }, (_, i) => String.fromCharCode(i + 1))
|
|
80
|
+
.filter((char) => char !== "\r" && char !== "\n")
|
|
81
|
+
.join("");
|
|
82
|
+
// UTF-8 bytes of non-ASCII text, as a server receives them (one Latin-1 char per byte).
|
|
83
|
+
const utf8AsLatin1 = String.fromCharCode(...new TextEncoder().encode("Cardón 🌵 ñandú 漢字 "));
|
|
84
|
+
return [
|
|
85
|
+
["huge", `Bearer ${"A".repeat(64 * 1024)}`],
|
|
86
|
+
["huge JWT-like", `${"eyJ".repeat(8000)}.${"e30".repeat(8000)}.${"x".repeat(8000)}`],
|
|
87
|
+
["binary", binary],
|
|
88
|
+
["unicode", utf8AsLatin1],
|
|
89
|
+
["bearer unicode", `Bearer ${utf8AsLatin1}`],
|
|
90
|
+
["JWT-like", "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ4In0."],
|
|
91
|
+
["dots", "...."],
|
|
92
|
+
["empty bearer", "Bearer "],
|
|
93
|
+
["JSON", '{"ok":true,"identity":{"id":"x","kind":"user","roles":["admin"]}}'],
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
/** Requests whose every credential-like header (and every header of `valid`) is garbage. */
|
|
97
|
+
function garbageRequests(valid) {
|
|
98
|
+
const names = new Set([...CREDENTIAL_HEADERS, ...[...valid.headers.keys()]]);
|
|
99
|
+
const requests = [];
|
|
100
|
+
for (const [label, value] of garbageValues()) {
|
|
101
|
+
const headers = new Headers();
|
|
102
|
+
for (const name of names)
|
|
103
|
+
headers.set(name, value);
|
|
104
|
+
requests.push([label, new Request(valid.url, { method: valid.method, headers })]);
|
|
105
|
+
}
|
|
106
|
+
const many = new Headers();
|
|
107
|
+
for (let i = 0; i < 500; i++)
|
|
108
|
+
many.set(`x-junk-${i}`, `value-${i}`);
|
|
109
|
+
for (const name of names)
|
|
110
|
+
many.set(name, "garbage");
|
|
111
|
+
requests.push(["many headers", new Request(valid.url, { method: valid.method, headers: many })]);
|
|
112
|
+
const unicodeUrl = new URL(valid.url);
|
|
113
|
+
unicodeUrl.pathname = "/ñandú/🌵/%00/..%2f";
|
|
114
|
+
requests.push(["unicode URL without credentials", new Request(unicodeUrl)]);
|
|
115
|
+
return requests;
|
|
116
|
+
}
|
|
117
|
+
export const authenticatorContract = defineContract([
|
|
118
|
+
{
|
|
119
|
+
name: "a valid credential authenticates with the exact identity",
|
|
120
|
+
run: async (h) => {
|
|
121
|
+
const authenticator = await h.create();
|
|
122
|
+
const { request, identity } = await h.validRequest();
|
|
123
|
+
const outcome = await outcomeOf(authenticator, request);
|
|
124
|
+
if (outcome.kind !== "ok") {
|
|
125
|
+
fail("a valid credential must authenticate", [describe(outcome)]);
|
|
126
|
+
}
|
|
127
|
+
const expected = normalizeIdentity(identity);
|
|
128
|
+
const actual = normalizeIdentity(outcome.identity);
|
|
129
|
+
if (actual !== expected) {
|
|
130
|
+
fail("a valid credential must produce the exact identity (id, kind, email, roles)", [
|
|
131
|
+
`expected ${expected}`,
|
|
132
|
+
`got ${actual}`,
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: "requests without a credential fail with missing",
|
|
139
|
+
run: async (h) => {
|
|
140
|
+
await expectFailures(await h.create(), await h.missingRequests(), "missing", 'a request without a credential must fail with reason "missing"');
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
name: "invalid credentials fail with invalid",
|
|
145
|
+
run: async (h) => {
|
|
146
|
+
await expectFailures(await h.create(), await h.invalidRequests(), "invalid", 'an invalid credential must fail with reason "invalid"');
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
name: "expired credentials fail with expired",
|
|
151
|
+
run: async (h) => {
|
|
152
|
+
await expectFailures(await h.create(), await h.expiredRequests(), "expired", 'an expired credential must fail with reason "expired"');
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
name: "garbage requests never throw and never authenticate",
|
|
157
|
+
run: async (h) => {
|
|
158
|
+
const authenticator = await h.create();
|
|
159
|
+
const { request } = await h.validRequest();
|
|
160
|
+
const problems = [];
|
|
161
|
+
for (const [label, garbage] of garbageRequests(request)) {
|
|
162
|
+
const outcome = await outcomeOf(authenticator, garbage);
|
|
163
|
+
if (outcome.kind !== "failed")
|
|
164
|
+
problems.push(`${label}: ${describe(outcome)}`);
|
|
165
|
+
}
|
|
166
|
+
if (problems.length > 0) {
|
|
167
|
+
fail("a garbage request must fail with a known reason, never throw or succeed", problems);
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
name: "results are not cached across requests",
|
|
173
|
+
run: async (h) => {
|
|
174
|
+
const authenticator = await h.create();
|
|
175
|
+
const followUps = [
|
|
176
|
+
["missing", await h.missingRequests()],
|
|
177
|
+
["invalid", await h.invalidRequests()],
|
|
178
|
+
["expired", await h.expiredRequests()],
|
|
179
|
+
];
|
|
180
|
+
const problems = [];
|
|
181
|
+
// Always checked, whatever the harness lists: a request with no headers at all.
|
|
182
|
+
const { request: template } = await h.validRequest();
|
|
183
|
+
const bare = new Request(template.url, { method: template.method });
|
|
184
|
+
const first = await outcomeOf(authenticator, template);
|
|
185
|
+
const afterValid = await outcomeOf(authenticator, bare);
|
|
186
|
+
if (first.kind === "ok" && afterValid.kind !== "failed") {
|
|
187
|
+
problems.push(`a request without headers after a valid one: ${describe(afterValid)}`);
|
|
188
|
+
}
|
|
189
|
+
for (const [reason, requests] of followUps) {
|
|
190
|
+
for (const [index, request] of requests.entries()) {
|
|
191
|
+
// A fresh valid request first, so a cached identity would be returned next.
|
|
192
|
+
const { request: valid } = await h.validRequest();
|
|
193
|
+
const first = await outcomeOf(authenticator, valid);
|
|
194
|
+
if (first.kind !== "ok") {
|
|
195
|
+
problems.push(`the valid request before ${reason} ${describeRequest(request, index)}: ${describe(first)}`);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const second = await outcomeOf(authenticator, request);
|
|
199
|
+
if (second.kind !== "failed" || second.reason !== reason) {
|
|
200
|
+
problems.push(`${reason} ${describeRequest(request, index)} after a valid one: ${describe(second)}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (problems.length > 0) {
|
|
205
|
+
fail("a result must not be reused for a later request", problems);
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
]);
|
|
210
|
+
//# sourceMappingURL=contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAqB,cAAc,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAuD,aAAa,EAAE,MAAM,eAAe,CAAC;AAkBnG,gGAAgG;AAChG,KAAK,UAAU,SAAS,CAAC,aAA4B,EAAE,OAAgB;IACrE,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,aAAa,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAClC,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,IAAI,IAAI,KAAK,EAAE,CAAC;QACjE,IAAI,KAAK,CAAC,EAAE,KAAK,IAAI,IAAI,UAAU,IAAI,KAAK;YAAE,OAAO,EAAE,IAAI,EAA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IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;wBACzD,QAAQ,CAAC,IAAI,CACX,GAAG,MAAM,IAAI,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,uBAAuB,QAAQ,CAAC,MAAM,CAAC,EAAE,CACtF,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC;YACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACxB,IAAI,CAAC,iDAAiD,EAAE,QAAQ,CAAC,CAAC;YACpE,CAAC;QACH,CAAC;KACF;CACF,CAAC,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { Identity } from "./identity.js";
|
|
3
|
+
/**
|
|
4
|
+
* The identity of the request, or `undefined` when there is none: on an optional route called
|
|
5
|
+
* without a credential, or on a public route. Never throws.
|
|
6
|
+
*/
|
|
7
|
+
export declare function getOptionalIdentity(c: Context): Identity | undefined;
|
|
8
|
+
/** The identity of an authenticated request; throws `UnauthorizedError` when there is none. */
|
|
9
|
+
export declare function getIdentity(c: Context): Identity;
|
|
10
|
+
/**
|
|
11
|
+
* `403 FORBIDDEN` unless the identity has at least one of the roles; `401 UNAUTHORIZED` when the
|
|
12
|
+
* request is not authenticated (e.g. on a public route). Use it after `requireAuth`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function requireRole(...roles: [string, ...string[]]): MiddlewareHandler;
|
|
15
|
+
//# sourceMappingURL=helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAQ9C;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,CAEpE;AAED,+FAA+F;AAC/F,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,QAAQ,CAIhD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,iBAAiB,CAa9E"}
|
package/dist/helpers.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ForbiddenError, UnauthorizedError } from "@cardonjs/core";
|
|
2
|
+
/** `c.var.identity` when it is set, without trusting its type. */
|
|
3
|
+
function currentIdentity(c) {
|
|
4
|
+
const identity = c.get("identity");
|
|
5
|
+
return typeof identity === "object" && identity !== null ? identity : undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The identity of the request, or `undefined` when there is none: on an optional route called
|
|
9
|
+
* without a credential, or on a public route. Never throws.
|
|
10
|
+
*/
|
|
11
|
+
export function getOptionalIdentity(c) {
|
|
12
|
+
return currentIdentity(c);
|
|
13
|
+
}
|
|
14
|
+
/** The identity of an authenticated request; throws `UnauthorizedError` when there is none. */
|
|
15
|
+
export function getIdentity(c) {
|
|
16
|
+
const identity = currentIdentity(c);
|
|
17
|
+
if (!identity)
|
|
18
|
+
throw new UnauthorizedError();
|
|
19
|
+
return identity;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* `403 FORBIDDEN` unless the identity has at least one of the roles; `401 UNAUTHORIZED` when the
|
|
23
|
+
* request is not authenticated (e.g. on a public route). Use it after `requireAuth`.
|
|
24
|
+
*/
|
|
25
|
+
export function requireRole(...roles) {
|
|
26
|
+
if (roles.length === 0 || !roles.every((role) => typeof role === "string" && role !== "")) {
|
|
27
|
+
throw new Error("requireRole: pass at least one role, each a non-empty string.");
|
|
28
|
+
}
|
|
29
|
+
const wanted = new Set(roles);
|
|
30
|
+
return async (c, next) => {
|
|
31
|
+
const identity = getIdentity(c);
|
|
32
|
+
const held = identity.roles;
|
|
33
|
+
if (!Array.isArray(held) || !held.some((role) => wanted.has(role))) {
|
|
34
|
+
throw new ForbiddenError();
|
|
35
|
+
}
|
|
36
|
+
await next();
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAInE,kEAAkE;AAClE,SAAS,eAAe,CAAC,CAAU;IACjC,MAAM,QAAQ,GAAY,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC5C,OAAO,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAE,QAAqB,CAAC,CAAC,CAAC,SAAS,CAAC;AAChG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,CAAU;IAC5C,OAAO,eAAe,CAAC,CAAC,CAAC,CAAC;AAC5B,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,WAAW,CAAC,CAAU;IACpC,MAAM,QAAQ,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;IACpC,IAAI,CAAC,QAAQ;QAAE,MAAM,IAAI,iBAAiB,EAAE,CAAC;IAC7C,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,GAAG,KAA4B;IACzD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,EAAE,CAAC,EAAE,CAAC;QAC1F,MAAM,IAAI,KAAK,CAAC,+DAA+D,CAAC,CAAC;IACnF,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