@genation/bridge-peer
v0.4.4
Published
Browser, Node.js, Electron, and React Native peer SDK for Genation Bridge
Downloads
1,669
Readme
@genation/bridge-peer
Role-neutral Genation Bridge peer SDK for browsers, Node.js, Electron main or utility processes, and React Native. The SDK owns the peer's connection and E2EE keys, relay lifecycle, grant renewal, exposure replacement, reconnect, and invocation framing.
import { createPeer } from "@genation/bridge-peer";
const peer = createPeer({
projectId: process.env.BRIDGE_PROJECT_ID!,
peerId: "desktop.user-123",
grantProvider: async (request) => {
const response = await fetch("https://customer.example/bridge/grants", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(request),
});
if (!response.ok) throw new Error("grant denied");
return await response.json() as { grant: string };
},
requestedInvokeCapabilities: ["phone.echo"],
});
peer.expose("desktop.echo", ({ text }: { text: string }, { caller }) => {
// Apply customer resource policy from caller.authorization when this exposure needs it.
return { text, subject: caller.authorization?.subject };
});
await peer.connect();
const reply = await peer.invoke("phone.echo", { text: "hello" }, {
targetPeer: "phone.user-123",
});AI-callable tools
Tool metadata is optional and never replaces the exposure handler. A unary exposer can produce one serializable catalog record for its customer backend:
const registration = peer.expose(
"hr.employee.summary",
({ department }: { department: string }) => summarize(department),
).withTool({
version: 1,
name: "hr_employee_summary",
description: "Summarize the authorized HR employee population.",
inputSchema: {
type: "object",
properties: { department: { type: "string" } },
required: ["department"],
additionalProperties: false,
},
});
await registerWithCustomerBackend(registration.catalogEntry);An invoker loads only records already authorized by its customer backend. Definitions
contain no peer binding and can be mapped into any external AI SDK; execute() maps a
selected function name back to one direct encrypted invocation:
const tools = peer.loadToolSet(await loadAuthorizedCatalog());
const modelTools = tools.definitions;
const result = await tools.execute("hr_employee_summary", {
department: "engineering",
});Every loaded capability must also appear in the peer's requestedInvokeCapabilities.
Discovery does not grant authority, query relay presence, run an AI loop, or expose MCP.
A statically approved offline department stays discoverable and fails at execution with
TOOL_PROVIDER_OFFLINE. If an exposer violates its declared output schema, the peer SDK
returns TOOL_OUTPUT_INVALID through encrypted peer content; the relay still observes
only the ordinary sanitized failure metadata.
Portable agent context
.agent(...) groups readable instructions and exact tool versions without adding an
agent runtime. A creator can resolve a draft locally and publish one metadata-only
proposal through its customer backend:
const draft = peer.agent({
projectId: peer.projectId,
id: "quarterly-report",
version: 1,
name: "Quarterly report",
instructions: "Analyze HR and Sales before preparing the report.",
inputSchema: {
type: "object",
properties: { period: { type: "string" } },
required: ["period"],
additionalProperties: false,
},
tools: [
{ toolId: "hr.analysis", version: 1, required: true },
{ toolId: "sales.analysis", version: 1, required: true },
],
});
const preflight = draft.resolve(peer.loadToolSet(authorizedCatalog));
if (preflight.status === "complete") {
await draft.publish((proposal) => submitToCustomerBackend(proposal));
}Another peer loads the approved manifest from the customer backend, calls its own
peer.agent(manifest).resolve(consumerTools), and gives the resulting instructions
and restricted tools to its chosen AI SDK. Missing required tools return an incomplete
preflight; optional tools are reported and omitted. The creator's grants and peer
binding never enter the consumer context, and the creator can be offline.
There is deliberately no agent.run() or agent.expose(). resolve() performs no tool
execution or model call, and publish() is only a customer callback boundary.
Omit targetPeer for bounded unary fanout. Set stream: true with one explicit target
to receive a fetch-compatible Response backed by an incremental ReadableStream. Pass
an AbortSignal to cancel direct work. close() is terminal for that peer object;
creating another object with the same project and peer IDs reloads its stored identity.
The default Node key store is internal SDK state. keyStore and fileKeyStore exist
only as advanced overrides; ordinary device code does not supply private keys.
Browser boundary
Supported browser bundlers select the browser adapter from the same package-root import.
The default browser key store uses origin-scoped IndexedDB and keeps one identity for
each exact (projectId, peerId) pair. Same-origin tabs representing different peers
should therefore use different peer IDs.
The customer backend still owns grant signing and BRIDGE_SERVER_SECRET_KEY; neither
belongs in browser source or configuration. IndexedDB is durable browser storage, not a
native secure keystore: successful same-origin script execution can access identity
material visible to JavaScript, and clearing site data creates a new identity.
React Native boundary
React Native applications use the same createPeer() facade through the package's
react-native conditional export. The adapter maps AppState to foreground connection
intent and keeps persistent identity plus Noise session handles inside the native
module. Application JavaScript receives public keys and opaque handles only.
The package contains the Swift, Kotlin, and generated UniFFI sources. Building a mobile
application must also produce the target-specific Rust XCFramework or Android JNI
libraries described in react-native/BUILDING.md; JavaScript crypto and plaintext
storage are intentionally not fallback paths.
Electron boundary
Create and retain the peer in Electron's main process or a trusted utility process. Expose only the minimum application commands and results to a renderer through a validated IPC boundary. Do not import the Node adapter in a renderer or send grants, private keys, key-store paths, or raw relay frames through renderer IPC.
Verified caller context
Every unary and streaming exposure receives context.caller, built only from the
verified remote grant.v2. It contains the remote peerId and optional customer-signed
authorization. The object is immutable. The SDK validates its shape but never
interprets actions, roles, document IDs, or other business extensions; handlers that
need those constraints must enforce them and fail closed when required context is
missing.
Grant authorization is signed metadata, not E2EE payload. Customer backends must use opaque subjects and must not place JWTs, cookies, secrets, or directly identifying personal data in it. Use one client peer identity per authenticated principal during a grant lifetime so concurrent users cannot share caller context.
Routing limitation
Bridge authorizes capability directions but does not enforce customer subjects, rooms,
target allowlists, or same-user routing. The customer backend must authenticate the user
and decide which peer ID, capabilities, and optional authorization to sign. A name such
as desktop.user-123 is only a customer convention until a later routing-scope contract
adds a Bridge-enforced boundary.
