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,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) {