Skip to content

Agent Mesh

sdk/js: identity and encodings without node:crypto and Buffer

Antonio Ojea08d03ed254da
diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json
index 73101ea1..dcc383c4 100644
--- a/sdk/js/package-lock.json
+++ b/sdk/js/package-lock.json
@@ -26,8 +26,10 @@
"@libp2p/websockets": "^10.1.21",
"@modelcontextprotocol/sdk": "^1.30.1",
"@multiformats/multiaddr": "^13.0.3",
+ "@noble/curves": "^2.0.1",
"libp2p": "^3.3.11",
"multiformats": "^14.0.5",
+ "uint8arrays": "^6.1.1",
"zod": "^4.6.5"
},
"devDependencies": {
diff --git a/sdk/js/package.json b/sdk/js/package.json
index 544d401e..a735ce3b 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -51,8 +51,10 @@
"@libp2p/websockets": "^10.1.21",
"@modelcontextprotocol/sdk": "^1.30.1",
"@multiformats/multiaddr": "^13.0.3",
+ "@noble/curves": "^2.0.1",
"libp2p": "^3.3.11",
"multiformats": "^14.0.5",
+ "uint8arrays": "^6.1.1",
"zod": "^4.6.5"
},
"devDependencies": {
diff --git a/sdk/js/src/bytes.ts b/sdk/js/src/bytes.ts
new file mode 100644
index 00000000..ef8f0bea
--- /dev/null
+++ b/sdk/js/src/bytes.ts
@@ -0,0 +1,57 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Text encodings of bytes as the Go side reads them, for any JavaScript
+// runtime. The names say which alphabet and whether the text is padded:
+// a biscuit travels as padded standard base64 (Go base64.StdEncoding), a
+// challenge signature as unpadded base64url (Go base64.RawURLEncoding).
+
+import { fromString } from "uint8arrays/from-string";
+import { toString } from "uint8arrays/to-string";
+
+export function toHex(bytes: Uint8Array): string {
+ return toString(bytes, "hex");
+}
+
+export function fromHex(text: string): Uint8Array {
+ return fromString(text, "hex");
+}
+
+/** Padded standard base64 (RFC 4648 section 4), what Go base64.StdEncoding decodes. */
+export function toBase64(bytes: Uint8Array): string {
+ return toString(bytes, "base64pad");
+}
+
+export function fromBase64(text: string): Uint8Array {
+ return fromString(text, "base64pad");
+}
+
+/** Unpadded base64url (RFC 4648 section 5), what Go base64.RawURLEncoding decodes. */
+export function toBase64Url(bytes: Uint8Array): string {
+ return toString(bytes, "base64url");
+}
+
+export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
+ return a.length === b.length && a.every((v, i) => v === b[i]);
+}
+
+export function concatBytes(...parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let offset = 0;
+ for (const p of parts) {
+ out.set(p, offset);
+ offset += p.length;
+ }
+ return out;
+}
diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.ts
index ee77c80e..9149d692 100644
--- a/sdk/js/src/controlplane.ts
+++ b/sdk/js/src/controlplane.ts
@@ -34,6 +34,7 @@ import {
type KeysResponse,
} from "./gen/sam_pb.ts";
import type { Identity } from "./identity.ts";
+import { bytesEqual, toBase64, toBase64Url } from "./bytes.ts";
import { verifyEd25519 } from "./identity.ts";
export const PROTOBUF_CONTENT_TYPE = "application/x-protobuf";
@@ -154,10 +155,6 @@ export function validateControlPlaneURL(rawUrl: string, allowInsecure = false):
throw new Error(`control plane URL ${JSON.stringify(rawUrl)} must use http:// or https://`);
}
-function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
- return a.length === b.length && a.every((v, i) => v === b[i]);
-}
-
/**
* Returns the key set if it is fresh and at least one listed key is already
* trusted and its signature verifies. Mirrors api.VerifyKeysResponse.
@@ -280,7 +277,7 @@ export class ControlPlaneClient {
const sig = identity.sign(enrollStatusChallenge(identity.peerId, ts));
const body = await this.#request("GET", `/enroll/status?peer_id=${encodeURIComponent(identity.peerId)}`, undefined, {
[HEADER_CHALLENGE_TIMESTAMP]: String(ts),
- [HEADER_CHALLENGE_SIGNATURE]: Buffer.from(sig).toString("base64url"),
+ [HEADER_CHALLENGE_SIGNATURE]: toBase64Url(sig),
});
return fromBinary(BootstrapEnrollResponseSchema, body);
}
@@ -322,7 +319,7 @@ export class ControlPlaneClient {
peerId: identity.peerId,
});
const body = await this.#request("POST", "/refresh", toBinary(TokenRefreshRequestSchema, req), {
- Authorization: `Bearer ${Buffer.from(params.biscuit).toString("base64")}`,
+ Authorization: `Bearer ${toBase64(params.biscuit)}`,
});
const resp = fromBinary(TokenRefreshResponseSchema, body);
if (resp.errorMessage) {
@@ -341,7 +338,7 @@ export class ControlPlaneClient {
*/
async policyRules(biscuit: Uint8Array): Promise<string[]> {
const body = await this.#request("GET", "/policies", undefined, {
- Authorization: `Bearer ${Buffer.from(biscuit).toString("base64")}`,
+ Authorization: `Bearer ${toBase64(biscuit)}`,
});
const resp = fromBinary(PolicyConfigGetResponseSchema, body);
if (resp.$unknown !== undefined && resp.$unknown.length > 0) {
@@ -360,7 +357,7 @@ export class ControlPlaneClient {
signal: controller.signal,
};
if (body !== undefined) {
- init.body = Buffer.from(body);
+ init.body = new Uint8Array(body);
init.headers = { ...init.headers, "Content-Type": PROTOBUF_CONTENT_TYPE };
}
const resp = await this.#fetch(new URL(path, this.url), init);
diff --git a/sdk/js/src/credential.ts b/sdk/js/src/credential.ts
index e4490170..8f979b60 100644
--- a/sdk/js/src/credential.ts
+++ b/sdk/js/src/credential.ts
@@ -14,6 +14,7 @@
import { create, fromBinary, fromJson, toBinary, toJson } from "@bufbuild/protobuf";
import { timestampDate, timestampFromDate, type Timestamp } from "@bufbuild/protobuf/wkt";
+import { toHex } from "./bytes.ts";
import { AuthFrameSchema, AuthResponseSchema, MemberCredentialSchema, type AuthResponse, type OIDCSession } from "./gen/sam_pb.ts";
/** What a member holds after enrolling: its biscuit and what it trusts. */
@@ -44,8 +45,8 @@ export interface MeshCredential {
/** Whether a key trusted now was unknown when the credential was issued. */
export function credentialPredatesRotation(c: MeshCredential): boolean {
- const issued = new Set(c.issuedUnderKeys.map((k) => Buffer.from(k).toString("hex")));
- return c.controlPlaneKeys.some((k) => !issued.has(Buffer.from(k).toString("hex")));
+ const issued = new Set(c.issuedUnderKeys.map((k) => toHex(k)));
+ return c.controlPlaneKeys.some((k) => !issued.has(toHex(k)));
}
/** Seconds of validity left on the biscuit; negative once expired. */
@@ -78,7 +79,7 @@ export function credentialToJSON(c: MeshCredential): string {
biscuit: c.biscuit,
expireTime: timestampFromDate(new Date(c.expiration * 1000)),
trustedKeys: c.controlPlaneKeys.map((k) => {
- const receiveTime = c.extra?.receiveTime.get(Buffer.from(k).toString("hex"));
+ const receiveTime = c.extra?.receiveTime.get(toHex(k));
return receiveTime !== undefined ? { publicKey: k, receiveTime } : { publicKey: k };
}),
issuedUnderKeys: c.issuedUnderKeys,
@@ -97,7 +98,7 @@ export function credentialFromJSON(text: string): MeshCredential {
const receiveTime = new Map<string, Timestamp>();
for (const k of message.trustedKeys) {
if (k.receiveTime !== undefined) {
- receiveTime.set(Buffer.from(k.publicKey).toString("hex"), k.receiveTime);
+ receiveTime.set(toHex(k.publicKey), k.receiveTime);
}
}
return {
diff --git a/sdk/js/src/identity.ts b/sdk/js/src/identity.ts
index 1744d8a2..c5439a00 100644
--- a/sdk/js/src/identity.ts
+++ b/sdk/js/src/identity.ts
@@ -14,13 +14,17 @@
// A mesh identity is an ed25519 key pair. Its peer ID is the one libp2p
// derives, so the same key works in the SDK, in sam-node and on the wire.
+// The arithmetic is @noble/curves, the implementation libp2p itself uses,
+// so an identity is built and used the same way in Node and in a browser.
-import { createPrivateKey, createPublicKey, sign, verify, type KeyObject } from "node:crypto";
+import { ed25519 } from "@noble/curves/ed25519.js";
import { peerIdFromString } from "@libp2p/peer-id";
import { encodeBase58 } from "./base58.ts";
+import { bytesEqual, concatBytes as concat } from "./bytes.ts";
const PUBLIC_KEY_SIZE = 32;
const SEED_SIZE = 32;
+const SIGNATURE_SIZE = 64;
// libp2p crypto.proto PublicKey{Type: Ed25519 (1), Data: <32 bytes>}.
const LIBP2P_PUBLIC_KEY_PREFIX = Uint8Array.of(0x08, 0x01, 0x12, 0x20);
@@ -29,29 +33,21 @@ const LIBP2P_PRIVATE_KEY_PREFIX = Uint8Array.of(0x08, 0x01, 0x12, 0x40);
// multihash: identity function (0x00), digest length 36.
const IDENTITY_MULTIHASH_PREFIX = Uint8Array.of(0x00, 0x24);
-// PKCS#8 wrapper for a raw ed25519 seed (RFC 8410): what node:crypto imports.
-const PKCS8_ED25519_PREFIX = Uint8Array.of(
- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
-);
-// SubjectPublicKeyInfo wrapper for a raw ed25519 public key (RFC 8410).
-const SPKI_ED25519_PREFIX = Uint8Array.of(0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00);
-
-function concat(...parts: Uint8Array[]): Uint8Array {
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
- let offset = 0;
- for (const p of parts) {
- out.set(p, offset);
- offset += p.length;
- }
- return out;
-}
-
function startsWith(bytes: Uint8Array, prefix: Uint8Array): boolean {
return prefix.every((b, i) => bytes[i] === b);
}
-function publicKeyObject(publicKeyRaw: Uint8Array): KeyObject {
- return createPublicKey({ key: Buffer.from(concat(SPKI_ED25519_PREFIX, publicKeyRaw)), format: "der", type: "spki" });
+// RFC 8032 verification, as Go crypto/ed25519 and node:crypto do it; the
+// looser ZIP 215 rules noble defaults to accept signatures those reject.
+function verifyRaw(publicKeyRaw: Uint8Array, data: Uint8Array, signature: Uint8Array): boolean {
+ if (publicKeyRaw.length !== PUBLIC_KEY_SIZE || signature.length !== SIGNATURE_SIZE) {
+ return false;
+ }
+ try {
+ return ed25519.verify(signature, data, publicKeyRaw, { zip215: false });
+ } catch {
+ return false;
+ }
}
/** The libp2p protobuf encoding of an ed25519 public key. */
@@ -83,8 +79,6 @@ export function canonicalPeerId(text: string): string {
}
export class Identity {
- readonly #privateKey: KeyObject;
- readonly #publicKey: KeyObject;
readonly #seed: Uint8Array;
/** Raw 32-byte ed25519 public key. */
readonly publicKeyRaw: Uint8Array;
@@ -95,17 +89,7 @@ export class Identity {
throw new Error(`ed25519 seed must be ${SEED_SIZE} bytes, got ${seed.length}`);
}
this.#seed = new Uint8Array(seed);
- this.#privateKey = createPrivateKey({
- key: Buffer.from(concat(PKCS8_ED25519_PREFIX, this.#seed)),
- format: "der",
- type: "pkcs8",
- });
- this.#publicKey = createPublicKey(this.#privateKey);
- const spki = new Uint8Array(this.#publicKey.export({ format: "der", type: "spki" }));
- if (spki.length !== SPKI_ED25519_PREFIX.length + PUBLIC_KEY_SIZE || !startsWith(spki, SPKI_ED25519_PREFIX)) {
- throw new Error("unexpected ed25519 public key encoding");
- }
- this.publicKeyRaw = spki.slice(SPKI_ED25519_PREFIX.length);
+ this.publicKeyRaw = ed25519.getPublicKey(this.#seed);
this.peerId = peerIdFromPublicKey(this.publicKeyRaw);
}
@@ -127,7 +111,7 @@ export class Identity {
const seed = bytes.subarray(LIBP2P_PRIVATE_KEY_PREFIX.length, LIBP2P_PRIVATE_KEY_PREFIX.length + SEED_SIZE);
const pub = bytes.subarray(LIBP2P_PRIVATE_KEY_PREFIX.length + SEED_SIZE);
const id = new Identity(seed);
- if (!pub.every((b, i) => id.publicKeyRaw[i] === b)) {
+ if (!bytesEqual(pub, id.publicKeyRaw)) {
throw new Error("libp2p private key: public half does not match the seed");
}
return id;
@@ -144,18 +128,15 @@ export class Identity {
}
sign(data: Uint8Array): Uint8Array {
- return new Uint8Array(sign(null, data, this.#privateKey));
+ return ed25519.sign(data, this.#seed);
}
verify(data: Uint8Array, signature: Uint8Array): boolean {
- return verify(null, data, this.#publicKey, signature);
+ return verifyRaw(this.publicKeyRaw, data, signature);
}
}
/** Verifies an ed25519 signature with a raw 32-byte public key. */
export function verifyEd25519(publicKeyRaw: Uint8Array, data: Uint8Array, signature: Uint8Array): boolean {
- if (publicKeyRaw.length !== PUBLIC_KEY_SIZE) {
- return false;
- }
- return verify(null, data, publicKeyObject(publicKeyRaw), signature);
+ return verifyRaw(publicKeyRaw, data, signature);
}
diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.ts
index d5192207..f08be813 100644
--- a/sdk/js/src/mesh.ts
+++ b/sdk/js/src/mesh.ts
@@ -14,6 +14,7 @@
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { join } from "node:path";
+import { toHex } from "./bytes.ts";
import { ControlPlaneClient, ROLE_NODE, type Enrollment } from "./controlplane.ts";
import { credentialFromJSON, credentialPredatesRotation, credentialTimeToLiveSeconds, credentialToJSON, encodeAuthFrame, type MeshCredential } from "./credential.ts";
import { Identity } from "./identity.ts";
@@ -213,8 +214,8 @@ export class AgentMesh {
* credentials the new key signs verify before the next pull confirms it.
*/
addTrustedKey(key: Uint8Array): boolean {
- const hex = Buffer.from(key).toString("hex");
- if (this.#credential.controlPlaneKeys.some((k) => Buffer.from(k).toString("hex") === hex)) {
+ const hex = toHex(key);
+ if (this.#credential.controlPlaneKeys.some((k) => toHex(k) === hex)) {
return false;
}
this.#credential = { ...this.#credential, controlPlaneKeys: [...this.#credential.controlPlaneKeys, key] };
@@ -307,7 +308,7 @@ function newClient(options: AgentMeshOptions): ControlPlaneClient {
function sameKeySet(a: Uint8Array[], b: Uint8Array[]): boolean {
const hex = (keys: Uint8Array[]) =>
keys
- .map((k) => Buffer.from(k).toString("hex"))
+ .map((k) => toHex(k))
.sort()
.join(",");
return hex(a) === hex(b);