// An API that takes the identity provider's tokens: the key is picked from its JWKS by `kid`.
//
//   quillo run jwks.qwe      then open http://localhost:8080/check
//
// In a real app the JWKS comes from the provider, fetched now and then:
//   let JWKS = http.get("https://YOUR_TENANT.auth0.com/.well-known/jwks.json")?.body
// Here it is a sample file, and the sample private key stands in for the provider.

use "jwks.qwer"

let JWKS = read_file("jwks_sample.json")?
let ISSUER = "https://id.example.com/"
let AUDIENCE = "orders-api"

fn signed_in(req) {
    let token = replace(req.headers.authorization ?? "", "Bearer ", "")
    let claims = jwks_verify(token, JWKS, AUDIENCE, ISSUER)
    if is_err(claims) { reply 401 { error: claims.error } }
    claims
}

route GET /keys = jwks_keys(JWKS)?

route GET /check {
    let key = read_file("jwks_sample_key.pem")?
    let token = jwks_sign({ sub: "user-42", aud: AUDIENCE, iss: ISSUER }, key, "2026-11-key-1", 300)?
    let wrong_audience = jwks_sign({ sub: "user-42", aud: "billing", iss: ISSUER }, key, "2026-11-key-1", 300)?
    let unknown_kid = jwks_sign({ sub: "user-42", aud: AUDIENCE, iss: ISSUER }, key, "old-key", 300)?
    {
        user: jwks_verify(token, JWKS, AUDIENCE, ISSUER)?.sub,
        wrong_audience: jwks_verify(wrong_audience, JWKS, AUDIENCE, ISSUER).error,
        unknown_kid: jwks_verify(unknown_kid, JWKS, AUDIENCE, ISSUER).error,
    }
}

route GET /me = request | signed_in | ((c) => { user: c.sub })
