@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.
@@ -0,0 +1,31 @@
1
+ /** Who is making the request, as established by an {@link Authenticator}. */
2
+ export interface Identity {
3
+ /** Stable subject id from the credential. */
4
+ readonly id: string;
5
+ readonly kind: "user" | "service";
6
+ readonly email?: string;
7
+ /** Only from the authenticator, never from the client. */
8
+ readonly roles: readonly string[];
9
+ }
10
+ /** Why authentication failed: no credential, a bad one, or an expired one. */
11
+ export type AuthFailure = "missing" | "invalid" | "expired";
12
+ export type AuthResult = {
13
+ readonly ok: true;
14
+ readonly identity: Identity;
15
+ } | {
16
+ readonly ok: false;
17
+ readonly reason: AuthFailure;
18
+ };
19
+ /** Turns a request into an identity. Implemented by adapters such as `@cardonjs/auth-cf-access`. */
20
+ export interface Authenticator {
21
+ /** Never throws for any request content; infrastructure errors (e.g. key fetch) may reject. */
22
+ authenticate(request: Request): Promise<AuthResult>;
23
+ }
24
+ /** True for `"missing"`, `"invalid"` and `"expired"`. */
25
+ export declare function isAuthFailure(value: unknown): value is AuthFailure;
26
+ /**
27
+ * A frozen copy of `value` when it is a well-formed identity (non-empty `id`, known `kind`,
28
+ * string `email` if present, array of strings `roles`), or `undefined` otherwise.
29
+ */
30
+ export declare function toIdentity(value: unknown): Identity | undefined;
31
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,MAAM,WAAW,QAAQ;IACvB,6CAA6C;IAC7C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAED,8EAA8E;AAC9E,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC;AAE5D,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,GAClD;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;CAAE,CAAC;AAEzD,oGAAoG;AACpG,MAAM,WAAW,aAAa;IAC5B,+FAA+F;IAC/F,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACrD;AAID,yDAAyD;AACzD,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,CAa/D"}
@@ -0,0 +1,29 @@
1
+ const AUTH_FAILURES = new Set(["missing", "invalid", "expired"]);
2
+ /** True for `"missing"`, `"invalid"` and `"expired"`. */
3
+ export function isAuthFailure(value) {
4
+ return AUTH_FAILURES.has(value);
5
+ }
6
+ /**
7
+ * A frozen copy of `value` when it is a well-formed identity (non-empty `id`, known `kind`,
8
+ * string `email` if present, array of strings `roles`), or `undefined` otherwise.
9
+ */
10
+ export function toIdentity(value) {
11
+ if (typeof value !== "object" || value === null)
12
+ return undefined;
13
+ const { id, kind, email, roles } = value;
14
+ if (typeof id !== "string" || id === "")
15
+ return undefined;
16
+ if (kind !== "user" && kind !== "service")
17
+ return undefined;
18
+ if (email !== undefined && typeof email !== "string")
19
+ return undefined;
20
+ if (!Array.isArray(roles) || !roles.every((role) => typeof role === "string"))
21
+ return undefined;
22
+ return Object.freeze({
23
+ id,
24
+ kind,
25
+ ...(email === undefined ? {} : { email }),
26
+ roles: Object.freeze([...roles]),
27
+ });
28
+ }
29
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAuBA,MAAM,aAAa,GAAyB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;AAEvF,yDAAyD;AACzD,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,KAAgC,CAAC;IACpE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,SAAS,CAAC;IAC1D,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC5D,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACvE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC;QAAE,OAAO,SAAS,CAAC;IAChG,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,EAAE;QACF,IAAI;QACJ,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;QACzC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAI,KAAkB,CAAC,CAAC;KAC/C,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,6 @@
1
+ export type { SecuritySchemeObject } from "@cardonjs/core";
2
+ export { getIdentity, getOptionalIdentity, requireRole } from "./helpers.js";
3
+ export type { Authenticator, AuthFailure, AuthResult, Identity } from "./identity.js";
4
+ export { type AnyPolicy, definePolicies, type Policies, type Policy } from "./policies.js";
5
+ export { type IdentityVariables, type RequireAuthOptions, requireAuth } from "./require-auth.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC7E,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACtF,OAAO,EAAE,KAAK,SAAS,EAAE,cAAc,EAAE,KAAK,QAAQ,EAAE,KAAK,MAAM,EAAE,MAAM,eAAe,CAAC;AAC3F,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,kBAAkB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { getIdentity, getOptionalIdentity, requireRole } from "./helpers.js";
2
+ export { definePolicies } from "./policies.js";
3
+ export { requireAuth } from "./require-auth.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE7E,OAAO,EAAkB,cAAc,EAA8B,MAAM,eAAe,CAAC;AAC3F,OAAO,EAAmD,WAAW,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,27 @@
1
+ import type { Identity } from "./identity.js";
2
+ /** Whether `actor` may perform an action on `resource`. Only `true` allows. */
3
+ export type Policy<R> = (actor: Identity, resource: R) => boolean;
4
+ /**
5
+ * Any policy (the constraint of `definePolicies`). `never` as the resource accepts every
6
+ * `Policy<R>` (parameters are contravariant), so no `any` is needed,
7
+ * while `Parameters<P[A]>[1]` still recovers each policy's own resource type.
8
+ */
9
+ export type AnyPolicy = Policy<never>;
10
+ export interface Policies<P extends Record<string, AnyPolicy>> {
11
+ /** True only when the policy for `action` exists and returns exactly `true`. */
12
+ can<A extends keyof P & string>(actor: Identity, action: A, resource: Parameters<P[A]>[1]): boolean;
13
+ /** Throws `ForbiddenError` (403, generic message) when `can` is false. */
14
+ authorize<A extends keyof P & string>(actor: Identity, action: A, resource: Parameters<P[A]>[1]): void;
15
+ }
16
+ /**
17
+ * Names each authorization rule once, e.g.
18
+ * `definePolicies({ "order.read": (actor, order: Order) => order.ownerId === actor.id })`.
19
+ *
20
+ * - An unknown action (from JS callers) denies.
21
+ * - Anything other than `true` (e.g. a truthy string) denies.
22
+ * - A policy that throws: the error propagates from `can` and `authorize` (a programming error,
23
+ * a generic 500 through core); it is never an allow.
24
+ * - The 403 message never says whether the resource exists.
25
+ */
26
+ export declare function definePolicies<P extends Record<string, AnyPolicy>>(policies: P): Policies<P>;
27
+ //# sourceMappingURL=policies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policies.d.ts","sourceRoot":"","sources":["../src/policies.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,+EAA+E;AAC/E,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,KAAK,OAAO,CAAC;AAElE;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;AAEtC,MAAM,WAAW,QAAQ,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3D,gFAAgF;IAChF,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAC5B,KAAK,EAAE,QAAQ,EACf,MAAM,EAAE,CAAC,EACT,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAC5B,OAAO,CAAC;IACX,0EAA0E;IAC1E,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAClC,KAAK,EAAE,QAAQ,EACf,MAAM,EAAE,CAAC,EACT,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAC5B,IAAI,CAAC;CACT;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAwB5F"}
@@ -0,0 +1,37 @@
1
+ import { ForbiddenError } from "@cardonjs/core";
2
+ /**
3
+ * Names each authorization rule once, e.g.
4
+ * `definePolicies({ "order.read": (actor, order: Order) => order.ownerId === actor.id })`.
5
+ *
6
+ * - An unknown action (from JS callers) denies.
7
+ * - Anything other than `true` (e.g. a truthy string) denies.
8
+ * - A policy that throws: the error propagates from `can` and `authorize` (a programming error,
9
+ * a generic 500 through core); it is never an allow.
10
+ * - The 403 message never says whether the resource exists.
11
+ */
12
+ export function definePolicies(policies) {
13
+ if (typeof policies !== "object" || policies === null) {
14
+ throw new Error("definePolicies: pass an object of policy functions.");
15
+ }
16
+ const table = new Map();
17
+ for (const [action, policy] of Object.entries(policies)) {
18
+ if (typeof policy !== "function") {
19
+ throw new Error(`definePolicies: policy ${JSON.stringify(action)} must be a function.`);
20
+ }
21
+ table.set(action, policy);
22
+ }
23
+ const can = (actor, action, resource) => {
24
+ const policy = typeof action === "string" ? table.get(action) : undefined;
25
+ if (!policy)
26
+ return false;
27
+ return policy(actor, resource) === true;
28
+ };
29
+ return {
30
+ can,
31
+ authorize(actor, action, resource) {
32
+ if (!can(actor, action, resource))
33
+ throw new ForbiddenError();
34
+ },
35
+ };
36
+ }
37
+ //# sourceMappingURL=policies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policies.js","sourceRoot":"","sources":["../src/policies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AA4BhD;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAsC,QAAW;IAC7E,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,GAAG,EAA2D,CAAC;IACjF,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxD,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE,CAAC;YACjC,MAAM,IAAI,KAAK,CAAC,0BAA0B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,sBAAsB,CAAC,CAAC;QAC1F,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,MAAyD,CAAC,CAAC;IAC/E,CAAC;IAED,MAAM,GAAG,GAAG,CAAC,KAAe,EAAE,MAAc,EAAE,QAAiB,EAAW,EAAE;QAC1E,MAAM,MAAM,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC1E,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC1B,OAAO,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,KAAK,IAAI,CAAC;IAC1C,CAAC,CAAC;IAEF,OAAO;QACL,GAAG;QACH,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ;YAC/B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC;gBAAE,MAAM,IAAI,cAAc,EAAE,CAAC;QAChE,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,72 @@
1
+ import { type SecuritySchemeObject } from "@cardonjs/core";
2
+ import type { Context, Env, MiddlewareHandler } from "hono";
3
+ import { type Authenticator, type Identity } from "./identity.js";
4
+ /**
5
+ * `c.var.identity`: set by {@link requireAuth}; `undefined` on public routes and on optional
6
+ * routes called without a credential.
7
+ */
8
+ export interface IdentityVariables {
9
+ identity: Identity | undefined;
10
+ }
11
+ export interface RequireAuthOptions<E extends Env> {
12
+ /** The authenticator, chosen per request (e.g. from `c.var.adapters`). */
13
+ authenticator: (c: Context<E>) => Authenticator;
14
+ /**
15
+ * Public routes as `"METHOD /pattern"`, exactly as registered (Hono syntax, prefixes
16
+ * included), e.g. `"GET /v1/catalog/:id"`. A public `GET` also covers `HEAD`.
17
+ */
18
+ public?: readonly string[];
19
+ /**
20
+ * Optional routes, in the same `"METHOD /pattern"` format as `public`: the authenticator runs,
21
+ * a valid credential sets `c.var.identity`, no credential at all (`missing`) continues with
22
+ * `c.var.identity` `undefined`, and a credential that was presented but is `invalid` or
23
+ * `expired` is a `401`, as on a protected route (never downgraded to anonymous). Read the
24
+ * identity with `getOptionalIdentity(c)`. A route cannot be in both lists.
25
+ */
26
+ optional?: readonly string[];
27
+ /**
28
+ * How clients authenticate, for the generated OpenAPI spec: security schemes by name, e.g.
29
+ * `cfAccessSecuritySchemes` from `@cardonjs/auth-cf-access` or
30
+ * `{ bearer: { type: "http", scheme: "bearer" } }`. Documentation only: the authenticator
31
+ * decides at runtime. Without it the spec still documents the 401 and 403 responses of every
32
+ * protected operation, but writes no `security` at all, so a protected operation is told
33
+ * apart from a public one only by those responses. Invalid schemes throw a `TypeError` at
34
+ * creation.
35
+ */
36
+ securitySchemes?: Readonly<Record<string, SecuritySchemeObject>>;
37
+ /**
38
+ * Which schemes are presented together, e.g. `[["session"], ["clientId", "clientSecret"]]`:
39
+ * any one list authenticates, and every scheme in it is needed. Every name must be in
40
+ * `securitySchemes`. Default: each scheme alone. `cfAccessSecurityRequirements` from
41
+ * `@cardonjs/auth-cf-access` goes with `cfAccessSecuritySchemes`.
42
+ */
43
+ securityRequirements?: readonly (readonly string[])[];
44
+ }
45
+ /**
46
+ * Secure-by-default guard. Pass it to `createApp` as the `guard` option: it then runs for every
47
+ * route the app registers and for unknown paths, and for the docs with `docs.access: "auth"`.
48
+ * `/health`, `/ready` and `/version` stay outside it. `app.use(requireAuth(...))` also works, but
49
+ * only protects the routes registered after that call.
50
+ *
51
+ * - Public routes (matched route pattern listed in `public`): no authentication is attempted and
52
+ * `c.var.identity` is `undefined`.
53
+ * - Optional routes (listed in `optional`): the authenticator runs. Success sets
54
+ * `c.var.identity`; `missing` continues with `c.var.identity` `undefined`; `invalid` and
55
+ * `expired` are a `401`, as on a protected route.
56
+ * - Everything else, unknown paths included: authenticates. On success `c.var.identity` is set;
57
+ * on failure it answers `401 UNAUTHORIZED` with a generic message and logs the reason at
58
+ * `info`. A rejection from the authenticator is a generic `503` (its cause logged at `error`),
59
+ * never a pass.
60
+ *
61
+ * In the generated OpenAPI spec, protected operations get the 401, 403 and 503 responses and,
62
+ * with `securitySchemes`, a `security` naming them; optional ones get the 401 and 503 responses
63
+ * and the same `security` plus the empty requirement `{}`; public ones get none of those
64
+ * responses and, once some guard registered a scheme, `security: []`.
65
+ *
66
+ * Throws at creation on a malformed `public` or `optional` entry, a route listed in both, an
67
+ * invalid security scheme or a requirement naming an unknown scheme.
68
+ */
69
+ export declare function requireAuth<E extends Env>(options: RequireAuthOptions<E>): MiddlewareHandler<E & {
70
+ Variables: IdentityVariables;
71
+ }>;
72
+ //# sourceMappingURL=require-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../src/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,oBAAoB,EAG1B,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAG5D,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,QAAQ,EAA6B,MAAM,eAAe,CAAC;AAE7F;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC;CAChC;AAED,MAAM,WAAW,kBAAkB,CAAC,CAAC,SAAS,GAAG;IAC/C,0EAA0E;IAC1E,aAAa,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC;IAChD;;;OAGG;IACH,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,CAAC;IACjE;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,SAAS,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC;CACvD;AAmID;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,GAAG,EACvC,OAAO,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAC7B,iBAAiB,CAAC,CAAC,GAAG;IAAE,SAAS,EAAE,iBAAiB,CAAA;CAAE,CAAC,CAgFzD"}
@@ -0,0 +1,214 @@
1
+ import { documentMiddleware, ServiceUnavailableError, UnauthorizedError, } from "@cardonjs/core";
2
+ import { matchedRoutes } from "hono/route";
3
+ import { findTargetHandler } from "hono/utils/handler";
4
+ import { isAuthFailure, toIdentity } from "./identity.js";
5
+ /** Methods a public entry may name. `HEAD` is answered by `GET` routes, so it is not listed. */
6
+ const PUBLIC_METHODS = new Set([
7
+ "GET",
8
+ "POST",
9
+ "PUT",
10
+ "PATCH",
11
+ "DELETE",
12
+ "OPTIONS",
13
+ ]);
14
+ const PUBLIC_ENTRY = /^([A-Za-z]+) (\/\S*)$/;
15
+ /** Hono's method for `use()`/`all()` entries. */
16
+ const METHOD_ALL = "ALL";
17
+ function parseRoutes(list, entries) {
18
+ if (entries === undefined)
19
+ return new Set();
20
+ if (!Array.isArray(entries)) {
21
+ throw new Error(`requireAuth: ${list} must be an array of "METHOD /pattern" strings.`);
22
+ }
23
+ const keys = new Set();
24
+ for (const entry of entries) {
25
+ if (typeof entry !== "string") {
26
+ throw new Error(`requireAuth: each ${list} entry must be a "METHOD /pattern" string.`);
27
+ }
28
+ const match = PUBLIC_ENTRY.exec(entry);
29
+ const method = match?.[1];
30
+ const pattern = match?.[2];
31
+ if (method === undefined || pattern === undefined) {
32
+ throw new Error(`requireAuth: ${list} entry ${JSON.stringify(entry)} must be "METHOD /pattern" ` +
33
+ '(one space, the pattern starting with "/" and without spaces), e.g. "GET /v1/catalog".');
34
+ }
35
+ if (method === "HEAD") {
36
+ throw new Error(`requireAuth: ${list} entry ${JSON.stringify(entry)}: HEAD is answered by GET routes; ` +
37
+ "list the GET route instead.");
38
+ }
39
+ if (!PUBLIC_METHODS.has(method)) {
40
+ throw new Error(`requireAuth: ${list} entry ${JSON.stringify(entry)} has an unknown method; use one of ` +
41
+ `${[...PUBLIC_METHODS].join(", ")} (uppercase).`);
42
+ }
43
+ keys.add(`${method} ${pattern}`);
44
+ }
45
+ return keys;
46
+ }
47
+ /**
48
+ * Public when Hono matched at least one method route (not `use()`/`all()`) for the request,
49
+ * every one of them is listed in `public`, and no `ALL` entry with an exact path matched.
50
+ * Optional under the same conditions when every matched method route is listed in `public` or
51
+ * `optional` and at least one in `optional`: a request is served anonymously only when every
52
+ * route it reaches allows it. Anything else is protected.
53
+ *
54
+ * `ALL` entries are `use()` middleware and `all()` endpoints. One whose path ends in `*` is a
55
+ * middleware scope (core registers all of its own middleware as `/*`; a module prefix scope is
56
+ * `/prefix/*`) and is ignored. Any other `ALL` entry (`app.all("/graphql")`,
57
+ * `app.use("/files/internal", ...)`) may answer the request itself, so it makes the request
58
+ * protected. The guard's own entry is always ignored, whatever path it was mounted at, also
59
+ * when a module wraps it.
60
+ *
61
+ * Hono matches `HEAD` requests against `GET` routes, so their entries carry `GET`. Unknown
62
+ * paths only match `ALL` entries, so they are never public nor optional.
63
+ */
64
+ function accessOf(c, publicKeys, optionalKeys, self) {
65
+ if (publicKeys.size === 0 && optionalKeys.size === 0)
66
+ return "protected";
67
+ let methodRoutes = 0;
68
+ let optional = false;
69
+ for (const route of matchedRoutes(c)) {
70
+ if (route.method === METHOD_ALL) {
71
+ // A module with its own `onError` (Hono) or mounted at the root (core) wraps its entries;
72
+ // the wrapper points to the original, which is what is compared.
73
+ if (route.path.endsWith("*") || findTargetHandler(route.handler) === self)
74
+ continue;
75
+ return "protected";
76
+ }
77
+ methodRoutes++;
78
+ const key = `${route.method} ${route.path}`;
79
+ if (optionalKeys.has(key))
80
+ optional = true;
81
+ else if (!publicKeys.has(key))
82
+ return "protected";
83
+ }
84
+ if (methodRoutes === 0)
85
+ return "protected";
86
+ return optional ? "optional" : "public";
87
+ }
88
+ /** Hono's JWT errors (`JwtTokenInvalid`, ...) put the whole token in their message. */
89
+ const JWT_ERROR_NAME = /^Jwt/;
90
+ /**
91
+ * What is logged about an authenticator rejection: the error name, and its message unless it may
92
+ * carry a credential (Hono JWT errors, non-`Error` values). Never the stack or the error's own
93
+ * cause, which can repeat the message.
94
+ */
95
+ function describeRejection(cause) {
96
+ if (!(cause instanceof Error)) {
97
+ return { name: typeof cause, message: "the authenticator rejected with a non-Error value" };
98
+ }
99
+ const name = typeof cause.name === "string" ? cause.name : "Error";
100
+ if (JWT_ERROR_NAME.test(name)) {
101
+ return { name, message: "withheld: Hono JWT error messages include the token" };
102
+ }
103
+ return { name, message: String(cause.message) };
104
+ }
105
+ /**
106
+ * The `cause` of the 503: a new error holding only {@link describeRejection}'s name and message,
107
+ * so the authenticator's error (its stack repeats the message, its fields and cause may hold
108
+ * anything) never reaches the log through the error handler.
109
+ */
110
+ function safeRejection(rejection) {
111
+ const error = new Error(`authenticator failed (${rejection.name}): ${rejection.message}`);
112
+ error.name = "AuthenticatorError";
113
+ return error;
114
+ }
115
+ /**
116
+ * Secure-by-default guard. Pass it to `createApp` as the `guard` option: it then runs for every
117
+ * route the app registers and for unknown paths, and for the docs with `docs.access: "auth"`.
118
+ * `/health`, `/ready` and `/version` stay outside it. `app.use(requireAuth(...))` also works, but
119
+ * only protects the routes registered after that call.
120
+ *
121
+ * - Public routes (matched route pattern listed in `public`): no authentication is attempted and
122
+ * `c.var.identity` is `undefined`.
123
+ * - Optional routes (listed in `optional`): the authenticator runs. Success sets
124
+ * `c.var.identity`; `missing` continues with `c.var.identity` `undefined`; `invalid` and
125
+ * `expired` are a `401`, as on a protected route.
126
+ * - Everything else, unknown paths included: authenticates. On success `c.var.identity` is set;
127
+ * on failure it answers `401 UNAUTHORIZED` with a generic message and logs the reason at
128
+ * `info`. A rejection from the authenticator is a generic `503` (its cause logged at `error`),
129
+ * never a pass.
130
+ *
131
+ * In the generated OpenAPI spec, protected operations get the 401, 403 and 503 responses and,
132
+ * with `securitySchemes`, a `security` naming them; optional ones get the 401 and 503 responses
133
+ * and the same `security` plus the empty requirement `{}`; public ones get none of those
134
+ * responses and, once some guard registered a scheme, `security: []`.
135
+ *
136
+ * Throws at creation on a malformed `public` or `optional` entry, a route listed in both, an
137
+ * invalid security scheme or a requirement naming an unknown scheme.
138
+ */
139
+ export function requireAuth(options) {
140
+ if (typeof options?.authenticator !== "function") {
141
+ throw new Error("requireAuth: authenticator must be a function of the context, " +
142
+ "e.g. `authenticator: (c) => c.var.adapters.auth`.");
143
+ }
144
+ const select = options.authenticator;
145
+ const publicKeys = parseRoutes("public", options.public);
146
+ const optionalKeys = parseRoutes("optional", options.optional);
147
+ for (const key of optionalKeys) {
148
+ if (publicKeys.has(key)) {
149
+ throw new Error(`requireAuth: ${JSON.stringify(key)} is in both public and optional; list it in one.`);
150
+ }
151
+ }
152
+ const guard = async (c, next) => {
153
+ const access = accessOf(c, publicKeys, optionalKeys, guard);
154
+ if (access === "public") {
155
+ c.set("identity", undefined);
156
+ await next();
157
+ return;
158
+ }
159
+ // The context is the app's (typed `E` by the caller); only `identity` and `logger` are
160
+ // read or written here.
161
+ const authenticator = select(c);
162
+ let result;
163
+ try {
164
+ result = await authenticator.authenticate(c.req.raw);
165
+ }
166
+ catch (cause) {
167
+ // Infrastructure failure (e.g. key fetch): never a pass. Logged here, without credentials.
168
+ // Core's error handler logs the 503 with its cause chain, so the rejection itself is never
169
+ // attached (its message, stack or own cause may hold the token): only what is logged here.
170
+ const rejection = describeRejection(cause);
171
+ c.var.logger?.error("authenticator failed", { cause: rejection });
172
+ throw new ServiceUnavailableError(undefined, { cause: safeRejection(rejection) });
173
+ }
174
+ if (typeof result === "object" && result !== null && "ok" in result) {
175
+ if (result.ok === true && "identity" in result) {
176
+ const identity = toIdentity(result.identity);
177
+ if (identity) {
178
+ c.set("identity", identity);
179
+ await next();
180
+ return;
181
+ }
182
+ }
183
+ else if (result.ok === false && "reason" in result && isAuthFailure(result.reason)) {
184
+ // Only the absence of a credential is anonymous; a bad one is never downgraded.
185
+ if (access === "optional" && result.reason === "missing") {
186
+ c.set("identity", undefined);
187
+ await next();
188
+ return;
189
+ }
190
+ c.var.logger?.info("authentication failed", { reason: result.reason });
191
+ throw new UnauthorizedError();
192
+ }
193
+ }
194
+ // A broken authenticator is a programming error: generic 500, never a pass.
195
+ throw new Error("requireAuth: the authenticator returned a malformed AuthResult.");
196
+ };
197
+ // For the spec: what a protected or optional operation can answer (core adds the 403 to
198
+ // protected ones only), its schemes, and the public and optional routes (the same lists and
199
+ // the same per-route matching the guard applies above).
200
+ documentMiddleware(guard, {
201
+ errors: ["UNAUTHORIZED", "SERVICE_UNAVAILABLE"],
202
+ security: {
203
+ schemes: options.securitySchemes ?? {},
204
+ ...(options.securityRequirements === undefined
205
+ ? {}
206
+ : { requirements: options.securityRequirements }),
207
+ // Hono answers HEAD with GET routes, so a public GET covers HEAD here as at runtime.
208
+ isPublic: (method, path) => publicKeys.has(`${method === "HEAD" ? "GET" : method} ${path}`),
209
+ isOptional: (method, path) => optionalKeys.has(`${method === "HEAD" ? "GET" : method} ${path}`),
210
+ },
211
+ });
212
+ return guard;
213
+ }
214
+ //# sourceMappingURL=require-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-auth.js","sourceRoot":"","sources":["../src/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAGlB,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAqC,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AA6C7F,gGAAgG;AAChG,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC;IAClD,KAAK;IACL,MAAM;IACN,KAAK;IACL,OAAO;IACP,QAAQ;IACR,SAAS;CACV,CAAC,CAAC;AACH,MAAM,YAAY,GAAG,uBAAuB,CAAC;AAC7C,iDAAiD;AACjD,MAAM,UAAU,GAAG,KAAK,CAAC;AAEzB,SAAS,WAAW,CAAC,IAA2B,EAAE,OAAgB;IAChE,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,IAAI,GAAG,EAAE,CAAC;IAC5C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,gBAAgB,IAAI,iDAAiD,CAAC,CAAC;IACzF,CAAC;IACD,MAAM,IAAI,GAAG,I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C3B,YAAY,CAAC,GAAG,CAAC,GAAG,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;SACpE;KACF,CAAC,CAAC;IACH,OAAO,KAA2E,CAAC;AACrF,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { Authenticator, Identity } from "./identity.js";
2
+ export interface StaticAuthenticatorOptions {
3
+ /** Bearer token → the identity it authenticates. */
4
+ readonly tokens: Readonly<Record<string, Identity>>;
5
+ /** Header that carries `Bearer <token>`. Default: `"authorization"`. */
6
+ readonly header?: string;
7
+ }
8
+ /**
9
+ * **Test-only.** Authenticates `Bearer <token>` against a fixed table. A missing (or empty)
10
+ * header is `missing`; anything else that does not match is `invalid`. There is no expiry.
11
+ *
12
+ * Tokens are compared as SHA-256 digests with core's `timingSafeEqual`, against every
13
+ * configured token (no early exit), so timing reveals neither the token nor which one matched.
14
+ */
15
+ export declare function staticAuthenticator(options: StaticAuthenticatorOptions): Authenticator;
16
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAc,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzE,MAAM,WAAW,0BAA0B;IACzC,oDAAoD;IACpD,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IACpD,wEAAwE;IACxE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAUD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,aAAa,CAgDtF"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Test-only authenticator. Never use it in production: tokens are fixed strings in code.
3
+ * Import it from `@cardonjs/auth/testing`.
4
+ */
5
+ import { timingSafeEqual } from "@cardonjs/core";
6
+ import { toIdentity } from "./identity.js";
7
+ const BEARER = /^Bearer +(\S+)$/i;
8
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
9
+ const encoder = new TextEncoder();
10
+ async function sha256(value) {
11
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
12
+ }
13
+ /**
14
+ * **Test-only.** Authenticates `Bearer <token>` against a fixed table. A missing (or empty)
15
+ * header is `missing`; anything else that does not match is `invalid`. There is no expiry.
16
+ *
17
+ * Tokens are compared as SHA-256 digests with core's `timingSafeEqual`, against every
18
+ * configured token (no early exit), so timing reveals neither the token nor which one matched.
19
+ */
20
+ export function staticAuthenticator(options) {
21
+ const header = options?.header ?? "authorization";
22
+ if (typeof header !== "string" || !HEADER_NAME.test(header)) {
23
+ throw new Error("staticAuthenticator: header must be a valid HTTP header name.");
24
+ }
25
+ if (typeof options.tokens !== "object" || options.tokens === null) {
26
+ throw new Error("staticAuthenticator: tokens must be an object of token → identity.");
27
+ }
28
+ const table = [];
29
+ for (const [token, value] of Object.entries(options.tokens)) {
30
+ if (token === "" || /\s/.test(token)) {
31
+ throw new Error("staticAuthenticator: tokens must be non-empty and without whitespace.");
32
+ }
33
+ const identity = toIdentity(value);
34
+ if (!identity) {
35
+ throw new Error("staticAuthenticator: every token must map to a well-formed Identity.");
36
+ }
37
+ table.push([token, identity]);
38
+ }
39
+ // Digests are computed once, on first use (creation does no async work).
40
+ let digests;
41
+ const loadDigests = () => {
42
+ digests ??= Promise.all(table.map(async ([token, identity]) => [
43
+ await sha256(token),
44
+ identity,
45
+ ]));
46
+ return digests;
47
+ };
48
+ return {
49
+ async authenticate(request) {
50
+ const value = request.headers.get(header);
51
+ if (value === null || value === "")
52
+ return { ok: false, reason: "missing" };
53
+ const token = BEARER.exec(value)?.[1];
54
+ if (token === undefined)
55
+ return { ok: false, reason: "invalid" };
56
+ const given = await sha256(token);
57
+ let match;
58
+ for (const [digest, identity] of await loadDigests()) {
59
+ const equal = timingSafeEqual(digest, given);
60
+ match = equal ? identity : match;
61
+ }
62
+ return match ? { ok: true, identity: match } : { ok: false, reason: "invalid" };
63
+ },
64
+ };
65
+ }
66
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEjD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAS3C,MAAM,MAAM,GAAG,kBAAkB,CAAC;AAClC,MAAM,WAAW,GAAG,+BAA+B,CAAC;AACpD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,KAAK,UAAU,MAAM,CAAC,KAAa;IACjC,OAAO,IAAI,UAAU,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACtF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAmC;IACrE,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,IAAI,eAAe,CAAC;IAClD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,+DAA+D,CAAC,CAAC;IACnF,CAAC;IACD,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;IACxF,CAAC;IACD,MAAM,KAAK,GAAyB,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,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