Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/harden-private-jwk-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@agentcommercekit/keys": patch
---

Reject JWK objects with invalid private key fields in key type guards.
24 changes: 24 additions & 0 deletions packages/keys/src/encoding/jwk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest"

import { bytesToBase64url, isBase64url } from "./base64"
import {
isJwk,
isPrivateKeyJwk,
isPublicKeyJwk,
isPublicKeyJwkEd25519,
Expand Down Expand Up @@ -173,6 +174,29 @@ describe("JWK encoding", () => {
}
expect(isPrivateKeyJwk(invalidJwk)).toBe(false)
})

test("rejects private key JWKs with invalid d values", () => {
const baseJwk = {
kty: "OKP" as const,
crv: "Ed25519" as const,
x: "base64x",
}
const secp256k1Jwk = {
kty: "EC" as const,
crv: "secp256k1" as const,
x: "base64x",
y: "base64y",
}

expect(isPrivateKeyJwk({ ...baseJwk, d: 1 })).toBe(false)
expect(isPrivateKeyJwk({ ...baseJwk, d: "" })).toBe(false)
expect(isJwk({ ...baseJwk, d: 1 })).toBe(false)
expect(isJwk({ ...baseJwk, d: "" })).toBe(false)
expect(isPrivateKeyJwk({ ...secp256k1Jwk, d: 1 })).toBe(false)
expect(isPrivateKeyJwk({ ...secp256k1Jwk, d: "" })).toBe(false)
expect(isJwk({ ...secp256k1Jwk, d: 1 })).toBe(false)
expect(isJwk({ ...secp256k1Jwk, d: "" })).toBe(false)
})
})

describe("roundtrip", () => {
Expand Down
10 changes: 7 additions & 3 deletions packages/keys/src/encoding/jwk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}

function hasValidPrivateKey(jwk: Record<string, unknown>): boolean {
return !("d" in jwk) || (typeof jwk.d === "string" && jwk.d.length > 0)
}

/**
* JWK-encoding
*/
Expand Down Expand Up @@ -96,7 +100,7 @@ function isJwkSecp256(
return false
}

return true
return hasValidPrivateKey(jwk)
}

/**
Expand Down Expand Up @@ -142,7 +146,7 @@ export function isJwkEd25519(jwk: unknown): jwk is JwkEd25519 {
return false
}

return true
return hasValidPrivateKey(jwk)
}

export function isJwk(jwk: unknown): jwk is Jwk {
Expand Down Expand Up @@ -178,7 +182,7 @@ export function isPublicKeyJwkEd25519(
* Check if an object is a valid private key JWK
*/
export function isPrivateKeyJwk(jwk: unknown): jwk is PrivateKeyJwk {
return isJwk(jwk) && !!jwk.d
return isJwk(jwk) && "d" in jwk
}

export function isPrivateKeyJwkSecp256k1(
Expand Down