@lunora/cloudflare-access 0.0.1 → 1.0.0-alpha.2

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,36 @@
1
+ import { A as AccessClaims, R as RequestVerifyOptions } from "./packem_shared/types.d-BO8d74KI.mjs";
2
+ import 'jose';
3
+ /** Options for {@link accessAdminGate}; extends {@link RequestVerifyOptions}. */
4
+ interface AccessAdminGateOptions extends RequestVerifyOptions {
5
+ /**
6
+ * Decide whether the **verified** claims authorize the Studio/admin plane —
7
+ * e.g. `(claims) => claims.groups?.includes("ops") ?? false` or an email-domain
8
+ * check. Required: there is no implicit grant, so a verified-but-unprivileged
9
+ * identity is denied. Runs only after signature/issuer/audience/expiry pass.
10
+ */
11
+ isAdmin: (claims: AccessClaims) => boolean | Promise<boolean>;
12
+ }
13
+ /**
14
+ * Build an admin gate for `@lunora/runtime`'s `WorkerOptions.adminGate`: a
15
+ * request-only predicate that verifies the request's `Cf-Access-Jwt-Assertion`
16
+ * JWT and applies your `isAdmin(claims)` test. When it resolves `true` the
17
+ * request authorizes the `/_lunora/admin/*` plane (the Studio's HTTP + WS
18
+ * endpoints) in addition to — or instead of — the static admin bearer, so the
19
+ * Studio can sit behind Cloudflare Access.
20
+ *
21
+ * It is **fail-closed**: a missing token, a token that fails verification, or an
22
+ * `isAdmin` that returns `false` all resolve to `false` (the bearer remains the
23
+ * only other path). Verification needs no `env` binding (static team-domain/aud
24
+ * config + the remote JWKS over `fetch`), so the gate takes only the request and
25
+ * the runtime can evaluate it without threading async through every admin route.
26
+ *
27
+ * ```ts
28
+ * options.adminGate = accessAdminGate({
29
+ * teamDomain: env.CF_ACCESS_TEAM_DOMAIN,
30
+ * aud: env.CF_ACCESS_ADMIN_AUD,
31
+ * isAdmin: (claims) => claims.groups?.includes("lunora-admins") ?? false,
32
+ * });
33
+ * ```
34
+ */
35
+ declare const accessAdminGate: (options: AccessAdminGateOptions) => ((request: Request) => Promise<boolean>);
36
+ export { type AccessAdminGateOptions, accessAdminGate };
@@ -0,0 +1,36 @@
1
+ import { A as AccessClaims, R as RequestVerifyOptions } from "./packem_shared/types.d-BO8d74KI.js";
2
+ import 'jose';
3
+ /** Options for {@link accessAdminGate}; extends {@link RequestVerifyOptions}. */
4
+ interface AccessAdminGateOptions extends RequestVerifyOptions {
5
+ /**
6
+ * Decide whether the **verified** claims authorize the Studio/admin plane —
7
+ * e.g. `(claims) => claims.groups?.includes("ops") ?? false` or an email-domain
8
+ * check. Required: there is no implicit grant, so a verified-but-unprivileged
9
+ * identity is denied. Runs only after signature/issuer/audience/expiry pass.
10
+ */
11
+ isAdmin: (claims: AccessClaims) => boolean | Promise<boolean>;
12
+ }
13
+ /**
14
+ * Build an admin gate for `@lunora/runtime`'s `WorkerOptions.adminGate`: a
15
+ * request-only predicate that verifies the request's `Cf-Access-Jwt-Assertion`
16
+ * JWT and applies your `isAdmin(claims)` test. When it resolves `true` the
17
+ * request authorizes the `/_lunora/admin/*` plane (the Studio's HTTP + WS
18
+ * endpoints) in addition to — or instead of — the static admin bearer, so the
19
+ * Studio can sit behind Cloudflare Access.
20
+ *
21
+ * It is **fail-closed**: a missing token, a token that fails verification, or an
22
+ * `isAdmin` that returns `false` all resolve to `false` (the bearer remains the
23
+ * only other path). Verification needs no `env` binding (static team-domain/aud
24
+ * config + the remote JWKS over `fetch`), so the gate takes only the request and
25
+ * the runtime can evaluate it without threading async through every admin route.
26
+ *
27
+ * ```ts
28
+ * options.adminGate = accessAdminGate({
29
+ * teamDomain: env.CF_ACCESS_TEAM_DOMAIN,
30
+ * aud: env.CF_ACCESS_ADMIN_AUD,
31
+ * isAdmin: (claims) => claims.groups?.includes("lunora-admins") ?? false,
32
+ * });
33
+ * ```
34
+ */
35
+ declare const accessAdminGate: (options: AccessAdminGateOptions) => ((request: Request) => Promise<boolean>);
36
+ export { type AccessAdminGateOptions, accessAdminGate };
package/dist/admin.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import { verifyRequest } from './packem_shared/accessIssuer-DhKaNoyU.mjs';
2
+
3
+ const accessAdminGate = (options) => async (request) => {
4
+ const claims = await verifyRequest(request, options);
5
+ return claims === void 0 ? false : options.isAdmin(claims);
6
+ };
7
+
8
+ export { accessAdminGate };
@@ -0,0 +1,79 @@
1
+ import { M as Middleware } from "./packem_shared/index.d-C7lOF4ZA.mjs";
2
+ import { A as AccessClaims } from "./packem_shared/types.d-BO8d74KI.mjs";
3
+ import 'jose';
4
+ /**
5
+ * The slice of context {@link accessContext} reads: the `auth` facade every
6
+ * Lunora ctx carries. `getIdentity()` returns the verified identity envelope —
7
+ * `createAccessResolver`'s {@link import("./types").ResolvedAccessIdentity}
8
+ * output, which carries the full claim set under `access` plus the promoted
9
+ * `email` / `groups` / `commonName` fields.
10
+ */
11
+ interface AccessContextInput {
12
+ auth?: {
13
+ getIdentity?: () => (Record<string, unknown> | null) | Promise<Record<string, unknown> | null>;
14
+ userId?: string | null;
15
+ };
16
+ }
17
+ /**
18
+ * The typed, per-request `ctx.access` facade {@link accessContext} attaches. A
19
+ * synchronous, Access-shaped read over the already-resolved identity — so a
20
+ * handler reads `ctx.access.email` / `ctx.access.hasGroup("ops")` without an
21
+ * `await` or a cast off the generic `ctx.auth.getIdentity()` envelope.
22
+ */
23
+ interface AccessFacade {
24
+ /** True when a verified Access identity is present on the request. */
25
+ readonly authenticated: boolean;
26
+ /** The full verified claim set, or `undefined` when anonymous. */
27
+ readonly claims: AccessClaims | undefined;
28
+ /** Service-token name (`common_name`), for machine callers; `undefined` otherwise. */
29
+ readonly commonName: string | undefined;
30
+ /** Verified SSO email; `undefined` for service tokens or anonymous requests. */
31
+ readonly email: string | undefined;
32
+ /** IdP group memberships — empty when none are emitted or the request is anonymous. */
33
+ readonly groups: ReadonlyArray<string>;
34
+ /** True when the verified groups include `group`. Always `false` when anonymous. */
35
+ hasGroup: (group: string) => boolean;
36
+ /** The stable caller id (`ctx.auth.userId`), or `undefined` when anonymous. */
37
+ readonly userId: string | undefined;
38
+ }
39
+ /** The context shape {@link accessContext} produces — the input widened with `access`. */
40
+ interface AccessContextOutput extends AccessContextInput {
41
+ access: AccessFacade;
42
+ }
43
+ /**
44
+ * Build the `ctx.access` facade from a (possibly absent) resolved identity
45
+ * envelope. Returns the anonymous facade when no identity is present, so callers
46
+ * never null-check. Shared by {@link accessContext} and the codegen-wired global
47
+ * `ctx.access` (which calls this synchronously from the resolved identity locals
48
+ * at ctx-build time, so a global `ctx.access` adds only this object construction
49
+ * per request — no extra I/O or re-verification).
50
+ */
51
+ declare const accessFacade: (identity: Record<string, unknown> | null | undefined, userId: string | null | undefined) => AccessFacade;
52
+ /**
53
+ * Middleware that attaches a typed `ctx.access` facade derived from the verified
54
+ * Cloudflare Access identity. It resolves `ctx.auth.getIdentity()` once and
55
+ * exposes a **synchronous**, Access-shaped read — `ctx.access.email`,
56
+ * `ctx.access.groups`, `ctx.access.hasGroup("ops")`, `ctx.access.claims` — so a
57
+ * handler reads the verified identity ergonomically and with full typing instead
58
+ * of casting off the generic `getIdentity()` envelope.
59
+ *
60
+ * When no identity is resolved (anonymous request) it attaches the anonymous
61
+ * facade — `authenticated: false`, empty `groups`, `hasGroup` always `false` —
62
+ * so reads stay safe without a null check, and authorization decisions still
63
+ * fail closed.
64
+ *
65
+ * It does not gate the request; pair it with `rls(...)` (or
66
+ * `accessRoles(...)` → `rls(...)`) when you need enforcement. It only surfaces
67
+ * the identity for branching inside a handler.
68
+ *
69
+ * ```ts
70
+ * export const whoAmI = query
71
+ * .use(accessContext())
72
+ * .query(async ({ ctx }) => ({
73
+ * email: ctx.access.email,
74
+ * isOps: ctx.access.hasGroup("ops"),
75
+ * }));
76
+ * ```
77
+ */
78
+ declare const accessContext: <Context extends AccessContextInput>() => Middleware<Context, AccessContextOutput & Context>;
79
+ export { type AccessContextInput, type AccessContextOutput, type AccessFacade, accessContext, accessFacade };
@@ -0,0 +1,79 @@
1
+ import { M as Middleware } from "./packem_shared/index.d-C7lOF4ZA.js";
2
+ import { A as AccessClaims } from "./packem_shared/types.d-BO8d74KI.js";
3
+ import 'jose';
4
+ /**
5
+ * The slice of context {@link accessContext} reads: the `auth` facade every
6
+ * Lunora ctx carries. `getIdentity()` returns the verified identity envelope —
7
+ * `createAccessResolver`'s {@link import("./types").ResolvedAccessIdentity}
8
+ * output, which carries the full claim set under `access` plus the promoted
9
+ * `email` / `groups` / `commonName` fields.
10
+ */
11
+ interface AccessContextInput {
12
+ auth?: {
13
+ getIdentity?: () => (Record<string, unknown> | null) | Promise<Record<string, unknown> | null>;
14
+ userId?: string | null;
15
+ };
16
+ }
17
+ /**
18
+ * The typed, per-request `ctx.access` facade {@link accessContext} attaches. A
19
+ * synchronous, Access-shaped read over the already-resolved identity — so a
20
+ * handler reads `ctx.access.email` / `ctx.access.hasGroup("ops")` without an
21
+ * `await` or a cast off the generic `ctx.auth.getIdentity()` envelope.
22
+ */
23
+ interface AccessFacade {
24
+ /** True when a verified Access identity is present on the request. */
25
+ readonly authenticated: boolean;
26
+ /** The full verified claim set, or `undefined` when anonymous. */
27
+ readonly claims: AccessClaims | undefined;
28
+ /** Service-token name (`common_name`), for machine callers; `undefined` otherwise. */
29
+ readonly commonName: string | undefined;
30
+ /** Verified SSO email; `undefined` for service tokens or anonymous requests. */
31
+ readonly email: string | undefined;
32
+ /** IdP group memberships — empty when none are emitted or the request is anonymous. */
33
+ readonly groups: ReadonlyArray<string>;
34
+ /** True when the verified groups include `group`. Always `false` when anonymous. */
35
+ hasGroup: (group: string) => boolean;
36
+ /** The stable caller id (`ctx.auth.userId`), or `undefined` when anonymous. */
37
+ readonly userId: string | undefined;
38
+ }
39
+ /** The context shape {@link accessContext} produces — the input widened with `access`. */
40
+ interface AccessContextOutput extends AccessContextInput {
41
+ access: AccessFacade;
42
+ }
43
+ /**
44
+ * Build the `ctx.access` facade from a (possibly absent) resolved identity
45
+ * envelope. Returns the anonymous facade when no identity is present, so callers
46
+ * never null-check. Shared by {@link accessContext} and the codegen-wired global
47
+ * `ctx.access` (which calls this synchronously from the resolved identity locals
48
+ * at ctx-build time, so a global `ctx.access` adds only this object construction
49
+ * per request — no extra I/O or re-verification).
50
+ */
51
+ declare const accessFacade: (identity: Record<string, unknown> | null | undefined, userId: string | null | undefined) => AccessFacade;
52
+ /**
53
+ * Middleware that attaches a typed `ctx.access` facade derived from the verified
54
+ * Cloudflare Access identity. It resolves `ctx.auth.getIdentity()` once and
55
+ * exposes a **synchronous**, Access-shaped read — `ctx.access.email`,
56
+ * `ctx.access.groups`, `ctx.access.hasGroup("ops")`, `ctx.access.claims` — so a
57
+ * handler reads the verified identity ergonomically and with full typing instead
58
+ * of casting off the generic `getIdentity()` envelope.
59
+ *
60
+ * When no identity is resolved (anonymous request) it attaches the anonymous
61
+ * facade — `authenticated: false`, empty `groups`, `hasGroup` always `false` —
62
+ * so reads stay safe without a null check, and authorization decisions still
63
+ * fail closed.
64
+ *
65
+ * It does not gate the request; pair it with `rls(...)` (or
66
+ * `accessRoles(...)` → `rls(...)`) when you need enforcement. It only surfaces
67
+ * the identity for branching inside a handler.
68
+ *
69
+ * ```ts
70
+ * export const whoAmI = query
71
+ * .use(accessContext())
72
+ * .query(async ({ ctx }) => ({
73
+ * email: ctx.access.email,
74
+ * isOps: ctx.access.hasGroup("ops"),
75
+ * }));
76
+ * ```
77
+ */
78
+ declare const accessContext: <Context extends AccessContextInput>() => Middleware<Context, AccessContextOutput & Context>;
79
+ export { type AccessContextInput, type AccessContextOutput, type AccessFacade, accessContext, accessFacade };
@@ -0,0 +1,36 @@
1
+ const stringList = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
2
+ const stringClaim = (value) => typeof value === "string" ? value : void 0;
3
+ const ANONYMOUS_FACADE = {
4
+ authenticated: false,
5
+ claims: void 0,
6
+ commonName: void 0,
7
+ email: void 0,
8
+ groups: [],
9
+ hasGroup: () => false,
10
+ userId: void 0
11
+ };
12
+ const facadeFor = (identity, userId) => {
13
+ const raw = identity["access"];
14
+ if (typeof raw !== "object" || raw === null) {
15
+ return ANONYMOUS_FACADE;
16
+ }
17
+ const claims = raw;
18
+ const groups = stringList(identity["groups"] ?? claims.groups);
19
+ return {
20
+ authenticated: true,
21
+ claims,
22
+ commonName: stringClaim(identity["commonName"]) ?? stringClaim(claims.common_name),
23
+ email: stringClaim(identity["email"]) ?? stringClaim(claims.email),
24
+ groups,
25
+ hasGroup: (group) => groups.includes(group),
26
+ userId
27
+ };
28
+ };
29
+ const accessFacade = (identity, userId) => identity ? facadeFor(identity, userId ?? void 0) : ANONYMOUS_FACADE;
30
+ const accessContext = () => async ({ ctx, next }) => {
31
+ const identity = await ctx.auth?.getIdentity?.();
32
+ const access = accessFacade(identity, ctx.auth?.userId);
33
+ return next({ ctx: { access } });
34
+ };
35
+
36
+ export { accessContext, accessFacade };
@@ -0,0 +1,71 @@
1
+ import { a as ResolveIdentityFunction, C as CreateAccessResolverOptions, V as VerifyAccessJwtOptions, A as AccessClaims } from "./packem_shared/types.d-BO8d74KI.mjs";
2
+ export type { b as AccessKeySet, c as ResolvedAccessIdentity, d as ResolvedIdentityLike } from "./packem_shared/types.d-BO8d74KI.mjs";
3
+ import 'jose';
4
+ /**
5
+ * Create a `resolveIdentity` adapter for Cloudflare Access. The returned
6
+ * function reads the Access JWT off the request, verifies it (`verifyAccessJwt`),
7
+ * and maps the claims onto the identity shape `@lunora/runtime` expects — so a
8
+ * verified Access user/service-token becomes `ctx.auth` for every
9
+ * query/mutation/action (and feeds RLS) with no further wiring.
10
+ *
11
+ * Behaviour is **fail-closed → anonymous**: a missing token, or a token that
12
+ * fails verification, resolves to `null` (the request proceeds unauthenticated
13
+ * and RLS denies). Use {@link CreateAccessResolverOptions.onError} to observe
14
+ * verification failures.
15
+ *
16
+ * Wire it in your worker entry:
17
+ *
18
+ * ```ts
19
+ * options.resolveIdentity = createAccessResolver({
20
+ * teamDomain: env.CF_ACCESS_TEAM_DOMAIN, // "acme" | "acme.cloudflareaccess.com"
21
+ * aud: env.CF_ACCESS_AUD, // the Access app's AUD tag
22
+ * });
23
+ * ```
24
+ */
25
+ declare const createAccessResolver: (options: CreateAccessResolverOptions) => ResolveIdentityFunction;
26
+ /**
27
+ * Compose several `resolveIdentity` adapters into one: each is tried in order
28
+ * and the first to return a non-null identity wins. The canonical use is
29
+ * pairing Access with `@lunora/auth` —
30
+ * `composeResolvers(accessResolver, betterAuthResolver)` — so a request carrying
31
+ * an Access JWT (machine/SSO) is authenticated by Access while everyone else
32
+ * falls through to the app's own session.
33
+ */
34
+ declare const composeResolvers: (...resolvers: ResolveIdentityFunction[]) => ResolveIdentityFunction;
35
+ /**
36
+ * Normalize a configured team domain to the canonical Access issuer URL.
37
+ *
38
+ * Accepts a short team name (`acme`), a host (`acme.cloudflareaccess.com`), or a
39
+ * full URL, and always returns an `https://` origin with no trailing slash. A
40
+ * bare name with no dot is expanded to the `cloudflareaccess.com` host.
41
+ */
42
+ declare const accessIssuer: (teamDomain: string) => string;
43
+ /**
44
+ * Verify a Cloudflare Access JWT and return its claims.
45
+ *
46
+ * Enforces, in one shot: RS256 signature against the team JWKS, `iss` equal to
47
+ * the team issuer, `aud` containing one of the configured Access application AUD
48
+ * tags, and a non-expired `exp` (with optional clock tolerance). The algorithm
49
+ * is pinned to `RS256` so an `alg:none` or HS-signed forgery is rejected
50
+ * outright.
51
+ *
52
+ * Throws (a `jose` error) on any failure — callers that want fail-closed
53
+ * anonymous behaviour should catch and treat it as "no identity" (the
54
+ * `createAccessResolver` adapter does exactly this).
55
+ * @param token The raw compact JWT (header value or cookie value).
56
+ */
57
+ declare const verifyAccessJwt: (token: string, options: VerifyAccessJwtOptions) => Promise<AccessClaims>;
58
+ /**
59
+ * Read the Access JWT off a request and verify it. Returns the verified claims,
60
+ * or `undefined` when no token is present **or** verification fails — the single
61
+ * fail-closed "no Access identity" signal that both `createAccessResolver` and
62
+ * `accessAdminGate` build their distinct mapping / authorization step on top of.
63
+ *
64
+ * This is the package's one place that turns a request into verified claims:
65
+ * header/cookie default resolution, the {@link readToken} read, the
66
+ * {@link verifyAccessJwt} call, and the `onError`-observed fail-closed catch all
67
+ * live here so the resolver and the admin gate carry only their genuinely
68
+ * distinct line. `onError` fires for a present-but-invalid token, never for an
69
+ * absent one.
70
+ */
71
+ export { type AccessClaims, type CreateAccessResolverOptions, type ResolveIdentityFunction, type VerifyAccessJwtOptions, accessIssuer, composeResolvers, createAccessResolver, verifyAccessJwt };
@@ -0,0 +1,71 @@
1
+ import { a as ResolveIdentityFunction, C as CreateAccessResolverOptions, V as VerifyAccessJwtOptions, A as AccessClaims } from "./packem_shared/types.d-BO8d74KI.js";
2
+ export type { b as AccessKeySet, c as ResolvedAccessIdentity, d as ResolvedIdentityLike } from "./packem_shared/types.d-BO8d74KI.js";
3
+ import 'jose';
4
+ /**
5
+ * Create a `resolveIdentity` adapter for Cloudflare Access. The returned
6
+ * function reads the Access JWT off the request, verifies it (`verifyAccessJwt`),
7
+ * and maps the claims onto the identity shape `@lunora/runtime` expects — so a
8
+ * verified Access user/service-token becomes `ctx.auth` for every
9
+ * query/mutation/action (and feeds RLS) with no further wiring.
10
+ *
11
+ * Behaviour is **fail-closed → anonymous**: a missing token, or a token that
12
+ * fails verification, resolves to `null` (the request proceeds unauthenticated
13
+ * and RLS denies). Use {@link CreateAccessResolverOptions.onError} to observe
14
+ * verification failures.
15
+ *
16
+ * Wire it in your worker entry:
17
+ *
18
+ * ```ts
19
+ * options.resolveIdentity = createAccessResolver({
20
+ * teamDomain: env.CF_ACCESS_TEAM_DOMAIN, // "acme" | "acme.cloudflareaccess.com"
21
+ * aud: env.CF_ACCESS_AUD, // the Access app's AUD tag
22
+ * });
23
+ * ```
24
+ */
25
+ declare const createAccessResolver: (options: CreateAccessResolverOptions) => ResolveIdentityFunction;
26
+ /**
27
+ * Compose several `resolveIdentity` adapters into one: each is tried in order
28
+ * and the first to return a non-null identity wins. The canonical use is
29
+ * pairing Access with `@lunora/auth` —
30
+ * `composeResolvers(accessResolver, betterAuthResolver)` — so a request carrying
31
+ * an Access JWT (machine/SSO) is authenticated by Access while everyone else
32
+ * falls through to the app's own session.
33
+ */
34
+ declare const composeResolvers: (...resolvers: ResolveIdentityFunction[]) => ResolveIdentityFunction;
35
+ /**
36
+ * Normalize a configured team domain to the canonical Access issuer URL.
37
+ *
38
+ * Accepts a short team name (`acme`), a host (`acme.cloudflareaccess.com`), or a
39
+ * full URL, and always returns an `https://` origin with no trailing slash. A
40
+ * bare name with no dot is expanded to the `cloudflareaccess.com` host.
41
+ */
42
+ declare const accessIssuer: (teamDomain: string) => string;
43
+ /**
44
+ * Verify a Cloudflare Access JWT and return its claims.
45
+ *
46
+ * Enforces, in one shot: RS256 signature against the team JWKS, `iss` equal to
47
+ * the team issuer, `aud` containing one of the configured Access application AUD
48
+ * tags, and a non-expired `exp` (with optional clock tolerance). The algorithm
49
+ * is pinned to `RS256` so an `alg:none` or HS-signed forgery is rejected
50
+ * outright.
51
+ *
52
+ * Throws (a `jose` error) on any failure — callers that want fail-closed
53
+ * anonymous behaviour should catch and treat it as "no identity" (the
54
+ * `createAccessResolver` adapter does exactly this).
55
+ * @param token The raw compact JWT (header value or cookie value).
56
+ */
57
+ declare const verifyAccessJwt: (token: string, options: VerifyAccessJwtOptions) => Promise<AccessClaims>;
58
+ /**
59
+ * Read the Access JWT off a request and verify it. Returns the verified claims,
60
+ * or `undefined` when no token is present **or** verification fails — the single
61
+ * fail-closed "no Access identity" signal that both `createAccessResolver` and
62
+ * `accessAdminGate` build their distinct mapping / authorization step on top of.
63
+ *
64
+ * This is the package's one place that turns a request into verified claims:
65
+ * header/cookie default resolution, the {@link readToken} read, the
66
+ * {@link verifyAccessJwt} call, and the `onError`-observed fail-closed catch all
67
+ * live here so the resolver and the admin gate carry only their genuinely
68
+ * distinct line. `onError` fires for a present-but-invalid token, never for an
69
+ * absent one.
70
+ */
71
+ export { type AccessClaims, type CreateAccessResolverOptions, type ResolveIdentityFunction, type VerifyAccessJwtOptions, accessIssuer, composeResolvers, createAccessResolver, verifyAccessJwt };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export { composeResolvers, createAccessResolver } from './packem_shared/composeResolvers-C_7T5dDj.mjs';
2
+ export { accessIssuer, verifyAccessJwt } from './packem_shared/accessIssuer-DhKaNoyU.mjs';
@@ -0,0 +1,91 @@
1
+ import { jwtVerify, createRemoteJWKSet } from 'jose';
2
+
3
+ const DEFAULT_HEADER = "cf-access-jwt-assertion";
4
+ const DEFAULT_COOKIE = "CF_Authorization";
5
+ const readToken = (request, headerName, cookieName) => {
6
+ const headerValue = request.headers.get(headerName);
7
+ if (headerValue !== null && headerValue.length > 0) {
8
+ return headerValue;
9
+ }
10
+ const cookieHeader = request.headers.get("cookie");
11
+ if (cookieHeader === null) {
12
+ return void 0;
13
+ }
14
+ for (const part of cookieHeader.split(";")) {
15
+ const eq = part.indexOf("=");
16
+ if (eq === -1) {
17
+ continue;
18
+ }
19
+ if (part.slice(0, eq).trim() === cookieName) {
20
+ const value = part.slice(eq + 1).trim();
21
+ return value.length > 0 ? value : void 0;
22
+ }
23
+ }
24
+ return void 0;
25
+ };
26
+
27
+ const CERTS_PATH = "/cdn-cgi/access/certs";
28
+ const SCHEME_PREFIX = /^https?:\/\//i;
29
+ const stripTrailingSlashes = (value) => {
30
+ let end = value.length;
31
+ while (end > 0 && value[end - 1] === "/") {
32
+ end -= 1;
33
+ }
34
+ return value.slice(0, end);
35
+ };
36
+ const accessIssuer = (teamDomain) => {
37
+ const trimmed = stripTrailingSlashes(teamDomain.trim().replace(SCHEME_PREFIX, ""));
38
+ if (trimmed.length === 0) {
39
+ throw new Error('@lunora/cloudflare-access: `teamDomain` is required (e.g. "acme" or "acme.cloudflareaccess.com")');
40
+ }
41
+ const candidate = trimmed.includes(".") ? `https://${trimmed}` : `https://${trimmed}.cloudflareaccess.com`;
42
+ const host = new URL(candidate).host.toLowerCase();
43
+ return `https://${host}`;
44
+ };
45
+ const jwksByIssuer = /* @__PURE__ */ new Map();
46
+ const remoteJwks = (issuer) => {
47
+ let getter = jwksByIssuer.get(issuer);
48
+ if (getter === void 0) {
49
+ getter = createRemoteJWKSet(new URL(`${issuer}${CERTS_PATH}`));
50
+ jwksByIssuer.set(issuer, getter);
51
+ }
52
+ return getter;
53
+ };
54
+ const verifyAccessJwt = async (token, options) => {
55
+ const issuer = accessIssuer(options.teamDomain);
56
+ const audiences = (Array.isArray(options.aud) ? options.aud : [options.aud]).filter(
57
+ (entry) => typeof entry === "string" && entry.length > 0
58
+ );
59
+ if (audiences.length === 0) {
60
+ throw new Error(
61
+ "@lunora/cloudflare-access: `aud` is required and must be a non-empty Access AUD tag — refusing to verify a token without an audience to scope it to your application"
62
+ );
63
+ }
64
+ const keySet = options.keySet ?? remoteJwks(issuer);
65
+ const { payload } = await jwtVerify(token, keySet, {
66
+ algorithms: ["RS256"],
67
+ audience: audiences,
68
+ clockTolerance: options.clockToleranceSec,
69
+ issuer
70
+ });
71
+ return payload;
72
+ };
73
+ const verifyRequest = async (request, options) => {
74
+ const headerName = (options.headerName ?? DEFAULT_HEADER).toLowerCase();
75
+ const cookieName = options.cookieName ?? DEFAULT_COOKIE;
76
+ const token = readToken(request, headerName, cookieName);
77
+ if (token === void 0) {
78
+ return void 0;
79
+ }
80
+ try {
81
+ return await verifyAccessJwt(token, options);
82
+ } catch (error) {
83
+ try {
84
+ options.onError?.(error, request);
85
+ } catch {
86
+ }
87
+ return void 0;
88
+ }
89
+ };
90
+
91
+ export { accessIssuer, verifyAccessJwt, verifyRequest };
@@ -0,0 +1,38 @@
1
+ import { verifyRequest } from './accessIssuer-DhKaNoyU.mjs';
2
+
3
+ const ANONYMOUS = null;
4
+ const deriveUserId = (claims) => {
5
+ const sub = typeof claims.sub === "string" && claims.sub.length > 0 ? claims.sub : void 0;
6
+ return sub ?? claims.email ?? claims.common_name;
7
+ };
8
+ const toIdentity = (claims, mapClaims) => {
9
+ const overrides = mapClaims?.(claims) ?? {};
10
+ const userId = typeof overrides.userId === "string" ? overrides.userId : deriveUserId(claims);
11
+ if (userId === void 0) {
12
+ return ANONYMOUS;
13
+ }
14
+ return {
15
+ access: claims,
16
+ ...claims.common_name === void 0 ? {} : { commonName: claims.common_name },
17
+ ...claims.email === void 0 ? {} : { email: claims.email },
18
+ ...claims.exp === void 0 ? {} : { exp: claims.exp },
19
+ ...claims.groups === void 0 ? {} : { groups: claims.groups },
20
+ ...overrides,
21
+ userId
22
+ };
23
+ };
24
+ const createAccessResolver = (options) => async (request) => {
25
+ const claims = await verifyRequest(request, options);
26
+ return claims === void 0 ? ANONYMOUS : toIdentity(claims, options.mapClaims);
27
+ };
28
+ const composeResolvers = (...resolvers) => async (request, env) => {
29
+ for (const resolve of resolvers) {
30
+ const identity = await resolve(request, env);
31
+ if (identity) {
32
+ return identity;
33
+ }
34
+ }
35
+ return ANONYMOUS;
36
+ };
37
+
38
+ export { composeResolvers, createAccessResolver };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `next()` advances the middleware chain. Called with no argument it forwards
3
+ * the current context unchanged; called with `{ ctx }` it shallow-merges the
4
+ * extension, and the result type reflects the widened context.
5
+ */
6
+ interface MiddlewareNext<ContextIn> {
7
+ (): Promise<ContextIn>;
8
+ <Extension extends Record<string, unknown>>(options: {
9
+ ctx: Extension;
10
+ }): Promise<ContextIn & Extension>;
11
+ }
12
+ /**
13
+ * A middleware receives the current context and a `next` continuation. Its
14
+ * return type becomes the builder's new context, so `return next({ ctx })`
15
+ * propagates the extension into every downstream `.use()` and the handler.
16
+ */
17
+ type Middleware<ContextIn, ContextOut> = (options: {
18
+ ctx: ContextIn;
19
+ next: MiddlewareNext<ContextIn>;
20
+ }) => ContextOut | Promise<ContextOut>;
21
+ /** Options accepted by `initLunora.dataModel&lt;DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
22
+ export { Middleware as M };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `next()` advances the middleware chain. Called with no argument it forwards
3
+ * the current context unchanged; called with `{ ctx }` it shallow-merges the
4
+ * extension, and the result type reflects the widened context.
5
+ */
6
+ interface MiddlewareNext<ContextIn> {
7
+ (): Promise<ContextIn>;
8
+ <Extension extends Record<string, unknown>>(options: {
9
+ ctx: Extension;
10
+ }): Promise<ContextIn & Extension>;
11
+ }
12
+ /**
13
+ * A middleware receives the current context and a `next` continuation. Its
14
+ * return type becomes the builder's new context, so `return next({ ctx })`
15
+ * propagates the extension into every downstream `.use()` and the handler.
16
+ */
17
+ type Middleware<ContextIn, ContextOut> = (options: {
18
+ ctx: ContextIn;
19
+ next: MiddlewareNext<ContextIn>;
20
+ }) => ContextOut | Promise<ContextOut>;
21
+ /** Options accepted by `initLunora.dataModel&lt;DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
22
+ export { Middleware as M };