workers-start 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0 (2026-11-20)
4
+
5
+ - `workers-start/access`: `verifyAccessToken(token, config)` checks a Cloudflare Access JWT (RS256 against the team's certs, issuer, audience, `exp`, `nbf`, then an email or service token allowlist) and returns a result with a `code` of `unconfigured`, `unauthenticated`, `forbidden` or `unavailable` instead of throwing. `parseAccessConfig`, `accessToken` (header, then cookie) and `createAccessVerifier` for a verifier with its own key cache and clock.
6
+ - `workers-start/access/testing`: `createTestAccessTeam()` makes a key pair, serves its certs and signs tokens, for tests of code that checks Access.
7
+
8
+ ## 0.7.1 (2026-11-20)
9
+
10
+ - Package metadata (`repository`, `homepage`, `bugs`) points at [ryanio/workers-kit](https://github.com/ryanio/workers-kit), where the package now lives. The first release published from there.
11
+
3
12
  ## 0.7.0 (2026-11-20)
4
13
 
5
14
  - `workers-start/cache`: `withEdgeCache(request, render, { version })` keeps rendered pages in the Workers Cache API by their `s-maxage`, with `sharedMaxAge` and `withoutBrowserMaxAge`.
package/README.md CHANGED
@@ -8,16 +8,18 @@ It has no runtime dependencies. Each piece is its own entry point, so an app tak
8
8
 
9
9
  Check this list before writing a helper in an app. Anything generic to TanStack Start on Workers that is missing belongs here, with a test, rather than in one app.
10
10
 
11
- | Entry point | Exports | For |
12
- | ---------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
13
- | `workers-start/entry` | `createEntry`, `withHeaders`, `wantsMarkdown`, `acceptsHtml` | The Worker entry: Markdown for agents, Accept fixes, 405s, headers on every response |
14
- | `workers-start/head` | `createPageHead`, `jsonLdScript` | Per-route head tags and escaped JSON-LD |
15
- | `workers-start/scripts` | `themeScript`, `analyticsScript`, `tagManagerScript`, `gaEvent`, `inlineJson` | Inline bootstraps, analytics events, JSON safe inside a script tag |
16
- | `workers-start/cache` | `withEdgeCache`, `sharedMaxAge`, `withoutBrowserMaxAge` | Rendered pages kept in the Workers Cache API |
17
- | `workers-start/workers` | `getBinding`, `getEnvString`, `afterResponse`, `isKvNamespace` | Bindings and `waitUntil` without a static `cloudflare:workers` import |
18
- | `workers-start/seo` | `sitemapXml`, `robotsTxt`, `escapeXml` | `/sitemap.xml` and `/robots.txt` bodies |
19
- | `workers-start/accept` | `parseAccept`, `quality` | Accept header parsing |
20
- | `workers-start/check-bundle` | `workers-start-check-bundle` (bin) | Fails a build that would ship a local secret |
11
+ | Entry point | Exports | For |
12
+ | ------------------------------ | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
13
+ | `workers-start/entry` | `createEntry`, `withHeaders`, `wantsMarkdown`, `acceptsHtml` | The Worker entry: Markdown for agents, Accept fixes, 405s, headers on every response |
14
+ | `workers-start/head` | `createPageHead`, `jsonLdScript` | Per-route head tags and escaped JSON-LD |
15
+ | `workers-start/scripts` | `themeScript`, `analyticsScript`, `tagManagerScript`, `gaEvent`, `inlineJson` | Inline bootstraps, analytics events, JSON safe inside a script tag |
16
+ | `workers-start/cache` | `withEdgeCache`, `sharedMaxAge`, `withoutBrowserMaxAge` | Rendered pages kept in the Workers Cache API |
17
+ | `workers-start/workers` | `getBinding`, `getEnvString`, `afterResponse`, `isKvNamespace` | Bindings and `waitUntil` without a static `cloudflare:workers` import |
18
+ | `workers-start/access` | `verifyAccessToken`, `createAccessVerifier`, `parseAccessConfig`, `accessToken` | Cloudflare Access sign-ins checked in the Worker, failing closed |
19
+ | `workers-start/access/testing` | `createTestAccessTeam` | A fake Access team for tests: keys, certs and signed tokens |
20
+ | `workers-start/seo` | `sitemapXml`, `robotsTxt`, `escapeXml` | `/sitemap.xml` and `/robots.txt` bodies |
21
+ | `workers-start/accept` | `parseAccept`, `quality` | Accept header parsing |
22
+ | `workers-start/check-bundle` | `workers-start-check-bundle` (bin) | Fails a build that would ship a local secret |
21
23
 
22
24
  ## Why
23
25
 
@@ -179,6 +181,59 @@ return withEdgeCache(request, () => handler.fetch(request), {
179
181
 
180
182
  A cache hit has its browser `max-age` removed (the zone adds one, and a browser holding page HTML that long outlives the next deploy's assets). The store runs after the response through `afterResponse`; pass `waitUntil` or `cache` to override, as tests do. Outside workerd every request renders.
181
183
 
184
+ ## Cloudflare Access
185
+
186
+ Access adds a signed JWT to every request it lets through, as the `Cf-Access-Jwt-Assertion` header and the `CF_Authorization` cookie. The header alone proves nothing: anyone can send it to the Worker's `workers.dev` or other hostnames, and paths Access does not cover (such as `/_serverFn`) never get one. `workers-start/access` checks the token itself, on WebCrypto with no dependencies: the RS256 signature against the team's published keys, the issuer, the audience, `exp` and `nbf` (60 seconds of leeway), then the email against an allowlist.
187
+
188
+ ```ts
189
+ import {
190
+ accessToken,
191
+ parseAccessConfig,
192
+ verifyAccessToken,
193
+ } from "workers-start/access";
194
+
195
+ const config = parseAccessConfig({
196
+ teamDomain: env.ACCESS_TEAM_DOMAIN, // myteam.cloudflareaccess.com
197
+ aud: env.ACCESS_AUD,
198
+ emails: env.ADMIN_EMAILS, // comma or space separated
199
+ });
200
+
201
+ const result = await verifyAccessToken(accessToken(request), config);
202
+ if (!result.ok) {
203
+ return Response.json({ error: { code: result.code, message: result.reason } }, {
204
+ status: result.status,
205
+ });
206
+ }
207
+ // result.email is the signed-in address, lowercased.
208
+ ```
209
+
210
+ Every failure is a result, never a throw:
211
+
212
+ | `code` | `status` | When |
213
+ | ----------------- | -------- | ----------------------------------------------------------------------- |
214
+ | `unconfigured` | 503 | `parseAccessConfig` returned null: a value is missing |
215
+ | `unauthenticated` | 401 | No token, a malformed one, or a bad signature, issuer, audience or time |
216
+ | `forbidden` | 403 | A valid token for an address or service token not on the list |
217
+ | `unavailable` | 503 | The team's certs could not be fetched and no keys are cached |
218
+
219
+ `parseAccessConfig` returns null unless it has a team domain, an audience and at least one allowed email or service token, so a missing secret refuses everyone instead of letting everyone in.
220
+
221
+ `verifyAccessToken` keeps the team's keys for an hour in the isolate. A token that names a key id it has not seen (Access rotates keys) refetches the certs, at most once a minute, so made-up key ids cannot hammer the certs URL. A failed fetch keeps the keys it already has. `createAccessVerifier({ fetch, now, ttlMs, refreshMs, timeoutMs, leewaySeconds })` makes a verifier with its own cache and clock, for tests or for a custom `fetch`.
222
+
223
+ Access service tokens carry no email. List their client ids in `serviceTokens` to let them in; a match returns `{ ok: true, service: clientId }`. Only a token Access issued for a service (`type: "app"`, empty `sub`, no email) counts, so a client certificate with the same name does not.
224
+
225
+ In tests, `workers-start/access/testing` stands in for the team:
226
+
227
+ ```ts
228
+ import { createAccessVerifier } from "workers-start/access";
229
+ import { createTestAccessTeam } from "workers-start/access/testing";
230
+
231
+ const team = await createTestAccessTeam({ emails: ["admin@example.com"] });
232
+ const verify = createAccessVerifier({ fetch: team.fetch });
233
+ const result = await verify(await team.token("admin@example.com"), team.config);
234
+ // { ok: true, email: "admin@example.com" }
235
+ ```
236
+
182
237
  ## Sitemap and robots.txt
183
238
 
184
239
  `workers-start/seo` builds the bodies for `/sitemap.xml` and `/robots.txt` routes. The entries and options take the same shape as Next's `MetadataRoute.Sitemap` and `MetadataRoute.Robots`.
@@ -228,7 +283,7 @@ The same check is exported from `workers-start/check-bundle` as `checkBundle(env
228
283
 
229
284
  ## Related
230
285
 
231
- [`workers-jobs`](https://github.com/ryanio/workers-jobs) runs background jobs on Cron Triggers and Workflows, with dedup, explicit retries, a run ledger and a backstop for missed cron slots.
286
+ [`workers-jobs`](https://github.com/ryanio/workers-kit/tree/main/packages/jobs) runs background jobs on Cron Triggers and Workflows, with dedup, explicit retries, a run ledger and a backstop for missed cron slots.
232
287
 
233
288
  ## License
234
289
 
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A stand-in for a Cloudflare Access team in tests: a key pair made on the
3
+ * spot, a `fetch` that serves its public key at the team's certs URL, and a
4
+ * signer for tokens shaped like the ones Access issues.
5
+ */
6
+ import type { AccessConfig } from "./access.js";
7
+ export interface TestAccessTeam {
8
+ /** Config for `createAccessVerifier`, with `emails` allowed. */
9
+ config: AccessConfig;
10
+ /** Serves the team's certs; pass it as the verifier's `fetch`. */
11
+ fetch: (url: string) => Promise<Response>;
12
+ /** A signed token for `email`, valid for an hour, with `claims` on top. */
13
+ token: (email: string, claims?: Record<string, unknown>) => Promise<string>;
14
+ /** A signed token for a service token's client id. */
15
+ serviceToken: (clientId: string, claims?: Record<string, unknown>) => Promise<string>;
16
+ /** Signs any claims and header fields with the team's key. */
17
+ sign: (claims: Record<string, unknown>, header?: Record<string, unknown>) => Promise<string>;
18
+ }
19
+ export interface TestAccessTeamOptions {
20
+ teamDomain?: string;
21
+ aud?: string;
22
+ emails?: string[];
23
+ serviceTokens?: string[];
24
+ kid?: string;
25
+ /** Milliseconds since the epoch, for `iat`, `nbf` and `exp`. */
26
+ now?: () => number;
27
+ }
28
+ export declare function createTestAccessTeam(options?: TestAccessTeamOptions): Promise<TestAccessTeam>;
29
+ //# sourceMappingURL=access-testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-testing.d.ts","sourceRoot":"","sources":["../src/access-testing.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,cAAc;IAC7B,gEAAgE;IAChE,MAAM,EAAE,YAAY,CAAC;IACrB,kEAAkE;IAClE,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC1C,2EAA2E;IAC3E,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5E,sDAAsD;IACtD,YAAY,EAAE,CACZ,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,OAAO,CAAC,MAAM,CAAC,CAAC;IACrB,8DAA8D;IAC9D,IAAI,EAAE,CACJ,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB;AAED,MAAM,WAAW,qBAAqB;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gEAAgE;IAChE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED,wBAAsB,oBAAoB,CACxC,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,cAAc,CAAC,CA0EzB"}
@@ -0,0 +1,60 @@
1
+ export async function createTestAccessTeam(options = {}) {
2
+ const { teamDomain = "test.cloudflareaccess.com", aud = "test-aud", emails = ["admin@example.com"], serviceTokens = [], kid = "test-key", now = Date.now, } = options;
3
+ const pair = (await crypto.subtle.generateKey({
4
+ name: "RSASSA-PKCS1-v1_5",
5
+ modulusLength: 2048,
6
+ publicExponent: new Uint8Array([1, 0, 1]),
7
+ hash: "SHA-256",
8
+ }, true, ["sign", "verify"]));
9
+ const jwk = {
10
+ ...(await crypto.subtle.exportKey("jwk", pair.publicKey)),
11
+ kid,
12
+ alg: "RS256",
13
+ use: "sig",
14
+ };
15
+ const certsUrl = `https://${teamDomain}/cdn-cgi/access/certs`;
16
+ const sign = async (claims, header = {}) => {
17
+ const head = encode(JSON.stringify({ alg: "RS256", kid, ...header }));
18
+ const body = encode(JSON.stringify(claims));
19
+ const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(`${head}.${body}`));
20
+ return `${head}.${body}.${encode(new Uint8Array(sig))}`;
21
+ };
22
+ const base = () => {
23
+ const iat = Math.floor(now() / 1000);
24
+ return {
25
+ aud: [aud],
26
+ iss: `https://${teamDomain}`,
27
+ iat,
28
+ nbf: iat,
29
+ exp: iat + 3600,
30
+ };
31
+ };
32
+ return {
33
+ config: {
34
+ teamDomain,
35
+ aud,
36
+ emails: emails.map((e) => e.toLowerCase()),
37
+ serviceTokens,
38
+ },
39
+ fetch: async (url) => url === certsUrl
40
+ ? Response.json({ keys: [jwk] })
41
+ : new Response("not found", { status: 404 }),
42
+ token: (email, claims = {}) => sign({ ...base(), email, sub: "user-id", type: "app", ...claims }),
43
+ serviceToken: (clientId, claims = {}) => sign({
44
+ ...base(),
45
+ sub: "",
46
+ type: "app",
47
+ common_name: clientId,
48
+ ...claims,
49
+ }),
50
+ sign,
51
+ };
52
+ }
53
+ function encode(value) {
54
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
55
+ let bin = "";
56
+ for (const b of bytes)
57
+ bin += String.fromCharCode(b);
58
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
59
+ }
60
+ //# sourceMappingURL=access-testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-testing.js","sourceRoot":"","sources":["../src/access-testing.ts"],"names":[],"mappings":"AAoCA,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,OAAO,GAA0B,EAAE;IAEnC,MAAM,EACJ,UAAU,GAAG,2BAA2B,EACxC,GAAG,GAAG,UAAU,EAChB,MAAM,GAAG,CAAC,mBAAmB,CAAC,EAC9B,aAAa,GAAG,EAAE,EAClB,GAAG,GAAG,UAAU,EAChB,GAAG,GAAG,IAAI,CAAC,GAAG,GACf,GAAG,OAAO,CAAC;IACZ,MAAM,IAAI,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,WAAW,CAC3C;QACE,IAAI,EAAE,mBAAmB;QACzB,aAAa,EAAE,IAAI;QACnB,cAAc,EAAE,IAAI,UAAU,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C,CAAC,CAAC;IACrD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Cloudflare Access sign-ins. Access sits in front of an app (or a path of
3
+ * it) and adds a signed JWT to every request it lets through, as the
4
+ * `Cf-Access-Jwt-Assertion` header and the `CF_Authorization` cookie. The
5
+ * header alone proves nothing, since anyone can send it to the Worker's other
6
+ * hostnames, so this checks the token: RS256 signature against the team's
7
+ * published keys, issuer, audience, `exp` and `nbf`, then the email against an
8
+ * allowlist, or a service token's client id against its own list.
9
+ *
10
+ * WebCrypto only, so it runs in workerd, the browser and Node. Every failure
11
+ * is a result, never a throw, and a missing config refuses everything.
12
+ */
13
+ export interface AccessConfig {
14
+ /** The team domain without scheme, such as `myteam.cloudflareaccess.com`. */
15
+ teamDomain: string;
16
+ /** The Access application's audience tag. */
17
+ aud: string;
18
+ /** Lowercased addresses allowed in. */
19
+ emails: readonly string[];
20
+ /** Client ids of Access service tokens allowed in. */
21
+ serviceTokens: readonly string[];
22
+ }
23
+ /** Raw config values, as they come from Worker vars or secrets. */
24
+ export interface AccessEnv {
25
+ teamDomain?: string | undefined;
26
+ aud?: string | undefined;
27
+ /** Comma or whitespace separated. */
28
+ emails?: string | undefined;
29
+ /** Comma or whitespace separated service token client ids. */
30
+ serviceTokens?: string | undefined;
31
+ }
32
+ /**
33
+ * The parsed config, or null when the team domain or audience is missing, or
34
+ * when neither an email nor a service token is allowed. A null config makes
35
+ * every check fail with `unconfigured`.
36
+ */
37
+ export declare function parseAccessConfig(env: AccessEnv): AccessConfig | null;
38
+ /** The Access token on a request: the header Access adds, else its cookie. */
39
+ export declare function accessToken(request: Request): string | null;
40
+ export type AccessFailure =
41
+ /** No config: 503. */
42
+ "unconfigured"
43
+ /** No token, or one that does not verify: 401. */
44
+ | "unauthenticated"
45
+ /** A valid token for someone not on the list: 403. */
46
+ | "forbidden"
47
+ /** The team's keys could not be fetched: 503. */
48
+ | "unavailable";
49
+ export type AccessResult = {
50
+ ok: true;
51
+ email: string;
52
+ service?: undefined;
53
+ } | {
54
+ ok: true;
55
+ service: string;
56
+ email?: undefined;
57
+ } | {
58
+ ok: false;
59
+ status: 401 | 403 | 503;
60
+ code: AccessFailure;
61
+ reason: string;
62
+ };
63
+ export interface AccessVerifierOptions {
64
+ /** Fetches the certs URL. Defaults to the global `fetch`. */
65
+ fetch?: (url: string, init?: RequestInit) => Promise<Response>;
66
+ /** Milliseconds since the epoch. Defaults to `Date.now`. */
67
+ now?: () => number;
68
+ /** How long fetched keys are trusted. Default one hour. */
69
+ ttlMs?: number;
70
+ /** An unknown key id refetches at most this often. Default one minute. */
71
+ refreshMs?: number;
72
+ /** Timeout on the certs fetch. Default 5 seconds. */
73
+ timeoutMs?: number;
74
+ /** Seconds of clock difference allowed on `exp` and `nbf`. Default 60. */
75
+ leewaySeconds?: number;
76
+ }
77
+ export type AccessVerifier = (token: string | null | undefined, config: AccessConfig | null) => Promise<AccessResult>;
78
+ /**
79
+ * A verifier with its own key cache. Keys are cached per team for `ttlMs`; a
80
+ * token naming a key id the cache lacks refetches at most once per
81
+ * `refreshMs`, so a stream of made-up key ids cannot hammer the certs URL. A
82
+ * failed or empty fetch keeps the keys already held.
83
+ */
84
+ export declare function createAccessVerifier(options?: AccessVerifierOptions): AccessVerifier;
85
+ /**
86
+ * Checks a token with a verifier shared by the whole isolate, so the team's
87
+ * keys are fetched once per hour, not once per request.
88
+ */
89
+ export declare function verifyAccessToken(token: string | null | undefined, config: AccessConfig | null): Promise<AccessResult>;
90
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAA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qBAAqB;IACpC,6DAA6D;IAC7D,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC/D,4DAA4D;IAC5D,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qDAAqD;IACrD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,MAAM,cAAc,GAAG,CAC3B,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,MAAM,EAAE,YAAY,GAAG,IAAI,KACxB,OAAO,CAAC,YAAY,CAAC,CAAC;AAmB3B;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,GAAE,qBAA0B,GAClC,cAAc,CA+IhB;AAID;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,MAAM,EAAE,YAAY,GAAG,IAAI,GAC1B,OAAO,CAAC,YAAY,CAAC,CAGvB"}
package/dist/access.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Cloudflare Access sign-ins. Access sits in front of an app (or a path of
3
+ * it) and adds a signed JWT to every request it lets through, as the
4
+ * `Cf-Access-Jwt-Assertion` header and the `CF_Authorization` cookie. The
5
+ * header alone proves nothing, since anyone can send it to the Worker's other
6
+ * hostnames, so this checks the token: RS256 signature against the team's
7
+ * published keys, issuer, audience, `exp` and `nbf`, then the email against an
8
+ * allowlist, or a service token's client id against its own list.
9
+ *
10
+ * WebCrypto only, so it runs in workerd, the browser and Node. Every failure
11
+ * is a result, never a throw, and a missing config refuses everything.
12
+ */
13
+ /**
14
+ * The parsed config, or null when the team domain or audience is missing, or
15
+ * when neither an email nor a service token is allowed. A null config makes
16
+ * every check fail with `unconfigured`.
17
+ */
18
+ export function parseAccessConfig(env) {
19
+ const teamDomain = (env.teamDomain ?? "")
20
+ .trim()
21
+ .replace(/^https?:\/\//, "")
22
+ .replace(/\/+$/, "");
23
+ const aud = (env.aud ?? "").trim();
24
+ const emails = list(env.emails)
25
+ .map((e) => e.toLowerCase())
26
+ .filter((e) => e.includes("@"));
27
+ const serviceTokens = list(env.serviceTokens);
28
+ if (!teamDomain || !aud)
29
+ return null;
30
+ if (emails.length === 0 && serviceTokens.length === 0)
31
+ return null;
32
+ return { teamDomain, aud, emails, serviceTokens };
33
+ }
34
+ const list = (value) => (value ?? "").split(/[\s,]+/).filter(Boolean);
35
+ /** The Access token on a request: the header Access adds, else its cookie. */
36
+ export function accessToken(request) {
37
+ const header = request.headers.get("cf-access-jwt-assertion");
38
+ if (header)
39
+ return header;
40
+ const cookie = /(?:^|;\s*)CF_Authorization=([^;]+)/.exec(request.headers.get("cookie") ?? "");
41
+ return cookie?.[1] ?? null;
42
+ }
43
+ const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
44
+ const deny = (status, code, reason) => ({ ok: false, status, code, reason });
45
+ /**
46
+ * A verifier with its own key cache. Keys are cached per team for `ttlMs`; a
47
+ * token naming a key id the cache lacks refetches at most once per
48
+ * `refreshMs`, so a stream of made-up key ids cannot hammer the certs URL. A
49
+ * failed or empty fetch keeps the keys already held.
50
+ */
51
+ export function createAccessVerifier(options = {}) {
52
+ const { fetch: fetcher = (url, init) => fetch(url, init), now = Date.now, ttlMs = 60 * 60_000, refreshMs = 60_000, timeoutMs = 5_000, leewaySeconds = 60, } = options;
53
+ const sets = new Map();
54
+ async function refresh(url, set) {
55
+ set.fetchedAt = now();
56
+ set.ok = await load(url, set);
57
+ }
58
+ async function load(url, set) {
59
+ try {
60
+ const res = await fetcher(url, {
61
+ signal: AbortSignal.timeout(timeoutMs),
62
+ });
63
+ if (!res.ok)
64
+ return false;
65
+ const body = (await res.json());
66
+ const next = new Map();
67
+ for (const jwk of Array.isArray(body.keys) ? body.keys : []) {
68
+ const { kid, kty } = (jwk ?? {});
69
+ if (typeof kid !== "string" || kty !== "RSA")
70
+ continue;
71
+ try {
72
+ next.set(kid, await crypto.subtle.importKey("jwk", jwk, RS256, false, ["verify"]));
73
+ }
74
+ catch {
75
+ // A key that will not import is skipped; the others still work.
76
+ }
77
+ }
78
+ if (next.size === 0)
79
+ return false;
80
+ set.keys = next;
81
+ return true;
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ /** The key for `kid`, null when the team has none, or "unavailable". */
88
+ async function key(teamDomain, kid) {
89
+ const url = `https://${teamDomain}/cdn-cgi/access/certs`;
90
+ let set = sets.get(url);
91
+ if (!set) {
92
+ set = {
93
+ keys: new Map(),
94
+ fetchedAt: Number.NEGATIVE_INFINITY,
95
+ ok: false,
96
+ };
97
+ sets.set(url, set);
98
+ }
99
+ if (set.refreshing)
100
+ await set.refreshing;
101
+ const age = now() - set.fetchedAt;
102
+ if (age <= ttlMs && set.keys.has(kid))
103
+ return set.keys.get(kid) ?? null;
104
+ if (age > refreshMs) {
105
+ const current = set;
106
+ current.refreshing ??= refresh(url, current).finally(() => {
107
+ current.refreshing = undefined;
108
+ });
109
+ await current.refreshing;
110
+ }
111
+ const found = set.keys.get(kid);
112
+ if (found)
113
+ return found;
114
+ return !set.ok && set.keys.size === 0 ? "unavailable" : null;
115
+ }
116
+ return async (token, config) => {
117
+ if (!config)
118
+ return deny(503, "unconfigured", "Access is not configured.");
119
+ if (!token)
120
+ return deny(401, "unauthenticated", "No Access token.");
121
+ const parts = token.split(".");
122
+ if (parts.length !== 3)
123
+ return deny(401, "unauthenticated", "Malformed token.");
124
+ const [head, body, signature] = parts;
125
+ const header = decodeJson(head);
126
+ const claims = decodeJson(body);
127
+ if (!header || !claims)
128
+ return deny(401, "unauthenticated", "Malformed token.");
129
+ if (header.alg !== "RS256")
130
+ return deny(401, "unauthenticated", "Unexpected algorithm.");
131
+ if (typeof header.kid !== "string" || !header.kid)
132
+ return deny(401, "unauthenticated", "Token has no key id.");
133
+ const found = await key(config.teamDomain, header.kid);
134
+ if (found === "unavailable")
135
+ return deny(503, "unavailable", "Could not load the Access keys.");
136
+ if (!found)
137
+ return deny(401, "unauthenticated", "Unknown signing key.");
138
+ let valid = false;
139
+ try {
140
+ const sig = base64UrlDecode(signature);
141
+ valid =
142
+ sig !== null &&
143
+ (await crypto.subtle.verify(RS256, found, sig, new TextEncoder().encode(`${head}.${body}`)));
144
+ }
145
+ catch {
146
+ valid = false;
147
+ }
148
+ if (!valid)
149
+ return deny(401, "unauthenticated", "Bad signature.");
150
+ if (claims.iss !== `https://${config.teamDomain}`)
151
+ return deny(401, "unauthenticated", "Wrong issuer.");
152
+ const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
153
+ if (!aud.includes(config.aud))
154
+ return deny(401, "unauthenticated", "Wrong audience.");
155
+ const nowS = now() / 1000;
156
+ if (typeof claims.exp !== "number" || claims.exp + leewaySeconds < nowS)
157
+ return deny(401, "unauthenticated", "Token expired.");
158
+ if (typeof claims.nbf === "number" && claims.nbf - leewaySeconds > nowS)
159
+ return deny(401, "unauthenticated", "Token not valid yet.");
160
+ if (typeof claims.email === "string" && claims.email.includes("@")) {
161
+ const email = claims.email.trim().toLowerCase();
162
+ return config.emails.includes(email)
163
+ ? { ok: true, email }
164
+ : deny(403, "forbidden", "This account is not on the allowed list.");
165
+ }
166
+ // A service token's sign-in: an app token for nobody, named by client id.
167
+ // A client certificate's sign-in also has a name and no email, so the
168
+ // name alone is not enough.
169
+ const service = claims.type === "app" &&
170
+ claims.sub === "" &&
171
+ claims.email === undefined &&
172
+ typeof claims.common_name === "string"
173
+ ? claims.common_name
174
+ : null;
175
+ if (service && config.serviceTokens.includes(service))
176
+ return { ok: true, service };
177
+ return deny(403, "forbidden", "This sign-in is not on the allowed list.");
178
+ };
179
+ }
180
+ let shared;
181
+ /**
182
+ * Checks a token with a verifier shared by the whole isolate, so the team's
183
+ * keys are fetched once per hour, not once per request.
184
+ */
185
+ export function verifyAccessToken(token, config) {
186
+ shared ??= createAccessVerifier();
187
+ return shared(token, config);
188
+ }
189
+ function base64UrlDecode(part) {
190
+ try {
191
+ const b64 = part.replace(/-/g, "+").replace(/_/g, "/");
192
+ const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
193
+ return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));
194
+ }
195
+ catch {
196
+ return null;
197
+ }
198
+ }
199
+ function decodeJson(part) {
200
+ const bytes = base64UrlDecode(part);
201
+ if (!bytes)
202
+ return null;
203
+ try {
204
+ const value = JSON.parse(new TextDecoder().decode(bytes));
205
+ return typeof value === "object" && value !== null && !Array.isArray(value)
206
+ ? value
207
+ : null;
208
+ }
209
+ catch {
210
+ return null;
211
+ }
212
+ }
213
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.js","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAuBH;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAc;IAC9C,MAAM,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,IAAI,EAAE,CAAC;SACtC,IAAI,EAAE;SACN,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;SAC3B,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACvB,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACnC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;SAC5B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;SAC3B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC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AAC,CAAC,CAAC;QACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YACzE,CAAC,CAAE,KAAiC;YACpC,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export type { MediaRange } from "./accept.js";
2
2
  export { parseAccept, quality } from "./accept.js";
3
+ export type { AccessConfig, AccessEnv, AccessFailure, AccessResult, AccessVerifier, AccessVerifierOptions, } from "./access.js";
4
+ export { accessToken, createAccessVerifier, parseAccessConfig, verifyAccessToken, } from "./access.js";
3
5
  export type { EdgeCacheOptions } from "./cache.js";
4
6
  export { sharedMaxAge, withEdgeCache, withoutBrowserMaxAge, } from "./cache.js";
5
7
  export type { EntryOptions, FetchHandler, MarkdownPage, MarkdownResult, } from "./entry.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACnD,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,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,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,OAAO,EACP,QAAQ,GACT,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzD,YAAY,EACV,sBAAsB,EACtB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC5D,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { parseAccept, quality } from "./accept.js";
2
+ export { accessToken, createAccessVerifier, parseAccessConfig, verifyAccessToken, } from "./access.js";
2
3
  export { sharedMaxAge, withEdgeCache, withoutBrowserMaxAge, } from "./cache.js";
3
4
  export { acceptsHtml, createEntry, defaultIsPage, MARKDOWN_HEADERS, mergeVary, normalizePath, underPrefix, wantsMarkdown, withHeaders, } from "./entry.js";
4
5
  export { createPageHead, jsonLdScript } from "./head.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AAUpB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAOzD,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAE5D,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AASnD,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AAUpB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAOzD,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAE5D,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,17 @@
1
1
  {
2
2
  "name": "workers-start",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "The parts every TanStack Start app on Cloudflare Workers ends up writing: Markdown for agents on the same URL, a head helper that stops share cards leaking between pages, lazy Workers bindings, and a check that no local secret ships in the build.",
5
5
  "license": "MIT",
6
6
  "author": "Ryan Ghods",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/ryanio/workers-start.git"
9
+ "url": "git+https://github.com/ryanio/workers-kit.git",
10
+ "directory": "packages/start"
11
+ },
12
+ "homepage": "https://github.com/ryanio/workers-kit/tree/main/packages/start#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/ryanio/workers-kit/issues"
10
15
  },
11
16
  "keywords": [
12
17
  "cloudflare",
@@ -66,6 +71,16 @@
66
71
  "import": "./dist/accept.js",
67
72
  "default": "./dist/accept.js"
68
73
  },
74
+ "./access": {
75
+ "types": "./dist/access.d.ts",
76
+ "import": "./dist/access.js",
77
+ "default": "./dist/access.js"
78
+ },
79
+ "./access/testing": {
80
+ "types": "./dist/access-testing.d.ts",
81
+ "import": "./dist/access-testing.js",
82
+ "default": "./dist/access-testing.js"
83
+ },
69
84
  "./package.json": "./package.json"
70
85
  },
71
86
  "bin": {
@@ -84,23 +99,15 @@
84
99
  "scripts": {
85
100
  "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/check-bundle-cli.js",
86
101
  "typecheck": "tsc --noEmit",
87
- "lint": "biome check",
88
- "format": "biome check --write",
89
102
  "test": "npm run build && vitest run",
90
- "check": "npm run check:doc-refs && npm run check:lockfile && npm run lint && npm run typecheck && npm run build && vitest run && npm run deadcode",
91
- "prepack": "npm run build",
92
- "prepare": "git config core.hooksPath .githooks || true",
93
- "deadcode": "knip",
94
- "check:doc-refs": "node scripts/doc-refs/doc-refs.mjs",
95
- "check:lockfile": "node scripts/check-lockfile-platforms.mjs"
103
+ "check": "npm run typecheck && npm run build && vitest run",
104
+ "prepack": "npm run build"
96
105
  },
97
106
  "publishConfig": {
98
107
  "access": "public"
99
108
  },
100
109
  "devDependencies": {
101
- "@biomejs/biome": "^2.6.8",
102
110
  "@types/node": "^24.19.2",
103
- "knip": "^6.47.0",
104
111
  "typescript": "^7.0.2",
105
112
  "vitest": "^5.1.0"
106
113
  }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * A stand-in for a Cloudflare Access team in tests: a key pair made on the
3
+ * spot, a `fetch` that serves its public key at the team's certs URL, and a
4
+ * signer for tokens shaped like the ones Access issues.
5
+ */
6
+ import type { AccessConfig } from "./access.js";
7
+
8
+ export interface TestAccessTeam {
9
+ /** Config for `createAccessVerifier`, with `emails` allowed. */
10
+ config: AccessConfig;
11
+ /** Serves the team's certs; pass it as the verifier's `fetch`. */
12
+ fetch: (url: string) => Promise<Response>;
13
+ /** A signed token for `email`, valid for an hour, with `claims` on top. */
14
+ token: (email: string, claims?: Record<string, unknown>) => Promise<string>;
15
+ /** A signed token for a service token's client id. */
16
+ serviceToken: (
17
+ clientId: string,
18
+ claims?: Record<string, unknown>,
19
+ ) => Promise<string>;
20
+ /** Signs any claims and header fields with the team's key. */
21
+ sign: (
22
+ claims: Record<string, unknown>,
23
+ header?: Record<string, unknown>,
24
+ ) => Promise<string>;
25
+ }
26
+
27
+ export interface TestAccessTeamOptions {
28
+ teamDomain?: string;
29
+ aud?: string;
30
+ emails?: string[];
31
+ serviceTokens?: string[];
32
+ kid?: string;
33
+ /** Milliseconds since the epoch, for `iat`, `nbf` and `exp`. */
34
+ now?: () => number;
35
+ }
36
+
37
+ export async function createTestAccessTeam(
38
+ options: TestAccessTeamOptions = {},
39
+ ): Promise<TestAccessTeam> {
40
+ const {
41
+ teamDomain = "test.cloudflareaccess.com",
42
+ aud = "test-aud",
43
+ emails = ["admin@example.com"],
44
+ serviceTokens = [],
45
+ kid = "test-key",
46
+ now = Date.now,
47
+ } = options;
48
+ const pair = (await crypto.subtle.generateKey(
49
+ {
50
+ name: "RSASSA-PKCS1-v1_5",
51
+ modulusLength: 2048,
52
+ publicExponent: new Uint8Array([1, 0, 1]),
53
+ hash: "SHA-256",
54
+ },
55
+ true,
56
+ ["sign", "verify"],
57
+ )) as { privateKey: CryptoKey; publicKey: CryptoKey };
58
+ const jwk = {
59
+ ...((await crypto.subtle.exportKey("jwk", pair.publicKey)) as object),
60
+ kid,
61
+ alg: "RS256",
62
+ use: "sig",
63
+ };
64
+ const certsUrl = `https://${teamDomain}/cdn-cgi/access/certs`;
65
+
66
+ const sign = async (
67
+ claims: Record<string, unknown>,
68
+ header: Record<string, unknown> = {},
69
+ ) => {
70
+ const head = encode(JSON.stringify({ alg: "RS256", kid, ...header }));
71
+ const body = encode(JSON.stringify(claims));
72
+ const sig = await crypto.subtle.sign(
73
+ "RSASSA-PKCS1-v1_5",
74
+ pair.privateKey,
75
+ new TextEncoder().encode(`${head}.${body}`),
76
+ );
77
+ return `${head}.${body}.${encode(new Uint8Array(sig))}`;
78
+ };
79
+ const base = () => {
80
+ const iat = Math.floor(now() / 1000);
81
+ return {
82
+ aud: [aud],
83
+ iss: `https://${teamDomain}`,
84
+ iat,
85
+ nbf: iat,
86
+ exp: iat + 3600,
87
+ };
88
+ };
89
+
90
+ return {
91
+ config: {
92
+ teamDomain,
93
+ aud,
94
+ emails: emails.map((e) => e.toLowerCase()),
95
+ serviceTokens,
96
+ },
97
+ fetch: async (url) =>
98
+ url === certsUrl
99
+ ? Response.json({ keys: [jwk] })
100
+ : new Response("not found", { status: 404 }),
101
+ token: (email, claims = {}) =>
102
+ sign({ ...base(), email, sub: "user-id", type: "app", ...claims }),
103
+ serviceToken: (clientId, claims = {}) =>
104
+ sign({
105
+ ...base(),
106
+ sub: "",
107
+ type: "app",
108
+ common_name: clientId,
109
+ ...claims,
110
+ }),
111
+ sign,
112
+ };
113
+ }
114
+
115
+ function encode(value: string | Uint8Array): string {
116
+ const bytes =
117
+ typeof value === "string" ? new TextEncoder().encode(value) : value;
118
+ let bin = "";
119
+ for (const b of bytes) bin += String.fromCharCode(b);
120
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
121
+ }
package/src/access.ts ADDED
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Cloudflare Access sign-ins. Access sits in front of an app (or a path of
3
+ * it) and adds a signed JWT to every request it lets through, as the
4
+ * `Cf-Access-Jwt-Assertion` header and the `CF_Authorization` cookie. The
5
+ * header alone proves nothing, since anyone can send it to the Worker's other
6
+ * hostnames, so this checks the token: RS256 signature against the team's
7
+ * published keys, issuer, audience, `exp` and `nbf`, then the email against an
8
+ * allowlist, or a service token's client id against its own list.
9
+ *
10
+ * WebCrypto only, so it runs in workerd, the browser and Node. Every failure
11
+ * is a result, never a throw, and a missing config refuses everything.
12
+ */
13
+
14
+ export interface AccessConfig {
15
+ /** The team domain without scheme, such as `myteam.cloudflareaccess.com`. */
16
+ teamDomain: string;
17
+ /** The Access application's audience tag. */
18
+ aud: string;
19
+ /** Lowercased addresses allowed in. */
20
+ emails: readonly string[];
21
+ /** Client ids of Access service tokens allowed in. */
22
+ serviceTokens: readonly string[];
23
+ }
24
+
25
+ /** Raw config values, as they come from Worker vars or secrets. */
26
+ export interface AccessEnv {
27
+ teamDomain?: string | undefined;
28
+ aud?: string | undefined;
29
+ /** Comma or whitespace separated. */
30
+ emails?: string | undefined;
31
+ /** Comma or whitespace separated service token client ids. */
32
+ serviceTokens?: string | undefined;
33
+ }
34
+
35
+ /**
36
+ * The parsed config, or null when the team domain or audience is missing, or
37
+ * when neither an email nor a service token is allowed. A null config makes
38
+ * every check fail with `unconfigured`.
39
+ */
40
+ export function parseAccessConfig(env: AccessEnv): AccessConfig | null {
41
+ const teamDomain = (env.teamDomain ?? "")
42
+ .trim()
43
+ .replace(/^https?:\/\//, "")
44
+ .replace(/\/+$/, "");
45
+ const aud = (env.aud ?? "").trim();
46
+ const emails = list(env.emails)
47
+ .map((e) => e.toLowerCase())
48
+ .filter((e) => e.includes("@"));
49
+ const serviceTokens = list(env.serviceTokens);
50
+ if (!teamDomain || !aud) return null;
51
+ if (emails.length === 0 && serviceTokens.length === 0) return null;
52
+ return { teamDomain, aud, emails, serviceTokens };
53
+ }
54
+
55
+ const list = (value: string | undefined) =>
56
+ (value ?? "").split(/[\s,]+/).filter(Boolean);
57
+
58
+ /** The Access token on a request: the header Access adds, else its cookie. */
59
+ export function accessToken(request: Request): string | null {
60
+ const header = request.headers.get("cf-access-jwt-assertion");
61
+ if (header) return header;
62
+ const cookie = /(?:^|;\s*)CF_Authorization=([^;]+)/.exec(
63
+ request.headers.get("cookie") ?? "",
64
+ );
65
+ return cookie?.[1] ?? null;
66
+ }
67
+
68
+ export type AccessFailure =
69
+ /** No config: 503. */
70
+ | "unconfigured"
71
+ /** No token, or one that does not verify: 401. */
72
+ | "unauthenticated"
73
+ /** A valid token for someone not on the list: 403. */
74
+ | "forbidden"
75
+ /** The team's keys could not be fetched: 503. */
76
+ | "unavailable";
77
+
78
+ export type AccessResult =
79
+ | { ok: true; email: string; service?: undefined }
80
+ | { ok: true; service: string; email?: undefined }
81
+ | {
82
+ ok: false;
83
+ status: 401 | 403 | 503;
84
+ code: AccessFailure;
85
+ reason: string;
86
+ };
87
+
88
+ export interface AccessVerifierOptions {
89
+ /** Fetches the certs URL. Defaults to the global `fetch`. */
90
+ fetch?: (url: string, init?: RequestInit) => Promise<Response>;
91
+ /** Milliseconds since the epoch. Defaults to `Date.now`. */
92
+ now?: () => number;
93
+ /** How long fetched keys are trusted. Default one hour. */
94
+ ttlMs?: number;
95
+ /** An unknown key id refetches at most this often. Default one minute. */
96
+ refreshMs?: number;
97
+ /** Timeout on the certs fetch. Default 5 seconds. */
98
+ timeoutMs?: number;
99
+ /** Seconds of clock difference allowed on `exp` and `nbf`. Default 60. */
100
+ leewaySeconds?: number;
101
+ }
102
+
103
+ export type AccessVerifier = (
104
+ token: string | null | undefined,
105
+ config: AccessConfig | null,
106
+ ) => Promise<AccessResult>;
107
+
108
+ type Key = Awaited<ReturnType<typeof crypto.subtle.importKey>>;
109
+ interface KeySet {
110
+ keys: Map<string, Key>;
111
+ fetchedAt: number;
112
+ /** Whether the last fetch gave keys. */
113
+ ok: boolean;
114
+ refreshing?: Promise<void> | undefined;
115
+ }
116
+
117
+ const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
118
+
119
+ const deny = (
120
+ status: 401 | 403 | 503,
121
+ code: AccessFailure,
122
+ reason: string,
123
+ ): AccessResult => ({ ok: false, status, code, reason });
124
+
125
+ /**
126
+ * A verifier with its own key cache. Keys are cached per team for `ttlMs`; a
127
+ * token naming a key id the cache lacks refetches at most once per
128
+ * `refreshMs`, so a stream of made-up key ids cannot hammer the certs URL. A
129
+ * failed or empty fetch keeps the keys already held.
130
+ */
131
+ export function createAccessVerifier(
132
+ options: AccessVerifierOptions = {},
133
+ ): AccessVerifier {
134
+ const {
135
+ fetch: fetcher = (url, init) => fetch(url, init),
136
+ now = Date.now,
137
+ ttlMs = 60 * 60_000,
138
+ refreshMs = 60_000,
139
+ timeoutMs = 5_000,
140
+ leewaySeconds = 60,
141
+ } = options;
142
+ const sets = new Map<string, KeySet>();
143
+
144
+ async function refresh(url: string, set: KeySet): Promise<void> {
145
+ set.fetchedAt = now();
146
+ set.ok = await load(url, set);
147
+ }
148
+
149
+ async function load(url: string, set: KeySet): Promise<boolean> {
150
+ try {
151
+ const res = await fetcher(url, {
152
+ signal: AbortSignal.timeout(timeoutMs),
153
+ });
154
+ if (!res.ok) return false;
155
+ const body = (await res.json()) as { keys?: unknown };
156
+ const next = new Map<string, Key>();
157
+ for (const jwk of Array.isArray(body.keys) ? body.keys : []) {
158
+ const { kid, kty } = (jwk ?? {}) as { kid?: unknown; kty?: unknown };
159
+ if (typeof kid !== "string" || kty !== "RSA") continue;
160
+ try {
161
+ next.set(
162
+ kid,
163
+ await crypto.subtle.importKey("jwk", jwk, RS256, false, ["verify"]),
164
+ );
165
+ } catch {
166
+ // A key that will not import is skipped; the others still work.
167
+ }
168
+ }
169
+ if (next.size === 0) return false;
170
+ set.keys = next;
171
+ return true;
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ /** The key for `kid`, null when the team has none, or "unavailable". */
178
+ async function key(
179
+ teamDomain: string,
180
+ kid: string,
181
+ ): Promise<Key | null | "unavailable"> {
182
+ const url = `https://${teamDomain}/cdn-cgi/access/certs`;
183
+ let set = sets.get(url);
184
+ if (!set) {
185
+ set = {
186
+ keys: new Map(),
187
+ fetchedAt: Number.NEGATIVE_INFINITY,
188
+ ok: false,
189
+ };
190
+ sets.set(url, set);
191
+ }
192
+ if (set.refreshing) await set.refreshing;
193
+ const age = now() - set.fetchedAt;
194
+ if (age <= ttlMs && set.keys.has(kid)) return set.keys.get(kid) ?? null;
195
+ if (age > refreshMs) {
196
+ const current = set;
197
+ current.refreshing ??= refresh(url, current).finally(() => {
198
+ current.refreshing = undefined;
199
+ });
200
+ await current.refreshing;
201
+ }
202
+ const found = set.keys.get(kid);
203
+ if (found) return found;
204
+ return !set.ok && set.keys.size === 0 ? "unavailable" : null;
205
+ }
206
+
207
+ return async (token, config) => {
208
+ if (!config) return deny(503, "unconfigured", "Access is not configured.");
209
+ if (!token) return deny(401, "unauthenticated", "No Access token.");
210
+
211
+ const parts = token.split(".");
212
+ if (parts.length !== 3)
213
+ return deny(401, "unauthenticated", "Malformed token.");
214
+ const [head, body, signature] = parts as [string, string, string];
215
+ const header = decodeJson(head);
216
+ const claims = decodeJson(body);
217
+ if (!header || !claims)
218
+ return deny(401, "unauthenticated", "Malformed token.");
219
+ if (header.alg !== "RS256")
220
+ return deny(401, "unauthenticated", "Unexpected algorithm.");
221
+ if (typeof header.kid !== "string" || !header.kid)
222
+ return deny(401, "unauthenticated", "Token has no key id.");
223
+
224
+ const found = await key(config.teamDomain, header.kid);
225
+ if (found === "unavailable")
226
+ return deny(503, "unavailable", "Could not load the Access keys.");
227
+ if (!found) return deny(401, "unauthenticated", "Unknown signing key.");
228
+
229
+ let valid = false;
230
+ try {
231
+ const sig = base64UrlDecode(signature);
232
+ valid =
233
+ sig !== null &&
234
+ (await crypto.subtle.verify(
235
+ RS256,
236
+ found,
237
+ sig,
238
+ new TextEncoder().encode(`${head}.${body}`),
239
+ ));
240
+ } catch {
241
+ valid = false;
242
+ }
243
+ if (!valid) return deny(401, "unauthenticated", "Bad signature.");
244
+
245
+ if (claims.iss !== `https://${config.teamDomain}`)
246
+ return deny(401, "unauthenticated", "Wrong issuer.");
247
+ const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
248
+ if (!aud.includes(config.aud))
249
+ return deny(401, "unauthenticated", "Wrong audience.");
250
+ const nowS = now() / 1000;
251
+ if (typeof claims.exp !== "number" || claims.exp + leewaySeconds < nowS)
252
+ return deny(401, "unauthenticated", "Token expired.");
253
+ if (typeof claims.nbf === "number" && claims.nbf - leewaySeconds > nowS)
254
+ return deny(401, "unauthenticated", "Token not valid yet.");
255
+
256
+ if (typeof claims.email === "string" && claims.email.includes("@")) {
257
+ const email = claims.email.trim().toLowerCase();
258
+ return config.emails.includes(email)
259
+ ? { ok: true, email }
260
+ : deny(403, "forbidden", "This account is not on the allowed list.");
261
+ }
262
+ // A service token's sign-in: an app token for nobody, named by client id.
263
+ // A client certificate's sign-in also has a name and no email, so the
264
+ // name alone is not enough.
265
+ const service =
266
+ claims.type === "app" &&
267
+ claims.sub === "" &&
268
+ claims.email === undefined &&
269
+ typeof claims.common_name === "string"
270
+ ? claims.common_name
271
+ : null;
272
+ if (service && config.serviceTokens.includes(service))
273
+ return { ok: true, service };
274
+ return deny(403, "forbidden", "This sign-in is not on the allowed list.");
275
+ };
276
+ }
277
+
278
+ let shared: AccessVerifier | undefined;
279
+
280
+ /**
281
+ * Checks a token with a verifier shared by the whole isolate, so the team's
282
+ * keys are fetched once per hour, not once per request.
283
+ */
284
+ export function verifyAccessToken(
285
+ token: string | null | undefined,
286
+ config: AccessConfig | null,
287
+ ): Promise<AccessResult> {
288
+ shared ??= createAccessVerifier();
289
+ return shared(token, config);
290
+ }
291
+
292
+ function base64UrlDecode(part: string): Uint8Array<ArrayBuffer> | null {
293
+ try {
294
+ const b64 = part.replace(/-/g, "+").replace(/_/g, "/");
295
+ const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
296
+ return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ function decodeJson(part: string): Record<string, unknown> | null {
303
+ const bytes = base64UrlDecode(part);
304
+ if (!bytes) return null;
305
+ try {
306
+ const value: unknown = JSON.parse(new TextDecoder().decode(bytes));
307
+ return typeof value === "object" && value !== null && !Array.isArray(value)
308
+ ? (value as Record<string, unknown>)
309
+ : null;
310
+ } catch {
311
+ return null;
312
+ }
313
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  export type { MediaRange } from "./accept.js";
2
2
  export { parseAccept, quality } from "./accept.js";
3
+ export type {
4
+ AccessConfig,
5
+ AccessEnv,
6
+ AccessFailure,
7
+ AccessResult,
8
+ AccessVerifier,
9
+ AccessVerifierOptions,
10
+ } from "./access.js";
11
+ export {
12
+ accessToken,
13
+ createAccessVerifier,
14
+ parseAccessConfig,
15
+ verifyAccessToken,
16
+ } from "./access.js";
3
17
  export type { EdgeCacheOptions } from "./cache.js";
4
18
  export {
5
19
  sharedMaxAge,