fix(sdk,transport): bounded prekey requests and a real registration retry (4.13.2)

An unreachable prekey server (packets dropped, not refused) held
createShade for ~2 min per call, and a failed registration was never
retried despite the log saying so. Every request now has a deadline,
registration retries with backoff until it lands, and
registration: 'background' lets an app open its identity offline.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-15 20:49:56 +02:00
parent 5d04e18482
commit bcae7b346e
35 changed files with 406 additions and 60 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/cli",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/cli.ts",
"bin": {

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/core",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/crypto-web",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/dashboard",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/files",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/inbox-server",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/inbox",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/key-transparency",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/keychain",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/observability",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/observer",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/proto",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/recovery",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/sdk",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,7 @@
import type { StorageProvider } from '@shade/core';
import { ConfigurationError } from '@shade/core';
import type { ObservabilityHook } from '@shade/observability';
import { DEFAULT_REQUEST_TIMEOUT_MS } from '@shade/transport';
/**
* Shade SDK configuration.
@@ -84,6 +85,29 @@ export interface ShadeConfig {
* Default: KT verification disabled. Set this to enable.
*/
keyTransparency?: ShadeKTConfig;
/**
* What `initialize()` does about registering with the prekey server.
*
* - `'await'` (default): wait for it — at most `requestTimeoutMs` — so a
* peer can fetch this identity's bundle the moment `createShade`
* resolves.
* - `'background'`: don't wait. For apps where opening the identity must
* not depend on the network, e.g. a local unlock gate.
*
* Either way a registration that fails is retried in the background with
* backoff until it succeeds or `shutdown()` runs.
*/
registration?: 'await' | 'background';
/** Every prekey-server request gives up after this many ms. Default 15 000. */
requestTimeoutMs?: number;
/**
* Fetch for every prekey-server request — to observe the server's
* reachability, or to stub the network in tests. Default: global fetch.
*/
fetch?: typeof fetch;
}
/** Public configuration shape for `Shade.keyTransparency`. */
@@ -117,6 +141,9 @@ export interface ResolvedConfig {
};
observability?: ObservabilityHook;
keyTransparency?: ResolvedKTConfig;
registration: 'await' | 'background';
requestTimeoutMs: number;
fetch?: typeof fetch;
}
export interface ResolvedKTConfig {
@@ -146,8 +173,20 @@ export function resolveConfig(input: ShadeConfig): ResolvedConfig {
address: input.address,
autoReplenish,
autoRotate: input.autoRotate ?? false,
registration: input.registration ?? 'await',
requestTimeoutMs: input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
};
if (resolved.registration !== 'await' && resolved.registration !== 'background') {
throw new ConfigurationError(`registration must be 'await' or 'background'`);
}
if (!Number.isFinite(resolved.requestTimeoutMs) || resolved.requestTimeoutMs <= 0) {
throw new ConfigurationError('requestTimeoutMs must be a positive number');
}
if (input.fetch !== undefined) {
resolved.fetch = input.fetch;
}
if (input.observer) {
if (!input.observer.token || input.observer.token.length < 16) {
throw new ConfigurationError('observer.token must be at least 16 characters');

View File

@@ -143,6 +143,9 @@ export interface ShadeUploadOptions extends TransferOptions {
generateThumbnail?: boolean | ThumbnailGenerationOptions;
}
/** Delays between retries of the initial registration; the last repeats. */
const REGISTRATION_RETRY_MS: readonly number[] = [5_000, 15_000, 30_000, 60_000];
/**
* The high-level Shade API.
*
@@ -157,6 +160,9 @@ export class Shade {
private manager!: ShadeSessionManager;
private transport!: ShadeFetchTransport;
private _background: BackgroundTasks | null = null;
/** Pending retry of the initial registration; see [retryRegistration]. */
private registrationRetry: ReturnType<typeof setTimeout> | null = null;
private shutDown = false;
private address!: string;
private initialized = false;
@@ -279,28 +285,23 @@ export class Shade {
};
}
this.transport = new ShadeFetchTransport({
baseUrl: this.config.prekeyServer,
crypto: this.crypto,
signingPrivateKey: identity.signingPrivateKey,
...(ktOpts ? { keyTransparency: ktOpts } : {}),
});
this.transport = this.makeTransport(identity.signingPrivateKey, ktOpts);
// Step 5: Initial prekeys + register
const otpks = await this.manager.generateOneTimePreKeys(20);
const bundle = await this.manager.createPreKeyBundle();
const publicIdentity = this.manager.getPublicIdentity();
const register = () =>
this.transport.register(this.address, publicIdentity, bundle.signedPreKey, otpks);
try {
await this.transport.register(
this.address,
this.manager.getPublicIdentity(),
bundle.signedPreKey,
otpks,
);
} catch (err) {
console.warn(
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${(err as Error).message}. Will retry on next replenish.`,
);
if (this.config.registration === 'background') {
this.retryRegistration(register, 0, 0);
} else {
try {
await register();
} catch (err) {
this.retryRegistration(register, 1, undefined, err as Error);
}
}
// Step 6: Background tasks
@@ -742,6 +743,10 @@ export class Shade {
async rotate(): Promise<void> {
if (!this.initialized) throw new Error('Not initialized');
// The initial registration's retry would publish the identity we are
// about to replace; this rotation registers the new one itself.
this.cancelRegistrationRetry();
// Rotate locally first
const newBundle = await this.manager.rotateIdentity();
@@ -749,11 +754,7 @@ export class Shade {
// signed operations (replenish, delete, register) work
const identity = await this.storage.getIdentityKeyPair();
if (!identity) throw new Error('Identity missing after rotate');
this.transport = new ShadeFetchTransport({
baseUrl: this.config.prekeyServer,
crypto: this.crypto,
signingPrivateKey: identity.signingPrivateKey,
});
this.transport = this.makeTransport(identity.signingPrivateKey);
// Re-upload the new bundle
await this.transport.register(
@@ -822,17 +823,79 @@ export class Shade {
: {}),
});
await this.manager.initialize();
this.transport = new ShadeFetchTransport({
baseUrl: this.config.prekeyServer,
crypto: this.crypto,
signingPrivateKey: restored.signingPrivateKey,
});
// Same reason as in rotate(): the pending retry is for the old identity.
this.cancelRegistrationRetry();
this.transport = this.makeTransport(restored.signingPrivateKey);
}
}
private makeTransport(
signingPrivateKey: Uint8Array,
keyTransparency?: KTVerifierOptions,
): ShadeFetchTransport {
return new ShadeFetchTransport({
baseUrl: this.config.prekeyServer,
crypto: this.crypto,
signingPrivateKey,
requestTimeoutMs: this.config.requestTimeoutMs,
...(this.config.fetch ? { fetch: this.config.fetch } : {}),
...(keyTransparency ? { keyTransparency } : {}),
});
}
/**
* Register with the prekey server, retrying with backoff until it works,
* the identity changes, or the instance shuts down.
*
* This used to be one attempt whose failure promised "will retry on next
* replenish" — but replenish never registers, so an identity that came
* up while the server was unreachable stayed unregistered until the next
* restart.
*
* `attempt` 0 is the first try (no delay unless `delayMs` says so); each
* failure moves one step along [REGISTRATION_RETRY_MS].
*/
private retryRegistration(
register: () => Promise<void>,
attempt: number,
delayMs?: number,
lastError?: Error,
): void {
if (this.shutDown) return;
const steps = REGISTRATION_RETRY_MS;
const delay = delayMs ?? steps[Math.min(Math.max(attempt - 1, 0), steps.length - 1)] ?? 60_000;
if (lastError) {
console.warn(
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${lastError.message}. Retrying in ${Math.round(delay / 1000)} s.`,
);
}
this.registrationRetry = setTimeout(() => {
this.registrationRetry = null;
if (this.shutDown) return;
register().then(
() => {
if (attempt > 0) {
console.warn(`[Shade] Registered with prekey server at ${this.config.prekeyServer}.`);
}
},
(err: Error) => this.retryRegistration(register, attempt + 1, undefined, err),
);
}, delay);
(this.registrationRetry as unknown as { unref?: () => void }).unref?.();
}
private cancelRegistrationRetry(): void {
if (this.registrationRetry !== null) {
clearTimeout(this.registrationRetry);
this.registrationRetry = null;
}
}
/** Clean shutdown: stop timers, close storage if it supports it */
async shutdown(): Promise<void> {
this._background?.stop();
this.cancelRegistrationRetry();
this.shutDown = true;
if (this.transferEngine !== null) this.transferEngine.destroy();
if (this.controlChannel !== null) this.controlChannel.destroy();
if (this.webrtcRuntime !== null) {

View File

@@ -0,0 +1,111 @@
import { describe, test, expect } from 'bun:test';
import { createShade } from '../src/index.js';
/**
* Opening an identity used to wait on the prekey server with no deadline:
* with the server unreachable (packets dropped, not refused) `createShade`
* hung until the kernel gave up on the TCP handshake, about two minutes —
* and the failed registration was never retried, despite the log saying
* it would be.
*/
describe('registration with an unreachable prekey server', () => {
/** Never answers; honours abort like the real fetch. Counts calls. */
function blackHole() {
const urls: string[] = [];
const fetch = ((url: string, init?: RequestInit) => {
urls.push(url);
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
});
}) as unknown as typeof globalThis.fetch;
return { fetch, urls };
}
test("'background' opens the identity without waiting on the server", async () => {
const net = blackHole();
const started = Date.now();
const shade = await createShade({
prekeyServer: 'https://prekey.invalid',
address: 'alice',
autoReplenish: false,
registration: 'background',
requestTimeoutMs: 60_000,
fetch: net.fetch,
});
try {
expect(Date.now() - started).toBeLessThan(5_000);
expect(shade.myAddress).toBe('alice');
await new Promise((r) => setTimeout(r, 20));
expect(net.urls).toEqual(['https://prekey.invalid/v1/keys/register']);
} finally {
await shade.shutdown();
}
});
test("'await' gives up at the request deadline instead of hanging", async () => {
const net = blackHole();
const started = Date.now();
const shade = await createShade({
prekeyServer: 'https://prekey.invalid',
address: 'bob',
autoReplenish: false,
requestTimeoutMs: 100,
fetch: net.fetch,
});
try {
expect(Date.now() - started).toBeLessThan(5_000);
expect(net.urls).toHaveLength(1);
} finally {
await shade.shutdown();
}
});
test('a failed registration is retried until the server answers', async () => {
let calls = 0;
const fetch = (async () => {
calls += 1;
if (calls === 1) throw new TypeError('Unable to connect');
return new Response('{}', { status: 200 });
}) as unknown as typeof globalThis.fetch;
const shade = await createShade({
prekeyServer: 'https://prekey.invalid',
address: 'carol',
autoReplenish: false,
fetch,
});
try {
expect(calls).toBe(1);
// First retry is due 5 s after the failure.
await new Promise((r) => setTimeout(r, 5_300));
expect(calls).toBe(2);
} finally {
await shade.shutdown();
}
}, 10_000);
test('shutdown stops the retries', async () => {
let calls = 0;
const fetch = (async () => {
calls += 1;
throw new TypeError('Unable to connect');
}) as unknown as typeof globalThis.fetch;
const shade = await createShade({
prekeyServer: 'https://prekey.invalid',
address: 'dave',
autoReplenish: false,
fetch,
});
await shade.shutdown();
await new Promise((r) => setTimeout(r, 5_300));
expect(calls).toBe(1);
}, 10_000);
test('nonsense settings are refused up front', async () => {
await expect(
createShade({ prekeyServer: 'https://x.invalid', requestTimeoutMs: 0 }),
).rejects.toThrow('requestTimeoutMs');
await expect(
createShade({ prekeyServer: 'https://x.invalid', registration: 'later' as never }),
).rejects.toThrow('registration');
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/server",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/storage-encrypted",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/storage-indexeddb",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/storage-postgres",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/storage-sqlite",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/streams",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/transfer",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/transport-bridge",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/transport-webrtc",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/transport",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -14,6 +14,9 @@ import {
KTVerificationError,
} from '@shade/key-transparency';
/** How long any prekey-server request may go unanswered. */
export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
/**
* HTTP transport client for the Shade Prekey Server.
*
@@ -67,15 +70,31 @@ export class ShadeFetchTransport {
private readonly crypto: CryptoProvider;
private readonly signingPrivateKey?: Uint8Array;
private readonly kt?: KTVerifierOptions;
private readonly fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
private readonly requestTimeoutMs: number;
constructor(options: {
baseUrl: string;
crypto: CryptoProvider;
signingPrivateKey?: Uint8Array;
keyTransparency?: KTVerifierOptions;
/**
* Fetch for every request. Lets an app observe its server's
* reachability, or tests stub the network. Default: global fetch.
*/
fetch?: typeof fetch;
/**
* A request with no response by then fails with a `NetworkError`.
* Default 15 000. Without it an unreachable server (packets dropped,
* not refused) held each call until the kernel gave up on the TCP
* handshake — about two minutes on Linux.
*/
requestTimeoutMs?: number;
}) {
this.baseUrl = options.baseUrl;
this.crypto = options.crypto;
this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
if (options.signingPrivateKey !== undefined) {
this.signingPrivateKey = options.signingPrivateKey;
}
@@ -84,6 +103,22 @@ export class ShadeFetchTransport {
}
}
/** Every request goes through here, so every request has a deadline. */
private async request(url: string, init: RequestInit = {}): Promise<Response> {
const timeout = AbortSignal.timeout(this.requestTimeoutMs);
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
try {
return await this.fetchImpl(url, { ...init, signal });
} catch (err) {
if (timeout.aborted && !init.signal?.aborted) {
throw new NetworkError(
`No response from ${new URL(url).host} within ${this.requestTimeoutMs} ms`,
);
}
throw err;
}
}
private headers(): Record<string, string> {
return { 'Content-Type': 'application/json' };
}
@@ -133,7 +168,7 @@ export class ShadeFetchTransport {
const signed = await this.sign(body);
const res = await fetch(`${this.baseUrl}/v1/keys/register`, {
const res = await this.request(`${this.baseUrl}/v1/keys/register`, {
method: 'POST',
headers: this.headers(),
body: JSON.stringify(signed),
@@ -159,7 +194,7 @@ export class ShadeFetchTransport {
* direct access to the proof side-channel.
*/
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
const res = await this.request(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
headers: this.headers(),
});
if (!res.ok) {
@@ -283,7 +318,7 @@ export class ShadeFetchTransport {
};
const signed = await this.sign(body);
const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, {
const res = await this.request(`${this.baseUrl}/v1/keys/replenish`, {
method: 'POST',
headers: this.headers(),
body: JSON.stringify(signed),
@@ -295,7 +330,7 @@ export class ShadeFetchTransport {
/** Get remaining one-time prekey count (anonymous) */
async getKeyCount(address: string): Promise<number> {
const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
const res = await this.request(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
headers: this.headers(),
});
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
@@ -306,7 +341,7 @@ export class ShadeFetchTransport {
/** Delete all keys for this identity (signed) */
async unregister(address: string): Promise<void> {
const signed = await this.sign({ address });
const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
const res = await this.request(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
method: 'DELETE',
headers: this.headers(),
body: JSON.stringify(signed),

View File

@@ -1,3 +1,3 @@
export { ShadeFetchTransport } from './fetch-transport.js';
export { ShadeFetchTransport, DEFAULT_REQUEST_TIMEOUT_MS } from './fetch-transport.js';
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
export { ShadeWebSocket } from './ws-adapter.js';

View File

@@ -82,3 +82,44 @@ describe('ShadeFetchTransport', () => {
}
});
});
/**
* A server that drops packets instead of refusing them used to hold every
* call until the kernel gave up on the TCP handshake — two minutes on
* Linux. Every request now has a deadline.
*/
describe('ShadeFetchTransport request deadline', () => {
/** A fetch that never answers, but honours abort like the real one. */
const blackHole = ((_url: unknown, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
})) as unknown as typeof fetch;
test('a request nobody answers fails with a NetworkError at the deadline', async () => {
const transport = new ShadeFetchTransport({
baseUrl: 'https://prekey.invalid',
crypto,
fetch: blackHole,
requestTimeoutMs: 50,
});
const started = Date.now();
const err = await transport.getKeyCount('bob').catch((e) => e);
expect(err.name).toBe('NetworkError');
expect(err.message).toContain('No response from prekey.invalid within 50 ms');
expect(Date.now() - started).toBeLessThan(2_000);
});
test('every request goes through the supplied fetch', async () => {
const urls: string[] = [];
const transport = new ShadeFetchTransport({
baseUrl: 'https://prekey.invalid',
crypto,
fetch: (async (url: string) => {
urls.push(url);
return new Response(JSON.stringify({ count: 7 }), { status: 200 });
}) as unknown as typeof fetch,
});
expect(await transport.getKeyCount('bob')).toBe(7);
expect(urls).toEqual(['https://prekey.invalid/v1/keys/count/bob']);
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/vault",
"version": "4.13.1",
"version": "4.13.2",
"description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log",
"type": "module",
"main": "src/index.ts",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/widgets",
"version": "4.13.1",
"version": "4.13.2",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",