release(v4.0.0): Shade GA — V3.x consolidation + audit prep
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
V3.1 → V3.12 consolidated and tagged for the first GA release. Wire format unchanged from 0.4.x — 4.0 peers interoperate with 0.4.x peers byte-for-byte. The version bump is semantic: audit-cycle complete, opt-in surface fully exposed, threat model refreshed for every new surface. Highlights: - All 24 @shade/* packages bumped to 4.0.0 in lockstep. - CHANGELOG 4.0.0 section is the canonical manifest of what landed. - THREAT-MODEL extended (§10 fingerprint gates, §11 WebRTC P2P, §12 Web-Worker boundary) + residual-risks table refreshed. - OpenAPI now covers all 27 routes: prekey, transfer, KT, inbox, bridge, observer, /metrics, /healthz, /ready. - MIGRATION 0.3.x → 4.0 documented + smoke-tested against shade migrate-storage on a real SQLite DB. - docs/audit/REVIEW-BUNDLE.md + SCOPE.md ready for external reviewer. - scripts/soak.ts harness for the GA-stable 2-week soak window. - All V*.md plans archived under docs/archive/ with Status: Done. - Voice/Video carved out into V5.0; 4.0 audit focuses on the frozen non-realtime stack. Tests: TS 1000/1000 + Kotlin 11/11 cross-platform vectors green. Docker: gt.zyon.no/stian/shade-prekey:4.0.0 builds and reports version 4.0.0 on /health. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
219
packages/shade-inbox/src/client.ts
Normal file
219
packages/shade-inbox/src/client.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import type { CryptoProvider, ShadeEnvelope } from '@shade/core';
|
||||
import {
|
||||
NetworkError,
|
||||
toBase64,
|
||||
fromBase64,
|
||||
ShadeError,
|
||||
ValidationError,
|
||||
} from '@shade/core';
|
||||
import { signPayload } from '@shade/server';
|
||||
import { encodeEnvelope, decodeEnvelope } from '@shade/proto';
|
||||
import { computeMsgId } from './msg-id.js';
|
||||
|
||||
/**
|
||||
* Low-level HTTP client for `@shade/inbox-server`.
|
||||
*
|
||||
* Stateless and reusable across many recipients. Higher-level orchestration
|
||||
* (queue, poll loop, ack-on-decrypt) lives in `Inbox` (see `inbox.ts`),
|
||||
* which composes this client.
|
||||
*/
|
||||
export interface InboxClientOptions {
|
||||
baseUrl: string;
|
||||
crypto: CryptoProvider;
|
||||
/** Used to sign requests on behalf of *this* identity. */
|
||||
signingPrivateKey: Uint8Array;
|
||||
/** Optional fetch override (defaults to globalThis.fetch). */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface PutResult {
|
||||
msgId: string;
|
||||
receivedAt: number;
|
||||
idempotent: boolean;
|
||||
}
|
||||
|
||||
export interface FetchedBlob {
|
||||
msgId: string;
|
||||
/** Wire-encoded ShadeEnvelope bytes. */
|
||||
ciphertext: Uint8Array;
|
||||
/** Server-assigned monotonic timestamp; pass back as `sinceCursor`. */
|
||||
receivedAt: number;
|
||||
/** Absolute expiry time (ms since epoch) reported by the server. */
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface FetchResult {
|
||||
blobs: FetchedBlob[];
|
||||
cursor: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export class InboxClient {
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
constructor(private readonly options: InboxClientOptions) {
|
||||
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* TOFU-register the address that this signing key will own.
|
||||
* Idempotent if the same key re-registers; rejected by the server if a
|
||||
* different key has already claimed the address.
|
||||
*/
|
||||
async register(args: {
|
||||
address: string;
|
||||
signingKey: Uint8Array;
|
||||
}): Promise<void> {
|
||||
const body = await signPayload(this.options.crypto, this.options.signingPrivateKey, {
|
||||
address: args.address,
|
||||
signingKey: toBase64(args.signingKey),
|
||||
});
|
||||
await this.postJson(`/v1/inbox/register`, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister the address. Drops every queued blob. Signed by the
|
||||
* registered signing key.
|
||||
*/
|
||||
async unregister(address: string): Promise<void> {
|
||||
const body = await signPayload(this.options.crypto, this.options.signingPrivateKey, {
|
||||
address,
|
||||
});
|
||||
await this.requestJson('DELETE', `/v1/inbox/register/${encodeURIComponent(address)}`, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT a ShadeEnvelope to a recipient's inbox. Idempotent: same
|
||||
* ciphertext yields the same msgId and the server folds the second PUT
|
||||
* into a 200 with `idempotent: true`.
|
||||
*/
|
||||
async put(args: {
|
||||
/** Recipient address (inbox owner). */
|
||||
recipientAddress: string;
|
||||
/** Sender's identity signing public key (the one matching `signingPrivateKey`). */
|
||||
senderSigningKey: Uint8Array;
|
||||
/** Encrypted Shade envelope. Either pre-encoded bytes or a parsed envelope. */
|
||||
envelope: ShadeEnvelope | Uint8Array;
|
||||
ttlSeconds?: number;
|
||||
}): Promise<PutResult> {
|
||||
const ciphertext =
|
||||
args.envelope instanceof Uint8Array ? args.envelope : encodeEnvelope(args.envelope);
|
||||
if (ciphertext.length === 0) {
|
||||
throw new ValidationError('Empty ciphertext');
|
||||
}
|
||||
const msgId = await computeMsgId(ciphertext);
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
senderSigningKey: toBase64(args.senderSigningKey),
|
||||
msgId,
|
||||
ciphertext: toBase64(ciphertext),
|
||||
};
|
||||
if (args.ttlSeconds !== undefined) payload.ttlSeconds = args.ttlSeconds;
|
||||
|
||||
const signed = await signPayload(
|
||||
this.options.crypto,
|
||||
this.options.signingPrivateKey,
|
||||
payload,
|
||||
);
|
||||
|
||||
const json = await this.postJson(
|
||||
`/v1/inbox/${encodeURIComponent(args.recipientAddress)}`,
|
||||
signed,
|
||||
);
|
||||
return {
|
||||
msgId: String(json.msgId),
|
||||
receivedAt: Number(json.receivedAt),
|
||||
idempotent: Boolean(json.idempotent),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all blobs for `address` whose `received_at > sinceCursor`.
|
||||
* Returns at most one server page; clients keep calling with the new
|
||||
* cursor until `hasMore === false`.
|
||||
*/
|
||||
async fetch(args: { address: string; sinceCursor?: number }): Promise<FetchResult> {
|
||||
const sinceCursor = args.sinceCursor ?? 0;
|
||||
const body = await signPayload(this.options.crypto, this.options.signingPrivateKey, {
|
||||
address: args.address,
|
||||
sinceCursor,
|
||||
});
|
||||
const json = await this.postJson(
|
||||
`/v1/inbox/${encodeURIComponent(args.address)}/fetch`,
|
||||
body,
|
||||
);
|
||||
const blobs = Array.isArray(json.blobs) ? json.blobs : [];
|
||||
return {
|
||||
blobs: blobs.map((b: any) => ({
|
||||
msgId: String(b.msgId),
|
||||
ciphertext: fromBase64(String(b.ciphertext)),
|
||||
receivedAt: Number(b.receivedAt),
|
||||
expiresAt: Number(b.expiresAt),
|
||||
})),
|
||||
cursor: Number(json.cursor ?? sinceCursor),
|
||||
hasMore: Boolean(json.hasMore),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Acknowledge — delete a fetched blob. Should be called after the
|
||||
* caller has successfully decrypted (or persisted) the message.
|
||||
*/
|
||||
async ack(args: { address: string; msgId: string }): Promise<boolean> {
|
||||
const body = await signPayload(this.options.crypto, this.options.signingPrivateKey, {
|
||||
address: args.address,
|
||||
msgId: args.msgId,
|
||||
});
|
||||
const json = await this.requestJson(
|
||||
'DELETE',
|
||||
`/v1/inbox/${encodeURIComponent(args.address)}/${encodeURIComponent(args.msgId)}`,
|
||||
body,
|
||||
);
|
||||
return Boolean(json.ok);
|
||||
}
|
||||
|
||||
// ─── HTTP plumbing ──────────────────────────────────────────
|
||||
|
||||
private async postJson(path: string, body: unknown): Promise<any> {
|
||||
return this.requestJson('POST', path, body);
|
||||
}
|
||||
|
||||
private async requestJson(method: string, path: string, body: unknown): Promise<any> {
|
||||
const url = joinUrl(this.options.baseUrl, path);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetchImpl(url, {
|
||||
method,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new NetworkError(`Inbox request failed: ${(err as Error).message}`);
|
||||
}
|
||||
const text = await res.text();
|
||||
let json: any;
|
||||
try {
|
||||
json = text.length > 0 ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
throw new NetworkError(`Inbox response not JSON: ${text.slice(0, 200)}`, res.status);
|
||||
}
|
||||
if (!res.ok) {
|
||||
// Surface server-mapped Shade errors in their original shape.
|
||||
const code = String(json.code ?? '');
|
||||
const message = String(json.message ?? text);
|
||||
throw new ShadeError(code || 'SHADE_NETWORK', message);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
function joinUrl(base: string, path: string): string {
|
||||
if (base.endsWith('/') && path.startsWith('/')) return base + path.slice(1);
|
||||
if (!base.endsWith('/') && !path.startsWith('/')) return base + '/' + path;
|
||||
return base + path;
|
||||
}
|
||||
|
||||
/** Decode a fetched blob into a ShadeEnvelope. */
|
||||
export function decodeFetchedEnvelope(b: FetchedBlob): ShadeEnvelope {
|
||||
return decodeEnvelope(b.ciphertext);
|
||||
}
|
||||
Reference in New Issue
Block a user