Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(live-links): a wrong-password lock lifts by itself; sealed unlocks on the host; 60 s full-link poll

reviewb8c4eb717882
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
index a87316111..f3546330c 100644
--- a/src/core/watch-link/link-host.test.ts
+++ b/src/core/watch-link/link-host.test.ts
@@ -14,9 +14,12 @@ import { IPC } from '../../shared/ipc'
import { isHostOnlyChannel } from '../../shared/host-control'
import { connectWatchClient } from '../../shared/watch-link/client'
import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
+import { readUnlockKey, sealUnlock } from '../../shared/watch-link/unlock-seal'
+import { bytesToB64 } from '../../shared/watch-link/bytes'
import {
INPUT_MAX,
TYPING_NAMES_MAX,
+ WATCH_CHAT_CAST,
WATCH_EVENT,
WATCH_HISTORY_CAST,
WATCH_INPUT_CAST,
@@ -122,7 +125,7 @@ interface SetupOpts {
* service does). */
verifyPassword?: (pw: string) => Promise<boolean>
/** Replaces the service's lock (which sets `record.control.locked`); still counted in `locks()`. */
- onControlLocked?: () => void
+ onControlLocked?: (by?: string | null) => void
/** Replaces the service's record of the link-wide wrong count; still recorded in `wrongs`. */
onWrongAttempt?: (count: number) => void
join?: (clientId: number, nodeId: string, viewerId: string) => Promise<JoinAnswer | null> | JoinAnswer | null
@@ -163,6 +166,8 @@ function setup(o: SetupOpts = {}) {
const currents: ((() => boolean) | undefined)[] = []
/** Every link-wide wrong count the host reported (`onWrongAttempt`), in order. */
const wrongs: number[] = []
+ /** Who tipped each lock, as the host named it (`onControlLocked`). */
+ const lockedBy: (string | null)[] = []
let mints = 0
let changes = 0
let verifies = 0
@@ -255,9 +260,10 @@ function setup(o: SetupOpts = {}) {
taken.push(name)
},
// What the service does, synchronously, before returning (the host reads the record live).
- onControlLocked: () => {
+ onControlLocked: (by) => {
locks++
- if (o.onControlLocked) o.onControlLocked()
+ lockedBy.push(by ?? null)
+ if (o.onControlLocked) o.onControlLocked(by)
else if (record.control) record.control.locked = true
},
// What the service does: the count goes on the record (and to disk).
@@ -269,7 +275,7 @@ function setup(o: SetupOpts = {}) {
})
hosts.push(host)
return {
- record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, chats, joined, gone, reads,
+ record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, lockedBy, chats, joined, gone, reads,
keys: deriveWatchLinkKeys(secret),
mints: () => mints,
/** How many times the host reported a change to the registry (`onChange`). */
@@ -1041,7 +1047,11 @@ describe('createLinkHost — ending', () => {
for (let i = 0; i < MAX_VIEWERS_PER_LINK; i++) vs.push(await openViewer(t, i))
await clock.flush()
expect(t.peers).toHaveLength(MAX_VIEWERS_PER_LINK) // no idle listener while full
- await clock.advance(FULL_STATUS_POLL_MS)
+ // Finding L6: a revoke made elsewhere reaches a full link's viewers within a minute (it was five).
+ expect(FULL_STATUS_POLL_MS).toBe(60_000)
+ await clock.advance(FULL_STATUS_POLL_MS - 1)
+ expect(status).not.toHaveBeenCalled()
+ await clock.advance(1)
expect(status).toHaveBeenCalledTimes(1)
expect(t.gone).toEqual([])
state = 'revoked'
@@ -1317,6 +1327,80 @@ describe('createLinkHost — control', () => {
expect(metaOf(w).control).toEqual({ state: 'available' })
})
+ // --- finding L3: the unlock is sealed to a key pair of THIS connection's ---------------------------
+
+ it('a Control link offers each connection its own unlock key, the same on every rejoin; other roles none', async () => {
+ const clock = manualClock()
+ let n = 0
+ const t = controller({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
+ t.host.start()
+ const a = await openViewer(t, 0)
+ const b = await openViewer(t, 1)
+ const ka = metaOf(a).unlockKey
+ expect(readUnlockKey(ka)).not.toBeNull()
+ expect(readUnlockKey(metaOf(b).unlockKey)).not.toBeNull()
+ expect(metaOf(b).unlockKey).not.toBe(ka)
+ // Not derived from the link: nothing a link holder can compute.
+ expect([bytesToB64(t.keys.host.publicKey), bytesToB64(t.keys.viewer.publicKey)]).not.toContain(ka)
+ ptyEvent(t.sink(0), IPC.ptyExit('s1'), 0)
+ await clock.flush()
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(a.named(WATCH_EVENT.meta)).toHaveLength(2))
+ expect(metaOf(a, 1).unlockKey).toBe(ka)
+ for (const role of ['viewer', 'commenter'] as const) {
+ const o = setup({ role })
+ o.host.start()
+ const w = await openViewer(o)
+ expect('unlockKey' in metaOf(w)).toBe(false)
+ }
+ })
+
+ it('a sealed unlock opens with the connection key: the right password controls, and the real client seals', async () => {
+ const t = controller()
+ t.host.start()
+ // The real client (it seals on its own once the meta offered a key).
+ const v = await openViewer(t, 0)
+ expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
+ // A raw peer sealing it by hand to the key its own meta offered.
+ const p = await openRaw(t, 1)
+ const key = readUnlockKey((p.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
+ expect(await rawUnlock(p, [sealUnlock('Bob', PW, key)])).toEqual({ state: 'controlling' })
+ expect(t.taken).toEqual(['Ada', 'Bob'])
+ })
+
+ it('an unlock sealed to another key (another connection\'s, a replay) is wrong and counted, never verified', async () => {
+ const clock = manualClock()
+ const t = controller({ clock })
+ t.host.start()
+ const other = await openRaw(t, 0)
+ const p = await openRaw(t, 1)
+ const otherKey = readUnlockKey((other.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ expect(await rawUnlock(p, [sealUnlock('Eve', PW, otherKey)])).toEqual({ state: 'available', reason: 'wrong' })
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ expect(await rawUnlock(p, [{ sealed: { key: 'x', nonce: 'y', box: 'z' } }])).toEqual({ state: 'available', reason: 'wrong' })
+ expect(t.verifies()).toBe(0)
+ expect(t.wrongs).toEqual([1, 2])
+ })
+
+ it('a plain unlock (a page from before sealing) still works — but not after the same connection sent a sealed one', async () => {
+ const clock = manualClock()
+ const t = controller({ clock })
+ t.host.start()
+ const old = await openRaw(t, 0)
+ expect(await rawUnlock(old, [{ name: 'Ada', password: PW }])).toEqual({ state: 'controlling' })
+ const p = await openRaw(t, 1)
+ const key = readUnlockKey((p.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ expect(await rawUnlock(p, [sealUnlock('Bob', WRONG, key)])).toEqual({ state: 'available', reason: 'wrong' })
+ const verified = t.verifies()
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ // The right password, in the clear, on a connection that seals: refused unverified, counted.
+ expect(await rawUnlock(p, [{ name: 'Bob', password: PW }])).toEqual({ state: 'available', reason: 'wrong' })
+ expect(t.verifies()).toBe(verified)
+ expect(t.taken).toEqual(['Ada'])
+ })
+
// --- watch:unlock -----------------------------------------------------------------------------------
it('an unlock sent before the viewer joined is ignored, even with the right password: no answer, no verification', async () => {
@@ -1570,6 +1654,69 @@ describe('createLinkHost — control', () => {
expect(t.taken).toEqual(['Ada'])
}, 20_000) // eleven real scrypt checks
+ // Finding L2: the service gives a lock a lift time; every viewer is told how long it lasts, and the
+ // owner is told who tipped it.
+ it('a timed lock tells each viewer how long it lasts: in the lock, in a refused unlock, in a later meta', async () => {
+ const clock = manualClock()
+ let n = 0
+ const t: Setup = controller({
+ clock,
+ join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
+ control: ctl({ wrong: WRONG_PER_LINK - 1 }),
+ verifyPassword: async (pw) => pw === PW,
+ onControlLocked: () => {
+ t.record.control!.locked = true
+ t.record.control!.lockedUntil = clock.now() + 15 * 60_000
+ }
+ })
+ t.host.start()
+ const v = await openViewer(t, 0)
+ const w = await openViewer(t, 1)
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ const before = controlOf(v).length
+ expect(v.c.unlock('Eve', WRONG)).toBe(true)
+ await vi.waitFor(() => expect(controlOf(v).slice(before)).toEqual([
+ { state: 'available', reason: 'wrong' },
+ { state: 'locked', reason: 'locked', lockedForMs: 15 * 60_000 }
+ ]))
+ await vi.waitFor(() => expect(controlOf(w).at(-1)).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 15 * 60_000 }))
+ expect(t.lockedBy).toEqual(['Eve'])
+ await clock.advance(5 * 60_000)
+ expect(await unlock(v, 'Eve', PW)).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 10 * 60_000 })
+ // A rejoin's meta says what is left.
+ const metas = w.named(WATCH_EVENT.meta).length
+ ptyEvent(t.sink(1), IPC.ptyExit('s2'), 0)
+ await clock.flush()
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(w.named(WATCH_EVENT.meta)).toHaveLength(metas + 1))
+ expect(metaOf(w, metas).control).toEqual({ state: 'locked', lockedForMs: 10 * 60_000 - REJOIN_BACKOFF_MS[0] })
+ // The lock lifts (the service clears it and tells the host): every viewer may unlock again.
+ t.record.control!.locked = false
+ t.record.control!.lockedUntil = null
+ t.host.allowControl()
+ await vi.waitFor(() => expect(controlOf(w).at(-1)).toEqual({ state: 'available' }))
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ expect(await unlock(w, 'Ada', PW)).toEqual({ state: 'controlling' })
+ })
+
+ it('the lock names who tipped it: the attempt\'s own name, else the chat name of the connection that sent it, else nobody', async () => {
+ for (const c of [{ chat: 'Mallory', want: 'Mallory' }, { chat: null, want: null }]) {
+ const clock = manualClock()
+ const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }) })
+ t.host.start()
+ const p = await openRaw(t, 0)
+ if (c.chat) {
+ p.cast(WATCH_CHAT_CAST, [{ name: c.chat, text: 'hi' }])
+ await vi.waitFor(() => expect(t.chats).toHaveLength(1))
+ }
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ // A malformed attempt (no name left once cleaned) tips it.
+ await rawUnlock(p, [{ name: '\u200b', password: 'x' }])
+ await vi.waitFor(() => expect(t.locks()).toBe(1))
+ expect(t.lockedBy).toEqual([c.want])
+ }
+ })
+
it('allowControl resets the link count and tells every viewer it is available again', async () => {
const clock = manualClock()
const t = controller({ clock, verifyPassword: async (pw) => pw === PW })
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index 1f03284ed..0e9053e47 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -27,7 +27,12 @@
// attempts end that connection (`attempts`), WRONG_PER_LINK across the link lock it. The link count is
// the record's: the host starts from `record.control.wrong` and reports every new count to the service
// (`onWrongAttempt`), which writes it — an app restart does not reset it. `allowControl` and a password
-// change reset it. A verification is re-checked after its await: an
+// change reset it. A lock lifts by itself (finding L2): the service sets `record.control.lockedUntil`
+// with it and calls `allowControl` when it passes; every `locked` this host sends carries how long is
+// left (`lockedForMs`), and the lock's notice names who tipped it (`onControlLocked(by)`). The unlock
+// itself is SEALED to a key pair of the connection's own (finding L3, unlock-seal.ts): made with the
+// first meta, offered in every meta (`unlockKey`), zeroed at the end; a plain unlock (an older page) is
+// still read, except on a connection that already sent a sealed one. A verification is re-checked after its await: an
// ended viewer, a stopped host, or any change to control meanwhile (off, locked, a new password — the
// control epoch) voids it, uncounted. A join whose input route is `none` (Zellij, an unknown session;
// also what a missing or unknown route reads as) makes that viewer's state `off`/`unsupported`: its
@@ -142,6 +147,7 @@ import type { RpcErr } from '../../shared/rpc'
import { bytesToB64, bytesToHex } from '../../shared/watch-link/bytes'
import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
import {
+ CONTROL_LOCK_MAX_MS,
INPUT_MAX,
PASSWORD_MAX,
TYPING_NAMES_MAX,
@@ -169,6 +175,7 @@ import { isTerminalReport } from '../terminal-reports'
import { createStreamFilter, type StreamFilter } from './stream-filter'
import { historyPageFrom, type HistoryRead } from './history'
import { createTokenBucket, type TokenBucket } from './token-bucket'
+import { isSealedUnlock, openUnlock } from '../../shared/watch-link/unlock-seal'
import {
WATCHER_BUFFER_LIMIT,
WATCHER_REFUSAL,
@@ -181,8 +188,9 @@ import { errorText } from '../../shared/error-text'
export const MAX_VIEWERS_PER_LINK = 10
/** While the link is full (no idle listener, so no mint), how often the API is asked whether the link
- * was revoked or expired server-side. */
-export const FULL_STATUS_POLL_MS = 5 * 60_000
+ * was revoked or expired server-side: a Stop all from another machine reaches the viewers of a full
+ * link within this (finding L6; it was 5 minutes). Only while full: otherwise the next mint learns it. */
+export const FULL_STATUS_POLL_MS = 60_000
export const CHAT_MIN_INTERVAL_MS = 2_000
export const CHAT_HISTORY_MAX = 200
export const KEYFRAME_MIN_INTERVAL_MS = 1_000
@@ -294,8 +302,10 @@ export interface LinkHostDeps {
/** A viewer unlocked control, under this sanitized, self-chosen name. */
onControlTaken(name: string): void
/** WRONG_PER_LINK wrong attempts across the link. The service sets `record.control.locked = true`
- * before it returns (the host reads the record live and never writes it). */
- onControlLocked(): void
+ * (and when it lifts, `lockedUntil`) before it returns (the host reads the record live and never
+ * writes it). `by`: the name the attempt that tipped it gave, else the chat name of the connection
+ * that sent it, else null — a self-chosen claim, for the owner's notice. */
+ onControlLocked(by?: string | null): void
/** A wrong unlock attempt: the link-wide count is now `count` (1..WRONG_PER_LINK). The service puts it
* on `record.control.wrong` and writes it (the 10th rides the lock's own write), so a restart does
* not reset it. Called before `onControlLocked`. */
@@ -337,7 +347,8 @@ export interface LinkHost {
/** The password was replaced: every controller is demoted and must unlock with the new one, and the
* link-wide wrong count starts over (the service resets the record's). */
passwordChanged(): void
- /** The owner cleared the lock: the link-wide wrong count starts over, then as `controlChanged`. */
+ /** The lock was cleared — the owner's Allow control again, or its time ran out (the service's timer,
+ * finding L2): the link-wide wrong count starts over, then as `controlChanged`. */
allowControl(): void
}
@@ -384,6 +395,11 @@ interface Conn {
lastDroppedAt: number
/** The name control was taken under (the unlock's); a later chat name does not change who typed. */
controlName: string | null
+ /** A Control link: the key pair THIS connection's unlock is sealed to (finding L3), made with the
+ * first meta and kept for the connection's life (its public half rides every meta); zeroed at the end. */
+ unlockKeys: nacl.BoxKeyPair | null
+ /** This connection sent a sealed unlock: a later one in the clear is refused (counted as malformed). */
+ sealedOnly: boolean
// The watched session (null while waiting).
sessionId: string | null
altScreen: boolean
@@ -606,6 +622,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
// A delivery still waiting for the pane must not hold every other controller's batch.
c.delivery?.settle(false)
forgetTyping(c)
+ c.unlockKeys?.secretKey.fill(0)
+ c.unlockKeys = null
if (sid !== null) leave(c.clientId, sid, c.viewerId, c)
safe('the scheduler', () => c.ev.onClose())
updateSyncTimer()
@@ -837,8 +855,13 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
cols: res.cols,
rows: res.rows
}
- // A Control link's state for THIS viewer rides every (re)join; absent on every other role.
- if (record.role === 'controller') meta.control = controlStateFor(c)
+ // A Control link's state for THIS viewer rides every (re)join, with the key its unlock is sealed to
+ // (one per connection, the same on every rejoin); absent on every other role.
+ if (record.role === 'controller') {
+ meta.control = controlStateFor(c)
+ c.unlockKeys ??= nacl.box.keyPair()
+ meta.unlockKey = bytesToB64(c.unlockKeys.publicKey)
+ }
if (historySupported()) meta.history = true
if (!send(c, WATCH_EVENT.meta, meta)) return
// The typing set is otherwise sent only when it changes: a viewer (re)joining mid-typing would
@@ -1009,10 +1032,32 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
// The watched terminal cannot take input (Zellij, an unknown session): no password changes that.
if (c.input === 'none') return { state: 'off', reason: 'unsupported' }
if (c.controlling && ctl && ctl.enabled && !ctl.locked) return { state: 'controlling' }
- if (ctl?.locked) return { state: 'locked' }
+ if (ctl?.locked) return lockedState()
if (!ctl || !ctl.enabled) return { state: 'off' }
return { state: 'available' }
}
+ /** `locked`, with how long until it lifts by itself when it does (finding L2): from the record's
+ * `lockedUntil`, which the service sets with the lock and clears when it lifts. */
+ function lockedState(reason?: 'locked'): WatchControlEvent {
+ const until = record.control?.lockedUntil
+ const ev: WatchControlEvent = reason ? { state: 'locked', reason } : { state: 'locked' }
+ if (typeof until === 'number' && Number.isFinite(until)) {
+ ev.lockedForMs = Math.min(CONTROL_LOCK_MAX_MS, Math.max(0, Math.round(until - deps.now())))
+ }
+ return ev
+ }
+ /**
+ * An unlock cast's `{ name, password }`, sealed or plain, or null when it is malformed (counted). A
+ * sealed one must open with THIS connection's key (finding L3) and latches the connection: a plain
+ * one after it is malformed — a page that seals never sends one, so it can only be a replay or a
+ * downgrade. A plain one is what a page from before sealing sends, and is read as before.
+ */
+ function unlockOf(c: Conn, arg: unknown): { name: string; password: string } | null {
+ if (!isSealedUnlock(arg)) return c.sealedOnly ? null : readUnlock(arg)
+ c.sealedOnly = true
+ const opened = c.unlockKeys ? openUnlock(arg, c.unlockKeys.secretKey) : null
+ return opened ? readUnlock(opened) : null
+ }
function sendControl(c: Conn, ev: WatchControlEvent): void {
send(c, WATCH_EVENT.control, ev)
}
@@ -1027,7 +1072,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
return
}
if (state.state === 'locked' || state.state === 'off') {
- sendControl(c, { state: state.state, reason: state.reason ?? state.state })
+ sendControl(c, { ...state, reason: state.reason ?? state.state })
return
}
const now = deps.now()
@@ -1036,10 +1081,10 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
return
}
c.lastUnlockAt = now
- const attempt = readUnlock(args[0])
+ const attempt = unlockOf(c, args[0])
// A malformed attempt is still an attempt.
if (!attempt) {
- wrongAttempt(c)
+ wrongAttempt(c, null)
return
}
verifying = true
@@ -1058,7 +1103,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
return
}
if (!right) {
- wrongAttempt(c)
+ wrongAttempt(c, attempt.name)
return
}
c.controlling = true
@@ -1075,30 +1120,31 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
* wrong. Nothing is counted, and the viewer may try again. */
function refuseVoid(c: Conn): void {
const state = controlStateFor(c)
- if (state.state === 'locked' || state.state === 'off') sendControl(c, { state: state.state, reason: state.reason ?? state.state })
+ if (state.state === 'locked' || state.state === 'off') sendControl(c, { ...state, reason: state.reason ?? state.state })
else sendControl(c, { state: state.state, reason: 'too-soon' })
}
- function wrongAttempt(c: Conn): void {
+ /** `name`: the name this attempt gave, when it was well formed; the lock's notice names it. */
+ function wrongAttempt(c: Conn, name: string | null): void {
c.wrong++
linkWrong++
// The service records (and writes) the link-wide count before any lock below.
const count = Math.min(linkWrong, WRONG_PER_LINK)
safe('onWrongAttempt', () => deps.onWrongAttempt(count))
sendControl(c, { state: controlStateFor(c).state, reason: 'wrong' })
- if (linkWrong >= WRONG_PER_LINK) lockLink()
+ if (linkWrong >= WRONG_PER_LINK) lockLink(name ?? c.name)
if (c.wrong >= WRONG_PER_CONN) endConn(c, 'attempts')
}
/** Locked: the service records it (synchronously, in `onControlLocked`), every viewer is told, and
- * every controller drops back to watching. */
- function lockLink(): void {
+ * every controller drops back to watching. `by`: who tipped it, as it named itself (or null). */
+ function lockLink(by: string | null): void {
controlEpoch++
- safe('onControlLocked', () => deps.onControlLocked())
+ safe('onControlLocked', () => deps.onControlLocked(by))
// The lock rests on the service recording it before it returns. If it did not (it threw, or a
// wiring slip), the next attempt would be verified again: say so loudly, and still demote and tell.
if (record.control?.locked !== true) console.error('[watch-link] onControlLocked did not lock the link')
for (const c of joinedConns()) {
loseControl(c)
- sendControl(c, { state: 'locked', reason: 'locked' })
+ sendControl(c, lockedState('locked'))
}
safe('onChange', deps.onChange)
}
@@ -1383,6 +1429,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
delivery: null,
lastDroppedAt: -Infinity,
controlName: null,
+ unlockKeys: null,
+ sealedOnly: false,
sessionId: null,
altScreen: false,
joining: false,
diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.ts
index f89f26e0b..0cff9787d 100644
--- a/src/core/watch-link/service.test.ts
+++ b/src/core/watch-link/service.test.ts
@@ -1047,7 +1047,7 @@ describe('createWatchLinkService — creating a Control link', () => {
expect(text).not.toContain(Buffer.from(PW).toString('base64'))
expect(text).not.toContain(Buffer.from(PW).toString('hex'))
const [loaded] = await t.store.load()
- expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'locked', 'salt', 'wrong'])
+ expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'lockStep', 'locked', 'lockedUntil', 'salt', 'wrong'])
expect(loaded.control).toMatchObject({ enabled: true, locked: false })
expect(await verifyControlPassword(PW, loaded.control!)).toBe(true)
const h = t.hosts.made[0]
@@ -1172,10 +1172,12 @@ describe('createWatchLinkService — the Control host seams', () => {
const h = t.hosts.made[0]
h.deps.onControlLocked()
expect(h.record.control?.locked).toBe(true) // before any await: the host's lock rests on it
- expect(t.notices().at(-1)).toEqual({ kind: 'control-locked', linkId: r.link.linkId, nodeId: 'n1', title: 'build' })
+ const until = h.record.control?.lockedUntil
+ expect(until).toEqual(expect.any(Number))
+ expect(t.notices().at(-1)).toEqual({ kind: 'control-locked', linkId: r.link.linkId, nodeId: 'n1', title: 'build', by: null, until })
expect((await t.store.load())[0].control?.locked).toBe(true)
await flush()
- expect(t.states().at(-1)?.[0].control).toEqual({ enabled: true, locked: true })
+ expect(t.states().at(-1)?.[0].control).toEqual({ enabled: true, locked: true, lockedUntil: until })
})
it('a lock whose write fails still holds in memory, and the failure is logged', async () => {
@@ -1188,7 +1190,7 @@ describe('createWatchLinkService — the Control host seams', () => {
outcome = 'failed'
t.hosts.made[0].deps.onControlLocked()
await vi.waitFor(() => expect(warn.mock.calls.some(([l]) => /lock/.test(String(l)))).toBe(true))
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })
+ expect(t.s.list()[0].control).toMatchObject({ enabled: true, locked: true })
const c = t.hosts.made[0].record.control!
for (const secret of [PW, c.salt, c.hash]) expect(allLogged([warn])).not.toContain(secret)
warn.mockRestore()
@@ -1249,6 +1251,132 @@ describe('createWatchLinkService — the Control host seams', () => {
expect(again.hosts.made[0].record.control?.wrong).toBe(9)
})
+ // Finding L2: a lock lifts by itself — 15 minutes for the first since the owner last allowed control,
+ // doubling each time, 24 h at most — so a link holder cannot lock control for everyone for good.
+ describe('a timed lock (finding L2)', () => {
+ const MIN = 60_000
+ async function locked(o: Opts = {}) {
+ vi.useFakeTimers()
+ const t = service({ hashPassword: fastHash, ...o })
+ // Unlimited: a lock can outlast a finite link, which would end it first.
+ const r = await t.s.create(ctlReq({ ttlSeconds: 0 }))
+ if (!r.ok) throw new Error(r.error)
+ const h = t.hosts.made[0]
+ return { t, h, id: r.link.linkId }
+ }
+ const lockNow = (h: FakeHost, by: string | null = null): void => {
+ for (let n = 1; n <= WRONG_PER_LINK; n++) h.deps.onWrongAttempt(n)
+ h.deps.onControlLocked(by)
+ }
+
+ it('lasts 15 minutes, names who tipped it, then lifts by itself: unlocking allowed again, the count over, the host told, saved', async () => {
+ const { t, h } = await locked()
+ const t0 = Date.now()
+ lockNow(h, 'Mert')
+ expect(h.record.control).toMatchObject({ locked: true, lockedUntil: t0 + 15 * MIN, lockStep: 1, wrong: WRONG_PER_LINK })
+ expect(t.notices().at(-1)).toMatchObject({ kind: 'control-locked', by: 'Mert', until: t0 + 15 * MIN })
+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true, lockedUntil: t0 + 15 * MIN })
+ await vi.advanceTimersByTimeAsync(15 * MIN - 1)
+ expect(h.record.control?.locked).toBe(true)
+ expect(h.hooks).toEqual([])
+ await vi.advanceTimersByTimeAsync(1)
+ expect(h.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
+ expect(h.hooks).toEqual(['allowControl'])
+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
+ await flush()
+ expect((await t.store.load())[0].control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
+ })
+
+ it('each later lock lasts twice as long, never past 24 h; Allow control again lifts it at once and starts the backoff over', async () => {
+ const { t, h, id } = await locked()
+ const lasted: number[] = []
+ for (let i = 0; i < 9; i++) {
+ lockNow(h)
+ lasted.push((h.record.control!.lockedUntil as number) - Date.now())
+ await vi.advanceTimersByTimeAsync(lasted.at(-1)!)
+ expect(h.record.control?.locked).toBe(false)
+ }
+ expect(lasted.map((ms) => ms / MIN)).toEqual([15, 30, 60, 120, 240, 480, 960, 1440, 1440])
+ lockNow(h)
+ expect(await t.s.allowControl(id)).toBe(true)
+ expect(h.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 0 })
+ // The pending lift finds nothing to do when its time comes.
+ const hooks = h.hooks.length
+ await vi.advanceTimersByTimeAsync(25 * HOUR)
+ expect(h.hooks.length).toBe(hooks)
+ lockNow(h)
+ expect((h.record.control!.lockedUntil as number) - Date.now()).toBe(15 * MIN)
+ })
+
+ it('a restart neither lifts a lock early nor makes it permanent', async () => {
+ const { t, h } = await locked()
+ const t0 = Date.now()
+ lockNow(h, 'Mert')
+ await flush()
+ await t.s.shutdown()
+ await vi.advanceTimersByTimeAsync(5 * MIN)
+ const again = service({ store: new WatchLinkStore({ file: t.file }) })
+ await again.s.init()
+ const h2 = again.hosts.made[0]
+ expect(h2.record.control).toMatchObject({ locked: true, lockedUntil: t0 + 15 * MIN, wrong: WRONG_PER_LINK, lockStep: 1 })
+ await vi.advanceTimersByTimeAsync(10 * MIN)
+ expect(h2.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
+ expect(h2.hooks).toEqual(['allowControl'])
+ })
+
+ it('a restart after the lock should have lifted lifts it BEFORE the host is built (it starts from a count of 0), and saves that', async () => {
+ const { t, h } = await locked()
+ lockNow(h)
+ await flush()
+ await t.s.shutdown()
+ await vi.advanceTimersByTimeAsync(2 * HOUR)
+ const again = service({ store: new WatchLinkStore({ file: t.file }) })
+ await again.s.init()
+ const h2 = again.hosts.made[0]
+ // The host was handed a record already lifted: nothing to tell it.
+ expect(h2.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
+ expect(h2.hooks).toEqual([])
+ await flush()
+ expect((await again.store.load())[0].control).toMatchObject({ locked: false, wrong: 0, lockStep: 1 })
+ })
+
+ it('a lock written before timed locks (no lift time) keeps its meaning: it waits for the owner', async () => {
+ vi.useFakeTimers()
+ const t = service({ hashPassword: fastHash })
+ const r = await t.s.create(ctlReq({ ttlSeconds: 0 }))
+ if (!r.ok) throw new Error(r.error)
+ const old = t.hosts.made[0].record
+ await t.s.shutdown()
+ const legacy = { ...old, control: { enabled: true, salt: old.control!.salt, hash: old.control!.hash, locked: true, wrong: WRONG_PER_LINK } }
+ await new WatchLinkStore({ file: t.file }).save([legacy])
+ const again = service({ store: new WatchLinkStore({ file: t.file }) })
+ await again.s.init()
+ const h = again.hosts.made[0]
+ expect(h.record.control).toMatchObject({ locked: true, lockedUntil: null })
+ expect(again.s.list()[0].control).toEqual({ enabled: true, locked: true, lockedUntil: null })
+ await vi.advanceTimersByTimeAsync(400 * HOUR)
+ expect(h.record.control?.locked).toBe(true)
+ expect(h.hooks).toEqual([])
+ expect(await again.s.allowControl(r.link.linkId)).toBe(true)
+ expect(h.record.control).toMatchObject({ locked: false, lockStep: 0 })
+ })
+
+ it('a lift time further off than 24 h (the clock went back, a hand edit) is brought in to 24 h from now', async () => {
+ const { t, h } = await locked()
+ lockNow(h)
+ await flush()
+ await t.s.shutdown()
+ const saved = (await new WatchLinkStore({ file: t.file }).load())[0]
+ await new WatchLinkStore({ file: t.file }).save([{ ...saved, control: { ...saved.control!, lockedUntil: Date.now() + 400 * HOUR } }])
+ const again = service({ store: new WatchLinkStore({ file: t.file }) })
+ await again.s.init()
+ const h2 = again.hosts.made[0]
+ expect(h2.record.control?.lockedUntil).toBe(Date.now() + 24 * HOUR)
+ await vi.advanceTimersByTimeAsync(24 * HOUR)
+ expect(h2.record.control?.locked).toBe(false)
+ })
+ })
+
it('a new password and Allow control again reset the count, on the record and on disk', async () => {
const t = service({ hashPassword: fastHash })
const r = await t.s.create(ctlReq())
@@ -1284,7 +1412,7 @@ describe('createWatchLinkService — the Control host seams', () => {
{ viewerId: 'v-2', name: null, joinedAt: 6, waiting: false, controlling: false, typing: false }
]
expect(t.s.list()[0].viewers.map((v) => [v.controlling, v.typing])).toEqual([[true, true], [false, false]])
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })
+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
})
})
@@ -1299,7 +1427,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
expect(h.hooks).toEqual(['controlChanged'])
expect((await t.store.load()).find((l) => l.linkId === r.link.linkId)?.control?.enabled).toBe(false)
await flush()
- expect(t.states().at(-1)?.find((l) => l.linkId === r.link.linkId)?.control).toEqual({ enabled: false, locked: false })
+ expect(t.states().at(-1)?.find((l) => l.linkId === r.link.linkId)?.control).toEqual({ enabled: false, locked: false, lockedUntil: null })
expect(await t.s.setControl(r.link.linkId, true)).toBe(true)
expect(h.hooks).toEqual(['controlChanged', 'controlChanged'])
// Not a Control link, an unknown link, an ended one.
@@ -1343,7 +1471,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
expect(await t.s.allowControl(r.link.linkId)).toBe(true)
expect(h.hooks).toEqual(['allowControl'])
expect((await t.store.load())[0].control?.locked).toBe(false)
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })
+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
expect(await t.s.allowControl('Nope000000000000000000')).toBe(false)
})
@@ -1376,7 +1504,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
expect(await t.s.setControl(id, false)).toBe('unsaved')
// Never undone: the record the host reads, the owner's view, and the host told once.
expect(h.record.control?.enabled).toBe(false)
- expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false })
+ expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
expect(h.hooks).toEqual(['controlChanged'])
expect(f.saves.length).toBe(saves + 1) // no "corrected" list queued behind it
expect(f.written.at(-1)?.enabled).toBe(false)
@@ -1385,7 +1513,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
const other = await t.s.create(req({ nodeId: 'n2' }))
expect(other.ok).toBe(true)
expect(f.written.at(-1)?.enabled).toBe(false)
- expect(t.s.list().find((l) => l.linkId === id)?.control).toEqual({ enabled: false, locked: false })
+ expect(t.s.list().find((l) => l.linkId === id)?.control).toEqual({ enabled: false, locked: false, lockedUntil: null })
expect(allLogged([warn])).not.toContain(PW)
warn.mockRestore()
})
@@ -1431,7 +1559,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
expect(await t.s.setPassword(id, NEW_PW)).toBe('unsaved')
expect(h.hooks).toEqual(['controlChanged', 'passwordChanged'])
const after = { ...h.record.control! }
- expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false })
+ expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
// The disk answers again: the hung writes land, and the next write carries both changes.
const d = held
held = null
@@ -1456,7 +1584,7 @@ describe('createWatchLinkService — the owner controls a Control link', () => {
h.deps.onControlLocked() // its own write fails too: the lock holds
expect(await t.s.allowControl(id)).toBe(false)
expect(h.hooks).toEqual([]) // a widening the write refused never reached the host
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })
+ expect(t.s.list()[0].control).toMatchObject({ enabled: true, locked: true })
warn.mockRestore()
})
})
@@ -1512,7 +1640,7 @@ describe('createWatchLinkService — owner changes, by direction', () => {
// What an unlock checks (the host reads the record live): still off while the write is in flight.
expect(x.h.record.control?.enabled).toBe(false)
expect(x.h.hooks).toEqual([])
- expect(x.t.s.list()[0].control).toEqual({ enabled: false, locked: false })
+ expect(x.t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
// …and yet the write carries the change.
expect(x.written.at(-1)?.enabled).toBe(true)
x.release('failed')
@@ -1534,7 +1662,7 @@ describe('createWatchLinkService — owner changes, by direction', () => {
expect(await on).toBe(true)
expect(x.h.record.control?.enabled).toBe(true)
expect(x.h.hooks).toEqual(['controlChanged'])
- expect(x.t.s.list()[0].control).toEqual({ enabled: true, locked: false })
+ expect(x.t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
})
it('allowControl waits for the write too: still locked throughout, and a failed write never unlocks it', async () => {
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
index 4f6e73627..92d8a1a1f 100644
--- a/src/core/watch-link/service.ts
+++ b/src/core/watch-link/service.ts
@@ -93,13 +93,16 @@ import { WRONG_PER_LINK, createLinkHost, type LinkHost, type QuietClients, type
import type { HistoryRead } from './history'
import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'
import {
+ CONTROL_LOCK_STEP_MAX,
WatchLinkStoreUnreadable,
+ controlLockMs,
type WatchLinkControlRecord,
type WatchLinkRecord,
type WatchLinkStore
} from './store'
import type { RelayTransport } from '../relay/relay-socket'
import { errorText } from '../../shared/error-text'
+import { CONTROL_LOCK_MAX_MS } from '../../shared/watch-link/protocol'
/** setTimeout's own ceiling (a longer delay fires at once). A link lives ≤ 24 h, far below it. */
const MAX_DELAY_MS = 2_147_483_647
@@ -322,6 +325,8 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
const writing = new Map<string, WatchLinkRecord>()
const hosts = new Map<string, LinkHost>()
const expiry = new Map<string, unknown>()
+ /** A timed wrong-password lock's timer, per link (finding L2). */
+ const lockTimers = new Map<string, unknown>()
let initPromise: Promise<void> | null = null
/** Creates between their cap check and their answer (G17): they count against the cap. A create's
* record joins `records` only as it answers, so it is never counted twice. */
@@ -411,7 +416,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
url: formatWatchLink(r.linkId, r.secret),
status,
viewers,
- control: r.role === 'controller' && r.control ? { enabled: r.control.enabled, locked: r.control.locked } : null
+ control:
+ r.role === 'controller' && r.control
+ ? {
+ enabled: r.control.enabled,
+ locked: r.control.locked,
+ lockedUntil: r.control.locked && typeof r.control.lockedUntil === 'number' ? r.control.lockedUntil : null
+ }
+ : null
}
}
const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))
@@ -511,6 +523,58 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
)
}
+ /**
+ * A Control link's wrong-password lock lifts by itself at `lockedUntil` (finding L2): arm that, or
+ * lift it now when its time has passed (an app restart past it, a lid-close). A lock with no
+ * `lockedUntil` (one written before timed locks) has nothing to arm: it waits for the owner, as it
+ * always did. A `lockedUntil` further away than the longest lock (the clock went back, a hand edit)
+ * is brought in to that: no lock outlasts `CONTROL_LOCK_MAX_MS` from now.
+ */
+ function armLock(r: WatchLinkRecord): void {
+ const t = lockTimers.get(r.linkId)
+ if (t !== undefined) clearT(t)
+ lockTimers.delete(r.linkId)
+ const c = r.control
+ if (!c || !c.locked || typeof c.lockedUntil !== 'number') return
+ if (c.lockedUntil - now() > CONTROL_LOCK_MAX_MS) c.lockedUntil = now() + CONTROL_LOCK_MAX_MS
+ const until = c.lockedUntil
+ const delay = until - now()
+ if (delay <= 0) {
+ liftLock(r, until)
+ return
+ }
+ lockTimers.set(
+ r.linkId,
+ setT(() => {
+ lockTimers.delete(r.linkId)
+ liftLock(r, until)
+ }, Math.min(MAX_DELAY_MS, delay))
+ )
+ }
+ /** The lock armed for `until` lifts: unlocking is allowed again and the link-wide count starts over;
+ * `lockStep` stays, so the next lock lasts twice as long. Nothing if the link ended, or the lock
+ * changed meanwhile (lifted by the owner, or a new lock). The record changes first and is then
+ * written; a write that fails changes nothing that matters — a `lockedUntil` in the past reads as
+ * lifted at the next launch too. */
+ function liftLock(r: WatchLinkRecord, until: number): void {
+ const c = r.control
+ if (stopped || !c || !c.locked || c.lockedUntil !== until) return
+ if (now() < until) {
+ armLock(r) // a clamped delay: not yet
+ return
+ }
+ c.locked = false
+ c.lockedUntil = null
+ c.wrong = 0
+ // The link may still be loading (`init` lifts a lapsed lock before any host exists).
+ if (records.get(r.linkId) !== r) return
+ tellHost(r.linkId, (h) => h.allowControl())
+ emitState()
+ void persist().then((saved) => {
+ if (!saved) warn("a Control link's lifted lock could not be saved; it reads as lifted at the next launch anyway")
+ })
+ }
+
/** The host's pty seam, with the node-gone check before every join (R29, G8). */
function guardedPty(r: WatchLinkRecord): WatchPty {
return {
@@ -545,6 +609,9 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
function start(r: WatchLinkRecord): void {
if (stopped || hosts.has(r.linkId)) return
armExpiry(r)
+ // Before the host exists: a lock whose time passed while nodeterm was closed is lifted first, so the
+ // host starts from a wrong count of 0.
+ armLock(r)
if (!deps.relayAllowed()) return // kept and listed `refused`, never hosted (G21)
let host: LinkHost
try {
@@ -587,17 +654,36 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
})
emitState()
},
- onControlLocked: () => {
+ onControlLocked: (by) => {
// SYNCHRONOUSLY, before any I/O: the host's lock rests on this flag (it reads the record live
- // and never writes it). Never undone: a lock whose write fails still holds until quit.
- if (r.control) r.control.locked = true
+ // and never writes it). Never undone by a failed write: a lock whose write fails still holds,
+ // and still lifts at its time (finding L2: it lifts by itself — 15 minutes for the first since
+ // the owner last allowed control, doubling each time, 24 h at most).
+ const c = r.control
+ let until: number | null = null
+ if (c) {
+ const step = Number.isInteger(c.lockStep) ? (c.lockStep as number) : 0
+ until = now() + controlLockMs(step)
+ c.locked = true
+ c.lockedUntil = until
+ c.lockStep = Math.min(CONTROL_LOCK_STEP_MAX, step + 1)
+ }
takeTurn(r, 'locked') // an "allow again" still being written must not land over it
if (records.get(r.linkId) === r) {
+ armLock(r)
void persist().then((saved) => {
- if (!saved) warn("a Control link's lock could not be saved; it holds until nodeterm quits")
+ if (!saved) warn("a Control link's lock could not be saved; a restart would lift it early")
})
}
- notice({ kind: 'control-locked', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title) })
+ notice({
+ kind: 'control-locked',
+ linkId: r.linkId,
+ nodeId: r.nodeId,
+ title: stripBidiControls(r.title),
+ // A name the attempt gave itself (sanitized by the host): a claim, shown as one.
+ by: typeof by === 'string' && by ? stripBidiControls(by) : null,
+ until
+ })
emitState()
},
onWrongAttempt: (count) => {
@@ -634,6 +720,9 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
const t = expiry.get(linkId)
if (t !== undefined) clearT(t)
expiry.delete(linkId)
+ const lt = lockTimers.get(linkId)
+ if (lt !== undefined) clearT(lt)
+ lockTimers.delete(linkId)
const host = hosts.get(linkId)
hosts.delete(linkId)
return { record, host }
@@ -841,7 +930,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
return fail('unsupported')
}
parsed.password = null
- control = { enabled: true, locked: false, wrong: 0, salt: h.salt, hash: h.hash }
+ control = { enabled: true, locked: false, wrong: 0, lockedUntil: null, lockStep: 0, salt: h.salt, hash: h.hash }
}
const secret = newWatchLinkSecret()
const joinKeyHash = await sha256Hex(deriveWatchLinkKeys(secret).joinKey)
@@ -1046,9 +1135,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
return widenControl(r, 'locked', {
change: (x) => {
x.locked = false
+ x.lockedUntil = null
x.wrong = 0 // the count starts over with the lock (the host resets its own)
+ x.lockStep = 0 // and so does the backoff: the next lock lasts 15 minutes again
},
- host: (h) => h.allowControl()
+ host: (h) => {
+ armLock(r) // nothing left to lift
+ h.allowControl()
+ }
})
},
@@ -1062,6 +1156,8 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
stopped = true
for (const t of expiry.values()) clearT(t)
expiry.clear()
+ for (const t of lockTimers.values()) clearT(t)
+ lockTimers.clear()
const all = [...hosts.values()]
hosts.clear()
for (const h of all) stopHost(h, 'host-stopping')
diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.ts
index a757560e0..077823c7a 100644
--- a/src/core/watch-link/store.test.ts
+++ b/src/core/watch-link/store.test.ts
@@ -528,7 +528,7 @@ describe('a keychain that stops sealing mid-run (R45)', () => {
describe('controller records and unlimited expiry', () => {
const SALT = b64(new Uint8Array(16).fill(1))
const HASH = b64(new Uint8Array(32).fill(2))
- const control = { enabled: true, salt: SALT, hash: HASH, locked: false, wrong: 0 }
+ const control = { enabled: true, salt: SALT, hash: HASH, locked: false, wrong: 0, lockedUntil: null, lockStep: 0 }
const ctl = (over: Partial<WatchLinkRecord> = {}) => rec({ role: 'controller', control, expiresAt: null, ...over })
it('round-trips a controller record with no expiry through save and a fresh store', async () => {
@@ -538,7 +538,7 @@ describe('controller records and unlimited expiry', () => {
expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([ctl()])
}
const f = file()
- const locked = ctl({ control: { enabled: false, salt: SALT, hash: HASH, locked: true, wrong: 10 } })
+ const locked = ctl({ control: { enabled: false, salt: SALT, hash: HASH, locked: true, wrong: 10, lockedUntil: null, lockStep: 0 } })
expect(await new WatchLinkStore({ file: f, seal, unseal }).save([locked])).toBe('saved')
expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([locked])
})
@@ -584,7 +584,16 @@ describe('controller records and unlimited expiry', () => {
{ ...control, wrong: 1.5 },
{ ...control, wrong: '3' },
{ ...control, wrong: null },
- { ...control, wrong: Number.MAX_SAFE_INTEGER }
+ { ...control, wrong: Number.MAX_SAFE_INTEGER },
+ // When a lock lifts (finding L2): null or a finite epoch ms ≥ 0; how many locks: 0..16.
+ { ...control, locked: true, lockedUntil: -1 },
+ { ...control, locked: true, lockedUntil: '1700000000000' },
+ { ...control, locked: true, lockedUntil: {} },
+ { ...control, lockStep: -1 },
+ { ...control, lockStep: 17 },
+ { ...control, lockStep: 1.5 },
+ { ...control, lockStep: '2' },
+ { ...control, lockStep: null }
]
const f = file()
writeLinks(f, [...bad.map((c, i) => rawEntry({ linkId: id(i), role: 'controller', control: c, expiresAt: null })), rawEntry()])
@@ -606,7 +615,32 @@ describe('controller records and unlimited expiry', () => {
expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl()])
})
- it('keeps only the five control fields: an extra one is not loaded or carried', async () => {
+ // Finding L2: a lock lifts by itself. When (`lockedUntil`) and how many locks there were since the
+ // owner last allowed control (`lockStep`) are persisted, so a restart neither lifts a lock early nor
+ // makes it permanent.
+ it('round-trips when a lock lifts and how many locks there were', async () => {
+ for (const opts of [{ seal, unseal }, {}]) {
+ const f = file()
+ const timed = ctl({ control: { ...control, locked: true, wrong: 10, lockedUntil: 1_700_000_900_000, lockStep: 3 } })
+ expect(await new WatchLinkStore({ file: f, ...opts }).save([timed])).toBe('saved')
+ expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([timed])
+ }
+ })
+
+ it('an existing lock with no lift time (written before timed locks) keeps its meaning: locked until the owner acts', async () => {
+ const f = file()
+ const older = { enabled: true, salt: SALT, hash: HASH, locked: true, wrong: 10 }
+ writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: older })])
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl({ control: { ...control, locked: true, wrong: 10, lockedUntil: null, lockStep: 0 } })])
+ })
+
+ it('carries a lift time only while locked: an unlocked record with one reads as none', async () => {
+ const f = file()
+ writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: { ...control, locked: false, lockedUntil: 1_700_000_900_000, lockStep: 2 } })])
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl({ control: { ...control, lockStep: 2 } })])
+ })
+
+ it('keeps only the seven control fields: an extra one is not loaded or carried', async () => {
const f = file()
writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: { ...control, password: 'hunter22' } })])
const s = new WatchLinkStore({ file: f })
@@ -615,7 +649,7 @@ describe('controller records and unlimited expiry', () => {
expect(readFileSync(f, 'utf8')).not.toContain('hunter22')
})
- it('writes only the five control fields of a record', async () => {
+ it('writes only the seven control fields of a record', async () => {
const f = file()
const withExtra = ctl({ control: { ...control, password: 'hunter22' } as WatchLinkRecord['control'] })
expect(await new WatchLinkStore({ file: f, seal, unseal }).save([withExtra])).toBe('saved')
@@ -640,7 +674,10 @@ describe('controller records and unlimited expiry', () => {
ctl({ control: { ...control, locked: undefined } as unknown as WatchLinkRecord['control'] }),
ctl({ control: { ...control, wrong: 11 } }),
ctl({ control: { ...control, wrong: -1 } }),
- ctl({ control: { ...control, wrong: 2.5 } })
+ ctl({ control: { ...control, wrong: 2.5 } }),
+ ctl({ control: { ...control, locked: true, lockedUntil: Number.NaN } }),
+ ctl({ control: { ...control, locked: true, lockedUntil: -5 } }),
+ ctl({ control: { ...control, lockStep: 99 } })
]
for (const r of broken) {
expect(await s.save([rec({ linkId: 'OtherLinkIjKlMnOpQrStU' }), r]), JSON.stringify(r.control ?? r.role)).toBe('failed')
@@ -654,7 +691,7 @@ describe('controller records and unlimited expiry', () => {
it('never writes the plaintext password: the file holds only its salt and scrypt hash', async () => {
const password = 'correct horse battery staple'
const h = await hashControlPassword(password)
- const r = ctl({ control: { enabled: true, salt: h.salt, hash: h.hash, locked: false, wrong: 0 } })
+ const r = ctl({ control: { enabled: true, salt: h.salt, hash: h.hash, locked: false, wrong: 0, lockedUntil: null, lockStep: 0 } })
for (const opts of [{ seal, unseal }, {}]) {
const f = file()
expect(await new WatchLinkStore({ file: f, ...opts }).save([r])).toBe('saved')
diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.ts
index 1216988f0..05df5e388 100644
--- a/src/core/watch-link/store.ts
+++ b/src/core/watch-link/store.ts
@@ -39,10 +39,15 @@
// at boot and links sealed earlier stay on disk, and a link no longer in the list is still dropped.
//
// A CONTROL LINK (role 'controller') carries `control`: whether typing is on, the password's scrypt
-// salt and hash (./password.ts — never the plaintext), whether wrong attempts locked it, and the
+// salt and hash (./password.ts — never the plaintext), whether wrong attempts locked it, the
// link-wide count of wrong attempts toward that lock (`wrong`, 0..CONTROL_WRONG_MAX — persisted, so an
// app restart does not hand an attacker who holds the link fresh guesses; a file written before the
-// count existed reads as 0). It is
+// count existed reads as 0), when the lock lifts by itself (`lockedUntil`, finding L2 — persisted, so a
+// restart neither lifts it early nor makes it permanent; a lock written before timed locks has none and
+// lasts until the owner allows control again, as it always did) and how many locks there have been
+// since the owner last did (`lockStep`, so each lock lasts twice as long as the last, up to 24 h). An
+// older build reads the file as before and ignores the two new fields: a timed lock is permanent there
+// (the safe direction for a downgrade). It is
// written as it is, not sealed: the hash is scrypt'd, and anyone who can read this 0600 file under
// userData is already this user. `control` is present IFF the role is 'controller', and a load drops
// any entry that breaks that rule: a hand-edited file cannot give a viewer link a password, and a
@@ -55,11 +60,20 @@ import { promises as fs } from 'node:fs'
import { createHash } from 'node:crypto'
import { renameAtomic, writeFileAtomic } from '../fs-atomic'
import { LINK_ID_RE } from '../../shared/watch-link/link'
-import type { WatchLinkRole } from '../../shared/watch-link/protocol'
+import { CONTROL_LOCK_MAX_MS, type WatchLinkRole } from '../../shared/watch-link/protocol'
import { isSafeNodeId } from '../../shared/safe-id'
/** Wrong unlock attempts across a Control link that lock it (link-host.ts `WRONG_PER_LINK`). */
export const CONTROL_WRONG_MAX = 10
+/** How long a wrong-password lock lasts by itself: 15 minutes for the first lock since the owner last
+ * allowed control, doubling with each later one, never past `CONTROL_LOCK_MAX_MS` (24 h). */
+export const CONTROL_LOCK_FIRST_MS = 15 * 60_000
+/** The most locks the record counts (`lockStep`): far past the step where the cap is reached. */
+export const CONTROL_LOCK_STEP_MAX = 16
+export function controlLockMs(step: number): number {
+ const n = Number.isInteger(step) && step > 0 ? Math.min(step, CONTROL_LOCK_STEP_MAX) : 0
+ return Math.min(CONTROL_LOCK_FIRST_MS * 2 ** n, CONTROL_LOCK_MAX_MS)
+}
/** A Control link's typing state. The salt and hash are base64 (16 and 32 bytes). */
export interface WatchLinkControlRecord {
@@ -68,8 +82,15 @@ export interface WatchLinkControlRecord {
hash: string
locked: boolean
/** Wrong unlock attempts across the link since the last reset (a new password, Allow control
- * again): an integer 0..CONTROL_WRONG_MAX. */
+ * again, a lock that lifted): an integer 0..CONTROL_WRONG_MAX. */
wrong: number
+ /** While `locked`: when the lock lifts by itself (epoch ms, this machine's clock); null (or absent)
+ * for a lock that lifts only when the owner allows control again — every lock a build from before
+ * timed locks wrote. Always null while not locked. */
+ lockedUntil?: number | null
+ /** How many locks since the owner last allowed control again (0..CONTROL_LOCK_STEP_MAX): the next
+ * lock lasts `controlLockMs(lockStep)`. A lock that lifts by itself does not reset it. Absent: 0. */
+ lockStep?: number
}
export interface WatchLinkRecord {
@@ -154,16 +175,25 @@ function isB64Of(v: unknown, bytes: number): v is string {
return b.length === bytes && b.toString('base64') === v
}
-/** A Control link's `control`, rebuilt from its five fields (nothing else is carried), or null. An
+/** A Control link's `control`, rebuilt from its seven fields (nothing else is carried), or null. An
* absent `wrong` is 0 (a file written before the count was persisted); a present one must be an
- * integer 0..CONTROL_WRONG_MAX. */
+ * integer 0..CONTROL_WRONG_MAX. An absent `lockedUntil` is null — a lock written before timed locks
+ * keeps its meaning, "until the owner allows control again" — and a present one must be null or a
+ * finite epoch ms ≥ 0; it is carried only while `locked`. An absent `lockStep` is 0; a present one must
+ * be an integer 0..CONTROL_LOCK_STEP_MAX. */
function readControl(v: unknown): WatchLinkControlRecord | null {
if (!v || typeof v !== 'object' || Array.isArray(v)) return null
- const { enabled, salt, hash, locked, wrong = 0 } = v as Record<string, unknown>
+ const { enabled, salt, hash, locked, wrong = 0, lockedUntil = null, lockStep = 0 } = v as Record<string, unknown>
if (typeof enabled !== 'boolean' || typeof locked !== 'boolean') return null
if (!isB64Of(salt, CONTROL_SALT_BYTES) || !isB64Of(hash, CONTROL_HASH_BYTES)) return null
if (!Number.isInteger(wrong) || (wrong as number) < 0 || (wrong as number) > CONTROL_WRONG_MAX) return null
- return { enabled, salt, hash, locked, wrong: wrong as number }
+ if (lockedUntil !== null && (!num(lockedUntil) || lockedUntil < 0)) return null
+ if (!Number.isInteger(lockStep) || (lockStep as number) < 0 || (lockStep as number) > CONTROL_LOCK_STEP_MAX) return null
+ return {
+ enabled, salt, hash, locked, wrong: wrong as number,
+ lockedUntil: locked ? (lockedUntil as number | null) : null,
+ lockStep: lockStep as number
+ }
}
export class WatchLinkStore {
@@ -351,7 +381,7 @@ export class WatchLinkStore {
}
sealedNext.set(r.linkId, { digest, sealed: secret })
}
- // Only the five control fields are written (as `readControl` read them above): nothing else that
+ // Only the seven control fields are written (as `readControl` read them above): nothing else that
// rides on the object reaches disk.
const c = r.control ? readControl(r.control) : null
const control = c ? { control: c } : {}
diff --git a/src/renderer/components/LiveLinkControls.tsx b/src/renderer/components/LiveLinkControls.tsx
index ed551269f..c453381af 100644
--- a/src/renderer/components/LiveLinkControls.tsx
+++ b/src/renderer/components/LiveLinkControls.tsx
@@ -10,7 +10,7 @@ import { Switch } from '../ui/Switch'
import {
CONTROL_CHANGE_FAILED_MESSAGE,
CONTROL_CHANGE_UNSAVED_MESSAGE,
- CONTROL_LOCKED_TEXT,
+ controlLockedText,
KICK_FAILED_MESSAGE,
KICK_NOT_DONE_MESSAGE,
PASSWORD_CHANGE_FAILED_MESSAGE,
@@ -213,7 +213,7 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W
{control.locked && (
<div className="live-pop__locked">
<p className="live-pop__status" role="status">
- {CONTROL_LOCKED_TEXT}
+ {controlLockedText(control.lockedUntil)}
</p>
<button
type="button"
diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.ts
index 8578cc663..f664b323f 100644
--- a/src/renderer/lib/liveLink.test.ts
+++ b/src/renderer/lib/liveLink.test.ts
@@ -7,6 +7,8 @@ import {
CHAT_NOT_SENT_MESSAGE,
chipView,
formatUntil,
+ controlLockedText,
+ controlLockedNoticeText,
watchableOnlyWhileOpen,
commentFromChat,
createErrorMessage,
@@ -527,6 +529,33 @@ describe('control notices', () => {
'Control of api-server was locked after 10 wrong passwords. Allow it again from the LIVE chip.'
)
})
+
+ // Finding L2: the lock lifts by itself, and the owner is told until when and who tipped it.
+ it('control-locked from a timed lock says until when and who tipped it — a name as a claim, else "a viewer"', () => {
+ const now = new Date(2026, 9, 23, 14, 0).getTime()
+ const until = new Date(2026, 9, 23, 14, 15).getTime()
+ const at = formatUntil(until, now)
+ expect(controlLockedNoticeText({ title: 'api‮-server', by: 'Me‮rt', until }, now)).toBe(
+ `Control of api-server is locked until ${at} after 10 wrong passwords; the last came from a viewer using the name “Mert”. Allow it again from the LIVE chip.`
+ )
+ expect(controlLockedNoticeText({ title: 'api-server', by: null, until }, now)).toBe(
+ `Control of api-server is locked until ${at} after 10 wrong passwords; the last came from a viewer. Allow it again from the LIVE chip.`
+ )
+ // A lock that waits for the owner (no lift time) but names who tipped it.
+ expect(controlLockedNoticeText({ title: 'api-server', by: ' ', until: null }, now)).toBe(
+ 'Control of api-server is locked after 10 wrong passwords; the last came from a viewer. Allow it again from the LIVE chip.'
+ )
+ // Tomorrow is named as such (a 24 h lock).
+ expect(controlLockedNoticeText({ title: 'a', by: null, until: until + 24 * 3600_000 }, now)).toContain(`until tomorrow`)
+ })
+
+ it('the locked line says until when a timed lock lasts, and nothing more for one that waits for the owner', () => {
+ const now = new Date(2026, 9, 23, 14, 0).getTime()
+ const until = new Date(2026, 9, 23, 14, 15).getTime()
+ expect(controlLockedText(until, now)).toBe(`Control locked after 10 wrong passwords, until ${formatUntil(until, now)}.`)
+ expect(controlLockedText(null, now)).toBe(CONTROL_LOCKED_TEXT)
+ expect(controlLockedText(undefined, now)).toBe(CONTROL_LOCKED_TEXT)
+ })
})
describe('final review copy', () => {
diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.ts
index 90b90178b..4f7a36832 100644
--- a/src/renderer/lib/liveLink.ts
+++ b/src/renderer/lib/liveLink.ts
@@ -119,8 +119,14 @@ export const PASSWORD_SHOWN_ONCE = 'This is the only time the password is shown.
/** Why Control is not offered on a node — the dialog's disabled option and the create error alike. */
export const CONTROL_UNSUPPORTED_REASON =
"Control isn't available for this terminal: its Zellij session's key bindings would reach every session."
-/** A Control link locked by wrong passwords (spec §2.3), beside "Allow control again". */
+/** A Control link locked by wrong passwords (spec §2.3), beside "Allow control again": the lock of a
+ * core from before timed locks, which waits for the owner. */
export const CONTROL_LOCKED_TEXT = 'Control locked after 10 wrong passwords.'
+/** The locked line, with when it lifts by itself (finding L2) when it does. */
+export function controlLockedText(lockedUntil: number | null | undefined, now: number = Date.now()): string {
+ if (typeof lockedUntil !== 'number' || !Number.isFinite(lockedUntil)) return CONTROL_LOCKED_TEXT
+ return `Control locked after 10 wrong passwords, until ${formatUntil(lockedUntil, now)}.`
+}
/** The popover's Change password form: a new password demotes every controller (Task 4 ruling). */
export const PASSWORD_CHANGE_NOTE = 'Anyone typing now goes back to watching until they unlock with the new password.'
/** `setControl` / `allowControl` answered false, or did not answer. */
@@ -463,6 +469,25 @@ export function controlTakenText(n: { name: string; title: string }): string {
return name ? `Someone using the name ${quoted(name)} can now type in ${title}.` : `Someone can now type in ${title}.`
}
+/**
+ * The lock notice (finding L2): until when, and who tipped it — the name the attempt gave itself, as a
+ * claim ("a viewer using the name “Mert”"), else "a viewer" — so a kick and a new password are obvious.
+ * A core from before timed locks sends neither field, and gets the old sentence.
+ */
+export function controlLockedNoticeText(
+ n: { title: string; by?: string | null; until?: number | null },
+ now: number = Date.now()
+): string {
+ const title = stripBidiControls(n.title)
+ if (n.by === undefined && n.until === undefined) {
+ return `Control of ${title} was locked after 10 wrong passwords. Allow it again from the LIVE chip.`
+ }
+ const name = typeof n.by === 'string' ? stripBidiControls(n.by).trim() : ''
+ const who = name ? `a viewer using the name ${quoted(name)}` : 'a viewer'
+ const when = typeof n.until === 'number' && Number.isFinite(n.until) ? ` until ${formatUntil(n.until, now)}` : ''
+ return `Control of ${title} is locked${when} after 10 wrong passwords; the last came from ${who}. Allow it again from the LIVE chip.`
+}
+
/**
* The info strip for a notice from core; null for a kind this build does not know (a newer core).
* Exhaustive over the kinds this build knows: a kind added to `WatchLinkNotice` fails to compile
@@ -489,7 +514,7 @@ export function noticeText(n: WatchLinkNotice): string | null {
case 'control-taken':
return controlTakenText(n)
case 'control-locked':
- return `Control of ${stripBidiControls(n.title)} was locked after 10 wrong passwords. Allow it again from the LIVE chip.`
+ return controlLockedNoticeText(n)
default: {
// Compile-time: every known kind is handled above. Runtime: a newer core's kind is no notice.
const unknown: never = n
diff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.ts
index 68d7260c6..c7439a07e 100644
--- a/src/shared/watch-link-types.ts
+++ b/src/shared/watch-link-types.ts
@@ -94,8 +94,13 @@ export interface WatchLinkViewerView {
export interface WatchLinkControlView {
/** Typing is on: a viewer with the password may unlock. */
enabled: boolean
- /** Too many wrong passwords across the link: nobody may unlock until the owner allows it again. */
+ /** Too many wrong passwords across the link: nobody may unlock until it lifts by itself
+ * (`lockedUntil`) or the owner allows it again. */
locked: boolean
+ /** While locked: when the lock lifts by itself (epoch ms, this machine's clock); null for a lock that
+ * waits for the owner (one written before timed locks), and always null while not locked. Absent
+ * from a core older than timed locks. */
+ lockedUntil?: number | null
}
export interface WatchLinkView {
@@ -131,8 +136,10 @@ export type WatchLinkNotice =
| { kind: 'not-persistent' }
/** A viewer unlocked a Control link. `name` is the name it gave itself: a claim, shown as one. */
| { kind: 'control-taken'; linkId: string; nodeId: string; title: string; name: string }
- /** Too many wrong passwords: control is locked on that link until the owner allows it again. */
- | { kind: 'control-locked'; linkId: string; nodeId: string; title: string }
+ /** Too many wrong passwords: control is locked on that link until `until` (epoch ms; null: until the
+ * owner allows it again) or until the owner allows it sooner. `by`: the name the attempt that tipped
+ * it gave itself (a claim), null when it gave none — so a kick and a new password are obvious. */
+ | { kind: 'control-locked'; linkId: string; nodeId: string; title: string; by?: string | null; until?: number | null }
/** Whether a node's terminal can take a Control link's input: `ok` (tmux, the Windows session host, a
* plain shell), `unsupported` (Zellij — its key bindings are session-wide), or `unknown` (nothing
@@ -143,7 +150,7 @@ export type ControlSupport = 'ok' | 'unsupported' | 'unknown'
* What "Stop all" reached. THIS machine's links always stop at once, before the answer; the answer
* is about the license-wide server revoke, the only thing that ends links shared from other machines:
* - `stopped` — the server accepted it: every other machine's links end at their next mint (≤ ~90 s)
- * or, while a link is full, at its status poll (≤ 5 min).
+ * or, while a link is full, at its status poll (≤ 1 min).
* - `no-entitlement` — no Pro entitlement is stored here, so the server was not asked: links on
* other machines keep running.
* - `failed` — the server call failed (no answer, a refusal, an expired token): they keep running.