@cardonjs/auth 0.0.0-stage → 0.2.6
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/llms.txt
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# @cardonjs/auth
|
|
2
|
+
|
|
3
|
+
Authentication and authorization interface for Cardón apps. 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 `requireAuth`, a guard under
|
|
6
|
+
which every route requires authentication unless listed as public, plus role and policy helpers,
|
|
7
|
+
the contract suite every authenticator adapter must pass, and a test-only authenticator. It uses
|
|
8
|
+
standard web APIs only and runs on Workers, Node, Bun and Deno.
|
|
9
|
+
|
|
10
|
+
Full documentation: README.md in this package.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
pnpm add @cardonjs/auth @cardonjs/core hono
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`@cardonjs/testing` is an optional peer, needed only by `@cardonjs/auth/contract` (adapter tests).
|
|
19
|
+
An app also needs an authenticator adapter, e.g. `@cardonjs/auth-cf-access`.
|
|
20
|
+
|
|
21
|
+
## Exports
|
|
22
|
+
|
|
23
|
+
### `@cardonjs/auth`
|
|
24
|
+
|
|
25
|
+
- `requireAuth<E>(options)`: guard middleware. Options: `authenticator: (c) => Authenticator`
|
|
26
|
+
(chosen per request), `public?: readonly string[]` and `optional?: readonly string[]` (both
|
|
27
|
+
`"METHOD /pattern"` entries). Pass it to `createApp` as the `guard` option. On success sets
|
|
28
|
+
`c.var.identity` (a frozen copy). Throws at creation on a malformed `public` or `optional`
|
|
29
|
+
entry, an entry in both lists, or a missing `authenticator`.
|
|
30
|
+
- `getIdentity(c)`: returns the request's `Identity`; throws `UnauthorizedError` (401) when there
|
|
31
|
+
is none.
|
|
32
|
+
- `getOptionalIdentity(c)`: the request's `Identity` or `undefined` (optional and public routes);
|
|
33
|
+
never throws.
|
|
34
|
+
- `requireRole(...roles)`: middleware, at least one role required. Answers `403 FORBIDDEN` unless
|
|
35
|
+
the identity has at least one of the roles, `401` when the request is not authenticated.
|
|
36
|
+
- `definePolicies(policies)`: takes a record of `(actor: Identity, resource: R) => boolean` and
|
|
37
|
+
returns `{ can(actor, action, resource): boolean; authorize(actor, action, resource): void }`.
|
|
38
|
+
`authorize` throws `ForbiddenError` (403, generic message) unless the policy returns exactly
|
|
39
|
+
`true`.
|
|
40
|
+
- Types: `Identity`, `Authenticator`, `AuthResult`, `AuthFailure`, `Policy`, `AnyPolicy`,
|
|
41
|
+
`Policies`, `RequireAuthOptions`, `IdentityVariables`.
|
|
42
|
+
|
|
43
|
+
Core shapes:
|
|
44
|
+
|
|
45
|
+
- `Identity`: `{ id: string; kind: "user" | "service"; email?: string; roles: readonly string[] }`.
|
|
46
|
+
- `AuthFailure`: `"missing" | "invalid" | "expired"`.
|
|
47
|
+
- `AuthResult`: `{ ok: true; identity: Identity } | { ok: false; reason: AuthFailure }`.
|
|
48
|
+
- `Authenticator`: `{ authenticate(request: Request): Promise<AuthResult> }`. It never throws for
|
|
49
|
+
any request content; infrastructure errors (e.g. a key fetch) may reject.
|
|
50
|
+
|
|
51
|
+
### `@cardonjs/auth/testing`
|
|
52
|
+
|
|
53
|
+
- `staticAuthenticator({ tokens, header? })`: test-only `Authenticator` that maps fixed bearer
|
|
54
|
+
tokens to identities. `tokens` is a record of token to `Identity`; `header` defaults to
|
|
55
|
+
`"authorization"`. `Authorization: Bearer <token>` authenticates; no header is `missing`;
|
|
56
|
+
anything else is `invalid`. There is no expiry.
|
|
57
|
+
- Type: `StaticAuthenticatorOptions`.
|
|
58
|
+
|
|
59
|
+
### `@cardonjs/auth/contract`
|
|
60
|
+
|
|
61
|
+
- `authenticatorContract`: readonly array of contract cases (`{ name, run(harness) }`) every
|
|
62
|
+
authenticator adapter runs in its tests. Needs `@cardonjs/testing`. Run with
|
|
63
|
+
`it.each(authenticatorContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness))`.
|
|
64
|
+
- Type: `AuthenticatorContractHarness` with `create()`, `validRequest()` (resolves to
|
|
65
|
+
`{ request, identity }`), `missingRequests()`, `invalidRequests()`, `expiredRequests()` (each
|
|
66
|
+
resolves to `Request[]`, which may be empty when the adapter cannot produce that failure).
|
|
67
|
+
|
|
68
|
+
## Minimal example
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { type CardonEnv, createApp } from "@cardonjs/core";
|
|
72
|
+
import { definePolicies, getIdentity, requireAuth, requireRole } from "@cardonjs/auth";
|
|
73
|
+
import { cfAccess } from "@cardonjs/auth-cf-access";
|
|
74
|
+
|
|
75
|
+
type Bindings = { ACCESS_AUD: string };
|
|
76
|
+
const adapters = (env: Bindings) => ({
|
|
77
|
+
auth: cfAccess({ teamDomain: "myteam", audience: env.ACCESS_AUD }),
|
|
78
|
+
});
|
|
79
|
+
type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
|
|
80
|
+
|
|
81
|
+
interface Order {
|
|
82
|
+
readonly id: string;
|
|
83
|
+
readonly ownerId: string;
|
|
84
|
+
}
|
|
85
|
+
const policies = definePolicies({
|
|
86
|
+
"order.read": (actor, order: Order) =>
|
|
87
|
+
order.ownerId === actor.id || actor.roles.includes("support"),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const app = createApp(adapters, {
|
|
91
|
+
guard: requireAuth<AppEnv>({
|
|
92
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
93
|
+
public: ["GET /v1/catalog", "GET /v1/catalog/:id"],
|
|
94
|
+
}),
|
|
95
|
+
docs: { access: "auth" }, // the docs use the same guard
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
app.get("/v1/catalog", (c) => c.json({ data: [] }));
|
|
99
|
+
app.get("/v1/orders/:id", async (c) => {
|
|
100
|
+
const order = { id: c.req.param("id"), ownerId: "user-1" }; // from a repository
|
|
101
|
+
policies.authorize(getIdentity(c), "order.read", order); // 403 unless allowed
|
|
102
|
+
return c.json({ data: order });
|
|
103
|
+
});
|
|
104
|
+
app.post("/v1/admin/reindex", requireRole("admin"), (c) => c.json({ data: { queued: true } }));
|
|
105
|
+
|
|
106
|
+
export default app;
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Rules and common mistakes
|
|
110
|
+
|
|
111
|
+
- Pass `requireAuth` as the `guard` option of `createApp`. Core then mounts it before every route
|
|
112
|
+
the app registers and for unknown paths. `app.use(requireAuth(...))` only protects routes
|
|
113
|
+
registered after that call; use it only for a guard scoped to part of the app.
|
|
114
|
+
- Give `requireAuth` the app env as its type argument (`requireAuth<AppEnv>`), otherwise the
|
|
115
|
+
`authenticator` callback does not see `c.var.adapters`.
|
|
116
|
+
- `public` entries are `"METHOD /pattern"` with the full pattern as registered, prefixes included:
|
|
117
|
+
a module with prefix `/v1/shop` and route `/products` is `"GET /v1/shop/products"`; an OpenAPI
|
|
118
|
+
path `/{id}` is `/:id`. Methods are uppercase `GET`, `POST`, `PUT`, `PATCH`, `DELETE`,
|
|
119
|
+
`OPTIONS`. A public `GET` also covers `HEAD`; a `HEAD` entry is rejected.
|
|
120
|
+
- A request is public only when Hono matched at least one route and every matched method route
|
|
121
|
+
is listed in `public`. On public routes no authentication is attempted and `c.var.identity` is
|
|
122
|
+
`undefined`, so `getIdentity` and `requireRole` answer 401 there.
|
|
123
|
+
- `optional` routes (same format and matching as `public`) serve signed-in and anonymous callers:
|
|
124
|
+
the authenticator runs; success sets the identity, `missing` continues with `c.var.identity`
|
|
125
|
+
`undefined`, `invalid`/`expired` is a `401` (a presented bad credential is never downgraded to
|
|
126
|
+
anonymous: an expired session cookie is a `401`, so clients clear it or sign in again on a
|
|
127
|
+
`401`), a rejecting authenticator a `503`. Read it with `getOptionalIdentity(c)`. A request
|
|
128
|
+
is optional only when every matched method route is listed in `public` or `optional`, at least
|
|
129
|
+
one in `optional`. The spec documents them with the requirements plus `{}`, `401` and `503`,
|
|
130
|
+
no `403`.
|
|
131
|
+
- An authenticator reading `Authorization: Bearer` answers `missing` only without that header:
|
|
132
|
+
any other credential there (e.g. an access token) is a `401` on an optional route.
|
|
133
|
+
- `all()` endpoints and `use()` middleware never make a request public; one registered on an
|
|
134
|
+
exact path makes every request it matches protected.
|
|
135
|
+
- Avoid public catch-alls (`"GET /*"`, `"GET /v1/:rest{.+}"`): they make public whatever the
|
|
136
|
+
pattern matches, including a `use()` middleware that answers by itself under a wildcard scope.
|
|
137
|
+
- Never list the docs routes as public (`"GET /openapi.json"`, `"GET /docs"`, or a catch-all
|
|
138
|
+
that matches them): that serves them without authentication, in production too. Use
|
|
139
|
+
`docs: { access: "auth" }`, or `docs.guard` for a different guard.
|
|
140
|
+
- `/health`, `/ready` and `/version` stay outside the guard. Core's CORS middleware answers
|
|
141
|
+
`OPTIONS` preflights before the guard.
|
|
142
|
+
- Roles come only from the authenticator, never from the client.
|
|
143
|
+
- Read the identity with `getIdentity(c)`; `c.var.identity` is not part of `CardonEnv`.
|
|
144
|
+
- Policy checks belong in the service, with the loaded resource. An unknown action denies. A
|
|
145
|
+
policy that throws is a programming error (generic 500), never an allow.
|
|
146
|
+
- Failures are generic: `401 UNAUTHORIZED` on a failed authentication (the reason is logged at
|
|
147
|
+
`info`, never the credential), `503 SERVICE_UNAVAILABLE` when the authenticator rejects, `500`
|
|
148
|
+
when it returns a malformed result. None lets the request through.
|
|
149
|
+
- `staticAuthenticator` is test-only: its tokens are fixed strings in code. It must not reach
|
|
150
|
+
production.
|
|
151
|
+
- An adapter's `authenticate` must not throw for any request content and must not cache results
|
|
152
|
+
across requests; the contract suite checks both.
|
|
153
|
+
|
|
154
|
+
## Out of scope
|
|
155
|
+
|
|
156
|
+
- Verifying credentials: that is the adapter's job (`@cardonjs/auth-cf-access` and others).
|
|
157
|
+
- Login flows, sessions, token issuance and user storage.
|
|
158
|
+
- Knowing where the docs routes are: `requireAuth` does not, so `public` must not name them.
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cardonjs/auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.6",
|
|
4
|
+
"description": "Authentication and authorization interface for Cardón apps: Identity, Authenticator, a secure-by-default guard, roles, policies and the shared authenticator contract suite.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/cardonjs/cardon.git",
|
|
9
|
+
"directory": "packages/auth"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/cardonjs/cardon/tree/main/packages/auth#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/cardonjs/cardon/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./contract": {
|
|
23
|
+
"types": "./dist/contract.d.ts",
|
|
24
|
+
"default": "./dist/contract.js"
|
|
25
|
+
},
|
|
26
|
+
"./testing": {
|
|
27
|
+
"types": "./dist/testing.d.ts",
|
|
28
|
+
"default": "./dist/testing.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"llms.txt"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"hono": "^4.13.18",
|
|
40
|
+
"@cardonjs/core": "^0.5.1",
|
|
41
|
+
"@cardonjs/testing": "^0.6.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependenciesMeta": {
|
|
44
|
+
"@cardonjs/testing": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@hono/zod-openapi": "1.6.3",
|
|
50
|
+
"@scalar/hono-api-reference": "0.12.20",
|
|
51
|
+
"hono": "4.13.18",
|
|
52
|
+
"typescript": "7.0.2",
|
|
53
|
+
"vitest": "5.1.0",
|
|
54
|
+
"zod": "4.6.7",
|
|
55
|
+
"@cardonjs/config": "0.0.0",
|
|
56
|
+
"@cardonjs/testing": "0.6.0",
|
|
57
|
+
"@cardonjs/core": "0.5.1"
|
|
58
|
+
},
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsc -p tsconfig.build.json",
|
|
61
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
62
|
+
"test": "vitest run"
|
|
63
|
+
}
|
|
6
64
|
}
|