workers-start 0.7.1 → 0.9.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 +9 -0
- package/README.md +111 -10
- package/dist/access-testing.d.ts +29 -0
- package/dist/access-testing.d.ts.map +1 -0
- package/dist/access-testing.js +60 -0
- package/dist/access-testing.js.map +1 -0
- package/dist/access.d.ts +90 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +213 -0
- package/dist/access.js.map +1 -0
- package/dist/google.d.ts +148 -0
- package/dist/google.d.ts.map +1 -0
- package/dist/google.js +224 -0
- package/dist/google.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +19 -2
- package/src/access-testing.ts +121 -0
- package/src/access.ts +313 -0
- package/src/google.ts +418 -0
- package/src/index.ts +43 -0
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
|
+
}
|