Contracts 1.4.0: crosscode.link/1 and a public key in the v2 heartbeat
- crosscode.link/1 (link.connect / link.connected / link.disconnect), with signLink / verifyLink, PEM conversion, link secrets and nonces. - The v2 heartbeat can carry the install's publicKey; the reply says saved / matches / mismatch (Hub 2.2.0). Never a failed heartbeat. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -221,7 +221,18 @@ export const accountsStatsSchema = z.object({
|
||||
linkedProducts: count,
|
||||
});
|
||||
|
||||
const heartbeatBase = z.object({ protocolVersion, version: semverSchema, health: healthSchema });
|
||||
const heartbeatBase = z.object({
|
||||
protocolVersion,
|
||||
version: semverSchema,
|
||||
health: healthSchema,
|
||||
/**
|
||||
* The install's Ed25519 public key (PEM), contracts 1.4.0 / Hub 2.2.0. Lets an install that
|
||||
* registered with protocol v1 move to v2 without its licence key (the heartbeat is already
|
||||
* signed with the install secret). The Hub saves it when the install has none; see
|
||||
* `publicKeyStatus` in the reply.
|
||||
*/
|
||||
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----").optional(),
|
||||
});
|
||||
|
||||
export const heartbeatRequestSchema = z.discriminatedUnion("product", [
|
||||
heartbeatBase.extend({ product: z.literal("events"), stats: eventsStatsSchema }),
|
||||
@@ -231,6 +242,8 @@ export const heartbeatRequestSchema = z.discriminatedUnion("product", [
|
||||
]);
|
||||
export type HeartbeatRequest = z.infer<typeof heartbeatRequestSchema>;
|
||||
|
||||
export const PUBLIC_KEY_STATUSES = ["saved", "matches", "mismatch"] as const;
|
||||
|
||||
export const heartbeatResponseSchema = z.object({
|
||||
licence: z.string(),
|
||||
latestVersion: semverSchema.nullable(),
|
||||
@@ -239,6 +252,12 @@ export const heartbeatResponseSchema = z.object({
|
||||
/** The church's other installs. The install caches this, so a Hub outage changes nothing. */
|
||||
linkedProducts: z.array(linkedProductSchema),
|
||||
serverTime: dateTimeSchema,
|
||||
/**
|
||||
* Only when the heartbeat sent `publicKey` (Hub 2.2.0+): `saved` (the Hub had none),
|
||||
* `matches`, or `mismatch` (the Hub has another key; it keeps its own and flags the install
|
||||
* until Joshua clears it). Never a failed heartbeat: the licence keeps refreshing either way.
|
||||
*/
|
||||
publicKeyStatus: z.enum(PUBLIC_KEY_STATUSES).optional(),
|
||||
});
|
||||
export type HeartbeatResponse = z.infer<typeof heartbeatResponseSchema>;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ export * from "./event";
|
||||
export * from "./church";
|
||||
export * from "./identity";
|
||||
export * from "./return-to";
|
||||
export * from "./link";
|
||||
export * as hub from "./hub";
|
||||
export * as agent from "./agent";
|
||||
export * from "./church-export";
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, idSchema, productSchema, urlSchema } from "./common";
|
||||
import { schemaName } from "./schema-name";
|
||||
|
||||
/**
|
||||
* `crosscode.link/1` — **Connect** under Settings → Linked products (docs/EVENTS-2.4-PLAN.md §2).
|
||||
*
|
||||
* The Hub tells each install which of its church's other installs exist and their Ed25519 public
|
||||
* keys (`linkedProducts` in the heartbeat reply). Connect turns that into a working link between
|
||||
* two of them: a shared secret for signed calls (`LINK_HEADERS` in `@crosscode/contracts/signing`:
|
||||
* the `event.changed` webhook, later Accounts' back-channel calls).
|
||||
*
|
||||
* ```
|
||||
* A → POST {B.url}/api/links/v1/connect link.connect (signed by A, carries the new secret)
|
||||
* ← 200 link.connected (signed by B, echoes A's nonce)
|
||||
* A → POST {B.url}/api/links/v1/disconnect link.disconnect (signed by A)
|
||||
* ← 200 link.disconnected
|
||||
* ```
|
||||
*
|
||||
* B accepts A only when A is in **B's own cached** `linkedProducts` with the key that signed the
|
||||
* message, so only installs of the same church can link, and the Hub isn't on the path at the time
|
||||
* of the call. Signatures are Ed25519 over the message without `signature`, as canonical JSON
|
||||
* (`signLink` / `verifyLink`). Messages more than five minutes off the receiver's clock are
|
||||
* refused, and a nonce is only accepted once.
|
||||
*/
|
||||
|
||||
export const LINK_SCHEMA = schemaName("link", 1);
|
||||
|
||||
/** Where the endpoints live on every product, relative to its address. */
|
||||
export const LINK_PATHS = { connect: "/api/links/v1/connect", disconnect: "/api/links/v1/disconnect" } as const;
|
||||
|
||||
export const LINK_ERROR_CODES = ["NOT_LINKED", "WRONG_INSTALL", "BAD_SIGNATURE", "STALE_REQUEST", "REPLAYED", "INVALID_REQUEST", "LINKS_UNAVAILABLE"] as const;
|
||||
|
||||
export const linkPartySchema = z.object({
|
||||
product: productSchema,
|
||||
installId: idSchema,
|
||||
url: urlSchema,
|
||||
});
|
||||
export type LinkParty = z.infer<typeof linkPartySchema>;
|
||||
|
||||
/** 32 random bytes, base64url without padding. */
|
||||
export const linkSecretSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "Expected 32 bytes, base64url");
|
||||
const nonceSchema = z.string().regex(/^[A-Za-z0-9_-]{22,64}$/, "Expected a random base64url nonce");
|
||||
const signatureSchema = z.string().regex(/^[A-Za-z0-9_-]{86}$/, "Expected an Ed25519 signature, base64url");
|
||||
|
||||
const signed = {
|
||||
schema: z.literal(LINK_SCHEMA),
|
||||
from: linkPartySchema,
|
||||
to: z.object({ installId: idSchema }),
|
||||
issuedAt: dateTimeSchema,
|
||||
nonce: nonceSchema,
|
||||
signature: signatureSchema,
|
||||
};
|
||||
|
||||
/** A asks B to link, and hands it the secret both will sign calls with. */
|
||||
export const linkConnectSchema = z.object({ ...signed, type: z.literal("link.connect"), secret: linkSecretSchema });
|
||||
export type LinkConnect = z.infer<typeof linkConnectSchema>;
|
||||
|
||||
/** B's answer: signed by B and echoing A's nonce, so A knows the real B stored the secret. */
|
||||
export const linkConnectedSchema = z.object({ ...signed, type: z.literal("link.connected"), inReplyTo: nonceSchema });
|
||||
export type LinkConnected = z.infer<typeof linkConnectedSchema>;
|
||||
|
||||
/** Either side ends the link; both drop the secret. */
|
||||
export const linkDisconnectSchema = z.object({ ...signed, type: z.literal("link.disconnect") });
|
||||
export type LinkDisconnect = z.infer<typeof linkDisconnectSchema>;
|
||||
|
||||
export const linkDisconnectedSchema = z.object({ schema: z.literal(LINK_SCHEMA), type: z.literal("link.disconnected") });
|
||||
export type LinkDisconnected = z.infer<typeof linkDisconnectedSchema>;
|
||||
|
||||
export const linkErrorSchema = z.object({ message: z.string(), code: z.enum(LINK_ERROR_CODES) });
|
||||
export type LinkError = z.infer<typeof linkErrorSchema>;
|
||||
|
||||
export type LinkMessage = LinkConnect | LinkConnected | LinkDisconnect;
|
||||
@@ -234,3 +234,52 @@ export function decryptExport(file: Uint8Array, key: string): Buffer {
|
||||
decipher.setAuthTag(buf.subarray(buf.length - 16));
|
||||
return Buffer.concat([decipher.update(buf.subarray(12, buf.length - 16)), decipher.final()]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Product links (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2). The Hub lists each install's
|
||||
// key as PEM (it's what register and the heartbeat send), so these take PEM.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** An install's Ed25519 public key as PEM (SPKI), from the raw key `generateEd25519` returns. */
|
||||
export function ed25519PublicToPem(publicKey: string): string {
|
||||
return okpPublic("Ed25519", publicKey).export({ format: "pem", type: "spki" }).toString();
|
||||
}
|
||||
|
||||
/** The raw base64url key in an Ed25519 PEM. Throws for anything that isn't an Ed25519 public key. */
|
||||
export function ed25519PublicFromPem(pem: string): string {
|
||||
const key = createPublicKey(pem);
|
||||
if (key.asymmetricKeyType !== "ed25519") throw new Error("Not an Ed25519 public key");
|
||||
return rawPublic(key);
|
||||
}
|
||||
|
||||
/** A fresh link secret: 32 random bytes, base64url. */
|
||||
export function newLinkSecret(): string {
|
||||
return b64u(randomBytes(32));
|
||||
}
|
||||
|
||||
/** A fresh nonce for a link message. */
|
||||
export function newLinkNonce(): string {
|
||||
return b64u(randomBytes(18));
|
||||
}
|
||||
|
||||
/** Sign a `crosscode.link/1` message (everything but `signature`, as canonical JSON). */
|
||||
export function signLink<T extends Record<string, unknown>>(message: T, privateKeyPem: string): T & { signature: string } {
|
||||
return { ...message, signature: ed25519Sign(privateKeyPem, jobSigningInput(message)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a `crosscode.link/1` message against the sender's PEM key as the receiver's Hub list has
|
||||
* it, and its `issuedAt` against the clock. Replays (`nonce`) are the receiver's to track.
|
||||
*/
|
||||
export function verifyLink(message: Record<string, unknown>, publicKeyPem: string, opts: { now?: Date; maxSkewMs?: number } = {}): VerifyResult {
|
||||
const issuedAt = typeof message.issuedAt === "string" ? Date.parse(message.issuedAt) : NaN;
|
||||
const now = (opts.now ?? new Date()).getTime();
|
||||
if (!Number.isFinite(issuedAt) || Math.abs(now - issuedAt) > (opts.maxSkewMs ?? MAX_CLOCK_SKEW_MS)) return { ok: false, code: "STALE_REQUEST" };
|
||||
let raw: string;
|
||||
try {
|
||||
raw = ed25519PublicFromPem(publicKeyPem);
|
||||
} catch {
|
||||
return { ok: false, code: "BAD_SIGNATURE" };
|
||||
}
|
||||
return ed25519Verify(raw, jobSigningInput(message), message.signature) ? { ok: true } : { ok: false, code: "BAD_SIGNATURE" };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user