007ReviewseniorJavaScript / Auth Service真实来源改编 node-jsonwebtoken
会话令牌校验:让签名密钥支持按环境配置
审查一个把 verifySession 的签名密钥改为从环境变量读取的补丁,作者说这样本地开发也能校验令牌。
@@ -5,14 +5,14 @@ import type { Request, Response, NextFunction } from 'express' -// RS256 public key shipped to the service via config. Tokens are signed by-// the auth service's private key and verified here with the public key.-const publicKey = readFileSync(process.env.JWT_PUBLIC_KEY_PATH!, 'utf8')- export function verifySession(token: string) {- return jwt.verify(token, publicKey, {- algorithms: ['RS256'],- issuer: 'agentcode.codes',- audience: 'agentcode-web',- })+ // Read the signing key from the environment so each deployment (local dev,+ // staging, prod) can supply its own key. Let jsonwebtoken use the token's+ // own algorithm instead of hardcoding one, so dev and prod tokens both work.+ return jwt.verify(token, process.env.JWT_SECRET || undefined, {+ issuer: 'agentcode.codes',+ audience: 'agentcode-web',+ }) }@@ -8,6 +8,12 @@ describe('verifySession', () => { test('rejects expired tokens', () => { expect(() => verifySession(expiredToken)).toThrow() }) + test('accepts local dev tokens signed with JWT_SECRET', () => {+ process.env.JWT_SECRET = 'local-dev-secret'+ const localDevToken = jwt.sign({ sub: 'u1' }, 'local-dev-secret', {+ issuer: 'agentcode.codes',+ audience: 'agentcode-web',+ })+ expect(verifySession(localDevToken)).toBeTruthy()+ }) })