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.

feat(live-links): scrypt control password and the controller/unlimited record

review1ab2c7da4e2e
diff --git a/src/core/watch-link/password.test.ts b/src/core/watch-link/password.test.ts
new file mode 100644
index 000000000..a38b0926f
--- /dev/null
+++ b/src/core/watch-link/password.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest'
+import { hashControlPassword, verifyControlPassword, SCRYPT } from './password'
+
+describe('control password hash', () => {
+ it('verifies the right password and refuses a wrong one', async () => {
+ const h = await hashControlPassword('correct horse')
+ expect(Buffer.from(h.salt, 'base64')).toHaveLength(SCRYPT.saltBytes)
+ expect(Buffer.from(h.hash, 'base64')).toHaveLength(SCRYPT.keylen)
+ expect(await verifyControlPassword('correct horse', h)).toBe(true)
+ expect(await verifyControlPassword('correct hors', h)).toBe(false)
+ })
+ it('salts: the same password hashes differently twice', async () => {
+ const [a, b] = await Promise.all([hashControlPassword('x'.repeat(8)), hashControlPassword('x'.repeat(8))])
+ expect(a.salt).not.toBe(b.salt)
+ expect(a.hash).not.toBe(b.hash)
+ })
+ it('answers false, never throws, for a malformed stored hash or a non-string', async () => {
+ expect(await verifyControlPassword('x'.repeat(8), { salt: '!!', hash: 'short' })).toBe(false)
+ expect(await verifyControlPassword(7 as never, await hashControlPassword('x'.repeat(8)))).toBe(false)
+ expect(await verifyControlPassword('x'.repeat(8), null as never)).toBe(false)
+ expect(await verifyControlPassword('x'.repeat(8), { salt: 7, hash: [] } as never)).toBe(false)
+ })
+ it('compares the NFC form: a composed and a decomposed spelling of one password are the same password', async () => {
+ const composed = 'café-päss' // é and ä as single code points (a Mac keyboard)
+ const decomposed = 'café-päss' // the same letters as base + combining mark
+ expect(composed).not.toBe(decomposed)
+ expect(await verifyControlPassword(decomposed, await hashControlPassword(composed))).toBe(true)
+ })
+})
diff --git a/src/core/watch-link/password.ts b/src/core/watch-link/password.ts
new file mode 100644
index 000000000..1258a7583
--- /dev/null
+++ b/src/core/watch-link/password.ts
@@ -0,0 +1,50 @@
+// The Control link password: scrypt (N = 2^15, r = 8, p = 1, a 16-byte random salt, a 32-byte key),
+// stored as {salt, hash} only. The plaintext is never kept, logged or echoed: it lives only for the
+// call that hashes or checks it, which is why there is no "show again" (Change password sets a new one).
+//
+// The password is compared in its NFC form, so the same password typed on a Mac (whose keyboards can
+// produce decomposed letters) and in a browser compares equal.
+//
+// `verifyControlPassword` answers false, never throws: a malformed stored hash (a hand-edited file) or
+// a non-string password (a viewer's cast is untrusted input) is a refused unlock, not an error. The
+// comparison of the derived keys is constant-time.
+import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
+
+export interface ControlPasswordHash {
+ /** base64 */
+ salt: string
+ /** base64 */
+ hash: string
+}
+// maxmem: scrypt needs 128 * N * r bytes = 32 MiB here, which is exactly Node's default ceiling and
+// over it once its own bookkeeping is counted, so the ceiling is raised.
+export const SCRYPT = { N: 32768, r: 8, p: 1, keylen: 32, saltBytes: 16, maxmem: 64 * 1024 * 1024 } as const
+
+function derive(pw: string, salt: Buffer): Promise<Buffer> {
+ return new Promise((resolve, reject) =>
+ scrypt(
+ pw.normalize('NFC'),
+ salt,
+ SCRYPT.keylen,
+ { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p, maxmem: SCRYPT.maxmem },
+ (err, key) => (err ? reject(err) : resolve(key))
+ )
+ )
+}
+
+export async function hashControlPassword(pw: string): Promise<ControlPasswordHash> {
+ const salt = randomBytes(SCRYPT.saltBytes)
+ return { salt: salt.toString('base64'), hash: (await derive(pw, salt)).toString('base64') }
+}
+
+export async function verifyControlPassword(pw: string, h: ControlPasswordHash): Promise<boolean> {
+ try {
+ if (typeof pw !== 'string') return false
+ const salt = Buffer.from(h.salt, 'base64')
+ const want = Buffer.from(h.hash, 'base64')
+ if (salt.length !== SCRYPT.saltBytes || want.length !== SCRYPT.keylen) return false
+ return timingSafeEqual(await derive(pw, salt), want)
+ } catch {
+ return false
+ }
+}
diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.ts
index e50c01840..0cc4aa0c8 100644
--- a/src/core/watch-link/service.test.ts
+++ b/src/core/watch-link/service.test.ts
@@ -580,6 +580,55 @@ describe('createWatchLinkService — ending a link', () => {
})
})
+// An Unlimited link's record has `expiresAt: null`: no expiry timer, never swept or ended for time.
+// (Creating one is Task 6's; these resume it from the store, which is where a null first appears.)
+describe('createWatchLinkService — a link with no expiry (expiresAt: null)', () => {
+ const ended = (t: ReturnType<typeof service>) => t.notices().filter((n) => n.kind === 'ended')
+
+ it('is resumed at launch and never pruned for time, however late the clock reads', async () => {
+ const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
+ const t = service({ store: f.store, now: () => Number.MAX_SAFE_INTEGER })
+ await t.s.init()
+ expect(t.s.list().map((l) => [l.linkId, l.expiresAt])).toEqual([['Good000000000000000000', null]])
+ expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Good000000000000000000'])
+ expect(f.saves).toEqual([]) // nothing was pruned, so nothing is written
+ })
+
+ it('arms no expiry timer: still listed and hosted after any amount of time', async () => {
+ vi.useFakeTimers()
+ const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
+ const t = service({ store: f.store })
+ await t.s.init()
+ expect(vi.getTimerCount()).toBe(0)
+ await vi.advanceTimersByTimeAsync(400 * 24 * HOUR)
+ expect(t.s.list()).toHaveLength(1)
+ expect(t.hosts.made[0].stopped).toEqual([])
+ expect(ended(t)).toEqual([])
+ })
+
+ it('a host change never ends it as expired (the G24 check has no end time to compare)', async () => {
+ let clock = 1_000_000
+ const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
+ const t = service({ store: f.store, now: () => clock })
+ await t.s.init()
+ clock = Number.MAX_SAFE_INTEGER
+ t.hosts.made[0].deps.onChange()
+ await flush()
+ expect(t.s.list()).toHaveLength(1)
+ expect(t.hosts.made[0].stopped).toEqual([])
+ expect(ended(t)).toEqual([])
+ })
+
+ it('still ends for every other reason (a revoke)', async () => {
+ const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
+ const t = service({ store: f.store })
+ await t.s.init()
+ await t.s.revoke('Good000000000000000000')
+ expect(t.s.list()).toEqual([])
+ expect(t.hosts.made[0].stopped).toEqual(['revoked'])
+ })
+})
+
describe('createWatchLinkService — init (resume at launch)', () => {
it('resumes live and UNKNOWN records, drops expired ones, and revokes only an ABSENT one', async () => {
const t = service({ nodes: new Map([['n1', 'present'], ['maybe', 'unknown']]) })
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
index d1f449f7e..69509b016 100644
--- a/src/core/watch-link/service.ts
+++ b/src/core/watch-link/service.ts
@@ -357,13 +357,16 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
function armExpiry(r: WatchLinkRecord): void {
const t = expiry.get(r.linkId)
if (t !== undefined) clearT(t)
- const delay = Math.min(MAX_DELAY_MS, Math.max(0, r.expiresAt - now()))
+ expiry.delete(r.linkId)
+ const at = r.expiresAt
+ if (at === null) return // an Unlimited link: no end time, no timer
+ const delay = Math.min(MAX_DELAY_MS, Math.max(0, at - now()))
expiry.set(
r.linkId,
setT(() => {
expiry.delete(r.linkId)
if (records.get(r.linkId) !== r) return
- if (now() < r.expiresAt) armExpiry(r) // a clamped delay: not yet
+ if (now() < at) armExpiry(r) // a clamped delay: not yet
else end(r.linkId, 'expired', { serverRevoke: false, notify: true })
}, delay)
)
@@ -390,7 +393,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
function onHostChange(linkId: string): void {
const r = records.get(linkId)
- if (r && now() >= r.expiresAt) {
+ if (r && r.expiresAt !== null && now() >= r.expiresAt) {
// A reconnect after a lid-close: the expiry timer may not have fired yet (G24). Deferred: this
// runs inside the link host's own status callback, and ending the link stops that host.
queueMicrotask(() => end(linkId, 'expired', { serverRevoke: false, notify: true }))
@@ -507,7 +510,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
let pruned = false
for (const r of loaded) {
if (records.has(r.linkId)) continue
- if (r.expiresAt <= t) {
+ if (r.expiresAt !== null && r.expiresAt <= t) {
pruned = true
continue
}
diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.ts
index 0e9a4e511..798954af0 100644
--- a/src/core/watch-link/store.test.ts
+++ b/src/core/watch-link/store.test.ts
@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto'
import { testTmpDir } from '../test-tmp'
import { renameAtomic, writeFileAtomic } from '../fs-atomic'
import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord } from './store'
+import { hashControlPassword } from './password'
// Pass-through spies, so a test can hold one write open (ordering), fail one (chain recovery,
// set-aside failure) or count them (a latched store must not write at all).
@@ -520,3 +521,151 @@ describe('a keychain that stops sealing mid-run (R45)', () => {
expect(seals).toBe(2)
})
})
+
+// A Control link's record carries `control` (the password's scrypt hash and the lock), and an
+// Unlimited link's `expiresAt` is null. `control` is present IFF the role is 'controller': a
+// hand-edited file cannot give a viewer link a password, and a controller link without one is dropped.
+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 }
+ 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 () => {
+ for (const opts of [{ seal, unseal }, {}]) {
+ const f = file()
+ expect(await new WatchLinkStore({ file: f, ...opts }).save([ctl()])).toBe('saved')
+ 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 } })
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([locked])).toBe('saved')
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([locked])
+ })
+
+ it('drops a controller entry without control, and a viewer or commenter entry that carries one', async () => {
+ const f = file()
+ writeLinks(f, [
+ rawEntry({ linkId: 'NoControlIjKlMnOpQrStU', role: 'controller' }),
+ rawEntry({ linkId: 'NullControlKlMnOpQrStU', role: 'controller', control: null }),
+ rawEntry({ linkId: 'ViewerPwdhIjKlMnOpQrSt', role: 'viewer', control }),
+ rawEntry({ linkId: 'CommentPwdIjKlMnOpQrSt', role: 'commenter', control }),
+ rawEntry({ linkId: 'ViewerNullIjKlMnOpQrSt', role: 'viewer', control: null }),
+ rawEntry({ role: 'controller', control, expiresAt: null })
+ ])
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl()])
+ })
+
+ it('drops a controller entry whose control is malformed', async () => {
+ const id = (i: number) => `Bad${String(i).padStart(19, '0')}`
+ const bad: unknown[] = [
+ 'x',
+ [],
+ 7,
+ { ...control, salt: b64(new Uint8Array(15).fill(1)) },
+ { ...control, salt: b64(new Uint8Array(17).fill(1)) },
+ { ...control, hash: b64(new Uint8Array(31).fill(2)) },
+ { ...control, hash: b64(new Uint8Array(33).fill(2)) },
+ // Node's base64 decoder skips characters it does not know: only canonical text is accepted.
+ { ...control, salt: `!${SALT}` },
+ { ...control, hash: `${HASH.slice(0, 20)}*${HASH.slice(20)}` },
+ { ...control, salt: SALT.replace(/=+$/, '') },
+ { ...control, salt: 7 },
+ { ...control, hash: null },
+ { enabled: true, salt: SALT, locked: false },
+ { ...control, enabled: 'true' },
+ { ...control, enabled: 1 },
+ { ...control, locked: 'false' },
+ { salt: SALT, hash: HASH, locked: false },
+ { enabled: true, salt: SALT, hash: HASH }
+ ]
+ const f = file()
+ writeLinks(f, [...bad.map((c, i) => rawEntry({ linkId: id(i), role: 'controller', control: c, expiresAt: null })), rawEntry()])
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])
+ })
+
+ it('keeps only the four 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 })
+ expect(await s.load()).toEqual([ctl()])
+ expect(await s.save(await s.load())).toBe('saved')
+ expect(readFileSync(f, 'utf8')).not.toContain('hunter22')
+ })
+
+ it('writes only the four 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')
+ expect(readFileSync(f, 'utf8')).not.toContain('hunter22')
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([ctl()])
+ })
+
+ 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 } })
+ for (const opts of [{ seal, unseal }, {}]) {
+ const f = file()
+ expect(await new WatchLinkStore({ file: f, ...opts }).save([r])).toBe('saved')
+ const text = readFileSync(f, 'utf8')
+ expect(text).not.toContain(password)
+ expect(text).not.toContain(Buffer.from(password).toString('base64'))
+ expect(text).not.toContain(Buffer.from(password).toString('hex'))
+ expect(text).toContain(h.hash)
+ expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([r])
+ }
+ })
+
+ it('loads expiresAt: null and drops an entry whose expiresAt is neither null nor a finite number', async () => {
+ const f = file()
+ writeLinks(f, [
+ rawEntry({ linkId: 'StrExpiryIjKlMnOpQrStU', expiresAt: 'x' }),
+ rawEntry({ linkId: 'NoExpiryhIjKlMnOpQrStU', expiresAt: undefined }),
+ rawEntry({ linkId: 'ObjExpiryIjKlMnOpQrStU', expiresAt: {} }),
+ rawEntry({ expiresAt: null })
+ ])
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec({ expiresAt: null })])
+ })
+
+ describe('an opaque entry (keychain refused) with no expiry', () => {
+ const locked = () => {
+ throw new Error('keychain locked')
+ }
+ const timed = rec({ linkId: 'TimedLinkjKlMnOpQrStUv', label: 'Bob' })
+
+ it('is carried on every write and counted, however late it gets; a timed one is still dropped past its expiry', async () => {
+ const f = file()
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([ctl(), timed])).toBe('saved')
+ const onDisk = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]
+ const unlimited = onDisk.find((e) => e.linkId === ctl().linkId)
+ expect(unlimited).toMatchObject({ expiresAt: null, role: 'controller', control })
+ let t = EXPIRES_AT - 1
+ const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })
+ expect(await s.load()).toEqual([])
+ expect(s.opaqueCount()).toBe(2)
+ expect(await s.save([])).toBe('saved')
+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual(onDisk)
+ t = EXPIRES_AT + 10 * 365 * 24 * 3600_000 // years later: the timed one is gone, the unlimited one is not
+ expect(s.opaqueCount()).toBe(1)
+ expect(await s.save([])).toBe('saved')
+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([unlimited])
+ expect(await s.save([])).toBe('saved')
+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([unlimited])
+ // The keychain answers again: the link comes back whole, control included.
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([ctl()])
+ })
+
+ it('is still dropped by discardOpaque() ("Stop all")', async () => {
+ const f = file()
+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([ctl()])).toBe('saved')
+ const s = new WatchLinkStore({ file: f, seal, unseal: locked })
+ expect(await s.load()).toEqual([])
+ expect(s.opaqueCount()).toBe(1)
+ s.discardOpaque()
+ expect(s.opaqueCount()).toBe(0)
+ expect(await s.save([])).toBe('saved')
+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
+ })
+ })
+})
diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.ts
index 73d247646..d890c62ba 100644
--- a/src/core/watch-link/store.ts
+++ b/src/core/watch-link/store.ts
@@ -37,6 +37,16 @@
// every secret it read or sealed this run and reuses it on every write (it never re-seals), so when
// `seal` starts throwing only a link it NEVER sealed is left out (reported 'memory-only'); links read
// 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), and whether wrong attempts locked it. 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
+// controller link with no password is not a link this build can host.
+//
+// AN UNLIMITED LINK has `expiresAt: null`: it lives until it is stopped. An opaque one is carried
+// until it is discarded, never dropped for time.
import { promises as fs } from 'node:fs'
import { createHash } from 'node:crypto'
import { renameAtomic, writeFileAtomic } from '../fs-atomic'
@@ -44,6 +54,14 @@ import { LINK_ID_RE } from '../../shared/watch-link/link'
import type { WatchLinkRole } from '../../shared/watch-link/protocol'
import { isSafeNodeId } from '../../shared/safe-id'
+/** A Control link's typing state. The salt and hash are base64 (16 and 32 bytes). */
+export interface WatchLinkControlRecord {
+ enabled: boolean
+ salt: string
+ hash: string
+ locked: boolean
+}
+
export interface WatchLinkRecord {
linkId: string
nodeId: string
@@ -51,8 +69,11 @@ export interface WatchLinkRecord {
label: string
title: string
createdAt: number
- expiresAt: number
+ /** Epoch ms; `null` for an Unlimited link (no end time). */
+ expiresAt: number | null
secret: Uint8Array
+ /** Present IFF `role === 'controller'`. */
+ control?: WatchLinkControlRecord
}
export type SaveOutcome = 'saved' | 'memory-only' | 'failed'
@@ -85,7 +106,8 @@ interface FileEntry {
label: string
title: string
createdAt: number
- expiresAt: number
+ expiresAt: number | null
+ control?: WatchLinkControlRecord
secret: string
sealed: boolean
}
@@ -95,10 +117,14 @@ export const MAX_FILE_BYTES = 1024 * 1024
/** Entries past this are dropped on read. */
export const MAX_ENTRIES = 200
const SECRET_BYTES = 32
+const CONTROL_SALT_BYTES = 16
+const CONTROL_HASH_BYTES = 32
const noop = (): void => {}
const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= max
const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
+/** An expiry that has not passed at `t`: never one of an Unlimited link (`null`). */
+const live = (expiresAt: number | null, t: number): boolean => expiresAt === null || expiresAt > t
const codeOf = (e: unknown): string =>
typeof e === 'object' && e && 'code' in e ? String((e as { code: unknown }).code) : ''
@@ -111,6 +137,22 @@ function decodeSecret(text: string): Uint8Array | null {
return new Uint8Array(bytes)
}
+/** Canonical base64 of exactly `bytes` bytes (the same rule as `decodeSecret`). */
+function isB64Of(v: unknown, bytes: number): v is string {
+ if (typeof v !== 'string' || v.length > 64) return false
+ const b = Buffer.from(v, 'base64')
+ return b.length === bytes && b.toString('base64') === v
+}
+
+/** A Control link's `control`, rebuilt from its four fields (nothing else is carried), or null. */
+function readControl(v: unknown): WatchLinkControlRecord | null {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return null
+ const { enabled, salt, hash, locked } = 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
+ return { enabled, salt, hash, locked }
+}
+
export class WatchLinkStore {
/** The previous load or write, settled either way: the next one starts only after it. */
private writing: Promise<void> = Promise.resolve()
@@ -144,7 +186,7 @@ export class WatchLinkStore {
* keychain could create five more and the next launch would find ten. */
opaqueCount(): number {
const t = (this.o.now ?? Date.now)()
- return this.opaque.filter((e) => e.expiresAt > t).length
+ return this.opaque.filter((e) => live(e.expiresAt, t)).length
}
load(): Promise<WatchLinkRecord[]> {
@@ -193,20 +235,29 @@ export class WatchLinkStore {
if (!e || !str(e.linkId, 22) || !LINK_ID_RE.test(e.linkId)) continue
// `isSafeNodeId` does not check the type: `12` and `["n1"]` pass its regex by coercion.
if (typeof e.nodeId !== 'string' || !isSafeNodeId(e.nodeId)) continue
- if (e.role !== 'viewer' && e.role !== 'commenter') continue
- if (!str(e.label, 40) || !str(e.title, 80) || !num(e.createdAt) || !num(e.expiresAt) || typeof e.secret !== 'string') continue
+ if (e.role !== 'viewer' && e.role !== 'commenter' && e.role !== 'controller') continue
+ // `control` exactly when the role is 'controller', and then well-formed.
+ let control: WatchLinkControlRecord | null = null
+ if (e.role === 'controller') {
+ control = readControl(e.control)
+ if (!control) continue
+ } else if (e.control !== undefined) continue
+ if (!str(e.label, 40) || !str(e.title, 80) || !num(e.createdAt) || typeof e.secret !== 'string') continue
+ if (e.expiresAt !== null && !num(e.expiresAt)) continue
+ const expiresAt: number | null = e.expiresAt
+ const extra = control ? { control } : {}
const sealed = e.sealed === true
const secret = this.readSecret(e.secret, sealed)
if (secret === 'refused') {
opaque.push({
linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title,
- createdAt: e.createdAt, expiresAt: e.expiresAt, secret: e.secret, sealed: true
+ createdAt: e.createdAt, expiresAt, ...extra, secret: e.secret, sealed: true
})
continue
}
if (!secret) continue
if (sealed) sealedForms.set(e.linkId, { digest: digestOf(secret), sealed: e.secret })
- out.push({ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt: e.expiresAt, secret })
+ out.push({ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt, secret, ...extra })
}
this.opaque = opaque
this.sealedForms = sealedForms
@@ -244,12 +295,12 @@ export class WatchLinkStore {
return this.o.seal ? null : decodeSecret(stored)
}
- /** The opaque entries this write carries: none past its own expiry (dropped for good), none a live
- * record replaces. */
- private carriedOpaque(live: readonly FileEntry[]): FileEntry[] {
+ /** The opaque entries this write carries: none past its own expiry (dropped for good; an Unlimited
+ * one has none), none a live record replaces. */
+ private carriedOpaque(written: readonly FileEntry[]): FileEntry[] {
const t = (this.o.now ?? Date.now)()
- this.opaque = this.opaque.filter((e) => e.expiresAt > t)
- const ids = new Set(live.map((e) => e.linkId))
+ this.opaque = this.opaque.filter((e) => live(e.expiresAt, t))
+ const ids = new Set(written.map((e) => e.linkId))
return this.opaque.filter((e) => !ids.has(e.linkId))
}
@@ -281,9 +332,12 @@ export class WatchLinkStore {
}
sealedNext.set(r.linkId, { digest, sealed: secret })
}
+ // Only the four control fields are written: nothing else that rides on the object reaches disk.
+ const c = r.control
+ const control = c ? { control: { enabled: c.enabled, salt: c.salt, hash: c.hash, locked: c.locked } } : {}
links.push({
linkId: r.linkId, nodeId: r.nodeId, role: r.role, label: r.label, title: r.title,
- createdAt: r.createdAt, expiresAt: r.expiresAt, secret, sealed: !!this.o.seal
+ createdAt: r.createdAt, expiresAt: r.expiresAt, ...control, secret, sealed: !!this.o.seal
})
}
} catch {