From c41793ad70b7312effca48707c2c13030cc5034f Mon Sep 17 00:00:00 2001 From: Shadowy Super Coder Date: Wed, 25 Nov 2026 07:59:59 -0700 Subject: [PATCH 01/10] fix(web): re-sign a dropped session admission with the server clock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Encrypted RPC signs every browser admission, anonymous setup included, with the device clock. A server whose clock is synchronized drops an admission more than 30 s off without replying, and the client reports only "Encrypted RPC transport failed": a skewed browser cannot sign in, open tabs reconnect forever, and an uninitialized StartWRT router shows the Root CA page instead of the password form. When the server closes an opened session socket without answering the handshake, the session client reads the server's Date header with one HEAD to the server origin. If the measured offset differs from the one it signed with by more than half the server's tolerance, it signs the handshake again once with the server's time. Once that admission succeeds it keeps the offset for later admissions to that host, as AWS SDKs do for RequestTimeTooSkewed. A retry the server still drops is not remembered, so a Date header the verifier disagrees with never outlives the connection that read it, and a remembered offset is replaced the same way when the device clock is corrected. The server's ±30 s window and nonce cache are unchanged; its tolerance becomes the public TIMESTAMP_TOLERANCE_SECS and reaches the client through the generated SIGNATURE_PROFILE. Signed HTTP keeps the local clock: its proofs bind only the host and body, so one dated from a forged Date header on plain HTTP would later authorize any empty-body request to that host. StartOS's signed icon and package-document fetches therefore still need a correct device clock. A replayed hello cannot complete a session without the ephemeral X25519 secret. --- .../patch-changed-rpc-authentication.md | 1 + .../patch-changed-rpc-authentication.md | 1 + .../patch-changed-rpc-authentication.md | 1 + .../start-core/examples/generate_bindings.rs | 2 + .../crates/start-core/signed-session.md | 9 +- .../src/middleware/auth/signature.rs | 5 +- .../shared/scripts/session-transport.test.mjs | 210 +++++++++++++++++- .../shared/src/services/session-identity.ts | 3 +- .../shared/src/services/session-websocket.ts | 128 ++++++++--- .../start-core/lib/auth/signature.ts | 14 +- .../lib/osBindings/signature-profile.ts | 1 + .../start-core/lib/test/signature.test.ts | 14 ++ 12 files changed, 349 insertions(+), 40 deletions(-) diff --git a/projects/start-os/changelog/patch-changed-rpc-authentication.md b/projects/start-os/changelog/patch-changed-rpc-authentication.md index 381c9aaf7e..13b7ae54cb 100644 --- a/projects/start-os/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-os/changelog/patch-changed-rpc-authentication.md @@ -20,3 +20,4 @@ release-notes: false - Keep encrypted browser RPC available over HTTP/2 connections. - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. +- Sign the browser's encrypted RPC connection with the server's clock when this device's clock is wrong, so signing in, setup and RPC still work. diff --git a/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md b/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md index 36f3273ffb..9bfd07daa6 100644 --- a/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md @@ -14,3 +14,4 @@ release-notes: false - Keep encrypted browser RPC available over HTTP/2 connections. - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. +- Sign the browser's encrypted RPC connection with the server's clock when this device's clock is wrong, so the web interface still works. diff --git a/projects/start-wrt/changelog/patch-changed-rpc-authentication.md b/projects/start-wrt/changelog/patch-changed-rpc-authentication.md index 8de8d9d563..4ac8e7dbcd 100644 --- a/projects/start-wrt/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-wrt/changelog/patch-changed-rpc-authentication.md @@ -19,3 +19,4 @@ release-notes: false - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. - Stream update progress and live logs over the encrypted RPC session instead of separate continuation sockets, ending log follow and update observation when the requesting key is revoked; the CLI and older clients keep the GUID WebSocket. +- Sign the browser's encrypted RPC connection with the router's clock when this device's clock is wrong, so the web interface and first-time setup still work. diff --git a/shared-libs/crates/start-core/examples/generate_bindings.rs b/shared-libs/crates/start-core/examples/generate_bindings.rs index 26952063b0..c99669cb8c 100644 --- a/shared-libs/crates/start-core/examples/generate_bindings.rs +++ b/shared-libs/crates/start-core/examples/generate_bindings.rs @@ -44,6 +44,8 @@ fn main() -> Result<(), Box> { )?; let mut signature_profile = start_core::sign::browser_profile(); signature_profile["http"] = start_core::middleware::auth::signature::wire_profile(); + signature_profile["timestampToleranceSecs"] = + start_core::middleware::auth::signature::TIMESTAMP_TOLERANCE_SECS.into(); std::fs::write( directory.join("signature-profile.ts"), format!( diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index e76c6a5f74..1816e9b01c 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -81,8 +81,13 @@ connection. No callback receives unauthenticated plaintext as an admitted reques Each physical connection gets fresh DH keys, commitment and nonce. Client signing finishes before the 30-second network/admission deadline; provider handles may be reused, prepared hellos may not. The existing signed-timestamp freshness policy still -applies while signing and connecting. There is no relaxed clock policy or hidden -signing retry. The server signs only after validating the initiation. +applies while signing and connecting, and the server never relaxes it. When the server +closes an opened browser connection without answering, the browser reads the server's +`Date` header. If that time differs from the one it signed with by more than half the +tolerance, it signs one fresh hello on a new connection with the server's time. Once that +admission succeeds, later connections to that host start from the same offset. Native +clients and the browser's signed HTTP requests sign with the local clock. The server +signs only after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, diff --git a/shared-libs/crates/start-core/src/middleware/auth/signature.rs b/shared-libs/crates/start-core/src/middleware/auth/signature.rs index dec31736ae..16cb6ce7b3 100644 --- a/shared-libs/crates/start-core/src/middleware/auth/signature.rs +++ b/shared-libs/crates/start-core/src/middleware/auth/signature.rs @@ -435,6 +435,9 @@ impl SignatureAuth { const SIG_TIME_GRACE_PERIOD_SECS: u64 = 60; +/// Largest difference between a signed timestamp and this server's synchronized clock. +pub const TIMESTAMP_TOLERANCE_SECS: u64 = SIG_TIME_GRACE_PERIOD_SECS / 2; + const MAX_UNTIMED_NONCES: usize = 1024 * 1024; /// Retains nonces for 60 seconds with a trusted clock. @@ -597,7 +600,7 @@ async fn accept_nonce( .duration_since(UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1); - if now.abs_diff(commitment.timestamp) > SIG_TIME_GRACE_PERIOD_SECS / 2 { + if now.abs_diff(commitment.timestamp) > TIMESTAMP_TOLERANCE_SECS { return Err(Error::new( eyre!("{}", t!("middleware.auth.timestamp-not-within-30s")), ErrorKind::InvalidSignature, diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index 7141535c83..ddef549f43 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -13,7 +13,8 @@ registerHooks({ format: 'module', shortCircuit: true, source: ` - export async function prepareSession() { + export async function prepareSession(...args) { + globalThis.preparedSessions?.push(args) return { message: new Uint8Array([1]), async finish(response) { return { temporary: response[0] === 2, peer: ${JSON.stringify(auth.ed25519PublicKeyDer64(new Uint8Array(32).fill(7)))}, cipher: { async write(bytes) { return bytes.slice() }, async read(bytes) { await globalThis.sessionRecordGate?.(); return bytes.slice() } @@ -177,6 +178,213 @@ test('plaintext downgrade never opens admission or exposes RPC data', async () = assert.equal(url.searchParams.get('existing'), 'kept') }) +function admissionServer(answers) { + return class extends Socket { + constructor(url) { + super(url) + queueMicrotask(() => this.dispatchEvent(new Event('open'))) + } + send(data) { + super.send(data) + if (this.writes.length !== 1) return + const answer = answers.shift() + queueMicrotask(() => + answer === undefined ? this.close() : this.receive(record(answer)), + ) + } + } +} +async function withServerClock(skewMs, run) { + const fetch = globalThis.fetch + const requests = [] + globalThis.preparedSessions = [] + globalThis.fetch = async (url, init) => { + requests.push({ url: String(url), method: init.method }) + return new Response(null, { + headers: { date: new Date(Date.now() + skewMs).toUTCString() }, + }) + } + try { + await run(requests, globalThis.preparedSessions) + } finally { + globalThis.fetch = fetch + delete globalThis.preparedSessions + } +} +function connect(host, Server) { + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + 'rpc', + Server, + ) + const socket = new Constructor(`wss://${host}/rpc/v2`) + return new Promise(resolve => { + socket.addEventListener('open', () => resolve({ socket, opened: true }), { + once: true, + }) + socket.addEventListener( + 'close', + event => resolve({ socket, opened: false, event }), + { once: true }, + ) + }) +} + +test('an unanswered admission is re-signed once with the server clock and remembered', async () => { + await withServerClock(120_000, async (requests, prepared) => { + Socket.instances = [] + const first = await connect( + 'skewed.test', + admissionServer([undefined, [1]]), + ) + assert.equal(first.opened, true) + assert.equal(Socket.instances.length, 2) + assert.deepEqual(requests, [ + { url: 'https://skewed.test/', method: 'HEAD' }, + ]) + const [initial, retried] = prepared.map(args => args[3] - Date.now()) + assert.ok(Math.abs(initial) < 1_000) + assert.ok(Math.abs(retried - 120_000) < 2_000) + first.socket.close() + + const second = await connect('skewed.test', admissionServer([[1]])) + assert.equal(second.opened, true) + assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now() - 120_000) < 2_000) + second.socket.close() + }) +}) + +test('an unanswered admission within the signing tolerance is not retried', async () => { + await withServerClock(5_000, async (requests, prepared) => { + Socket.instances = [] + const result = await connect( + 'synced.test', + admissionServer([undefined, [1]]), + ) + assert.equal(result.opened, false) + assert.equal(result.event.code, profile.abnormalCloseCode) + assert.equal(Socket.instances.length, 1) + assert.equal(requests.length, 1) + assert.equal(prepared.length, 1) + }) +}) + +test('a socket that never opens never consults the server clock', async () => { + class Unreachable extends Socket { + constructor(url) { + super(url) + queueMicrotask(() => this.close()) + } + } + await withServerClock(120_000, async (requests, prepared) => { + Socket.instances = [] + const result = await connect('unreachable.test', Unreachable) + assert.equal(result.opened, false) + assert.equal(Socket.instances.length, 1) + assert.equal(requests.length, 0) + assert.equal(prepared.length, 1) + }) +}) + +test('an answered admission failure never consults the server clock', async () => { + await withServerClock(120_000, async (requests, prepared) => { + Socket.instances = [] + const result = await connect('answered.test', admissionServer([[2], [1]])) + assert.equal(result.opened, false) + assert.equal(Socket.instances.length, 1) + assert.equal(requests.length, 0) + assert.equal(prepared.length, 1) + }) +}) + +test('a re-signed admission the server still drops is not remembered', async () => { + await withServerClock(120_000, async (requests, prepared) => { + Socket.instances = [] + const first = await connect( + 'disputed.test', + admissionServer([undefined, undefined]), + ) + assert.equal(first.opened, false) + assert.equal(Socket.instances.length, 2) + assert.equal(requests.length, 1) + + const second = await connect('disputed.test', admissionServer([[1]])) + assert.equal(second.opened, true) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + second.socket.close() + }) +}) + +test('a remembered offset follows a corrected device clock', async () => { + await withServerClock(120_000, async () => { + const skewed = await connect( + 'corrected.test', + admissionServer([undefined, [1]]), + ) + assert.equal(skewed.opened, true) + skewed.socket.close() + }) + await withServerClock(0, async (requests, prepared) => { + Socket.instances = [] + const corrected = await connect( + 'corrected.test', + admissionServer([undefined, [1]]), + ) + assert.equal(corrected.opened, true) + assert.equal(Socket.instances.length, 2) + assert.equal(requests.length, 1) + const [stale, fresh] = prepared.map(args => args[3] - Date.now()) + assert.ok(Math.abs(stale - 120_000) < 2_000) + assert.ok(Math.abs(fresh) < 1_000) + corrected.socket.close() + + const next = await connect('corrected.test', admissionServer([[1]])) + assert.equal(next.opened, true) + assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + next.socket.close() + }) +}) + +test('closing while the server clock is read opens no second connection', async () => { + const fetch = globalThis.fetch + globalThis.preparedSessions = [] + let reading + const started = new Promise(resolve => (reading = resolve)) + globalThis.fetch = (_url, init) => + new Promise((_, reject) => { + reading() + init.signal.addEventListener('abort', () => reject(init.signal.reason), { + once: true, + }) + }) + try { + Socket.instances = [] + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + 'rpc', + admissionServer([undefined, [1]]), + ) + const socket = new Constructor('wss://closing.test/rpc/v2') + const events = [] + for (const type of ['open', 'error', 'close']) + socket.addEventListener(type, () => events.push(type)) + await started + socket.close() + await new Promise(resolve => setTimeout(resolve, 10)) + assert.deepEqual(events, ['close']) + assert.equal(socket.readyState, socket.CLOSED) + assert.equal(Socket.instances.length, 1) + assert.equal(globalThis.preparedSessions.length, 1) + } finally { + globalThis.fetch = fetch + delete globalThis.preparedSessions + } +}) + for (const [name, bytes] of [ ['plaintext', 'unexpected text'], ['oversized raw chunk', new ArrayBuffer(profile.maxWireChunkBytes + 1)], diff --git a/shared-libs/ts-modules/shared/src/services/session-identity.ts b/shared-libs/ts-modules/shared/src/services/session-identity.ts index 5d041b036f..8353f833b3 100644 --- a/shared-libs/ts-modules/shared/src/services/session-identity.ts +++ b/shared-libs/ts-modules/shared/src/services/session-identity.ts @@ -89,6 +89,7 @@ export async function prepareSession( signer: auth.RequestSigner, context: string, target: Target, + time?: number, ) { const dh = x25519.utils.randomPrivateKey() const ephemeral = new Uint8Array(x25519.getPublicKey(dh)) @@ -98,7 +99,7 @@ export async function prepareSession( hello: { role: 'client', ephemeral, target }, } const payload = encode(body) - const proof = await signer.sign(context, payload) + const proof = await signer.sign(context, payload, time) const wire = new Uint8Array(payload.length + proof.length) wire.set(payload) wire.set(proof, payload.length) diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 03a741a71e..2a09c36ba4 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -1,6 +1,7 @@ import { auth } from '@start9labs/start-core' import type { Target } from '@start9labs/start-core/osBindings/session' import { SESSION_PROFILE } from '@start9labs/start-core/osBindings/session-profile' +import { SIGNATURE_PROFILE } from '@start9labs/start-core/osBindings/signature-profile' import { pEvent } from 'p-event' import type { SessionCipher } from './session-identity' @@ -9,6 +10,29 @@ import { SessionWebSocketStream } from './session-stream' const profile = SESSION_PROFILE.transport const encoder = new TextEncoder() const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) +const RETRYABLE_SKEW_MS = (SIGNATURE_PROFILE.timestampToleranceSecs * 1000) / 2 +const serverClockOffsets = new Map() + +async function measureServerClockOffset( + url: string, + signal: AbortSignal, +): Promise { + const origin = new URL('/', url) + origin.protocol = origin.protocol === 'wss:' ? 'https:' : 'http:' + const sent = Date.now() + const response = await fetch(origin, { + method: 'HEAD', + cache: 'no-store', + signal: AbortSignal.any([ + signal, + AbortSignal.timeout(profile.handshakeTimeoutMs), + ]), + }).catch(() => undefined) + const date = Date.parse(response?.headers.get('date') ?? '') + if (Number.isNaN(date)) return undefined + // Date truncates to the second. + return date + 500 - (sent + Date.now()) / 2 +} export interface SessionSocketIdentity { readonly signer: auth.RequestSigner @@ -100,6 +124,7 @@ export function sessionWebSocketConstructor( private offset = 0 private writer = Promise.resolve() private queuedBytes = 0 + private handshake: 'connecting' | 'open' | 'answered' = 'connecting' constructor(url: string | URL, protocols?: string | string[]) { super() @@ -134,38 +159,29 @@ export function sessionWebSocketConstructor( () => this.fail(identity.signal.reason), { once: true, signal: this.lifetime.signal }, ) - const { prepareSession } = await import('./session-identity') - const prepared = await prepareSession(identity.signer, context, target) - if (this.readyState !== this.CONNECTING) return - identity.signal.throwIfAborted() - const signal = AbortSignal.any([ - identity.signal, - this.lifetime.signal, - AbortSignal.timeout(profile.handshakeTimeoutMs), - ]) - const socket = (this.socket = new Socket(this.url, protocols)) - const raw = (this.raw = new SessionWebSocketStream(socket)) + const host = new URL(this.url).host + const offset = serverClockOffsets.get(host) ?? 0 + const admitted = await this.admit(identity, protocols, offset).catch( + async (error: unknown) => { + if (this.handshake !== 'open' || this.readyState !== this.CONNECTING) + throw error + const measured = await measureServerClockOffset( + this.url, + AbortSignal.any([identity.signal, this.lifetime.signal]), + ) + if ( + measured === undefined || + Math.abs(measured - offset) <= RETRYABLE_SKEW_MS + ) + throw error + const retried = await this.admit(identity, protocols, measured) + if (retried) serverClockOffsets.set(host, measured) + return retried + }, + ) + if (!admitted) return + const { opened, raw } = admitted const abort = () => raw.abort(new Error('Encrypted WebSocket aborted')) - signal.addEventListener('abort', abort, { once: true }) - let opened: SessionOpenEvent - try { - await pEvent(socket, 'open', { - signal, - rejectionEvents: ['error', 'close'], - }) - await raw.writeRecord(prepared.message, signal) - const response = await raw.readRecord( - profile.maxHandshakeRecordBytes, - signal, - ) - const secured = await prepared.finish(response) - signal.throwIfAborted() - assertServerIdentity(secured, allowTemporaryIdentity) - opened = new SessionOpenEvent(secured.peer, secured.temporary) - this.cipher = secured.cipher - } finally { - signal.removeEventListener('abort', abort) - } this.lifetime.signal.addEventListener('abort', abort, { once: true }) this.readyState = this.OPEN this.dispatchEvent(opened) @@ -205,6 +221,56 @@ export function sessionWebSocketConstructor( } } + private async admit( + identity: SessionSocketIdentity, + protocols: string | string[] | undefined, + offset: number, + ) { + this.handshake = 'connecting' + const { prepareSession } = await import('./session-identity') + const prepared = await prepareSession( + identity.signer, + context, + target, + Date.now() + offset, + ) + if (this.readyState !== this.CONNECTING) return + identity.signal.throwIfAborted() + const signal = AbortSignal.any([ + identity.signal, + this.lifetime.signal, + AbortSignal.timeout(profile.handshakeTimeoutMs), + ]) + this.raw?.abort(new Error('Encrypted WebSocket retried')) + const socket = (this.socket = new Socket(this.url, protocols)) + const raw = (this.raw = new SessionWebSocketStream(socket)) + const abort = () => raw.abort(new Error('Encrypted WebSocket aborted')) + signal.addEventListener('abort', abort, { once: true }) + try { + await pEvent(socket, 'open', { + signal, + rejectionEvents: ['error', 'close'], + }) + this.handshake = 'open' + await raw.writeRecord(prepared.message, signal) + const response = await raw.readRecord( + profile.maxHandshakeRecordBytes, + signal, + ) + this.handshake = 'answered' + const secured = await prepared.finish(response) + signal.throwIfAborted() + assertServerIdentity(secured, allowTemporaryIdentity) + this.cipher = secured.cipher + return { + opened: new SessionOpenEvent(secured.peer, secured.temporary), + raw, + } + } finally { + signal.removeEventListener('abort', abort) + } + } + send(data: string | ArrayBufferLike | Blob | ArrayBufferView) { if (this.readyState === this.CONNECTING) throw new DOMException('WebSocket is connecting', 'InvalidStateError') diff --git a/shared-libs/ts-modules/start-core/lib/auth/signature.ts b/shared-libs/ts-modules/start-core/lib/auth/signature.ts index d19eb68770..5739cf08fe 100644 --- a/shared-libs/ts-modules/start-core/lib/auth/signature.ts +++ b/shared-libs/ts-modules/start-core/lib/auth/signature.ts @@ -23,7 +23,12 @@ export interface AuthKey { /** Signs captured body bytes and returns a binary CBOR request proof without exporting private keys. */ export interface RequestSigner { - sign(context: string, body: Uint8Array): Promise> + /** Stamps the proof with the given epoch-millisecond time, else the local clock. */ + sign( + context: string, + body: Uint8Array, + time?: number, + ): Promise> } interface SigningIdentity { @@ -43,10 +48,10 @@ function webCryptoIdentity(key: AuthKey): SigningIdentity { function commitmentSigner(identity: SigningIdentity): RequestSigner { return { - sign: async (context, body) => { + sign: async (context, body, time) => { const { encode } = await import('./cbor') return encode( - await signTaggedRequest(identity, context, body, COMMITMENT_TAG), + await signTaggedRequest(identity, context, body, COMMITMENT_TAG, time), ) }, } @@ -129,8 +134,9 @@ async function signTaggedRequest( context: string, body: Uint8Array, tag: Uint8Array, + time = Date.now(), ): Promise { - const timestamp = BigInt(Math.floor(Date.now() / 1000)) + const timestamp = BigInt(Math.floor(time / 1000)) const nonce = crypto.getRandomValues(new BigUint64Array(1))[0] const size = BigInt(body.length) const hash = blake3(body) diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts b/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts index 9abd0af183..6b95bc76bf 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts @@ -28,4 +28,5 @@ export const SIGNATURE_PROFILE = { ], header: 'X-Start-Auth-Sig', }, + timestampToleranceSecs: 30, } as const diff --git a/shared-libs/ts-modules/start-core/lib/test/signature.test.ts b/shared-libs/ts-modules/start-core/lib/test/signature.test.ts index 90b4486dd9..48e58eaa44 100644 --- a/shared-libs/ts-modules/start-core/lib/test/signature.test.ts +++ b/shared-libs/ts-modules/start-core/lib/test/signature.test.ts @@ -62,6 +62,20 @@ test('request proof verification rejects a normalized typed-byte tag', async () ).rejects.toThrow() }) +test('request proofs commit the requested signing time and still verify', async () => { + const signer = await generateEphemeralRequestSigner() + const body = new TextEncoder().encode('captured body') + const time = Date.UTC(2030, 0, 1, 0, 0, 30, 999) + const proof = await signer.sign('server.test', body, time) + const parsed = (await decodeFirst(proof)).value as BinaryRequestProof + expect(BigInt(parsed.commitment.timestamp)).toBe( + BigInt(Math.floor(time / 1000)), + ) + await expect( + verifyRequestProof(proof, 'server.test', body), + ).resolves.toBeTruthy() +}) + test('DER64 normalization preserves standard Base64 and padding', () => { expect(normalizeDer64(pem)).toBe(der64) expect(normalizeDer64(pem.replace(/\n/g, '\r\n'))).toBe(der64) From d084b6df7ff8e469c76f4735d9772c2f8b815a5e Mon Sep 17 00:00:00 2001 From: helix-white <267227783+helix-a@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:40:17 +0000 Subject: [PATCH 02/10] Proposed changes for #4939 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --- .../crates/start-core/signed-session.md | 8 ++- .../shared/scripts/session-transport.test.mjs | 72 ++++++++++++++++++- .../shared/src/services/session-websocket.ts | 50 +++++++++---- 3 files changed, 112 insertions(+), 18 deletions(-) diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index 1816e9b01c..0e95dda13f 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -85,9 +85,11 @@ applies while signing and connecting, and the server never relaxes it. When the closes an opened browser connection without answering, the browser reads the server's `Date` header. If that time differs from the one it signed with by more than half the tolerance, it signs one fresh hello on a new connection with the server's time. Once that -admission succeeds, later connections to that host start from the same offset. Native -clients and the browser's signed HTTP requests sign with the local clock. The server -signs only after validating the initiation. +admission succeeds, later connections to that host start from the same offset. A device-clock +change greater than half the tolerance refreshes the offset before opening another +connection. GUID continuations are single-use even when admission fails. Native clients +and the browser's signed HTTP requests sign with the local clock. The server signs only +after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index ddef549f43..5c6d10c108 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -3,6 +3,7 @@ import test from 'node:test' import { registerHooks } from 'node:module' import { auth } from '@start9labs/start-core' import { SESSION_PROFILE } from '@start9labs/start-core/osBindings/session-profile' +import { SIGNATURE_PROFILE } from '@start9labs/start-core/osBindings/signature-profile' import './typescript-loader.mjs' // Framing/lifecycle tests replace crypto; real signed-DH interoperability has separate coverage. @@ -218,7 +219,9 @@ function connect(host, Server) { 'rpc', Server, ) - const socket = new Constructor(`wss://${host}/rpc/v2`) + return connectionResult(new Constructor(`wss://${host}/rpc/v2`)) +} +function connectionResult(socket) { return new Promise(resolve => { socket.addEventListener('open', () => resolve({ socket, opened: true }), { once: true, @@ -317,7 +320,7 @@ test('a re-signed admission the server still drops is not remembered', async () }) }) -test('a remembered offset follows a corrected device clock', async () => { +test('a remembered offset follows a corrected server clock', async () => { await withServerClock(120_000, async () => { const skewed = await connect( 'corrected.test', @@ -348,6 +351,71 @@ test('a remembered offset follows a corrected device clock', async () => { }) }) +for (const skew of [-120_000, 120_000]) + test(`correcting a ${skew} ms device clock refreshes before single-use admission`, async () => { + const now = Date.now + let deviceSkew = skew + Date.now = () => now() + deviceSkew + const host = `corrected-device-${skew}.test` + try { + await withServerClock(-skew, async () => { + const initial = await connect(host, admissionServer([undefined, [1]])) + assert.equal(initial.opened, true) + initial.socket.close() + }) + deviceSkew = 0 + await withServerClock(0, async (requests, prepared) => { + Socket.instances = [] + let available = true + class SingleUse extends Socket { + constructor(url) { + super(url) + const found = available + available = false + queueMicrotask(() => + found ? this.dispatchEvent(new Event('open')) : this.close(), + ) + } + send(data) { + super.send(data) + if (this.writes.length !== 1) return + const timely = + Math.abs(prepared.at(-1)[3] - Date.now()) <= + SIGNATURE_PROFILE.timestampToleranceSecs * 1000 + queueMicrotask(() => + timely ? this.receive(record([1])) : this.close(), + ) + } + } + const guid = 'A'.repeat(32) + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + { continuation: guid }, + SingleUse, + ) + const result = await connectionResult( + new Constructor(`wss://${host}/rpc/v2/${guid}`), + ) + assert.equal(result.opened, true) + assert.equal(Socket.instances.length, 1) + assert.equal(prepared.length, 1) + assert.deepEqual(requests, [ + { url: `https://${host}/`, method: 'HEAD' }, + ]) + result.socket.close() + + const next = await connect(host, admissionServer([[1]])) + assert.equal(next.opened, true) + assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + next.socket.close() + }) + } finally { + Date.now = now + } + }) + test('closing while the server clock is read opens no second connection', async () => { const fetch = globalThis.fetch globalThis.preparedSessions = [] diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 2a09c36ba4..6fc7162d32 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -11,15 +11,22 @@ const profile = SESSION_PROFILE.transport const encoder = new TextEncoder() const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) const RETRYABLE_SKEW_MS = (SIGNATURE_PROFILE.timestampToleranceSecs * 1000) / 2 -const serverClockOffsets = new Map() + +interface ServerClockOffset { + offset: number + localTime: number + monotonicTime: number +} + +const serverClockOffsets = new Map() async function measureServerClockOffset( url: string, signal: AbortSignal, -): Promise { +): Promise { const origin = new URL('/', url) origin.protocol = origin.protocol === 'wss:' ? 'https:' : 'http:' - const sent = Date.now() + const sent = performance.now() const response = await fetch(origin, { method: 'HEAD', cache: 'no-store', @@ -30,8 +37,14 @@ async function measureServerClockOffset( }).catch(() => undefined) const date = Date.parse(response?.headers.get('date') ?? '') if (Number.isNaN(date)) return undefined + const monotonicTime = performance.now() + const localTime = Date.now() // Date truncates to the second. - return date + 500 - (sent + Date.now()) / 2 + return { + offset: date + 500 + (monotonicTime - sent) / 2 - localTime, + localTime, + monotonicTime, + } } export interface SessionSocketIdentity { @@ -160,26 +173,37 @@ export function sessionWebSocketConstructor( { once: true, signal: this.lifetime.signal }, ) const host = new URL(this.url).host - const offset = serverClockOffsets.get(host) ?? 0 + const cached = serverClockOffsets.get(host) + const signal = AbortSignal.any([identity.signal, this.lifetime.signal]) + let measured: ServerClockOffset | undefined + if ( + cached && + Math.abs( + Date.now() - + cached.localTime - + (performance.now() - cached.monotonicTime), + ) > RETRYABLE_SKEW_MS + ) { + measured = await measureServerClockOffset(this.url, signal) + if (measured === undefined) + throw new Error('Server clock is unavailable') + } + const offset = measured?.offset ?? cached?.offset ?? 0 const admitted = await this.admit(identity, protocols, offset).catch( async (error: unknown) => { if (this.handshake !== 'open' || this.readyState !== this.CONNECTING) throw error - const measured = await measureServerClockOffset( - this.url, - AbortSignal.any([identity.signal, this.lifetime.signal]), - ) + measured = await measureServerClockOffset(this.url, signal) if ( measured === undefined || - Math.abs(measured - offset) <= RETRYABLE_SKEW_MS + Math.abs(measured.offset - offset) <= RETRYABLE_SKEW_MS ) throw error - const retried = await this.admit(identity, protocols, measured) - if (retried) serverClockOffsets.set(host, measured) - return retried + return this.admit(identity, protocols, measured.offset) }, ) if (!admitted) return + if (measured) serverClockOffsets.set(host, measured) const { opened, raw } = admitted const abort = () => raw.abort(new Error('Encrypted WebSocket aborted')) this.lifetime.signal.addEventListener('abort', abort, { once: true }) From a4de0a29bd11be4c36e655503a6562a6739f6023 Mon Sep 17 00:00:00 2001 From: Shadowy Super Coder Date: Wed, 25 Nov 2026 10:10:47 -0700 Subject: [PATCH 03/10] fix(web): never re-admit a spent continuation and forget a disagreeing offset The server removes a continuation's GUID when it upgrades the socket, before admission is validated, so a second connection to the same GUID always gets 404. An unanswered continuation hello is no longer retried. When the server's Date disagrees with the offset the hello was signed with, the remembered offset is forgotten, so the next admission starts from the device clock instead of repeating a stale offset. This covers a server-clock change, which the monotonic check cannot see. Tests: a stale offset on a single-use continuation opens one socket and the next GUID signs with the device clock; an unreadable server clock after a device-clock change leaves the GUID unspent; prepareSession commits the requested signing time. The transport tests stub fetch, so the plaintext-downgrade case no longer reaches the network. signed-session.md and the ts-modules ARCHITECTURE describe when the offset is measured, forgotten and used. --- .../crates/start-core/signed-session.md | 20 ++- shared-libs/ts-modules/ARCHITECTURE.md | 2 +- .../shared/scripts/session-identity.test.mjs | 25 +++ .../shared/scripts/session-transport.test.mjs | 154 ++++++++++++------ .../shared/src/services/session-websocket.ts | 4 + 5 files changed, 143 insertions(+), 62 deletions(-) diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index 0e95dda13f..bf620c354f 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -81,15 +81,17 @@ connection. No callback receives unauthenticated plaintext as an admitted reques Each physical connection gets fresh DH keys, commitment and nonce. Client signing finishes before the 30-second network/admission deadline; provider handles may be reused, prepared hellos may not. The existing signed-timestamp freshness policy still -applies while signing and connecting, and the server never relaxes it. When the server -closes an opened browser connection without answering, the browser reads the server's -`Date` header. If that time differs from the one it signed with by more than half the -tolerance, it signs one fresh hello on a new connection with the server's time. Once that -admission succeeds, later connections to that host start from the same offset. A device-clock -change greater than half the tolerance refreshes the offset before opening another -connection. GUID continuations are single-use even when admission fails. Native clients -and the browser's signed HTTP requests sign with the local clock. The server signs only -after validating the initiation. +applies while signing and connecting, and the server never relaxes it. When an opened +browser connection fails before a complete answer record arrives, the browser reads the +server's `Date` header. If that time differs from the one it signed with by more than half +the tolerance, the browser forgets the offset it remembers for that host. For the RPC +target it then signs one fresh hello on a new connection with the server's time. A GUID +continuation is spent by its first upgrade, even when admission fails, and is never +retried. Once an admission signed with a measured offset succeeds, later connections to +that host start from that offset. A device-clock change greater than half the tolerance +measures the offset again before the next connection opens; a failed measurement fails +that connection unopened. Native clients and the browser's signed HTTP requests sign with +the local clock. The server signs only after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, diff --git a/shared-libs/ts-modules/ARCHITECTURE.md b/shared-libs/ts-modules/ARCHITECTURE.md index 3a2dcaf52c..e88867af0b 100644 --- a/shared-libs/ts-modules/ARCHITECTURE.md +++ b/shared-libs/ts-modules/ARCHITECTURE.md @@ -36,7 +36,7 @@ to its transport and must cancel only that operation, without replaying it or re - **`HttpService`** (`shared/src/services/http.service.ts`) — HTTP transport. `rpcRequest()` prepares an unsigned request; `rpcMessage()` sends an already serialized message unchanged. Both use the shared JSON headers and response-compatibility adapter. - **`AuthKeyService`** (`shared/src/services/auth-key.service.ts`) — Owns the browser's enrolled, nonextractable device key and its cancellation lifetime. `admissionLease` reuses possession of that key or an opaque, unpersisted Ed25519 signer when none is stored, without enrollment or a WebCrypto dependency for startup. Acquisition and enrollment started under a replaced, rolled-back or logged-out lifetime cannot adopt the next identity; fresh requests receive a fresh lifetime. StartOS and Tunnel use leases for encrypted RPC. StartWRT composes the same encrypted transport through its own RPC/reconnect owners; anonymous bootstrap uses unpersisted encrypted possession and omits normal-product peer-history observation. Resource requests keep header signing. -- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback. StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. +- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback. `session-websocket.ts` keeps a per-host server-clock offset, measured from a `HEAD` request's `Date` header, for a browser whose clock is wrong; the [signed-session contract](../crates/start-core/signed-session.md#admission) says when it is measured and used. StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. - **`local-rpc.ts`** — `localRpcRequest` owns OS/Tunnel local capture, nullable-key encrypted-or-public-HTTP dispatch, error metadata and PatchDB fences. `authenticatedRpcTransport` owns device-key typed-stream admission and the combined device/operation signal; it rejects missing keys without HTTP fallback. Server authorization remains live. StartOS's normal generated stream facade waits for initial fences, shares its code-34 logout owner and preserves the socket iterator's early disposal. `watchDb$` composes the raw transport separately: its initial dump establishes the fence. Fence cancellation releases cache subscriptions and prevents late adoption after logout/disposal. Explicit foreign echo remains unsigned HTTP and unfenced; its rejection never invalidates local authentication. - **`ServerIdentityService`** (`shared/src/services/server-identity.service.ts`) — Normal product API callers attach its open observer to RPC/stream/GUID operations. The transport caches one verified open event; reuse observes it only while its physical socket remains open. Observation precedes application replies, including authorization rejection, without introducing another connection owner. Same-origin API targets remember one fingerprint per app/API namespace, atomically in the existing identity IndexedDB store through `identity-store.ts`. This record is separate from the device-key record and survives logout. First contact is silent; rotation remembers the new key and lazily opens a nonblocking Taiga notice/details view. Storage failure never changes the RPC result. RPC, DOM and RxJS continuation open observers retain their owners. The signed handshake marks provisional setup and temporary recovery identities. Normal operations reject them before sending payloads, including when reusing a startup probe's socket; explicit setup/init/diagnostic operations opt in. Continuations enforce the same admission policy. Temporary identities, foreign API overrides and OS registry listings do not populate this history. The backend [identity lifecycle](../crates/start-core/encrypted-rpc.md#identity-and-trust) owns persistence and recovery policy. - **`StartupApiService`** (`ui/src/app/services/api/startup-api.service.ts`) — Explicit encrypted-possession boundary for StartOS initialization, diagnostics and the existing state/DNS probe. Setup-wizard calls and GUIDs use the same admission lease and socket owner. These callers neither enroll keys nor attach normal-product identity-history observers. Normal callers retain `ApiService` and its enrolled-key policy. An unauthenticated mode response never selects plaintext for a normal call. Diagnostic update observation uses the generated typed stream; the component-scoped `DiagnosticUpdate` service reports success after the actual terminal, not a progress counter or close code. Disposal cancels observation without canceling accepted backend work. Mock mode aliases the same concrete API fixture for both interfaces rather than duplicating its state; its initiating update and progress producers are shared with ordinary mock calls. Shared `pauseFor` accepts cancellation for mock progress waits. The setup wizard's component-scoped `SetupObservation` consumes typed `setup.status` through the same lease/socket owner; only successful termination permits navigation to its separate finalization step. Transport loss retries the read-only observation, never the accepted setup operation. Shared `isNetworkError` owns numeric code-zero classification for formatting and reconnect callers; StartWRT retains its existing exported binding and reconnect policy. Both transports share `rpcWebSocketUrl` and the native-generated endpoint. diff --git a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs index fd41a0a692..e66e2a5548 100644 --- a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs @@ -87,6 +87,31 @@ test('opaque fresh initiation signs once per connection and binds exact GUID int assert.equal(b.hello.target, 'rpc') }) +test('a hello proof carries the requested signing time', async () => { + const key = await auth.generateAuthKey() + const time = Date.UTC(2030, 0, 1, 0, 0, 30, 999) + const prepared = await prepareSession( + auth.requestSigner(key), + fixture.context, + 'rpc', + time, + ) + const body = await decodeFirst(prepared.message) + const proof = prepared.message.subarray(body.length) + assert.equal( + BigInt((await decodeFirst(proof)).value.commitment.timestamp), + BigInt(Math.floor(time / 1000)), + ) + assert.equal( + await auth.verifyRequestProof( + proof, + fixture.context, + prepared.message.subarray(0, body.length), + ), + auth.normalizeDer64(key.pubkeyPem), + ) +}) + test('independent WebCrypto golden matches both directional records and full captured hellos', async context => { const prepared = await frozenClient(context) assert.deepEqual(prepared.message, client) diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index 5c6d10c108..adf1f60bfb 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -6,6 +6,10 @@ import { SESSION_PROFILE } from '@start9labs/start-core/osBindings/session-profi import { SIGNATURE_PROFILE } from '@start9labs/start-core/osBindings/signature-profile' import './typescript-loader.mjs' +globalThis.fetch = async () => { + throw new TypeError('Transport tests have no network') +} + // Framing/lifecycle tests replace crypto; real signed-DH interoperability has separate coverage. registerHooks({ load(url, context, next) { @@ -195,12 +199,37 @@ function admissionServer(answers) { } } } +function singleUseServer(serverSkewMs = 0) { + let available = true + return class extends Socket { + constructor(url) { + super(url) + const found = available + available = false + queueMicrotask(() => + found ? this.dispatchEvent(new Event('open')) : this.close(), + ) + } + send(data) { + super.send(data) + if (this.writes.length !== 1) return + const timely = + Math.abs( + globalThis.preparedSessions.at(-1)[3] - Date.now() - serverSkewMs, + ) <= + SIGNATURE_PROFILE.timestampToleranceSecs * 1000 + queueMicrotask(() => (timely ? this.receive(record([1])) : this.close())) + } + } +} +/** A null skew makes the server's clock unreadable. */ async function withServerClock(skewMs, run) { const fetch = globalThis.fetch const requests = [] globalThis.preparedSessions = [] globalThis.fetch = async (url, init) => { requests.push({ url: String(url), method: init.method }) + if (skewMs === null) throw new TypeError('Failed to fetch') return new Response(null, { headers: { date: new Date(Date.now() + skewMs).toUTCString() }, }) @@ -212,6 +241,23 @@ async function withServerClock(skewMs, run) { delete globalThis.preparedSessions } } +async function withDeviceClock(skewMs, run) { + const now = Date.now + let skew = skewMs + Date.now = () => now() + skew + try { + await run(value => (skew = value)) + } finally { + Date.now = now + } +} +async function rememberOffset(host, serverSkewMs) { + await withServerClock(serverSkewMs, async () => { + const result = await connect(host, admissionServer([undefined, [1]])) + assert.equal(result.opened, true) + result.socket.close() + }) +} function connect(host, Server) { const Constructor = sessionWebSocketConstructor( async () => identity(), @@ -221,6 +267,15 @@ function connect(host, Server) { ) return connectionResult(new Constructor(`wss://${host}/rpc/v2`)) } +function redeem(host, Server, guid = 'A'.repeat(32)) { + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + { continuation: guid }, + Server, + ) + return connectionResult(new Constructor(`wss://${host}/rpc/v2/${guid}`)) +} function connectionResult(socket) { return new Promise(resolve => { socket.addEventListener('open', () => resolve({ socket, opened: true }), { @@ -321,14 +376,7 @@ test('a re-signed admission the server still drops is not remembered', async () }) test('a remembered offset follows a corrected server clock', async () => { - await withServerClock(120_000, async () => { - const skewed = await connect( - 'corrected.test', - admissionServer([undefined, [1]]), - ) - assert.equal(skewed.opened, true) - skewed.socket.close() - }) + await rememberOffset('corrected.test', 120_000) await withServerClock(0, async (requests, prepared) => { Socket.instances = [] const corrected = await connect( @@ -353,50 +401,13 @@ test('a remembered offset follows a corrected server clock', async () => { for (const skew of [-120_000, 120_000]) test(`correcting a ${skew} ms device clock refreshes before single-use admission`, async () => { - const now = Date.now - let deviceSkew = skew - Date.now = () => now() + deviceSkew const host = `corrected-device-${skew}.test` - try { - await withServerClock(-skew, async () => { - const initial = await connect(host, admissionServer([undefined, [1]])) - assert.equal(initial.opened, true) - initial.socket.close() - }) - deviceSkew = 0 + await withDeviceClock(skew, async setDeviceSkew => { + await rememberOffset(host, -skew) + setDeviceSkew(0) await withServerClock(0, async (requests, prepared) => { Socket.instances = [] - let available = true - class SingleUse extends Socket { - constructor(url) { - super(url) - const found = available - available = false - queueMicrotask(() => - found ? this.dispatchEvent(new Event('open')) : this.close(), - ) - } - send(data) { - super.send(data) - if (this.writes.length !== 1) return - const timely = - Math.abs(prepared.at(-1)[3] - Date.now()) <= - SIGNATURE_PROFILE.timestampToleranceSecs * 1000 - queueMicrotask(() => - timely ? this.receive(record([1])) : this.close(), - ) - } - } - const guid = 'A'.repeat(32) - const Constructor = sessionWebSocketConstructor( - async () => identity(), - 'server.test', - { continuation: guid }, - SingleUse, - ) - const result = await connectionResult( - new Constructor(`wss://${host}/rpc/v2/${guid}`), - ) + const result = await redeem(host, singleUseServer()) assert.equal(result.opened, true) assert.equal(Socket.instances.length, 1) assert.equal(prepared.length, 1) @@ -411,11 +422,50 @@ for (const skew of [-120_000, 120_000]) assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) next.socket.close() }) - } finally { - Date.now = now - } + }) }) +test('an unreadable server clock after a device-clock change leaves the continuation unspent', async () => { + const host = 'unreadable-refresh.test' + const Server = singleUseServer() + await withDeviceClock(120_000, async setDeviceSkew => { + await rememberOffset(host, -120_000) + setDeviceSkew(0) + await withServerClock(null, async (requests, prepared) => { + Socket.instances = [] + const refused = await redeem(host, Server) + assert.equal(refused.opened, false) + assert.equal(Socket.instances.length, 0) + assert.equal(prepared.length, 0) + assert.equal(requests.length, 1) + }) + await withServerClock(0, async () => { + const redeemed = await redeem(host, Server) + assert.equal(redeemed.opened, true) + redeemed.socket.close() + }) + }) +}) + +test('a continuation the server clock no longer admits forgets the offset without reconnecting', async () => { + const host = 'server-corrected.test' + await rememberOffset(host, 120_000) + await withServerClock(0, async (requests, prepared) => { + Socket.instances = [] + const stale = await redeem(host, singleUseServer()) + assert.equal(stale.opened, false) + assert.equal(Socket.instances.length, 1) + assert.equal(prepared.length, 1) + assert.equal(requests.length, 1) + + const next = await redeem(host, singleUseServer(), 'B'.repeat(32)) + assert.equal(next.opened, true) + assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + next.socket.close() + }) +}) + test('closing while the server clock is read opens no second connection', async () => { const fetch = globalThis.fetch globalThis.preparedSessions = [] diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 6fc7162d32..7628a68445 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -199,6 +199,10 @@ export function sessionWebSocketConstructor( Math.abs(measured.offset - offset) <= RETRYABLE_SKEW_MS ) throw error + if (serverClockOffsets.get(host) === cached) + serverClockOffsets.delete(host) + // The server spends a continuation's GUID on its first upgrade. + if (target !== SESSION_PROFILE.identity.rpcTarget) throw error return this.admit(identity, protocols, measured.offset) }, ) From f6ed343cadddf964f21160a3827e0124c73963d5 Mon Sep 17 00:00:00 2001 From: Shadowy Super Coder Date: Wed, 25 Nov 2026 10:32:28 -0700 Subject: [PATCH 04/10] fix(web): measure the server clock before redeeming a continuation A remembered offset can go stale without the wall clock diverging from the monotonic clock: NTP slews a corrected clock, and CLOCK_MONOTONIC slews with it, or the server's own clock changes. A continuation signed with that offset spends its GUID. While an offset is remembered for the host, a continuation now measures the server's Date before opening and fails unopened if it cannot. The RPC target keeps the divergence check, since it recovers by retrying. Tests: a server-clock change and a slewed device correction both redeem the continuation on one socket; an unanswered continuation without a remembered offset is not re-signed; a connection that fails after another stored a fresh offset leaves it in place. --- .../crates/start-core/signed-session.md | 9 +- .../shared/scripts/session-transport.test.mjs | 126 ++++++++++++++---- .../shared/src/services/session-websocket.ts | 16 ++- 3 files changed, 114 insertions(+), 37 deletions(-) diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index bf620c354f..27a6fac7d3 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -88,10 +88,11 @@ the tolerance, the browser forgets the offset it remembers for that host. For th target it then signs one fresh hello on a new connection with the server's time. A GUID continuation is spent by its first upgrade, even when admission fails, and is never retried. Once an admission signed with a measured offset succeeds, later connections to -that host start from that offset. A device-clock change greater than half the tolerance -measures the offset again before the next connection opens; a failed measurement fails -that connection unopened. Native clients and the browser's signed HTTP requests sign with -the local clock. The server signs only after validating the initiation. +that host start from that offset. The browser measures the offset again before opening a +GUID continuation while one is remembered, and before any connection once the device clock +has moved more than half the tolerance against its monotonic clock; a failed measurement +fails that connection unopened. Native clients and the browser's signed HTTP requests sign +with the local clock. The server signs only after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index adf1f60bfb..8079ab280e 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -425,44 +425,118 @@ for (const skew of [-120_000, 120_000]) }) }) -test('an unreadable server clock after a device-clock change leaves the continuation unspent', async () => { - const host = 'unreadable-refresh.test' - const Server = singleUseServer() - await withDeviceClock(120_000, async setDeviceSkew => { - await rememberOffset(host, -120_000) - setDeviceSkew(0) - await withServerClock(null, async (requests, prepared) => { - Socket.instances = [] - const refused = await redeem(host, Server) - assert.equal(refused.opened, false) - assert.equal(Socket.instances.length, 0) - assert.equal(prepared.length, 0) - assert.equal(requests.length, 1) - }) - await withServerClock(0, async () => { - const redeemed = await redeem(host, Server) - assert.equal(redeemed.opened, true) - redeemed.socket.close() - }) +test('an unreadable server clock leaves a continuation with a remembered offset unspent', async () => { + const host = 'unreadable.test' + const Server = singleUseServer(120_000) + await rememberOffset(host, 120_000) + await withServerClock(null, async (requests, prepared) => { + Socket.instances = [] + const refused = await redeem(host, Server) + assert.equal(refused.opened, false) + assert.equal(Socket.instances.length, 0) + assert.equal(prepared.length, 0) + assert.equal(requests.length, 1) + }) + await withServerClock(120_000, async () => { + const redeemed = await redeem(host, Server) + assert.equal(redeemed.opened, true) + redeemed.socket.close() }) }) -test('a continuation the server clock no longer admits forgets the offset without reconnecting', async () => { +test('a continuation measures the server clock before signing with a remembered offset', async () => { const host = 'server-corrected.test' await rememberOffset(host, 120_000) await withServerClock(0, async (requests, prepared) => { Socket.instances = [] - const stale = await redeem(host, singleUseServer()) - assert.equal(stale.opened, false) + const result = await redeem(host, singleUseServer()) + assert.equal(result.opened, true) assert.equal(Socket.instances.length, 1) assert.equal(prepared.length, 1) assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + result.socket.close() + }) +}) - const next = await redeem(host, singleUseServer(), 'B'.repeat(32)) - assert.equal(next.opened, true) +test('a slewed device-clock correction does not spend a continuation', async () => { + const host = 'slewed-device.test' + const monotonic = performance.now + let slew = 0 + performance.now = () => monotonic.call(performance) + slew + try { + await withDeviceClock(120_000, async setDeviceSkew => { + await rememberOffset(host, -120_000) + setDeviceSkew(0) + slew = -120_000 + await withServerClock(0, async (requests, prepared) => { + Socket.instances = [] + const result = await redeem(host, singleUseServer()) + assert.equal(result.opened, true) + assert.equal(Socket.instances.length, 1) + assert.equal(requests.length, 1) + assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) + result.socket.close() + }) + }) + } finally { + performance.now = monotonic + } +}) + +test('an unanswered continuation is never re-signed on a second connection', async () => { + await withServerClock(120_000, async (requests, prepared) => { + Socket.instances = [] + const result = await redeem('unanswered.test', singleUseServer(120_000)) + assert.equal(result.opened, false) + assert.equal(Socket.instances.length, 1) + assert.equal(prepared.length, 1) assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - next.socket.close() + }) +}) + +test('a failed connection keeps the offset another connection just remembered', async () => { + const host = 'concurrent.test' + const settled = async (count, pending) => { + while (pending.length < count) await new Promise(r => setTimeout(r, 1)) + } + await withDeviceClock(-120_000, async () => { + await rememberOffset(host, 180_000) + const fetch = globalThis.fetch + const pending = [] + globalThis.preparedSessions = [] + globalThis.fetch = () => + new Promise(resolve => + pending.push(() => + resolve( + new Response(null, { + headers: { date: new Date(Date.now() + 120_000).toUTCString() }, + }), + ), + ), + ) + try { + const first = connect(host, admissionServer([undefined, [1]])) + await settled(1, pending) + const second = connect(host, admissionServer([undefined, undefined])) + await settled(2, pending) + pending[0]() + const remembered = await first + assert.equal(remembered.opened, true) + pending[1]() + assert.equal((await second).opened, false) + + const next = await connect(host, admissionServer([[1]])) + assert.equal(next.opened, true) + assert.equal(pending.length, 2) + const signed = globalThis.preparedSessions.at(-1)[3] - Date.now() + assert.ok(Math.abs(signed - 120_000) < 2_000) + remembered.socket.close() + next.socket.close() + } finally { + globalThis.fetch = fetch + delete globalThis.preparedSessions + } }) }) diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 7628a68445..1b184d1c13 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -172,17 +172,20 @@ export function sessionWebSocketConstructor( () => this.fail(identity.signal.reason), { once: true, signal: this.lifetime.signal }, ) + // The server spends a continuation GUID on its first upgrade. + const reusable = target === SESSION_PROFILE.identity.rpcTarget const host = new URL(this.url).host const cached = serverClockOffsets.get(host) const signal = AbortSignal.any([identity.signal, this.lifetime.signal]) let measured: ServerClockOffset | undefined if ( cached && - Math.abs( - Date.now() - - cached.localTime - - (performance.now() - cached.monotonicTime), - ) > RETRYABLE_SKEW_MS + (!reusable || + Math.abs( + Date.now() - + cached.localTime - + (performance.now() - cached.monotonicTime), + ) > RETRYABLE_SKEW_MS) ) { measured = await measureServerClockOffset(this.url, signal) if (measured === undefined) @@ -201,8 +204,7 @@ export function sessionWebSocketConstructor( throw error if (serverClockOffsets.get(host) === cached) serverClockOffsets.delete(host) - // The server spends a continuation's GUID on its first upgrade. - if (target !== SESSION_PROFILE.identity.rpcTarget) throw error + if (!reusable) throw error return this.admit(identity, protocols, measured.offset) }, ) From 15838fc854a00d48700f39522e40b6c7183f18e7 Mon Sep 17 00:00:00 2001 From: helix-red <355572797+helix-red@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:47:54 +0000 Subject: [PATCH 05/10] fix(core): answer a clock-skewed session hello with the server's time A hello whose proof, target and peer validate but whose timestamp falls outside the synchronized window now gets an unsigned `retry` record carrying the server's clock, and the server accepts one more hello on the same socket within the handshake deadline. Every other rejection still drops without a reply. `accept_nonce` marks the skew case with a typed `ClockSkew` source, so replays stay indistinguishable on the wire. The native initiator re-signs a fresh hello at the server's time once, and reports the device clock when that hello is rejected too. Because the retry stays on the socket whose upgrade holds a continuation's handler, a GUID survives it. The browser's `HEAD /` measurement no longer feeds the bindings, so the signature profile drops `timestampToleranceSecs`. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- .../start-core/examples/generate_bindings.rs | 2 - .../crates/start-core/locales/i18n.yaml | 7 + .../src/middleware/auth/signature.rs | 39 ++++-- .../start-core/src/sign/commitment/request.rs | 30 ++++- .../crates/start-core/src/sign/session.rs | 71 +++++++++- .../start-core/src/sign/session/tests.rs | 30 +++++ .../crates/start-core/src/util/net/secure.rs | 63 +++++++-- .../start-core/src/util/net/secure/tests.rs | 126 ++++++++++++++++++ .../lib/osBindings/session.schemas.ts | 38 ++++++ .../lib/osBindings/signature-profile.ts | 1 - 10 files changed, 368 insertions(+), 39 deletions(-) diff --git a/shared-libs/crates/start-core/examples/generate_bindings.rs b/shared-libs/crates/start-core/examples/generate_bindings.rs index c99669cb8c..26952063b0 100644 --- a/shared-libs/crates/start-core/examples/generate_bindings.rs +++ b/shared-libs/crates/start-core/examples/generate_bindings.rs @@ -44,8 +44,6 @@ fn main() -> Result<(), Box> { )?; let mut signature_profile = start_core::sign::browser_profile(); signature_profile["http"] = start_core::middleware::auth::signature::wire_profile(); - signature_profile["timestampToleranceSecs"] = - start_core::middleware::auth::signature::TIMESTAMP_TOLERANCE_SECS.into(); std::fs::write( directory.join("signature-profile.ts"), format!( diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index a230b70951..1ad45594b4 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -5334,6 +5334,13 @@ util.rpc.unknown-scheme: pl_PL: "nieznany schemat: %{scheme}" # util/net.rs +util.net.secure.clock-rejected: + en_US: "The server rejected this device's clock; check this device's date, time and time zone" + de_DE: "Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts" + es_ES: "El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo" + fr_FR: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil" + pl_PL: "Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia" + util.net.secure.invalid-message: en_US: "Invalid encrypted WebSocket message" de_DE: "Ungültige verschlüsselte WebSocket-Nachricht" diff --git a/shared-libs/crates/start-core/src/middleware/auth/signature.rs b/shared-libs/crates/start-core/src/middleware/auth/signature.rs index 16cb6ce7b3..933b0a01f9 100644 --- a/shared-libs/crates/start-core/src/middleware/auth/signature.rs +++ b/shared-libs/crates/start-core/src/middleware/auth/signature.rs @@ -2,7 +2,6 @@ use std::collections::{BTreeSet, HashSet}; use std::future::Future; use std::net::IpAddr; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; use axum::body::Body; use axum::extract::Request; @@ -435,9 +434,6 @@ impl SignatureAuth { const SIG_TIME_GRACE_PERIOD_SECS: u64 = 60; -/// Largest difference between a signed timestamp and this server's synchronized clock. -pub const TIMESTAMP_TOLERANCE_SECS: u64 = SIG_TIME_GRACE_PERIOD_SECS / 2; - const MAX_UNTIMED_NONCES: usize = 1024 * 1024; /// Retains nonces for 60 seconds with a trusted clock. @@ -591,20 +587,37 @@ impl RequestReplayCheck { #[path = "signature/replay_tests.rs"] mod replay_tests; +/// The source of an `accept_nonce` rejection for a timestamp outside the synchronized window. +/// The rejected nonce stays unrecorded. +#[derive(Debug)] +pub struct ClockSkew { + /// This server's clock in Unix seconds when it rejected the timestamp. + pub now: i64, +} + +impl std::fmt::Display for ClockSkew { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&t!("middleware.auth.timestamp-not-within-30s")) + } +} + +impl std::error::Error for ClockSkew {} + +impl ClockSkew { + /// The skew behind an admission rejection, distinct from replay or a bad proof. + pub fn of(error: &Error) -> Option<&Self> { + error.source.downcast_ref() + } +} + async fn accept_nonce( context: &C, commitment: &RequestCommitment, ) -> Result<(), Error> { let now = if context.clock_synced().await { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1); - if now.abs_diff(commitment.timestamp) > TIMESTAMP_TOLERANCE_SECS { - return Err(Error::new( - eyre!("{}", t!("middleware.auth.timestamp-not-within-30s")), - ErrorKind::InvalidSignature, - )); + let now = crate::sign::commitment::request::unix_timestamp(); + if now.abs_diff(commitment.timestamp) > SIG_TIME_GRACE_PERIOD_SECS / 2 { + return Err(Error::new(ClockSkew { now }, ErrorKind::InvalidSignature)); } Some(now) } else { diff --git a/shared-libs/crates/start-core/src/sign/commitment/request.rs b/shared-libs/crates/start-core/src/sign/commitment/request.rs index 3f4e59ec11..564a001ed7 100644 --- a/shared-libs/crates/start-core/src/sign/commitment/request.rs +++ b/shared-libs/crates/start-core/src/sign/commitment/request.rs @@ -32,14 +32,24 @@ pub struct RequestCommitment { rpc_toolkit::reflect_ts!(RequestCommitment); rpc_toolkit::ts_export!(RequestCommitment, namespaces = [""]); +/// Seconds since the Unix epoch on this host's clock, negative before it. +pub fn unix_timestamp() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1) +} + impl RequestCommitment { /// Commits the complete byte slice with a fresh timestamp and nonce. pub fn for_bytes(body: &[u8]) -> Self { + Self::for_bytes_at(body, unix_timestamp()) + } + + /// Commits the complete byte slice with a fresh nonce, stamped with the given Unix seconds. + pub fn for_bytes_at(body: &[u8], timestamp: i64) -> Self { Self { - timestamp: SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1), + timestamp, nonce: rand::random(), size: body.len() as u64, blake3: Base64(*blake3::hash(body).as_bytes()), @@ -119,7 +129,17 @@ impl RequestProof { body: &[u8], context: &str, ) -> Result { - let commitment = RequestCommitment::for_bytes(body); + Self::sign_commitment_at(signer, body, context, unix_timestamp()).await + } + + /// Signs as [`Self::sign_commitment`], stamped with the given Unix seconds. + pub async fn sign_commitment_at( + signer: &Signer, + body: &[u8], + context: &str, + timestamp: i64, + ) -> Result { + let commitment = RequestCommitment::for_bytes_at(body, timestamp); let signature = signer .sign_message(&crate::sign::signing_message( crate::sign::COMMITMENT_SIG_TAG, diff --git a/shared-libs/crates/start-core/src/sign/session.rs b/shared-libs/crates/start-core/src/sign/session.rs index 3e5b5f3236..73e0697fcb 100644 --- a/shared-libs/crates/start-core/src/sign/session.rs +++ b/shared-libs/crates/start-core/src/sign/session.rs @@ -10,11 +10,11 @@ use x25519_dalek::{PublicKey, StaticSecret}; use zeroize::Zeroizing; use super::commitment::request::binary::BinaryRequestProof; -use super::commitment::request::{RequestCommitment, RequestProof}; +use super::commitment::request::{RequestCommitment, RequestProof, unix_timestamp}; use super::{AnyVerifyingKey, Signer}; use crate::prelude::*; use crate::rpc_continuations::Guid; -use crate::util::serde::binary::ByteString; +use crate::util::serde::binary::{ByteString, Integer}; mod cbor; @@ -65,6 +65,11 @@ enum Hello { #[serde(default, skip_serializing_if = "std::ops::Not::not")] temporary: bool, }, + /// Unsigned server answer to a client hello rejected only for its timestamp. + Retry { + /// The server's clock in Unix seconds. + timestamp: Integer, + }, } rpc_toolkit::reflect_ts!(Hello); @@ -80,7 +85,7 @@ fn ephemeral() -> StaticSecret { StaticSecret::from(rand::random::<[u8; 32]>()) } -async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result, Error> { +fn encode_body(hello: Hello) -> Result, Error> { let mut wire = Vec::new(); serde_cbor::ser::into_writer( &Message { @@ -91,7 +96,17 @@ async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result, &mut wire, ) .with_kind(ErrorKind::Serialization)?; - let proof = RequestProof::sign_commitment(signer, &wire, context).await?; + Ok(wire) +} + +async fn encode( + signer: &Signer, + context: &str, + hello: Hello, + timestamp: i64, +) -> Result, Error> { + let mut wire = encode_body(hello)?; + let proof = RequestProof::sign_commitment_at(signer, &wire, context, timestamp).await?; serde_cbor::ser::into_writer(&BinaryRequestProof::from(&proof), &mut wire) .with_kind(ErrorKind::Serialization)?; if wire.len() > MAX_HANDSHAKE_BYTES { @@ -163,8 +178,36 @@ pub struct PeerIdentity { pub temporary: bool, } +/// The server's clock from an unsigned retry answer, else `None`. +pub fn retry_timestamp(response: &[u8]) -> Option { + if response.len() > MAX_HANDSHAKE_BYTES { + return None; + } + let mut reader = std::io::Cursor::new(response); + let message: Message = cbor::read(&mut reader).ok()?; + match message { + Message { + protocol, + version: VERSION, + hello: Hello::Retry { timestamp }, + } if protocol == PROTOCOL && reader.position() as usize == response.len() => { + Some(timestamp.0) + } + _ => None, + } +} + +/// The unsigned answer inviting one hello signed at the server's clock. +pub(crate) fn retry(timestamp: i64) -> Result, Error> { + encode_body(Hello::Retry { + timestamp: Integer(timestamp), + }) +} + /// A single connection's signed initiation, prepared before network deadlines. pub struct PreparedClient { + signer: Signer, + target: Target, secret: StaticSecret, context: InternedString, message: Vec, @@ -173,23 +216,40 @@ pub struct PreparedClient { impl PreparedClient { /// Uses a fresh DH key and request commitment for every connection. pub async fn new(signer: &Signer, context: &str, target: Target) -> Result { + Self::at(signer, context, target, unix_timestamp()).await + } + + async fn at( + signer: &Signer, + context: &str, + target: Target, + timestamp: i64, + ) -> Result { let secret = ephemeral(); let message = encode( signer, context, Hello::Client { ephemeral: ByteString(PublicKey::from(&secret).to_bytes()), - target, + target: target.clone(), }, + timestamp, ) .await?; Ok(Self { + signer: signer.clone(), + target, secret, context: context.into(), message, }) } + /// A fresh initiation for the same signer and target, stamped with the server's clock. + pub async fn retry(&self, timestamp: i64) -> Result { + Self::at(&self.signer, &self.context, self.target.clone(), timestamp).await + } + /// The signed client envelope, without the transport's length prefix. pub fn message(&self) -> &[u8] { &self.message @@ -274,6 +334,7 @@ where client_hello: ByteString(Sha256::digest(request).into()), temporary: identity.temporary, }, + unix_timestamp(), ) .await?; let cipher = SessionCipher::derive( diff --git a/shared-libs/crates/start-core/src/sign/session/tests.rs b/shared-libs/crates/start-core/src/sign/session/tests.rs index 88747dd5d1..54508fc5ce 100644 --- a/shared-libs/crates/start-core/src/sign/session/tests.rs +++ b/shared-libs/crates/start-core/src/sign/session/tests.rs @@ -600,6 +600,8 @@ struct WebCryptoRecord { fn fixture_client(fixture: &WebCryptoFixture) -> PreparedClient { PreparedClient { + signer: signer(1), + target: Target::Rpc, secret: StaticSecret::from( <[u8; 32]>::try_from(hex::decode(&fixture.client_private).unwrap()).unwrap(), ), @@ -740,3 +742,31 @@ async fn malformed_and_oversized_envelopes_do_not_reach_replay_policy() { } assert_eq!(wire_profile()["version"], VERSION); } + +#[tokio::test] +async fn a_retry_answer_carries_the_server_clock_and_nothing_else() { + let timestamp = i64::MAX - 7; + let answer = retry(timestamp).unwrap(); + assert_eq!(retry_timestamp(&answer), Some(timestamp)); + assert_eq!(retry_timestamp(&[answer.as_slice(), &[0]].concat()), None); + let prepared = client(&signer(1)).await; + assert_eq!(retry_timestamp(prepared.message()), None); + let (_, response, _) = accept_rpc(&signer(2), prepared.message()).await; + assert_eq!(retry_timestamp(&response), None); + assert!(client(&signer(1)).await.finish(&answer).await.is_err()); +} + +#[tokio::test] +async fn a_retried_initiation_is_fresh_and_signed_at_the_given_time() { + let prepared = client(&signer(1)).await; + let timestamp = unix_timestamp() + 3600; + let retried = prepared.retry(timestamp).await.unwrap(); + let (_, proof) = split_proof(retried.message()); + assert_eq!(proof.commitment.timestamp, timestamp); + let (first, _) = split_proof(prepared.message()); + let (second, _) = split_proof(retried.message()); + assert_ne!(first, second); + let (peer, response, _) = accept_rpc(&signer(2), retried.message()).await; + assert_eq!(peer, signer(1).verifying_key().await.unwrap()); + retried.finish(&response).await.unwrap(); +} diff --git a/shared-libs/crates/start-core/src/util/net/secure.rs b/shared-libs/crates/start-core/src/util/net/secure.rs index 8923579da1..b657ab1e76 100644 --- a/shared-libs/crates/start-core/src/util/net/secure.rs +++ b/shared-libs/crates/start-core/src/util/net/secure.rs @@ -13,6 +13,7 @@ use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec}; use super::{MAX_CLOSE_PAYLOAD_BYTES, MAX_CLOSE_REASON_BYTES}; use crate::prelude::*; +use crate::middleware::auth::signature::ClockSkew; use crate::sign::AnyVerifyingKey; use crate::sign::commitment::request::RequestCommitment; use crate::sign::session::{PeerIdentity, PreparedClient, ServerIdentity, SessionCipher, Target}; @@ -120,6 +121,13 @@ fn retaining_decoder(header: usize, maximum: usize) -> LengthDelimitedCodec { .new_codec() } +fn clock_rejected() -> Error { + Error::new( + eyre!("{}", t!("util.net.secure.clock-rejected")), + ErrorKind::InvalidSignature, + ) +} + fn invalid_message() -> Error { Error::new( eyre!("{}", t!("util.net.secure.invalid-message")), @@ -348,7 +356,8 @@ impl EncryptedSocket { } /// Completes the initiator exchange before returning the verified remote identity. - /// Preparing the identity separately keeps interactive signing outside the handshake deadline. + /// Preparing the identity separately keeps interactive signing outside the handshake deadline, + /// except for the one re-signing a server's retry answer asks for. pub async fn initiate( mut socket: BoxWebSocket, prepared: PreparedClient, @@ -357,7 +366,19 @@ impl EncryptedSocket { tokio::time::timeout(HANDSHAKE_TIMEOUT, async move { let mut records = HandshakeRecords::new(); send_handshake(&mut socket, prepared.message()).await?; - let response = records.receive(&mut socket).await?; + let mut response = records.receive(&mut socket).await?; + let prepared = match crate::sign::session::retry_timestamp(&response) { + Some(timestamp) => { + let retried = prepared.retry(timestamp).await?; + send_handshake(&mut socket, retried.message()).await?; + response = records + .receive(&mut socket) + .await + .map_err(|_| clock_rejected())?; + retried + } + None => prepared, + }; let (peer, state) = prepared.finish(&response).await?; Ok((peer, Self::new(socket, state, records, incoming))) }) @@ -366,6 +387,7 @@ impl EncryptedSocket { } /// Completes the responder exchange, optionally restricting the admitted peer identity. + /// A hello rejected only as [`ClockSkew`] gets an unsigned retry answer and one more hello. pub async fn accept( mut socket: BoxWebSocket, identity: &ServerIdentity, @@ -376,21 +398,36 @@ impl EncryptedSocket { accept_nonce: F, ) -> Result<(AnyVerifyingKey, InternedString, Self), Error> where - F: FnOnce(RequestCommitment) -> Fut, + F: Fn(RequestCommitment) -> Fut, Fut: Future>, { tokio::time::timeout(HANDSHAKE_TIMEOUT, async move { let mut records = HandshakeRecords::new(); - let request = records.receive(&mut socket).await?; - let (peer, context, response, state) = crate::sign::session::accept( - identity, - contexts, - &request, - target, - expected, - accept_nonce, - ) - .await?; + let mut retried = false; + let (peer, context, response, state) = loop { + let request = records.receive(&mut socket).await?; + let error = match crate::sign::session::accept( + identity, + contexts, + &request, + target, + expected, + &accept_nonce, + ) + .await + { + Ok(accepted) => break accepted, + Err(error) => error, + }; + match ClockSkew::of(&error) { + Some(skew) if !retried => { + retried = true; + send_handshake(&mut socket, &crate::sign::session::retry(skew.now)?) + .await?; + } + _ => return Err(error), + } + }; send_handshake(&mut socket, &response).await?; Ok((peer, context, Self::new(socket, state, records, incoming))) }) diff --git a/shared-libs/crates/start-core/src/util/net/secure/tests.rs b/shared-libs/crates/start-core/src/util/net/secure/tests.rs index 10f99a08ea..f3112d065a 100644 --- a/shared-libs/crates/start-core/src/util/net/secure/tests.rs +++ b/shared-libs/crates/start-core/src/util/net/secure/tests.rs @@ -820,3 +820,129 @@ async fn expected_peer_restriction_rejects_different_authenticated_identity() { ); assert_eq!(context.calls.load(Ordering::SeqCst), 0); } + +type NonceCheck = Arc Result<(), Error> + Send + Sync>; + +async fn admission_server( + check: NonceCheck, +) -> ( + String, + tokio::sync::oneshot::Receiver>, + ServerGuard, +) { + let (done, completion) = tokio::sync::oneshot::channel(); + let done = Arc::new(std::sync::Mutex::new(Some(done))); + let route = get(move |upgrade: axum::extract::ws::WebSocketUpgrade| { + let done = done.clone(); + let check = check.clone(); + async move { + upgrade.on_upgrade(move |socket| async move { + let result = EncryptedSocket::accept( + Box::new(socket), + &signer(42).into(), + &[CONTEXT.into()], + NonZeroUsize::new(1024).unwrap(), + &Target::Rpc, + None, + |commitment| futures::future::ready(check(&commitment)), + ) + .await + .map(|_| ()); + done.lock().unwrap().take().unwrap().send(result).unwrap(); + }) + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/admit", listener.local_addr().unwrap()); + let guard = ServerGuard(tokio::spawn(async move { + axum::serve(listener, Router::new().route("/admit", route)) + .await + .unwrap(); + })); + (url, completion, guard) +} + +fn server_clock(skew: i64, seen: Arc>>) -> NonceCheck { + Arc::new(move |commitment| { + seen.lock().unwrap().push(commitment.timestamp); + let now = crate::sign::commitment::request::unix_timestamp() + skew; + if now.abs_diff(commitment.timestamp) > 30 { + return Err(Error::new(ClockSkew { now }, ErrorKind::InvalidSignature)); + } + Ok(()) + }) +} + +async fn initiate(url: &str) -> Result<(PeerIdentity, EncryptedSocket), Error> { + tokio::time::timeout( + Duration::from_secs(3), + EncryptedSocket::initiate( + raw_socket(url).await, + PreparedClient::new(&signer(41), CONTEXT, Target::Rpc) + .await + .unwrap(), + NonZeroUsize::new(1024).unwrap(), + ), + ) + .await + .unwrap() +} + +#[tokio::test] +async fn a_hello_rejected_for_its_timestamp_is_signed_again_with_the_server_clock() { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let (url, completion, _server) = admission_server(server_clock(120, seen.clone())).await; + let (peer, _socket) = initiate(&url).await.unwrap(); + assert_eq!(peer.key, signer(42).verifying_key().await.unwrap()); + completion.await.unwrap().unwrap(); + let seen = seen.lock().unwrap(); + let now = crate::sign::commitment::request::unix_timestamp(); + assert_eq!(seen.len(), 2); + assert!(seen[0].abs_diff(now) <= 2); + assert!(seen[1].abs_diff(now + 120) <= 2); +} + +#[tokio::test] +async fn a_second_timestamp_rejection_reports_the_device_clock_without_another_retry() { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let (url, completion, _server) = admission_server(Arc::new({ + let seen = seen.clone(); + move |commitment: &RequestCommitment| { + seen.lock().unwrap().push(commitment.timestamp); + Err(Error::new( + ClockSkew { + now: commitment.timestamp + 120, + }, + ErrorKind::InvalidSignature, + )) + } + })) + .await; + let error = initiate(&url).await.err().unwrap(); + assert_eq!( + error.source.to_string(), + t!("util.net.secure.clock-rejected") + ); + assert!(ClockSkew::of(&completion.await.unwrap().err().unwrap()).is_some()); + assert_eq!(seen.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn other_admission_rejections_get_no_retry_answer() { + let calls = Arc::new(AtomicUsize::new(0)); + let (url, completion, _server) = admission_server(Arc::new({ + let calls = calls.clone(); + move |_: &RequestCommitment| { + calls.fetch_add(1, Ordering::SeqCst); + Err(Error::new(eyre!("replayed"), ErrorKind::InvalidSignature)) + } + })) + .await; + let error = initiate(&url).await.err().unwrap(); + assert_ne!( + error.source.to_string(), + t!("util.net.secure.clock-rejected") + ); + assert!(ClockSkew::of(&completion.await.unwrap().err().unwrap()).is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts index 914579c759..2e286aa766 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts @@ -101,6 +101,20 @@ export const Hello: z.ZodUnion< temporary: z.ZodOptional }> >, + z.ZodIntersection< + z.ZodObject<{ + /** + * Unsigned server answer to a client hello rejected only for its timestamp. + */ + role: z.ZodLiteral<'retry'> + }>, + z.ZodObject<{ + /** + * The server's clock in Unix seconds. + */ + timestamp: typeof literal_0 + }> + >, ] > = /* @__PURE__ */ z .union([ @@ -128,6 +142,30 @@ export const Hello: z.ZodUnion< temporary: z.boolean().optional(), }), ), + z.intersection( + object({ + /** + * Unsigned server answer to a client hello rejected only for its timestamp. + */ + role: z.literal('retry').meta({ + description: + 'Unsigned server answer to a client hello rejected only for its timestamp.', + }), + }), + object({ + /** + * The server's clock in Unix seconds. + */ + timestamp: literal_0 + .meta({ + description: + 'A CBOR integer whose JavaScript decoder may return a bigint.', + }) + .meta({ + description: "The server's clock in Unix seconds.", + }), + }), + ), ]) .meta({ id: 'Hello', diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts b/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts index 6b95bc76bf..9abd0af183 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/signature-profile.ts @@ -28,5 +28,4 @@ export const SIGNATURE_PROFILE = { ], header: 'X-Start-Auth-Sig', }, - timestampToleranceSecs: 30, } as const From e25772e4c03ac547dda8699d29a9e377d6d11f8e Mon Sep 17 00:00:00 2001 From: helix-red <355572797+helix-red@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:15:23 +0000 Subject: [PATCH 06/10] fix(web): re-sign a session hello on the server's retry answer Replace the `HEAD /` clock measurement, the per-host offset map, its monotonic drift check and the never-retry-a-continuation rule with the server's retry answer: on a `retry` record the browser signs one fresh hello at the server's time on the same socket, so RPC and GUID continuations both recover. A rejected retried hello surfaces as `DeviceClockError`, whose message `RpcSocketService` reports instead of "Encrypted RPC transport failed"; the error keeps code 0. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- shared-libs/ts-modules/ARCHITECTURE.md | 2 +- .../shared/scripts/rpc-socket.test.mjs | 18 +- .../shared/scripts/session-identity.test.mjs | 30 +- .../shared/scripts/session-transport.test.mjs | 491 ++++-------------- .../shared/src/services/rpc-socket.service.ts | 22 +- .../shared/src/services/session-identity.ts | 21 + .../shared/src/services/session-websocket.ts | 179 ++----- 7 files changed, 232 insertions(+), 531 deletions(-) diff --git a/shared-libs/ts-modules/ARCHITECTURE.md b/shared-libs/ts-modules/ARCHITECTURE.md index e88867af0b..f8656a79fc 100644 --- a/shared-libs/ts-modules/ARCHITECTURE.md +++ b/shared-libs/ts-modules/ARCHITECTURE.md @@ -36,7 +36,7 @@ to its transport and must cancel only that operation, without replaying it or re - **`HttpService`** (`shared/src/services/http.service.ts`) — HTTP transport. `rpcRequest()` prepares an unsigned request; `rpcMessage()` sends an already serialized message unchanged. Both use the shared JSON headers and response-compatibility adapter. - **`AuthKeyService`** (`shared/src/services/auth-key.service.ts`) — Owns the browser's enrolled, nonextractable device key and its cancellation lifetime. `admissionLease` reuses possession of that key or an opaque, unpersisted Ed25519 signer when none is stored, without enrollment or a WebCrypto dependency for startup. Acquisition and enrollment started under a replaced, rolled-back or logged-out lifetime cannot adopt the next identity; fresh requests receive a fresh lifetime. StartOS and Tunnel use leases for encrypted RPC. StartWRT composes the same encrypted transport through its own RPC/reconnect owners; anonymous bootstrap uses unpersisted encrypted possession and omits normal-product peer-history observation. Resource requests keep header signing. -- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback. `session-websocket.ts` keeps a per-host server-clock offset, measured from a `HEAD` request's `Date` header, for a browser whose clock is wrong; the [signed-session contract](../crates/start-core/signed-session.md#admission) says when it is measured and used. StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. +- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback, and signs one more at the server's clock when the server answers with a [retry](../crates/start-core/signed-session.md#admission). StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. - **`local-rpc.ts`** — `localRpcRequest` owns OS/Tunnel local capture, nullable-key encrypted-or-public-HTTP dispatch, error metadata and PatchDB fences. `authenticatedRpcTransport` owns device-key typed-stream admission and the combined device/operation signal; it rejects missing keys without HTTP fallback. Server authorization remains live. StartOS's normal generated stream facade waits for initial fences, shares its code-34 logout owner and preserves the socket iterator's early disposal. `watchDb$` composes the raw transport separately: its initial dump establishes the fence. Fence cancellation releases cache subscriptions and prevents late adoption after logout/disposal. Explicit foreign echo remains unsigned HTTP and unfenced; its rejection never invalidates local authentication. - **`ServerIdentityService`** (`shared/src/services/server-identity.service.ts`) — Normal product API callers attach its open observer to RPC/stream/GUID operations. The transport caches one verified open event; reuse observes it only while its physical socket remains open. Observation precedes application replies, including authorization rejection, without introducing another connection owner. Same-origin API targets remember one fingerprint per app/API namespace, atomically in the existing identity IndexedDB store through `identity-store.ts`. This record is separate from the device-key record and survives logout. First contact is silent; rotation remembers the new key and lazily opens a nonblocking Taiga notice/details view. Storage failure never changes the RPC result. RPC, DOM and RxJS continuation open observers retain their owners. The signed handshake marks provisional setup and temporary recovery identities. Normal operations reject them before sending payloads, including when reusing a startup probe's socket; explicit setup/init/diagnostic operations opt in. Continuations enforce the same admission policy. Temporary identities, foreign API overrides and OS registry listings do not populate this history. The backend [identity lifecycle](../crates/start-core/encrypted-rpc.md#identity-and-trust) owns persistence and recovery policy. - **`StartupApiService`** (`ui/src/app/services/api/startup-api.service.ts`) — Explicit encrypted-possession boundary for StartOS initialization, diagnostics and the existing state/DNS probe. Setup-wizard calls and GUIDs use the same admission lease and socket owner. These callers neither enroll keys nor attach normal-product identity-history observers. Normal callers retain `ApiService` and its enrolled-key policy. An unauthenticated mode response never selects plaintext for a normal call. Diagnostic update observation uses the generated typed stream; the component-scoped `DiagnosticUpdate` service reports success after the actual terminal, not a progress counter or close code. Disposal cancels observation without canceling accepted backend work. Mock mode aliases the same concrete API fixture for both interfaces rather than duplicating its state; its initiating update and progress producers are shared with ordinary mock calls. Shared `pauseFor` accepts cancellation for mock progress waits. The setup wizard's component-scoped `SetupObservation` consumes typed `setup.status` through the same lease/socket owner; only successful termination permits navigation to its separate finalization step. Transport loss retries the read-only observation, never the accepted setup operation. Shared `isNetworkError` owns numeric code-zero classification for formatting and reconnect callers; StartWRT retains its existing exported binding and reconnect policy. Both transports share `rpcWebSocketUrl` and the native-generated endpoint. diff --git a/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs b/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs index a514464377..b2ee6f575d 100644 --- a/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs @@ -17,6 +17,8 @@ const { RPC_CONSOLE_LOG_GLOBAL, RpcConsoleLog } = await import('../src/services/rpc-console-log.ts') const { ServerIdentityService } = await import('../src/services/server-identity.service.ts') +const { DeviceClockError } = + await import('../src/services/session-websocket.ts') for (const name of ['CloseEvent', 'ErrorEvent']) globalThis[name] ??= class extends Event { @@ -159,8 +161,8 @@ class LogicalSocket { this.readyState = 3 this.onclose?.({ wasClean: true }) } - fail() { - this.onerror?.(new ErrorEvent('error', { error: Error('transport') })) + fail(error = Error('transport')) { + this.onerror?.(new ErrorEvent('error', { error })) } } @@ -582,6 +584,18 @@ test('transport loss cancels two established streams, pending initialization and assert.equal((await fresh).name, 'AbortError') }) +test('a rejected device clock names the clock instead of the transport', async context => { + const { service, lease } = await streamFixture(context) + const call = service.message(body, {}, lease).catch(error => error) + const other = service.message(body, {}, lease).catch(error => error) + await tick() + LogicalSocket.instances[0].fail(new DeviceClockError()) + const clock = await call + network(clock) + assert.equal(clock.message, new DeviceClockError().message) + network(await other) +}) + test('an unread burst survives while its sibling completes', async context => { const { service, lease } = await streamFixture(context) const pending = service.stream(body, lease) diff --git a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs index e66e2a5548..fddba06802 100644 --- a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs @@ -6,7 +6,8 @@ import { x25519 } from '@noble/curves/ed25519' import { decodeFirst, encode } from '@start9labs/start-core/auth/cbor' import './typescript-loader.mjs' -const { prepareSession } = await import('../src/services/session-identity.ts') +const { prepareSession, retryTime } = + await import('../src/services/session-identity.ts') const fixture = JSON.parse( readFileSync( new URL( @@ -112,6 +113,33 @@ test('a hello proof carries the requested signing time', async () => { ) }) +test('a native retry answer yields the server clock and nothing else does', async () => { + const retry = Uint8Array.from( + Buffer.from( + 'a36870726f746f636f6c7153746172742d5250432d53657373696f6e' + + '6776657273696f6e016568656c6c6fa264726f6c6565726574727969' + + '74696d657374616d701a713fb300', + 'hex', + ), + ) + assert.equal(await retryTime(retry), 1_900_000_000_000) + assert.equal( + await retryTime(concatenate(retry, new Uint8Array([0]))), + undefined, + ) + assert.equal(await retryTime(server), undefined) + assert.equal(await retryTime(client), undefined) + const body = { ...(await decodeFirst(retry)).value } + assert.equal( + await retryTime(encode({ ...body, hello: { ...body.hello, extra: 1 } })), + undefined, + ) + assert.equal( + await retryTime(encode({ ...body, protocol: 'Other' })), + undefined, + ) +}) + test('independent WebCrypto golden matches both directional records and full captured hellos', async context => { const prepared = await frozenClient(context) assert.deepEqual(prepared.message, client) diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index 8079ab280e..7d06946bc2 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -3,13 +3,8 @@ import test from 'node:test' import { registerHooks } from 'node:module' import { auth } from '@start9labs/start-core' import { SESSION_PROFILE } from '@start9labs/start-core/osBindings/session-profile' -import { SIGNATURE_PROFILE } from '@start9labs/start-core/osBindings/signature-profile' import './typescript-loader.mjs' -globalThis.fetch = async () => { - throw new TypeError('Transport tests have no network') -} - // Framing/lifecycle tests replace crypto; real signed-DH interoperability has separate coverage. registerHooks({ load(url, context, next) { @@ -18,6 +13,9 @@ registerHooks({ format: 'module', shortCircuit: true, source: ` + export async function retryTime(response) { + return response[0] === 3 ? globalThis.serverTime : undefined + } export async function prepareSession(...args) { globalThis.preparedSessions?.push(args) return { message: new Uint8Array([1]), async finish(response) { @@ -32,7 +30,7 @@ registerHooks({ }) const { SessionWebSocketStream } = await import('../src/services/session-stream.ts') -const { sessionWebSocketConstructor } = +const { DeviceClockError, sessionWebSocketConstructor } = await import('../src/services/session-websocket.ts') const profile = SESSION_PROFILE.transport for (const name of ['CloseEvent', 'ErrorEvent']) @@ -183,400 +181,6 @@ test('plaintext downgrade never opens admission or exposes RPC data', async () = assert.equal(url.searchParams.get('existing'), 'kept') }) -function admissionServer(answers) { - return class extends Socket { - constructor(url) { - super(url) - queueMicrotask(() => this.dispatchEvent(new Event('open'))) - } - send(data) { - super.send(data) - if (this.writes.length !== 1) return - const answer = answers.shift() - queueMicrotask(() => - answer === undefined ? this.close() : this.receive(record(answer)), - ) - } - } -} -function singleUseServer(serverSkewMs = 0) { - let available = true - return class extends Socket { - constructor(url) { - super(url) - const found = available - available = false - queueMicrotask(() => - found ? this.dispatchEvent(new Event('open')) : this.close(), - ) - } - send(data) { - super.send(data) - if (this.writes.length !== 1) return - const timely = - Math.abs( - globalThis.preparedSessions.at(-1)[3] - Date.now() - serverSkewMs, - ) <= - SIGNATURE_PROFILE.timestampToleranceSecs * 1000 - queueMicrotask(() => (timely ? this.receive(record([1])) : this.close())) - } - } -} -/** A null skew makes the server's clock unreadable. */ -async function withServerClock(skewMs, run) { - const fetch = globalThis.fetch - const requests = [] - globalThis.preparedSessions = [] - globalThis.fetch = async (url, init) => { - requests.push({ url: String(url), method: init.method }) - if (skewMs === null) throw new TypeError('Failed to fetch') - return new Response(null, { - headers: { date: new Date(Date.now() + skewMs).toUTCString() }, - }) - } - try { - await run(requests, globalThis.preparedSessions) - } finally { - globalThis.fetch = fetch - delete globalThis.preparedSessions - } -} -async function withDeviceClock(skewMs, run) { - const now = Date.now - let skew = skewMs - Date.now = () => now() + skew - try { - await run(value => (skew = value)) - } finally { - Date.now = now - } -} -async function rememberOffset(host, serverSkewMs) { - await withServerClock(serverSkewMs, async () => { - const result = await connect(host, admissionServer([undefined, [1]])) - assert.equal(result.opened, true) - result.socket.close() - }) -} -function connect(host, Server) { - const Constructor = sessionWebSocketConstructor( - async () => identity(), - 'server.test', - 'rpc', - Server, - ) - return connectionResult(new Constructor(`wss://${host}/rpc/v2`)) -} -function redeem(host, Server, guid = 'A'.repeat(32)) { - const Constructor = sessionWebSocketConstructor( - async () => identity(), - 'server.test', - { continuation: guid }, - Server, - ) - return connectionResult(new Constructor(`wss://${host}/rpc/v2/${guid}`)) -} -function connectionResult(socket) { - return new Promise(resolve => { - socket.addEventListener('open', () => resolve({ socket, opened: true }), { - once: true, - }) - socket.addEventListener( - 'close', - event => resolve({ socket, opened: false, event }), - { once: true }, - ) - }) -} - -test('an unanswered admission is re-signed once with the server clock and remembered', async () => { - await withServerClock(120_000, async (requests, prepared) => { - Socket.instances = [] - const first = await connect( - 'skewed.test', - admissionServer([undefined, [1]]), - ) - assert.equal(first.opened, true) - assert.equal(Socket.instances.length, 2) - assert.deepEqual(requests, [ - { url: 'https://skewed.test/', method: 'HEAD' }, - ]) - const [initial, retried] = prepared.map(args => args[3] - Date.now()) - assert.ok(Math.abs(initial) < 1_000) - assert.ok(Math.abs(retried - 120_000) < 2_000) - first.socket.close() - - const second = await connect('skewed.test', admissionServer([[1]])) - assert.equal(second.opened, true) - assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now() - 120_000) < 2_000) - second.socket.close() - }) -}) - -test('an unanswered admission within the signing tolerance is not retried', async () => { - await withServerClock(5_000, async (requests, prepared) => { - Socket.instances = [] - const result = await connect( - 'synced.test', - admissionServer([undefined, [1]]), - ) - assert.equal(result.opened, false) - assert.equal(result.event.code, profile.abnormalCloseCode) - assert.equal(Socket.instances.length, 1) - assert.equal(requests.length, 1) - assert.equal(prepared.length, 1) - }) -}) - -test('a socket that never opens never consults the server clock', async () => { - class Unreachable extends Socket { - constructor(url) { - super(url) - queueMicrotask(() => this.close()) - } - } - await withServerClock(120_000, async (requests, prepared) => { - Socket.instances = [] - const result = await connect('unreachable.test', Unreachable) - assert.equal(result.opened, false) - assert.equal(Socket.instances.length, 1) - assert.equal(requests.length, 0) - assert.equal(prepared.length, 1) - }) -}) - -test('an answered admission failure never consults the server clock', async () => { - await withServerClock(120_000, async (requests, prepared) => { - Socket.instances = [] - const result = await connect('answered.test', admissionServer([[2], [1]])) - assert.equal(result.opened, false) - assert.equal(Socket.instances.length, 1) - assert.equal(requests.length, 0) - assert.equal(prepared.length, 1) - }) -}) - -test('a re-signed admission the server still drops is not remembered', async () => { - await withServerClock(120_000, async (requests, prepared) => { - Socket.instances = [] - const first = await connect( - 'disputed.test', - admissionServer([undefined, undefined]), - ) - assert.equal(first.opened, false) - assert.equal(Socket.instances.length, 2) - assert.equal(requests.length, 1) - - const second = await connect('disputed.test', admissionServer([[1]])) - assert.equal(second.opened, true) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - second.socket.close() - }) -}) - -test('a remembered offset follows a corrected server clock', async () => { - await rememberOffset('corrected.test', 120_000) - await withServerClock(0, async (requests, prepared) => { - Socket.instances = [] - const corrected = await connect( - 'corrected.test', - admissionServer([undefined, [1]]), - ) - assert.equal(corrected.opened, true) - assert.equal(Socket.instances.length, 2) - assert.equal(requests.length, 1) - const [stale, fresh] = prepared.map(args => args[3] - Date.now()) - assert.ok(Math.abs(stale - 120_000) < 2_000) - assert.ok(Math.abs(fresh) < 1_000) - corrected.socket.close() - - const next = await connect('corrected.test', admissionServer([[1]])) - assert.equal(next.opened, true) - assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - next.socket.close() - }) -}) - -for (const skew of [-120_000, 120_000]) - test(`correcting a ${skew} ms device clock refreshes before single-use admission`, async () => { - const host = `corrected-device-${skew}.test` - await withDeviceClock(skew, async setDeviceSkew => { - await rememberOffset(host, -skew) - setDeviceSkew(0) - await withServerClock(0, async (requests, prepared) => { - Socket.instances = [] - const result = await redeem(host, singleUseServer()) - assert.equal(result.opened, true) - assert.equal(Socket.instances.length, 1) - assert.equal(prepared.length, 1) - assert.deepEqual(requests, [ - { url: `https://${host}/`, method: 'HEAD' }, - ]) - result.socket.close() - - const next = await connect(host, admissionServer([[1]])) - assert.equal(next.opened, true) - assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - next.socket.close() - }) - }) - }) - -test('an unreadable server clock leaves a continuation with a remembered offset unspent', async () => { - const host = 'unreadable.test' - const Server = singleUseServer(120_000) - await rememberOffset(host, 120_000) - await withServerClock(null, async (requests, prepared) => { - Socket.instances = [] - const refused = await redeem(host, Server) - assert.equal(refused.opened, false) - assert.equal(Socket.instances.length, 0) - assert.equal(prepared.length, 0) - assert.equal(requests.length, 1) - }) - await withServerClock(120_000, async () => { - const redeemed = await redeem(host, Server) - assert.equal(redeemed.opened, true) - redeemed.socket.close() - }) -}) - -test('a continuation measures the server clock before signing with a remembered offset', async () => { - const host = 'server-corrected.test' - await rememberOffset(host, 120_000) - await withServerClock(0, async (requests, prepared) => { - Socket.instances = [] - const result = await redeem(host, singleUseServer()) - assert.equal(result.opened, true) - assert.equal(Socket.instances.length, 1) - assert.equal(prepared.length, 1) - assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - result.socket.close() - }) -}) - -test('a slewed device-clock correction does not spend a continuation', async () => { - const host = 'slewed-device.test' - const monotonic = performance.now - let slew = 0 - performance.now = () => monotonic.call(performance) + slew - try { - await withDeviceClock(120_000, async setDeviceSkew => { - await rememberOffset(host, -120_000) - setDeviceSkew(0) - slew = -120_000 - await withServerClock(0, async (requests, prepared) => { - Socket.instances = [] - const result = await redeem(host, singleUseServer()) - assert.equal(result.opened, true) - assert.equal(Socket.instances.length, 1) - assert.equal(requests.length, 1) - assert.ok(Math.abs(prepared.at(-1)[3] - Date.now()) < 1_000) - result.socket.close() - }) - }) - } finally { - performance.now = monotonic - } -}) - -test('an unanswered continuation is never re-signed on a second connection', async () => { - await withServerClock(120_000, async (requests, prepared) => { - Socket.instances = [] - const result = await redeem('unanswered.test', singleUseServer(120_000)) - assert.equal(result.opened, false) - assert.equal(Socket.instances.length, 1) - assert.equal(prepared.length, 1) - assert.equal(requests.length, 1) - }) -}) - -test('a failed connection keeps the offset another connection just remembered', async () => { - const host = 'concurrent.test' - const settled = async (count, pending) => { - while (pending.length < count) await new Promise(r => setTimeout(r, 1)) - } - await withDeviceClock(-120_000, async () => { - await rememberOffset(host, 180_000) - const fetch = globalThis.fetch - const pending = [] - globalThis.preparedSessions = [] - globalThis.fetch = () => - new Promise(resolve => - pending.push(() => - resolve( - new Response(null, { - headers: { date: new Date(Date.now() + 120_000).toUTCString() }, - }), - ), - ), - ) - try { - const first = connect(host, admissionServer([undefined, [1]])) - await settled(1, pending) - const second = connect(host, admissionServer([undefined, undefined])) - await settled(2, pending) - pending[0]() - const remembered = await first - assert.equal(remembered.opened, true) - pending[1]() - assert.equal((await second).opened, false) - - const next = await connect(host, admissionServer([[1]])) - assert.equal(next.opened, true) - assert.equal(pending.length, 2) - const signed = globalThis.preparedSessions.at(-1)[3] - Date.now() - assert.ok(Math.abs(signed - 120_000) < 2_000) - remembered.socket.close() - next.socket.close() - } finally { - globalThis.fetch = fetch - delete globalThis.preparedSessions - } - }) -}) - -test('closing while the server clock is read opens no second connection', async () => { - const fetch = globalThis.fetch - globalThis.preparedSessions = [] - let reading - const started = new Promise(resolve => (reading = resolve)) - globalThis.fetch = (_url, init) => - new Promise((_, reject) => { - reading() - init.signal.addEventListener('abort', () => reject(init.signal.reason), { - once: true, - }) - }) - try { - Socket.instances = [] - const Constructor = sessionWebSocketConstructor( - async () => identity(), - 'server.test', - 'rpc', - admissionServer([undefined, [1]]), - ) - const socket = new Constructor('wss://closing.test/rpc/v2') - const events = [] - for (const type of ['open', 'error', 'close']) - socket.addEventListener(type, () => events.push(type)) - await started - socket.close() - await new Promise(resolve => setTimeout(resolve, 10)) - assert.deepEqual(events, ['close']) - assert.equal(socket.readyState, socket.CLOSED) - assert.equal(Socket.instances.length, 1) - assert.equal(globalThis.preparedSessions.length, 1) - } finally { - globalThis.fetch = fetch - delete globalThis.preparedSessions - } -}) - for (const [name, bytes] of [ ['plaintext', 'unexpected text'], ['oversized raw chunk', new ArrayBuffer(profile.maxWireChunkBytes + 1)], @@ -754,3 +358,90 @@ test('raw writes wait for bufferedAmount and abort without a retained drain task await assert.rejects(write) raw.abort(Error('test complete')) }) + +function retryingServer(answers) { + return class extends Socket { + constructor(url) { + super(url) + queueMicrotask(() => this.dispatchEvent(new Event('open'))) + } + send(data) { + super.send(data) + const answer = answers[this.writes.length - 1] + if (this.writes.length > answers.length) return + queueMicrotask(() => + answer === undefined ? this.close() : this.receive(record(answer)), + ) + } + } +} +async function admitted(target, url, Server) { + globalThis.preparedSessions = [] + globalThis.serverTime = Date.UTC(2031, 0, 1) + Socket.instances = [] + try { + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + target, + Server, + ) + const socket = new Constructor(url) + let error + socket.addEventListener('error', event => (error = event.error)) + const opened = await new Promise(resolve => { + socket.addEventListener('open', () => resolve(true), { once: true }) + socket.addEventListener('close', () => resolve(false), { once: true }) + }) + socket.close() + return { + opened, + error, + signedAt: globalThis.preparedSessions.map(args => args[3]), + sockets: Socket.instances.length, + writes: Socket.instances[0]?.writes.length, + } + } finally { + delete globalThis.preparedSessions + delete globalThis.serverTime + } +} + +for (const [name, target, url] of [ + ['RPC', 'rpc', 'wss://server.test/rpc/v2'], + [ + 'a GUID continuation', + { continuation: 'A'.repeat(32) }, + `wss://server.test/rpc/v2/${'A'.repeat(32)}`, + ], +]) + test(`a retry answer re-signs ${name} once at the server clock on the same socket`, async () => { + const result = await admitted(target, url, retryingServer([[3], [1]])) + assert.equal(result.opened, true) + assert.deepEqual(result.signedAt, [undefined, Date.UTC(2031, 0, 1)]) + assert.equal(result.sockets, 1) + assert.equal(result.writes, 2) + }) + +test('a rejected retried hello reports the device clock without a third hello', async () => { + const result = await admitted( + 'rpc', + 'wss://server.test/rpc/v2', + retryingServer([[3], undefined]), + ) + assert.equal(result.opened, false) + assert.ok(result.error instanceof DeviceClockError) + assert.equal(result.signedAt.length, 2) + assert.equal(result.writes, 2) +}) + +test('a dropped first hello is not re-signed', async () => { + const result = await admitted( + 'rpc', + 'wss://server.test/rpc/v2', + retryingServer([undefined]), + ) + assert.equal(result.opened, false) + assert.ok(!(result.error instanceof DeviceClockError)) + assert.equal(result.signedAt.length, 1) +}) diff --git a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts index 435b76062f..2335e3f476 100644 --- a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts +++ b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts @@ -24,6 +24,7 @@ import { AUTH_SIGNING_HOST, AuthKeyService } from './auth-key.service' import type { SessionSocketIdentity } from './session-websocket' import { withTimeout } from './http.service' import { + DeviceClockError, SessionOpenEvent, assertServerIdentity, sessionWebSocketConstructor, @@ -236,8 +237,23 @@ export class RpcSocketService { } } +function deviceClockError(cause: unknown): DeviceClockError | undefined { + for (let value = cause; value !== undefined;) { + if (value instanceof DeviceClockError) return value + value = + value instanceof Event + ? (value as ErrorEvent).error + : value instanceof Error + ? value.cause + : undefined + } + return undefined +} + function transportError(cause: unknown) { - return Object.assign(new Error('Encrypted RPC transport failed', { cause }), { - code: 0, - }) + const clock = deviceClockError(cause) + return Object.assign( + new Error(clock?.message ?? 'Encrypted RPC transport failed', { cause }), + { code: 0 }, + ) } diff --git a/shared-libs/ts-modules/shared/src/services/session-identity.ts b/shared-libs/ts-modules/shared/src/services/session-identity.ts index 8353f833b3..200883e6e3 100644 --- a/shared-libs/ts-modules/shared/src/services/session-identity.ts +++ b/shared-libs/ts-modules/shared/src/services/session-identity.ts @@ -84,6 +84,27 @@ export interface SessionCipher { read(bytes: Uint8Array): Promise> } +/** The server's clock in epoch milliseconds from an unsigned retry answer, else undefined. */ +export async function retryTime( + response: Uint8Array, +): Promise { + if (response.length > maximum) return undefined + try { + const captured = await decodeFirst(response) + if (captured.length !== response.length) return undefined + const message = parseHandshake(MessageSchema, captured.value) + if ( + message.protocol !== profile.protocol || + message.version !== profile.version || + message.hello.role !== 'retry' + ) + return undefined + return Number(message.hello.timestamp) * 1000 + } catch { + return undefined + } +} + /** Single-use initiation supports LAN HTTP without crypto.subtle; signing precedes network deadlines. */ export async function prepareSession( signer: auth.RequestSigner, diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 1b184d1c13..6625f912a8 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -1,7 +1,6 @@ import { auth } from '@start9labs/start-core' import type { Target } from '@start9labs/start-core/osBindings/session' import { SESSION_PROFILE } from '@start9labs/start-core/osBindings/session-profile' -import { SIGNATURE_PROFILE } from '@start9labs/start-core/osBindings/signature-profile' import { pEvent } from 'p-event' import type { SessionCipher } from './session-identity' @@ -10,40 +9,14 @@ import { SessionWebSocketStream } from './session-stream' const profile = SESSION_PROFILE.transport const encoder = new TextEncoder() const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) -const RETRYABLE_SKEW_MS = (SIGNATURE_PROFILE.timestampToleranceSecs * 1000) / 2 -interface ServerClockOffset { - offset: number - localTime: number - monotonicTime: number -} - -const serverClockOffsets = new Map() - -async function measureServerClockOffset( - url: string, - signal: AbortSignal, -): Promise { - const origin = new URL('/', url) - origin.protocol = origin.protocol === 'wss:' ? 'https:' : 'http:' - const sent = performance.now() - const response = await fetch(origin, { - method: 'HEAD', - cache: 'no-store', - signal: AbortSignal.any([ - signal, - AbortSignal.timeout(profile.handshakeTimeoutMs), - ]), - }).catch(() => undefined) - const date = Date.parse(response?.headers.get('date') ?? '') - if (Number.isNaN(date)) return undefined - const monotonicTime = performance.now() - const localTime = Date.now() - // Date truncates to the second. - return { - offset: date + 500 + (monotonicTime - sent) / 2 - localTime, - localTime, - monotonicTime, +/** A server rejected a hello signed at its own clock. */ +export class DeviceClockError extends Error { + constructor(options?: ErrorOptions) { + super( + "The server rejected this device's clock; check this device's date, time and time zone", + options, + ) } } @@ -137,7 +110,6 @@ export function sessionWebSocketConstructor( private offset = 0 private writer = Promise.resolve() private queuedBytes = 0 - private handshake: 'connecting' | 'open' | 'answered' = 'connecting' constructor(url: string | URL, protocols?: string | string[]) { super() @@ -172,46 +144,55 @@ export function sessionWebSocketConstructor( () => this.fail(identity.signal.reason), { once: true, signal: this.lifetime.signal }, ) - // The server spends a continuation GUID on its first upgrade. - const reusable = target === SESSION_PROFILE.identity.rpcTarget - const host = new URL(this.url).host - const cached = serverClockOffsets.get(host) - const signal = AbortSignal.any([identity.signal, this.lifetime.signal]) - let measured: ServerClockOffset | undefined - if ( - cached && - (!reusable || - Math.abs( - Date.now() - - cached.localTime - - (performance.now() - cached.monotonicTime), - ) > RETRYABLE_SKEW_MS) - ) { - measured = await measureServerClockOffset(this.url, signal) - if (measured === undefined) - throw new Error('Server clock is unavailable') - } - const offset = measured?.offset ?? cached?.offset ?? 0 - const admitted = await this.admit(identity, protocols, offset).catch( - async (error: unknown) => { - if (this.handshake !== 'open' || this.readyState !== this.CONNECTING) - throw error - measured = await measureServerClockOffset(this.url, signal) - if ( - measured === undefined || - Math.abs(measured.offset - offset) <= RETRYABLE_SKEW_MS - ) - throw error - if (serverClockOffsets.get(host) === cached) - serverClockOffsets.delete(host) - if (!reusable) throw error - return this.admit(identity, protocols, measured.offset) - }, - ) - if (!admitted) return - if (measured) serverClockOffsets.set(host, measured) - const { opened, raw } = admitted + const { prepareSession, retryTime } = await import('./session-identity') + let prepared = await prepareSession(identity.signer, context, target) + if (this.readyState !== this.CONNECTING) return + identity.signal.throwIfAborted() + const signal = AbortSignal.any([ + identity.signal, + this.lifetime.signal, + AbortSignal.timeout(profile.handshakeTimeoutMs), + ]) + const socket = (this.socket = new Socket(this.url, protocols)) + const raw = (this.raw = new SessionWebSocketStream(socket)) const abort = () => raw.abort(new Error('Encrypted WebSocket aborted')) + signal.addEventListener('abort', abort, { once: true }) + let opened: SessionOpenEvent + try { + await pEvent(socket, 'open', { + signal, + rejectionEvents: ['error', 'close'], + }) + await raw.writeRecord(prepared.message, signal) + let response = await raw.readRecord( + profile.maxHandshakeRecordBytes, + signal, + ) + const time = await retryTime(response) + if (time !== undefined) { + prepared = await prepareSession( + identity.signer, + context, + target, + time, + ) + signal.throwIfAborted() + await raw.writeRecord(prepared.message, signal) + response = await raw + .readRecord(profile.maxHandshakeRecordBytes, signal) + .catch((cause: unknown) => { + signal.throwIfAborted() + throw new DeviceClockError({ cause }) + }) + } + const secured = await prepared.finish(response) + signal.throwIfAborted() + assertServerIdentity(secured, allowTemporaryIdentity) + opened = new SessionOpenEvent(secured.peer, secured.temporary) + this.cipher = secured.cipher + } finally { + signal.removeEventListener('abort', abort) + } this.lifetime.signal.addEventListener('abort', abort, { once: true }) this.readyState = this.OPEN this.dispatchEvent(opened) @@ -251,56 +232,6 @@ export function sessionWebSocketConstructor( } } - private async admit( - identity: SessionSocketIdentity, - protocols: string | string[] | undefined, - offset: number, - ) { - this.handshake = 'connecting' - const { prepareSession } = await import('./session-identity') - const prepared = await prepareSession( - identity.signer, - context, - target, - Date.now() + offset, - ) - if (this.readyState !== this.CONNECTING) return - identity.signal.throwIfAborted() - const signal = AbortSignal.any([ - identity.signal, - this.lifetime.signal, - AbortSignal.timeout(profile.handshakeTimeoutMs), - ]) - this.raw?.abort(new Error('Encrypted WebSocket retried')) - const socket = (this.socket = new Socket(this.url, protocols)) - const raw = (this.raw = new SessionWebSocketStream(socket)) - const abort = () => raw.abort(new Error('Encrypted WebSocket aborted')) - signal.addEventListener('abort', abort, { once: true }) - try { - await pEvent(socket, 'open', { - signal, - rejectionEvents: ['error', 'close'], - }) - this.handshake = 'open' - await raw.writeRecord(prepared.message, signal) - const response = await raw.readRecord( - profile.maxHandshakeRecordBytes, - signal, - ) - this.handshake = 'answered' - const secured = await prepared.finish(response) - signal.throwIfAborted() - assertServerIdentity(secured, allowTemporaryIdentity) - this.cipher = secured.cipher - return { - opened: new SessionOpenEvent(secured.peer, secured.temporary), - raw, - } - } finally { - signal.removeEventListener('abort', abort) - } - } - send(data: string | ArrayBufferLike | Blob | ArrayBufferView) { if (this.readyState === this.CONNECTING) throw new DOMException('WebSocket is connecting', 'InvalidStateError') From 0ac5c274f36a3d99df839308c2af3b1005fe30a3 Mon Sep 17 00:00:00 2001 From: helix-red <355572797+helix-red@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:15:37 +0000 Subject: [PATCH 07/10] test(core): pin the session retry answer to the browser golden Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- .../crates/start-core/src/sign/session/tests.rs | 13 +++++++++++++ .../crates/start-core/src/util/net/secure.rs | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/shared-libs/crates/start-core/src/sign/session/tests.rs b/shared-libs/crates/start-core/src/sign/session/tests.rs index 54508fc5ce..9acd5c1074 100644 --- a/shared-libs/crates/start-core/src/sign/session/tests.rs +++ b/shared-libs/crates/start-core/src/sign/session/tests.rs @@ -770,3 +770,16 @@ async fn a_retried_initiation_is_fresh_and_signed_at_the_given_time() { assert_eq!(peer, signer(1).verifying_key().await.unwrap()); retried.finish(&response).await.unwrap(); } + +#[test] +fn a_retry_answer_matches_the_browser_golden() { + assert_eq!( + retry(1_900_000_000).unwrap(), + hex::decode(concat!( + "a36870726f746f636f6c7153746172742d5250432d53657373696f6e", + "6776657273696f6e016568656c6c6fa264726f6c6565726574727969", + "74696d657374616d701a713fb300", + )) + .unwrap() + ); +} diff --git a/shared-libs/crates/start-core/src/util/net/secure.rs b/shared-libs/crates/start-core/src/util/net/secure.rs index b657ab1e76..0dac6718f3 100644 --- a/shared-libs/crates/start-core/src/util/net/secure.rs +++ b/shared-libs/crates/start-core/src/util/net/secure.rs @@ -12,8 +12,8 @@ use tokio_util::codec::length_delimited::Builder; use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec}; use super::{MAX_CLOSE_PAYLOAD_BYTES, MAX_CLOSE_REASON_BYTES}; -use crate::prelude::*; use crate::middleware::auth::signature::ClockSkew; +use crate::prelude::*; use crate::sign::AnyVerifyingKey; use crate::sign::commitment::request::RequestCommitment; use crate::sign::session::{PeerIdentity, PreparedClient, ServerIdentity, SessionCipher, Target}; From 423a9973f0436dfbbe451b08815c2cbecceefadd Mon Sep 17 00:00:00 2001 From: helix-red <355572797+helix-red@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:15:37 +0000 Subject: [PATCH 08/10] docs(core): document the session retry answer and its changelog entries The signed-session Admission contract now describes the unsigned retry record, the one extra hello it allows and the client's clock error. start-cli and start-registry gain changelog entries, since the native initiator and the registry's acceptor change too. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- .../patch-changed-registry-transport.md | 1 + .../changelog/patch-changed-session-clock.md | 5 +++ .../crates/start-core/signed-session.md | 37 ++++++++++--------- 3 files changed, 26 insertions(+), 17 deletions(-) create mode 100644 projects/start-registry/changelog/patch-changed-session-clock.md diff --git a/projects/start-cli/changelog/patch-changed-registry-transport.md b/projects/start-cli/changelog/patch-changed-registry-transport.md index de84c76bc9..3bb33f7b1c 100644 --- a/projects/start-cli/changelog/patch-changed-registry-transport.md +++ b/projects/start-cli/changelog/patch-changed-registry-transport.md @@ -12,3 +12,4 @@ release-notes: false - Preserve deployment URL prefixes ending in a slash for RPC and continuation calls. - Preserve logical HTTP hostnames and ports when `.local` resolution pins an encrypted RPC or continuation's dial address. - Warn on registry CLI server-identity changes without interrupting commands; remember the new verified key while preserving JSON output and exit status. +- When this computer's clock is wrong, sign encrypted connections to StartOS, StartTunnel and registries again with the server's clock, and say the clock is wrong if the server still rejects it. diff --git a/projects/start-registry/changelog/patch-changed-session-clock.md b/projects/start-registry/changelog/patch-changed-session-clock.md new file mode 100644 index 0000000000..e9c3db68bd --- /dev/null +++ b/projects/start-registry/changelog/patch-changed-session-clock.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Answer an encrypted connection signed with a wrong clock with the registry's time, so clients whose clock is wrong can still connect. diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index 27a6fac7d3..b190af9522 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -21,9 +21,10 @@ ingress policy. The request authority ranks an allowed candidate first; the veri proof determines the matched name. Dial-IP and proxy aliases do not change the client's selected signing identity. No query parameter selects a trusted context. -There are two binary handshake records. Each record has a two-byte big-endian length -and exactly two consecutive CBOR objects: a body followed by a structured proof. -The record has at most 1,024 bytes, with CBOR nesting bounded at 16 levels. Extra +There are two binary handshake records, or four after a retry answer. Each record has a +two-byte big-endian length and exactly two consecutive CBOR objects: a body followed by a +structured proof. A retry answer is the one exception: a single unsigned body. A record has +at most 1,024 bytes, with CBOR nesting bounded at 16 levels. Extra objects, trailing data, duplicate/unknown fields and invalid binary lengths are rejected. Maps use text keys; admission values are untagged. Binary fields are definite CBOR byte strings, not Base64 or integer arrays. CBOR integers preserve the full @@ -41,6 +42,9 @@ Each body has `protocol: "Start-RPC-Session"`, `version: 1` and a `hello` map: SHA-256 of the exact captured client record contents, excluding the length prefix. Provisional setup and diagnostic recovery without an account identity include signed `temporary: true`; committed account identities omit it. Missing `temporary` means false for existing-server compatibility. +3. Server → client, unsigned and in place of the server hello: `role: "retry"` and + `timestamp`, the server's clock in Unix seconds as a CBOR integer. See the freshness + rules below. Temporary identities must not enter fingerprint history. Normal browser encrypted RPC and continuations reject them before sending application payloads; only explicit setup/init/diagnostic @@ -79,20 +83,19 @@ authorization. Enrollment and revocation affect subsequent calls on the same ope connection. No callback receives unauthenticated plaintext as an admitted request. Each physical connection gets fresh DH keys, commitment and nonce. Client signing -finishes before the 30-second network/admission deadline; provider handles may be -reused, prepared hellos may not. The existing signed-timestamp freshness policy still -applies while signing and connecting, and the server never relaxes it. When an opened -browser connection fails before a complete answer record arrives, the browser reads the -server's `Date` header. If that time differs from the one it signed with by more than half -the tolerance, the browser forgets the offset it remembers for that host. For the RPC -target it then signs one fresh hello on a new connection with the server's time. A GUID -continuation is spent by its first upgrade, even when admission fails, and is never -retried. Once an admission signed with a measured offset succeeds, later connections to -that host start from that offset. The browser measures the offset again before opening a -GUID continuation while one is remembered, and before any connection once the device clock -has moved more than half the tolerance against its monotonic clock; a failed measurement -fails that connection unopened. Native clients and the browser's signed HTTP requests sign -with the local clock. The server signs only after validating the initiation. +finishes before the 30-second network/admission deadline, except for the hello answering +a retry, which signs within it; provider handles may be reused, prepared hellos may not. The existing signed-timestamp freshness policy still +applies while signing and connecting, and the server never relaxes it. Clients sign with +the local clock. A synchronized server that finds a hello valid except for its timestamp +(`ClockSkew` from `accept_nonce`) answers with an unsigned retry record and accepts one more +hello on the same socket within the handshake deadline; every other rejection, and a second +timestamp rejection, drops the connection without a reply. A client that receives a retry +answer signs one fresh hello, with a new ephemeral key and nonce, stamped with the server's +`timestamp`, and reports a wrong device clock when that hello is rejected. The retry stays on +the upgraded socket, so a GUID continuation survives it. An unsynchronized server never sends +one. A forged retry time can only make the client sign a hello bound to its own ephemeral +key; a rejected timestamp never reaches the nonce cache. HTTP request proofs sign with the +local clock. The server signs only after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, From 8682dafc0399023cf3dc4e0f0efa66a041c91636 Mon Sep 17 00:00:00 2001 From: helix-red <355572797+helix-red@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:21:18 +0000 Subject: [PATCH 09/10] style(web): use a while loop for the device clock cause walk Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- .../ts-modules/shared/src/services/rpc-socket.service.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts index 2335e3f476..a302052319 100644 --- a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts +++ b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts @@ -238,7 +238,8 @@ export class RpcSocketService { } function deviceClockError(cause: unknown): DeviceClockError | undefined { - for (let value = cause; value !== undefined;) { + let value = cause + while (value !== undefined) { if (value instanceof DeviceClockError) return value value = value instanceof Event From e72e78690e0663b84cd12afbfdc1037426626c52 Mon Sep 17 00:00:00 2001 From: helix-white <267227783+helix-a@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:28:22 +0000 Subject: [PATCH 10/10] Proposed changes for #4939 Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts | 1 + projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts | 1 + projects/start-wrt/web/src/app/i18n/dictionaries/de.ts | 1 + projects/start-wrt/web/src/app/i18n/dictionaries/en.ts | 1 + projects/start-wrt/web/src/app/i18n/dictionaries/es.ts | 1 + projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts | 1 + projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts | 1 + .../start-core/src/middleware/auth/signature/replay_tests.rs | 5 +++-- shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts | 1 + shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts | 1 + shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts | 1 + shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts | 1 + shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts | 1 + 13 files changed, 15 insertions(+), 2 deletions(-) diff --git a/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts b/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts index 813d95a48d..a8d55b1b07 100644 --- a/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts @@ -147,6 +147,7 @@ export const ENGLISH: Record = { 'This browser is not enrolled yet': 133, 'Cancel': 134, 'Continue': 135, + "The server rejected this device's clock; check this device's date, time and time zone": 136, } export default ENGLISH diff --git a/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts b/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts index ffe0433a9d..810c1c13f5 100644 --- a/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts @@ -138,6 +138,7 @@ const es: Record = { 133: 'Este navegador aún no está registrado', 134: 'Cancelar', 135: 'Continuar', + 136: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } export default es diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts index 6e50c583c5..0c8364f86b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts @@ -605,4 +605,5 @@ export default { 653: '{port} sendet jedes Sicherheitsprofil mit seiner VLAN-ID getaggt an den Switch. Richten Sie die VLANs des Switches mit diesen IDs ein.', 654: '{profile} überschneidet sich mit dem vorgelagerten Netzwerk {network}', 655: 'Der Router kann den Zugang zum vorgelagerten Netzwerk oder zum Internet verlieren. Ein spezifischeres WAN-Netzwerk kann auch Geräten den Zugriff auf dieses Dashboard verwehren. Ändern Sie sein Subnetz in eines außerhalb dieses Netzwerks.', + 656: 'Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts index 1482344004..081bf48b5b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts @@ -610,4 +610,5 @@ export const ENGLISH: Record = { "{port} sends each security profile to the switch tagged with its VLAN ID. Set up the switch's VLANs with these IDs.": 653, '{profile} overlaps the upstream network {network}': 654, 'The router may lose upstream or Internet access. A more-specific WAN network can also block devices from this dashboard. Change its subnet to one outside that network.': 655, + "The server rejected this device's clock; check this device's date, time and time zone": 656, } diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts index 22262eb81d..464b9c5703 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts @@ -605,4 +605,5 @@ export default { 653: '{port} envía cada perfil de seguridad al switch etiquetado con su ID de VLAN. Configura las VLAN del switch con estos IDs.', 654: '{profile} se superpone con la red superior {network}', 655: 'El router puede perder el acceso a la red superior o a Internet. Una red WAN más específica también puede impedir que los dispositivos accedan a este panel. Cambie su subred a una fuera de esa red.', + 656: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts index 0c78581aa1..ad97003447 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts @@ -605,4 +605,5 @@ export default { 653: '{port} envoie chaque profil de sécurité au switch, étiqueté avec son ID de VLAN. Configurez les VLAN du switch avec ces ID.', 654: '{profile} chevauche le réseau amont {network}', 655: 'Le routeur peut perdre l’accès au réseau amont ou à Internet. Un réseau WAN plus spécifique peut aussi empêcher les appareils d’accéder à ce tableau de bord. Changez son sous-réseau pour un sous-réseau hors de ce réseau.', + 656: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil", } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts index 1a76547ed0..05652f0617 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts @@ -605,4 +605,5 @@ export default { 653: '{port} wysyła każdy profil bezpieczeństwa do przełącznika oznaczony jego identyfikatorem VLAN. Skonfiguruj sieci VLAN przełącznika z użyciem tych identyfikatorów.', 654: '{profile} nakłada się na sieć nadrzędną {network}', 655: 'Router może stracić dostęp do sieci nadrzędnej lub Internetu. Bardziej szczegółowa sieć WAN może też uniemożliwić urządzeniom dostęp do tego panelu. Zmień jego podsieć na leżącą poza tą siecią.', + 656: 'Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia', } satisfies i18n diff --git a/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs b/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs index fe1b3eb585..91a2a4e742 100644 --- a/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs +++ b/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs @@ -63,14 +63,15 @@ async fn an_unpolled_check_does_not_retain_or_revive_the_authentication_owner() } #[tokio::test] -async fn validator_uses_the_existing_clock_policy_without_consuming_rejected_nonces() { +async fn validator_reports_clock_skew_without_consuming_rejected_nonces() { let (_directory, context) = context().await; let check = context.replay_check(); let mut commitment = RequestCommitment::for_bytes(b"hello"); let now = commitment.timestamp; commitment.timestamp = 0; let expired = verified(commitment.clone()).await; - assert!(check.check(expired).await.is_err()); + let error = check.check(expired).await.unwrap_err(); + assert!(ClockSkew::of(&error).unwrap().now.abs_diff(now) <= 2); commitment.timestamp = now; check.check(verified(commitment).await).await.unwrap(); } diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts index e44ea28e1b..5cec8a6f83 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipsatz', 1320: 'Sensor', 1321: 'Keine Temperatursensoren gefunden', + 1322: 'Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts', } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts index 51122ef876..a2e39e56f5 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts @@ -1114,4 +1114,5 @@ export const ENGLISH: Record = { 'Chipset': 1319, 'Sensor': 1320, // as in, a temperature sensor 'No temperature sensors found': 1321, + "The server rejected this device's clock; check this device's date, time and time zone": 1322, } diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts index 57b86b9c62..57efa93c09 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Sensor', 1321: 'No se encontraron sensores de temperatura', + 1322: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts index 9a4ce98eff..304ddf27f4 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Capteur', 1321: 'Aucun capteur de température trouvé', + 1322: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil", } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts index 9c2403b7ab..7ed448ed4f 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Czujnik', 1321: 'Nie znaleziono czujników temperatury', + 1322: 'Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia', } satisfies i18n