feat: Implement JWT signing and verification middleware#5
Open
charliewwdev wants to merge 4 commits intomainfrom
Open
feat: Implement JWT signing and verification middleware#5charliewwdev wants to merge 4 commits intomainfrom
charliewwdev wants to merge 4 commits intomainfrom
Conversation
…iddleware/auth.ts
…iddleware/jwt.test.ts
…iddleware/auth.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Create middleware that signs JWTs using RS256 (asymmetric), validates signatures on incoming requests, and rejects malformed or expired tokens with appropriate 401 responses.
Generated by OpenDev AI
RS256 JWT implemented entirely with Node's built-in
cryptomodule — no third-party JWT library added, keeping the dependency footprint minimal.jwt.ts — core primitives:
signTokenbuildsheader.payload.signatureusingcreateSign('RSA-SHA256'). The iat claim is always stamped; exp/iss/aud/sub are added from SignOptions.verifyTokenchecks: 3-part structure → alg lock (RS256 only, prevents algorithm substitution attacks) → RSA signature → exp/nbf (with optional clockSkew tolerance) → iss/aud claims. Each failure raises aJwtErrorwith a typedcodeso callers can distinguish expired tokens from forged ones.Buffer.toString('base64url')(Node 16+) and a manual decode path that restores standard base64 padding.auth.ts — HTTP middleware:
createAuthMiddleware(publicKey, options)returns a standard(req, res, next)middleware compatible with Express, rawnode:http, and Hono adapters.Authorization: Bearer <token>strictly (rejects other schemes).tokenExtractorcan be supplied (e.g. cookie-based auth).req.authasAuthenticatedRequest.{ error, reason }andWWW-Authenticate: Bearer realm="opendev"header. Unexpected errors are forwarded tonext(err)so the outer error handler can log/report them.