@jgb-solutions/kit 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JGB Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # @jgb-solutions/kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Small, typed, tree-shakable modules for the generic plumbing web apps need: the kind of code every app would otherwise copy by hand. ESM with TypeScript types, one subpath per module, MIT licensed. The modules run anywhere with Web Crypto and `fetch`: Bun, Node and Cloudflare Workers.
4
+
5
+ ```bash
6
+ bun add @jgb-solutions/kit
7
+ ```
8
+
9
+ ## Modules
10
+
11
+ ### `@jgb-solutions/kit/access`: Cloudflare Access, checked on the server
12
+
13
+ Cloudflare Access signs people in at the edge and passes a signed token (RS256) with each request it lets through: the `Cf-Access-Jwt-Assertion` header and the `CF_Authorization` cookie. An edge rule only covers the paths it matches, so client-side navigation, server functions and RPC calls can reach the server without passing through it. Check the token on the server for every protected call:
14
+
15
+ ```ts
16
+ import { verifyAccess } from '@jgb-solutions/kit/access'
17
+
18
+ // The app's own Access application: its team domain and audience (AUD) tag.
19
+ const settings = { teamDomain: '<team>.cloudflareaccess.com', aud: '<the application AUD tag>' }
20
+
21
+ const result = await verifyAccess(request.headers, settings)
22
+ if (!result.ok) return new Response('Forbidden', { status: 403 }) // result.reason says why
23
+ result.email // the signed-in person (null for a service token)
24
+ ```
25
+
26
+ - **Fails closed.** Missing settings, no token, a bad signature, the wrong issuer or audience, an expired token or keys that can't be fetched all return `{ ok: false, reason }`. It never throws.
27
+ - **RS256 only.** The issuer must be `https://<team>.cloudflareaccess.com`, and the token must carry `exp`, `iat`, `iss` and `aud`. The default clock tolerance is 30 seconds.
28
+ - **Keys:** Access's public keys for the team, fetched from its `cdn-cgi/access/certs` endpoint and cached (5-second timeout).
29
+ - **Tests sign their own tokens.** A test server makes a throwaway key pair and passes the public key set in `ACCESS_TEST_JWKS`. `accessTestKeys(env, { enabled })` returns those keys only when the caller says it is a test server:
30
+
31
+ ```ts
32
+ const keys = accessTestKeys(process.env, { enabled: process.env.E2E === '1' && !isProductionBuild })
33
+ const result = await verifyAccess(headers, { ...settings, ...(keys ? { keys } : {}) })
34
+ ```
35
+
36
+ - **The production guard.** Anyone holding a test key could sign in where test keys are accepted. Where the production build starts, refuse to run with any test-only setting:
37
+
38
+ ```ts
39
+ const problems = accessTestProblems(process.env, { production: isProductionBuild, alsoForbidden: ['E2E'] })
40
+ if (problems.length) throw new Error(problems.join('\n'))
41
+ ```
42
+
43
+ Keep the app's own role check after this one: Access decides who may reach the app, and the app decides what they may do.
44
+
45
+ ## What goes in, and what never goes in
46
+
47
+ **In:** generic plumbing that several apps need in the same shape, written once and tested: checking a signed token, parsing a header, a retry or rate-limit helper, a typed client for a public protocol. Every module:
48
+
49
+ - takes its settings from the caller (team names, audiences, URLs, limits);
50
+ - has full unit tests;
51
+ - has no side effects at import, and no dependency it doesn't need.
52
+
53
+ **Never in:**
54
+
55
+ - **Business logic:** how an app works, decides, charges or ranks. That stays in the app.
56
+ - **Secrets of any kind:** keys, tokens, passwords, signing material.
57
+ - **App and account identifiers:** Access team names and AUD tags, account or zone IDs, database or bucket names, app slugs.
58
+ - **Infrastructure details:** hosts, IP addresses, server names, internal URLs, deploy setup.
59
+ - **Personal data, or real addresses outside `example.com`.**
60
+
61
+ `bun run check:package` scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside `example.com`, and on any file besides `dist/`, the README, the license and `package.json`.
62
+
63
+ ## Developing
64
+
65
+ Bun only: `bun install`, `bun test`, `bun run typecheck` (`bun check`), `bun run format` (`bun fmt`), `bun run build` (one ESM file per export, plus `.d.ts` types), `bun run check:package`.
66
+
67
+ A new module goes in `src/<name>.ts` with `src/<name>.test.ts`, and gets its own subpath in `package.json`'s `exports` (`./<name>` pointing at `./dist/<name>.js` and `./dist/<name>.d.ts`).
68
+
69
+ ## Publishing
70
+
71
+ Only GitHub Actions publishes (`.github/workflows/publish.yml`), when a GitHub release is published for the tag `vX.Y.Z` matching `package.json`'s version. It uses npm's trusted publishing (OIDC): no npm token is stored anywhere, and npm attaches a provenance statement that links each version to the commit and workflow that built it. The `npm` environment can hold each publish for the owner's approval.
72
+
73
+ Versions follow semver. A breaking change to any module is a new major version.
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Cloudflare Access, checked on the server.
3
+ *
4
+ * Access signs people in at the edge and sends a signed token (a JWT, RS256) with every request it
5
+ * lets through: the `Cf-Access-Jwt-Assertion` header, and the `CF_Authorization` cookie it sets for
6
+ * the host. An edge rule only covers what it matches: client-side navigation and server functions
7
+ * (`/_serverFn/…`, RPC calls) often don't pass through it. So the app checks the token itself, on every
8
+ * protected call, with the team domain and the application's audience (AUD) tag it passes in.
9
+ *
10
+ * Fails closed: no settings, no token, a bad signature, the wrong issuer or audience, an expired
11
+ * token, or keys that can't be fetched all mean no access.
12
+ *
13
+ * import { verifyAccess } from '@jgb-solutions/kit/access'
14
+ * const result = await verifyAccess(request.headers, { teamDomain, aud })
15
+ * if (!result.ok) return new Response('Forbidden', { status: 403 })
16
+ */
17
+ import { type JWTVerifyGetKey } from 'jose';
18
+ export type AccessSettings = {
19
+ /** The Zero Trust team domain: `<team>.cloudflareaccess.com`. */
20
+ teamDomain: string;
21
+ /** The Access application's audience (AUD) tag. */
22
+ aud: string;
23
+ /**
24
+ * The keys that sign the tokens. Leave it out in production: Access's public keys for the team are
25
+ * fetched from `https://<team>/cdn-cgi/access/certs` and cached. Tests pass `accessTestKeys(…)`.
26
+ */
27
+ keys?: JWTVerifyGetKey;
28
+ /** Allowed clock difference with Cloudflare, in seconds (30 by default). */
29
+ clockToleranceSeconds?: number;
30
+ };
31
+ export type AccessFailure = 'not-configured' | 'no-token' | 'bad-signature' | 'wrong-issuer' | 'wrong-audience' | 'expired' | 'keys-unavailable' | 'invalid';
32
+ export type AccessResult = {
33
+ ok: true;
34
+ /** The signed-in person's email, when the token carries one (service tokens don't). */
35
+ email: string | null;
36
+ /** The token's subject: the Access user ID, or the service token's client ID. */
37
+ subject: string | null;
38
+ } | {
39
+ ok: false;
40
+ reason: AccessFailure;
41
+ };
42
+ /** The token Access sent: its header first, then its cookie (server functions only carry the cookie). */
43
+ export declare function accessToken(headers: Headers): string | null;
44
+ /** Checks the request's Access token against the team and application. Never throws. */
45
+ export declare function verifyAccess(headers: Headers, settings: AccessSettings | null | undefined): Promise<AccessResult>;
46
+ /** The environment variables that only an app's test server may set (see `accessTestKeys`). */
47
+ export declare const ACCESS_TEST_VARIABLES: readonly ["ACCESS_TEST_JWKS", "ACCESS_TEST_TEAM_DOMAIN", "ACCESS_TEST_AUD"];
48
+ /**
49
+ * Test keys: a test server signs its own tokens with a throwaway key pair and passes the public half
50
+ * as a JSON Web Key Set in `ACCESS_TEST_JWKS`. Returns those keys only when the caller says this is a
51
+ * test server (`enabled`); otherwise undefined, so the real keys are used. Anyone holding a test key
52
+ * could sign in where these keys are accepted: enable them only in tests, and run
53
+ * `accessTestProblems` where the production build starts.
54
+ */
55
+ export declare function accessTestKeys(env: Record<string, string | undefined>, options: {
56
+ enabled: boolean;
57
+ }): JWTVerifyGetKey | undefined;
58
+ /**
59
+ * The production guard: what a production server must refuse to start with. Lists every test-only
60
+ * variable that is set (`ACCESS_TEST_*`, plus any the app names in `alsoForbidden`, such as its E2E
61
+ * flag); empty when the environment is safe. Outside production it always returns an empty list.
62
+ *
63
+ * const problems = accessTestProblems(process.env, { production: process.env.APP_IMAGE === '1', alsoForbidden: ['E2E'] })
64
+ * if (problems.length) throw new Error(problems.join('\n'))
65
+ */
66
+ export declare function accessTestProblems(env: Record<string, string | undefined>, options: {
67
+ production: boolean;
68
+ alsoForbidden?: readonly string[];
69
+ }): string[];
package/dist/access.js ADDED
@@ -0,0 +1,94 @@
1
+ // src/access.ts
2
+ import { createLocalJWKSet, createRemoteJWKSet, errors, jwtVerify } from "jose";
3
+ function accessToken(headers) {
4
+ const header = headers.get("cf-access-jwt-assertion")?.trim();
5
+ if (header)
6
+ return header;
7
+ for (const part of (headers.get("cookie") ?? "").split(";")) {
8
+ const [name, ...rest] = part.trim().split("=");
9
+ if (name === "CF_Authorization")
10
+ return rest.join("=") || null;
11
+ }
12
+ return null;
13
+ }
14
+ var TEAM_DOMAIN = /^[a-z0-9-]+\.cloudflareaccess\.com$/;
15
+ var remoteKeys = new Map;
16
+ function keysFor(teamDomain) {
17
+ let keys = remoteKeys.get(teamDomain);
18
+ if (!keys) {
19
+ keys = createRemoteJWKSet(new URL(`https://${teamDomain}/cdn-cgi/access/certs`), { timeoutDuration: 5000 });
20
+ remoteKeys.set(teamDomain, keys);
21
+ }
22
+ return keys;
23
+ }
24
+ async function verifyAccess(headers, settings) {
25
+ if (typeof settings?.aud !== "string" || !settings.aud.trim() || typeof settings.teamDomain !== "string" || !TEAM_DOMAIN.test(settings.teamDomain))
26
+ return { ok: false, reason: "not-configured" };
27
+ const token = accessToken(headers);
28
+ if (!token)
29
+ return { ok: false, reason: "no-token" };
30
+ try {
31
+ const { payload } = await jwtVerify(token, settings.keys ?? keysFor(settings.teamDomain), {
32
+ issuer: `https://${settings.teamDomain}`,
33
+ audience: settings.aud,
34
+ algorithms: ["RS256"],
35
+ requiredClaims: ["exp", "iat", "iss", "aud"],
36
+ clockTolerance: settings.clockToleranceSeconds ?? 30
37
+ });
38
+ return {
39
+ ok: true,
40
+ email: typeof payload.email === "string" ? payload.email : null,
41
+ subject: typeof payload.sub === "string" ? payload.sub : null
42
+ };
43
+ } catch (error) {
44
+ return { ok: false, reason: failureOf(error) };
45
+ }
46
+ }
47
+ function failureOf(error) {
48
+ if (error instanceof errors.JWTExpired)
49
+ return "expired";
50
+ if (error instanceof errors.JWTClaimValidationFailed) {
51
+ if (error.claim === "iss")
52
+ return "wrong-issuer";
53
+ if (error.claim === "aud")
54
+ return "wrong-audience";
55
+ return "invalid";
56
+ }
57
+ if (error instanceof errors.JWSSignatureVerificationFailed || error instanceof errors.JWKSNoMatchingKey)
58
+ return "bad-signature";
59
+ if (error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid || error instanceof TypeError)
60
+ return "keys-unavailable";
61
+ return "invalid";
62
+ }
63
+ var ACCESS_TEST_VARIABLES = ["ACCESS_TEST_JWKS", "ACCESS_TEST_TEAM_DOMAIN", "ACCESS_TEST_AUD"];
64
+ function accessTestKeys(env, options) {
65
+ if (!options.enabled)
66
+ return;
67
+ const jwks = env.ACCESS_TEST_JWKS;
68
+ return jwks ? createLocalJWKSet(parseKeySet(jwks)) : undefined;
69
+ }
70
+ function accessTestProblems(env, options) {
71
+ if (!options.production)
72
+ return [];
73
+ const set = (name) => env[name] !== undefined && env[name] !== "";
74
+ return [...ACCESS_TEST_VARIABLES, ...options.alsoForbidden ?? []].filter(set).map((name) => `${name} is set; it is for the test server only`);
75
+ }
76
+ function parseKeySet(text) {
77
+ let value;
78
+ try {
79
+ value = JSON.parse(text);
80
+ } catch {
81
+ throw new Error("ACCESS_TEST_JWKS must be a JSON Web Key Set (it is not JSON)");
82
+ }
83
+ if (typeof value !== "object" || value === null || !("keys" in value) || !Array.isArray(value.keys)) {
84
+ throw new Error('ACCESS_TEST_JWKS must be a JSON Web Key Set ({ "keys": [...] })');
85
+ }
86
+ return { keys: value.keys.filter((key) => typeof key === "object" && key !== null) };
87
+ }
88
+ export {
89
+ ACCESS_TEST_VARIABLES,
90
+ accessTestKeys,
91
+ accessTestProblems,
92
+ accessToken,
93
+ verifyAccess
94
+ };
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@jgb-solutions/kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Generic plumbing for web apps on Bun and Cloudflare Workers: small, typed, tree-shakable modules.",
5
+ "license": "MIT",
6
+ "author": "JGB Solutions",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jgb-solutions/kit.git"
10
+ },
11
+ "homepage": "https://github.com/jgb-solutions/kit#readme",
12
+ "bugs": "https://github.com/jgb-solutions/kit/issues",
13
+ "keywords": [
14
+ "cloudflare-access",
15
+ "jwt",
16
+ "jose",
17
+ "bun",
18
+ "cloudflare-workers"
19
+ ],
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "exports": {
28
+ "./access": {
29
+ "types": "./dist/access.d.ts",
30
+ "import": "./dist/access.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ },
41
+ "packageManager": "bun@1.4.5",
42
+ "scripts": {
43
+ "build": "bun scripts/build.ts",
44
+ "typecheck": "bun check",
45
+ "test": "bun test",
46
+ "format": "bun fmt .",
47
+ "format:check": "bun fmt --check .",
48
+ "check:package": "bun scripts/check-package.ts",
49
+ "prepublishOnly": "bun run build && bun run check:package"
50
+ },
51
+ "dependencies": {
52
+ "jose": "6.2.18"
53
+ },
54
+ "devDependencies": {
55
+ "@types/bun": "1.4.5",
56
+ "typescript": "6.0.3"
57
+ }
58
+ }