Skip to content

Commit c9d0374

Browse files
PiquelChipsclaude
andauthored
feat(sdk): validate auth.piquel.fr tokens from TypeScript, with no dependencies (#238)
Part of #58 · Stacked on #237 A JavaScript API that accepts tokens from auth.piquel.fr has to hand-roll JWT validation, JWKS caching and its `WWW-Authenticate` challenges, and get every edge case in `docs/architecture/sdk.md` right. This PR adds that to `@piquel/auth`, with no runtime dependencies, and checks it against the same vectors as the Rust SDK. ```ts const issuer = await Issuer.discover('https://auth.piquel.fr'); const notes = defineScopes('notes:read', 'notes:write'); const api = issuer.resource({ identifier: 'notes-api', scopes: notes }); const token = await api.authenticate(request); // throws AuthError; error.toResponse() is the challenge token.require('notes:write'); // narrows the type; an undeclared scope doesn't compile ``` ## How - **Discovery** parses the document as `unknown`, then applies serde's defaults and sdk.md's rules: the issuer must match exactly, S256 is required, every endpoint must use https, and unknown values are dropped. - **Key cache**: - an unknown `kid` triggers one refetch; - there is at most one fetch every 30 s; - keys stay fresh for `Cache-Control` max-age, bounded to 30 s–24 h; - a failed refresh keeps the last good set; - a set with a duplicate `kid` is rejected. RS256 is verified with WebCrypto, and the cache works with any JWKS URL. - **Token validation** runs sdk.md's 12 ordered checks for access, ID and logout tokens, with the shared reasons. `AccessToken.requireAuthentication` applies the same step-up rule as `StepUpRequirement`. - **Application claims**: a resource's `claims` reader reads the app's own claims into `token.extra`, typed by what it returns, like Rust's `with_claims`. It runs with the claims check, so throwing fails with `invalid_claims`. - **Challenges**: `AuthError` (`code`, `reason`, `cause`), its `challenge()` and `toResponse()`, and `parseChallenge` / `formatChallenge`, which follow the Rust grammar exactly. - **Tests** use Node's built-in runner on the TS sources, so they need no test dependency: `just web test`, now part of `just validate` and CI. - **Runtime smoke tests**: `just web smoke` validates a vector token with the built package in Node, Bun and workerd. CI installs Bun with a pinned setup action. Deno isn't covered: it is shutting down, with security updates only for a year. The one new dev dependency is `workerd`, pinned and in `packages/auth` only. Two decisions for review: - A request with no token, or a malformed `Authorization` header, has no shared category. `AuthError` reports these as `missing_token` (401) and `invalid_request` (400), and sdk.md documents this. - `Clock` returns milliseconds, like `Date.now`. ## Since review - **Weak keys:** RSA keys under 2048 or over 8192 bits verify nothing. The size is read from the imported key, so zero-padding `n` doesn't hide a weak key. A new shared vector, `tokens/access-weak-key.json`, checks this in both SDKs, and sdk.md states the rule. - **`authenticate(request, ...scopes)`:** it requires the scopes, narrowing the token's type to them, and names them in the challenge to a request without a token. - **Repeated `Authorization` headers:** several headers, one of them Bearer, are malformed (400). A single header of another scheme that contains commas, such as Digest, counts as no token. `Bearer a b` fails validation with 401. - **Constructors:** classes only the SDK builds have private constructors, so the `.d.ts` files no longer offer a public one that throws. - **Shared helper:** one `AuthError.invalidToken`. - **Vector runner:** a `null` nonce reads as none. - **Deno:** no longer checked, since it is shutting down. - **Policy links:** discovery reads `op_policy_uri` and `op_tos_uri`, which auth advertises since #320. The discovery vectors expect them. ## Proof - `pnpm test` passes 71/71: every discovery, jwks, token and challenge vector, plus key-cache, resource and `tsc`-checked type tests. - `just web smoke` passes in Node, Bun and workerd. - A consumer project type-checks against the built `.d.ts` files under both `node16` and `bundler` resolution. - `pnpm check`, `pnpm lint` (including publint and attw) and the generated-types stale check all pass. Reviewed with review-loop: 5 rounds with 5× Claude Opus 5.5 on xhigh, over the whole stack and #240. Verdict: approved > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol and Claude Opus 5.5 (via T3 Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e370227 commit c9d0374

39 files changed

Lines changed: 2939 additions & 26 deletions

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
#
44
# checks -> Rust formatting and the Rust dependency audit, which compile nothing
55
# web -> Prettier, tsc and ESLint, the passkey script included, the
6-
# TypeScript SDK's package checks and the web dependency audit
6+
# TypeScript SDK's package checks, tests and runtime smoke in Node,
7+
# Bun and workerd, and the web dependency audit
78
# rust -> Clippy, unit, database and doc tests against PostgreSQL, and the
89
# SQLx query cache checked against the migrated schema
910
# e2e -> the browser suite over HTTPS against the real binary and PostgreSQL,
@@ -120,6 +121,11 @@ jobs:
120121
- run: just web fmt-check
121122
- run: just web check
122123
- run: just web lint
124+
- run: just web test
125+
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
126+
with:
127+
bun-version: 1.x
128+
- run: just web smoke
123129
- if: needs.changes.outputs.deps == 'true'
124130
run: just web audit
125131

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -731,12 +731,13 @@ Use individual recipes while iterating:
731731

732732
| Task | Recipe |
733733
| --- | --- |
734-
| Full validation (format, Clippy/ESLint, Rust/TypeScript checks, unit/doc tests, audits) | `just validate` |
734+
| Full validation (format, Clippy/ESLint, Rust/TypeScript checks, Rust and SDK unit tests, doc tests, audits) | `just validate` |
735735
| Format Rust and web / check formatting | `just fmt` / `just fmt-check` |
736736
| Rust / TypeScript checks (tsc, the passkey script's JSDoc types included) | `just rust check` / `just web check` |
737737
| Clippy and ESLint, warnings denied; `publint` and `attw` on the built TypeScript SDK | `just lint` (`just rust lint` / `just web lint`) |
738738
| Regenerate the SDK vectors / the TypeScript SDK's wire types | `just sdk-vectors` / `just sdk-types` |
739739
| Unit tests / focused package tests | `just test` / `just test -p auth-service` |
740+
| TypeScript SDK tests, the shared vectors included / the built SDK in Node, Bun and workerd | `just web test` / `just web smoke` |
740741
| Documentation tests | `just doc-test` |
741742
| Database integration tests and query cache check, in a scratch cluster | `just db test` |
742743
| Query cache check alone, against a migrated `TEST_DATABASE_URL` | `just db prepare-check` |

‎crates/common/tests/sdk_vectors.rs‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ const CODE: &str = "pac_v1_01936f3e-8c00-7000-8000-000000000004.c2VjcmV0";
5151
const OLD_KID: &str = "key-2025";
5252
/// Key signing after the rotation.
5353
const NEW_KID: &str = "key-2026";
54+
/// A 1024-bit key, too weak for any SDK to accept.
55+
const WEAK_KID: &str = "key-weak";
5456

5557
/// One case file: inputs, the clock, and the expected result.
5658
#[derive(Serialize)]
@@ -98,6 +100,8 @@ struct Vectors {
98100
new: Rs256Key,
99101
/// The old key's PEM, to sign tokens whose header auth's signer would never write.
100102
old_pem: String,
103+
/// The weak key's PEM, which auth's signer refuses.
104+
weak_pem: String,
101105
}
102106

103107
impl Vectors {
@@ -118,6 +122,7 @@ impl Vectors {
118122
old: key(OLD_KID),
119123
new: key(NEW_KID),
120124
old_pem: pem(OLD_KID),
125+
weak_pem: pem(WEAK_KID),
121126
}
122127
}
123128

@@ -511,6 +516,26 @@ impl Vectors {
511516
),
512517
Expected::error(ErrorCategory::InvalidToken, ErrorReason::BadSignature),
513518
);
519+
// The Rust SDK's verifier refuses RSA keys under 2048 bits, so every SDK must.
520+
let weak = PKey::private_key_from_pem(self.weak_pem.as_bytes()).expect("weak test key");
521+
let weak = weak.rsa().expect("RSA test key");
522+
let weak_jwks = json!({ "keys": [{
523+
"alg": Algorithm::Rs256.as_str(), "e": URL_SAFE_NO_PAD.encode(weak.e().to_vec()),
524+
"kid": WEAK_KID, "kty": "RSA", "n": URL_SAFE_NO_PAD.encode(weak.n().to_vec()),
525+
"use": "sig",
526+
}]});
527+
let weak_header = json!({
528+
"alg": Algorithm::Rs256.as_str(), "kid": WEAK_KID, "typ": TokenType::Access.as_str(),
529+
});
530+
self.token(
531+
"access-weak-key",
532+
"a token signed with a 1024-bit RSA key is rejected",
533+
access_case(
534+
Self::sign_with(&self.weak_pem, &weak_header, &access),
535+
&weak_jwks,
536+
),
537+
Expected::error(ErrorCategory::InvalidToken, ErrorReason::BadSignature),
538+
);
514539
let mut incomplete = serde_json::to_value(&access).expect("serialize claims");
515540
incomplete
516541
.as_object_mut()
@@ -820,12 +845,17 @@ impl Vectors {
820845
/// Signs `claims` under a hand-written `header` with the old key, for headers
821846
/// auth's signer never writes.
822847
fn sign_header(&self, header: &Value, claims: &impl Serialize) -> String {
848+
Self::sign_with(&self.old_pem, header, claims)
849+
}
850+
851+
/// Signs `claims` under `header` with the key in `pem`.
852+
fn sign_with(pem: &str, header: &Value, claims: &impl Serialize) -> String {
823853
let input = format!(
824854
"{}.{}",
825855
URL_SAFE_NO_PAD.encode(serde_json::to_vec(header).expect("header")),
826856
URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).expect("claims"))
827857
);
828-
let key = PKey::private_key_from_pem(self.old_pem.as_bytes()).expect("test key");
858+
let key = PKey::private_key_from_pem(pem.as_bytes()).expect("test key");
829859
let mut signer = Signer::new(MessageDigest::sha256(), &key).expect("signer");
830860
signer.update(input.as_bytes()).expect("signing input");
831861
format!(

‎docs/architecture/monorepo.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ is authentication, with its account settings, and the admin dashboard.
1313
| `crates/crypto` | Random secrets, SHA-256, HMAC, PKCE and RS256 signing |
1414
| `crates/ui` | `piquel-ui`: the Topcoat components and layouts of auth's server-rendered pages, rendering plain data and taking URLs as props, the admin dashboard's included; the document piquel.fr's pages share, and the shared stylesheet, `assets/style.css` |
1515
| `crates/telemetry` | `piquel-telemetry`: stderr logs, and OpenTelemetry traces, metrics and logs over OTLP; request spans and access logs for axum routers, client spans, and typed metric instruments; see [telemetry.md](telemetry.md) |
16-
| `packages/auth` | `@piquel/auth`, the TypeScript SDK (#58), not yet published; `src/protocol.ts` is generated from `piquel_common::protocol` |
16+
| `packages/auth` | `@piquel/auth`, the TypeScript SDK, not yet published: discovery, token validation, typed scopes, challenges and the JWKS cache, with no runtime dependencies; `src/protocol.ts` is generated from `piquel_common::protocol` |
1717
| `tests/sdk-vectors` | Generated cases every SDK must pass; see [sdk.md](sdk.md) |
1818

1919
Prettier and type-aware ESLint cover all web code from the root configuration, as

‎docs/architecture/sdk.md‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
# SDK design
22

33
Applications integrate with auth.piquel.fr through its Rust SDK, `piquel-auth`, its
4-
TypeScript SDK, `@piquel/auth` (in development, #58), or any OpenID Connect library. The SDK follows this document and passes the shared
5-
vectors in [`tests/sdk-vectors`](../../tests/sdk-vectors/README.md); an SDK in another
6-
language would do the same, so every SDK accepts and rejects the same tokens and
7-
challenges.
4+
TypeScript SDK, `@piquel/auth`, or any OpenID Connect library. Both SDKs follow this
5+
document and pass the shared vectors in
6+
[`tests/sdk-vectors`](../../tests/sdk-vectors/README.md); an SDK in another language
7+
would do the same, so every SDK accepts and rejects the same tokens and challenges.
8+
The Rust SDK is the reference implementation, and the TypeScript SDK mirrors its
9+
behavior and names.
810

911
| Path | Package | Published | Role |
1012
| --- | --- | --- | --- |
1113
| `crates/common` | `piquel-common` | yes | Shared types; with no features, the IDs and wire types shared by auth and the Rust SDK |
1214
| `crates/auth-sdk` | `piquel-auth` | yes | Rust SDK; the `axum` feature adds the axum integration |
13-
| `packages/auth` | `@piquel/auth` | not yet | TypeScript SDK, ESM only, with no runtime dependencies |
15+
| `packages/auth` | `@piquel/auth` | not yet | TypeScript SDK, ESM only, with no runtime dependencies: `fetch` and WebCrypto, so it runs in browsers, Node, Bun and Workers |
1416
| `tests/sdk-vectors` | none | no | Shared test vectors |
1517

1618
## Wire types
@@ -54,7 +56,7 @@ older SDKs.
5456
it understands.
5557

5658
The SDK takes an injectable clock, so tests and the vectors can pin time, and an
57-
injectable HTTP client.
59+
injectable HTTP client: a `reqwest` client in Rust, a `fetch` in TypeScript.
5860

5961
## Token validation
6062

@@ -114,17 +116,20 @@ The SDK caches the issuer's key set:
114116
- Keys of an unknown `kty`, and keys whose `use` is not `sig`, are skipped (RFC 7517
115117
§5). A set where two keys share a `kid` is rejected as a whole, and the previous
116118
set stays in use.
119+
- An RSA key whose modulus is under 2048 or over 8192 bits verifies nothing: its
120+
tokens fail with `bad_signature`.
117121

118122
This handles signing key rotation: auth publishes the new key before it signs with
119-
it, so tokens from both keys verify during the overlap. The Rust key cache works
120-
with any JWKS URL, so auth also uses it for Google.
123+
it, so tokens from both keys verify during the overlap. Both SDKs' key caches work
124+
with any JWKS URL, so auth also uses the Rust one for Google.
121125

122126
## Scopes
123127

124128
Scopes are space-separated strings on the wire (RFC 6749 §3.3), and each token is
125-
printable ASCII without spaces, `"` or `\`. Each SDK types them: the Rust SDK
126-
declares an application's scopes once with a macro, so a required scope is a type
127-
and a misspelled scope does not compile.
129+
printable ASCII without spaces, `"` or `\`. Each SDK types them, so a misspelled
130+
scope does not compile: the Rust SDK declares an application's scopes once with a
131+
macro, so a required scope is a type, and the TypeScript SDK with `defineScopes`,
132+
whose names become a union that `AccessToken.require` accepts.
128133

129134
## Errors
130135

@@ -153,6 +158,10 @@ On a resource server, each error maps to one `WWW-Authenticate: Bearer` challeng
153158
| `insufficient_user_authentication` | 401 | `error="insufficient_user_authentication"` with `acr_values` and `max_age` |
154159
| A malformed `Authorization` header | 400 | `error="invalid_request"` |
155160

161+
The Rust SDK's axum extractors report the request rows themselves. The TypeScript
162+
SDK's `AuthError` reports them with two codes outside the shared categories,
163+
`missing_token` and `invalid_request`, and every row with `toResponse()`.
164+
156165
The parameters are always written in the order `error`, `error_description`,
157166
`scope`, `acr_values`, `max_age`, `resource_metadata`, with every value quoted, so
158167
every SDK produces identical headers. `error_description` is printable ASCII without

‎eslint.config.js‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,22 @@ export default defineConfig(
3535
// Node globals, so ESLint's environment-unaware check only adds noise.
3636
'no-undef': 'off',
3737
// The codebase consistently declares object shapes as type aliases.
38-
'@typescript-eslint/consistent-type-definitions': ['error', 'type']
38+
'@typescript-eslint/consistent-type-definitions': ['error', 'type'],
39+
// node:test reports the promises `test` and `describe` return itself.
40+
'@typescript-eslint/no-floating-promises': [
41+
'error',
42+
{
43+
allowForKnownSafeCalls: [
44+
{ from: 'package', package: 'node:test', name: ['test', 'describe'] }
45+
]
46+
}
47+
]
3948
}
49+
},
50+
{
51+
// The runtime smoke scripts import the built package, which does not exist yet
52+
// when linting runs, so they get the rules that need no types.
53+
files: ['packages/auth/test/smoke/*.js'],
54+
extends: [ts.configs.disableTypeChecked]
4055
}
4156
);

‎just/web.just‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@ fmt-check:
1212
lint:
1313
@pnpm lint
1414

15+
# The TypeScript SDK's unit tests, every shared vector but the callbacks included.
16+
test:
17+
@pnpm test
18+
19+
# workerd is the Cloudflare Workers runtime. Needs `bun`, as CI installs it.
20+
# Validate a vector token with the built TypeScript SDK in Node, Bun and workerd.
21+
smoke:
22+
@pnpm --filter @piquel/auth build
23+
@node packages/auth/test/smoke/smoke.js
24+
@bun packages/auth/test/smoke/smoke.js
25+
@pnpm --filter @piquel/auth exec node test/smoke/workerd.js
26+
1527
# Requires a running auth service; see tests/browser/README.md.
1628
[positional-arguments]
1729
test-browser *ARGS:

‎justfile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ default: validate
44
# Rust formatting, linting, checks, audits and the auth-service and piquel-web builds.
55
mod rust 'just/rust.just'
66

7-
# Web formatting, linting, type checks and the browser tests.
7+
# Web formatting, linting, type checks, the TypeScript SDK's tests and the browser tests.
88
mod web 'just/web.just'
99

1010
# Scratch PostgreSQL clusters, database tests, the SQLx query cache and migrations.
@@ -20,7 +20,7 @@ alias format := fmt
2020
alias preview := infra::preview
2121
alias preview-delete := infra::preview-delete
2222

23-
validate: fmt-check lint check test doc doc-test audit
23+
validate: fmt-check lint check test web::test doc doc-test audit
2424

2525
install:
2626
@pnpm install --frozen-lockfile

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
"type": "module",
55
"packageManager": "pnpm@11.25.0",
66
"scripts": {
7-
"check": "tsc && tsc -p apps/auth-service/assets && tsc -p packages/auth --noEmit",
7+
"check": "tsc && tsc -p apps/auth-service/assets && tsc -p packages/auth --noEmit && tsc -p packages/auth/test",
88
"lint": "eslint --max-warnings 0 . && pnpm --filter @piquel/auth lint",
9+
"test": "pnpm --filter @piquel/auth test",
910
"format": "prettier --write .",
1011
"format:check": "prettier --check .",
1112
"test:browser": "playwright test"

‎packages/auth/README.md‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# @piquel/auth
2+
3+
The TypeScript SDK for [auth.piquel.fr](https://auth.piquel.fr). It is ESM only and
4+
has no runtime dependencies: it uses `fetch` and WebCrypto, so it runs in browsers,
5+
Node 22+, Bun and Cloudflare Workers. It follows the
6+
[SDK design](../../docs/architecture/sdk.md) and passes the shared
7+
[test vectors](../../tests/sdk-vectors/README.md), as the Rust SDK does.
8+
9+
## Resource servers
10+
11+
Discover the issuer once, declare the API's scopes, then validate each request's
12+
bearer token:
13+
14+
```ts
15+
import { AuthError, Issuer, defineScopes } from '@piquel/auth';
16+
17+
const issuer = await Issuer.discover('https://auth.piquel.fr');
18+
const notes = defineScopes('notes:read', 'notes:write');
19+
const api = issuer.resource({ identifier: 'notes-api', scopes: notes });
20+
21+
export async function handle(request: Request): Promise<Response> {
22+
try {
23+
// Requires notes:write, which a request without a token is told; 'notes:delete'
24+
// would not compile.
25+
const token = await api.authenticate(request, 'notes:write');
26+
token.requireAuthentication({ acr_values: 'phr', max_age: 300 });
27+
return Response.json({ user: token.subject.id });
28+
} catch (error) {
29+
if (error instanceof AuthError) return error.toResponse();
30+
throw error;
31+
}
32+
}
33+
```
34+
35+
- `Issuer.discover` requires the document's `issuer` to equal the URL exactly, `S256`
36+
PKCE and `https` endpoints.
37+
- `authenticate` reads `Authorization: Bearer` only, and `validate` takes a token.
38+
Both run every check of the SDK design in order, with a 30-second leeway on times.
39+
`authenticate` also requires the scopes it is given, and names them in the
40+
challenge to a request without a token.
41+
- `require` narrows the token's type to the scopes it proves, so a function can ask
42+
for `AccessToken<Notes, 'notes:write'>`. `has` checks without throwing.
43+
- `requireAuthentication` checks a `StepUpRequirement`: `phr` meets every class, and
44+
`max_age` needs `auth_time`.
45+
- `token.subject` is `{ kind: 'user', id }`, or `{ kind: 'client', id }` for a client
46+
acting for itself; `token.claims` holds every validated claim.
47+
- A resource's `claims` option reads the application's own claims, which auth does
48+
not define, into `token.extra`, typed by what it returns:
49+
`claims: (claims) => ({ tenant: String(claims.tenant) })`. It runs with the claims
50+
check, so throwing fails the token with `invalid_claims`.
51+
52+
Every failure is an `AuthError` with a `code` (the category) and a `reason` (the check
53+
that failed). `toResponse()` answers with the status and the canonical
54+
`WWW-Authenticate` challenge, or 503 when signing keys cannot be fetched.
55+
`parseChallenge` reads a challenge back, for clients stepping up.
56+
57+
`Issuer.discover` takes `fetch` and `clock` options, to send requests through another
58+
client or pin time in tests.
59+
60+
## Other JWKS issuers
61+
62+
`KeyCache` verifies JWS signatures against any JWKS URL, refetching once on an unknown
63+
key ID and at most every 30 seconds:
64+
65+
```ts
66+
import { Jws, KeyCache } from '@piquel/auth';
67+
68+
const keys = new KeyCache('https://www.googleapis.com/oauth2/v3/certs');
69+
const jws = Jws.parse(token);
70+
await keys.verify(jws, jws.requireAlgorithm(['RS256']));
71+
const claims: unknown = JSON.parse(new TextDecoder().decode(jws.payload));
72+
```
73+
74+
## Development
75+
76+
`src/protocol.ts` is generated from the Rust wire types by `just sdk-types`; do not
77+
edit it. `just web test` runs the unit tests and every shared vector with Node's test
78+
runner on the TypeScript sources, and `just web smoke` validates a vector token with
79+
the built package in Node, Bun and workerd.

0 commit comments

Comments
 (0)