返回 CodeWhale
access.ts
根目录 / telemetry-stats / src / access.ts
1 import type { Env } from "./types";
2
3 interface Jwk {
4 kid: string;
5 kty: string;
6 n: string;
7 e: string;
8 }
9
10 let certCache: { team: string; at: number; keys: Jwk[] } | null = null;
11
12 export function resetAccessCache(): void {
13 certCache = null;
14 }
15
16 function b64url(input: string): Uint8Array<ArrayBuffer> {
17 const padded = input.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(input.length / 4) * 4, "=");
18 const raw = atob(padded);
19 return Uint8Array.from(raw, (char) => char.charCodeAt(0));
20 }
21
22 function json(input: string): Record<string, unknown> {
23 return JSON.parse(new TextDecoder().decode(b64url(input)));
24 }
25
26 async function certs(team: string, fetchImpl: typeof fetch, now: number): Promise<Jwk[]> {
27 if (certCache && certCache.team === team && now - certCache.at < 3_600_000) return certCache.keys;
28 const response = await fetchImpl(`https://${team}.cloudflareaccess.com/cdn-cgi/access/certs`);
29 if (!response.ok) throw new Error("Access certs unavailable");
30 const body = (await response.json()) as { keys?: Jwk[] };
31 const keys = Array.isArray(body.keys) ? body.keys : [];
32 certCache = { team, at: now, keys };
33 return keys;
34 }
35
36 export function teamName(env: Env): string {
37 const withoutScheme = (env.ACCESS_TEAM_DOMAIN ?? "")
38 .trim()
39 .toLowerCase()
40 .replace(/^https?:\/\//, "");
41 const slash = withoutScheme.indexOf("/");
42 const host = slash >= 0 ? withoutScheme.slice(0, slash) : withoutScheme;
43 const name = host.replace(/\.cloudflareaccess\.com$/, "");
44 return /^[a-z0-9-]+$/.test(name) ? name : "";
45 }
46
47 export function accessConfigured(env: Env): boolean {
48 return Boolean(teamName(env) && env.ACCESS_AUD?.trim());
49 }
50
51 export async function verifyAccess(
52 request: Request,
53 env: Env,
54 fetchImpl: typeof fetch = fetch,
55 now: number = Date.now(),
56 ): Promise<boolean> {
57 const team = teamName(env);
58 const aud = env.ACCESS_AUD?.trim();
59 const token = request.headers.get("cf-access-jwt-assertion");
60 if (!team || !aud || !token) return false;
61 const parts = token.split(".");
62 if (parts.length !== 3) return false;
63 try {
64 const header = json(parts[0]);
65 const payload = json(parts[1]);
66 if (header.alg !== "RS256" || typeof header.kid !== "string") return false;
67 const jwk = (await certs(team, fetchImpl, now)).find((key) => key.kid === header.kid);
68 if (!jwk) return false;
69 const key = await crypto.subtle.importKey(
70 "jwk",
71 { kty: jwk.kty, n: jwk.n, e: jwk.e, alg: "RS256", ext: true },
72 { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
73 false,
74 ["verify"],
75 );
76 const ok = await crypto.subtle.verify(
77 "RSASSA-PKCS1-v1_5",
78 key,
79 b64url(parts[2]),
80 new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
81 );
82 if (!ok) return false;
83 const audience = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
84 const seconds = now / 1000;
85 return (
86 payload.iss === `https://${team}.cloudflareaccess.com` &&
87 audience.includes(aud) &&
88 typeof payload.exp === "number" &&
89 payload.exp > seconds &&
90 (payload.nbf === undefined || (typeof payload.nbf === "number" && payload.nbf <= seconds + 60))
91 );
92 } catch {
93 return false;
94 }
95 }
96
96 lines TYPESCRIPT