oauth.test.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. CREDENTIAL_DECRYPT_ERROR_CODE,
  4. CREDENTIAL_DECRYPT_ERROR_PREFIX,
  5. isCredentialDecryptError,
  6. resolveJwtExpiration,
  7. } from "../src/oauth.js";
  8. function createUnsignedJwt(payload: Record<string, unknown>): string {
  9. const encode = (value: object) => Buffer.from(JSON.stringify(value)).toString("base64url");
  10. return `${encode({ alg: "none", typ: "JWT" })}.${encode(payload)}.`;
  11. }
  12. describe("oauth errors", () => {
  13. it("recognizes credential decrypt errors by stable code", () => {
  14. expect(
  15. isCredentialDecryptError({
  16. code: CREDENTIAL_DECRYPT_ERROR_CODE,
  17. message: "serialized error without localized prefix",
  18. }),
  19. ).toBe(true);
  20. });
  21. it("keeps legacy message fallback only when code is missing", () => {
  22. expect(
  23. isCredentialDecryptError({
  24. message: `${CREDENTIAL_DECRYPT_ERROR_PREFIX}密钥不匹配或密文已损坏`,
  25. }),
  26. ).toBe(true);
  27. });
  28. it("does not let another error code match by localized message prefix", () => {
  29. expect(
  30. isCredentialDecryptError({
  31. code: "OTHER_ERROR",
  32. message: `${CREDENTIAL_DECRYPT_ERROR_PREFIX}业务错误`,
  33. }),
  34. ).toBe(false);
  35. });
  36. });
  37. describe("resolveJwtExpiration", () => {
  38. it("reports a JWT as expired with the configured clock skew", () => {
  39. const token = createUnsignedJwt({ exp: 1_000 });
  40. expect(resolveJwtExpiration(token, 1_030_000, 30_000)).toEqual({
  41. kind: "expired",
  42. expiresAt: 1_000_000,
  43. });
  44. });
  45. it("keeps a JWT valid before the expiration boundary", () => {
  46. const token = createUnsignedJwt({ exp: 1_001 });
  47. expect(resolveJwtExpiration(token, 970_000, 30_000)).toEqual({
  48. kind: "valid",
  49. expiresAt: 1_001_000,
  50. });
  51. });
  52. it.each(["legacy-token", createUnsignedJwt({ sub: "u-1" })])(
  53. "keeps an unprovable token compatible: %s",
  54. (token) => {
  55. expect(resolveJwtExpiration(token, 1_000_000, 30_000)).toEqual({ kind: "unknown" });
  56. },
  57. );
  58. });