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.

20.5 KB
Raw Blame

Live link Control — Plan 1 of 3: Backend (nodeterm-server) Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Let a live link be created with no end time (ttlSeconds: 0 → expiresAt: null), and stop an unlimited link from outliving its owner's Pro by more than a day.

Architecture: A migration makes watch_links.expires_at nullable. Every query and rule that reads expires_at learns that NULL means "live until stopped". The host-token route, which already runs for every listener the desktop opens, checks the license's liveness for an unlimited link at most once per 24 h per license (in memory), reusing the create route's licenseLiveness.

Tech Stack: Hono 4.12, zod, drizzle-orm 0.36 + drizzle-kit (Postgres; pglite in tests), vitest 2.1, Node crypto.

Spec: /root/nodeterm/wtshare/docs/superpowers/specs/2026-10-03-live-link-control-design.md §3 and §8. Base spec: /root/nodeterm/wtshare/docs/superpowers/specs/2026-09-28-live-share-link-design.md.

Plans in this series: 1 = this (backend), 2 = 2026-10-03-live-link-control-2-desktop.md, 3 = 2026-10-03-live-link-control-3-web.md. This plan merges and deploys FIRST: an old desktop never sends 0, and an old backend answers 0 with 400 bad_ttl, which the new desktop shows as "Unlimited links need a newer server".

Repo: /root/nodeterm-server-watch is a worktree of eneskirca/nodeterm-server. Create a NEW branch feat/watch-links-unlimited from origin/main (currently a4f7d9c; the local main there is behind — do not base on it). Never push main.

Global Constraints

  • Wire value for Unlimited: ttlSeconds: 0. The create response then carries "expiresAt": null (JSON null, not absent, not 0).
  • ttlSeconds: 0 is granted only when no WATCH_LINK_MAX_TTL_SECONDS cap is configured (deps.maxTtlSeconds undefined or ≤ 0). With a cap configured it is clamped to the largest allowed standard length, exactly like an over-cap request.
  • The standard lengths stay {900, 3600, 28800, 86400}; any other value (negative, fractional, 1) is still 400 bad_ttl / bad_request as today.
  • NULL expires_at = live, everywhere: linkState, the per-license active count, revoke-all, status, host-token, join.
  • The 7-day purge never deletes a NULL row (expires_at < x is false for NULL; a test pins it).
  • Unlimited host-token liveness: live cached 24 h per license; unknown (keygen unreachable) allows the mint and is cached 10 min; dead answers 402 {"error":"not_entitled"} and is never cached. Finite links keep the rule that a host-token mint never calls keygen.
  • Never log tokens, entitlements, license ids or bodies.

Review Focus

  1. A row created by the old code path (non-null expires_at) after the migration → behaves exactly as before; the migration must not touch existing rows.
  2. Revoke-all with a mix of finite, expired and unlimited rows → finite live and unlimited rows are stopped; expired rows keep reporting expired (their revoked_at stays NULL).
  3. A keygen outage while an unlimited link reconnects → host-token answers 200 (fail open, the spec's choice) and keygen is not asked again for 10 minutes even if the desktop reconnects many times.
  4. An entitlement without a string deviceId on an unlimited host-token → 402, never a keygen call with undefined.
  5. Two licenses sharing the cache → a live verdict for license A never answers for license B.

File Structure

  • Modify src/db/schema.ts — watchLinks.expiresAt loses .notNull().
  • Create src/db/migrations/0017_<generated>.sql + meta/0017_snapshot.json + _journal.json entry, generated by npx drizzle-kit generate (never hand-write the snapshot).
  • Modify src/routes/watch-links.ts — grant rule, linkState, active count, revoke-all, create response, unlimited liveness on host-token, an injectable clock.
  • Modify test/watch-links.test.ts — new cases (same file, same helpers).

Task 1: Unlimited links (nullable expiry, grant rule, null-aware queries)

Files:

  • Modify: src/db/schema.ts (the watchLinks table, expiresAt line)
  • Create: src/db/migrations/0017_*.sql, src/db/migrations/meta/0017_snapshot.json (generated), src/db/migrations/meta/_journal.json (generated entry)
  • Modify: src/routes/watch-links.ts
  • Test: test/watch-links.test.ts

Interfaces:

  • Consumes: nothing new.

  • Produces: linkState(row: Pick<LinkRow,'revokedAt'|'expiresAt'>, nowMs?) accepting expiresAt: Date | null; POST /v1/watch-links answering { linkId, expiresAt: number | null }; export const UNLIMITED_TTL = 0.

  • Step 1: Write the failing tests (append to test/watch-links.test.ts; reuse appWith, create, post, ent, joinKeyHash, makeTestDb, watchLinks, eq already imported there; add sql from drizzle-orm if you use it)

describe('unlimited links', () => {
  it('linkState treats a NULL expiry as live and still honours revocation', () => {
    expect(linkState({ revokedAt: null, expiresAt: null })).toBe('live')
    expect(linkState({ revokedAt: new Date(), expiresAt: null })).toBe('revoked')
  })

  it('grants ttlSeconds 0 with no cap configured and answers expiresAt null', async () => {
    const { app, db } = await appWith()
    const res = await create(app, { ttlSeconds: 0 })
    expect(res.status).toBe(200)
    const body = (await res.json()) as { linkId: string; expiresAt: number | null }
    expect(body.expiresAt).toBeNull()
    expect(Object.prototype.hasOwnProperty.call(body, 'expiresAt')).toBe(true)
    const rows = await db.select().from(watchLinks).where(eq(watchLinks.id, body.linkId))
    expect(rows[0].expiresAt).toBeNull()
  })

  it('clamps ttlSeconds 0 to the largest allowed length when a cap is configured', async () => {
    for (const [cap, granted] of [[3600, 3600], [86400, 86400], [30000, 28800]] as const) {
      const { app } = await appWith({}, { maxTtlSeconds: cap })
      const before = Math.floor(Date.now() / 1000)
      const res = await create(app, { ttlSeconds: 0 })
      expect(res.status).toBe(200)
      const body = (await res.json()) as { expiresAt: number }
      expect(body.expiresAt).toBeGreaterThanOrEqual(before + granted)
      expect(body.expiresAt).toBeLessThanOrEqual(before + granted + 1)
    }
  })

  it('still refuses a non-standard length', async () => {
    const { app } = await appWith()
    for (const ttlSeconds of [-1, 1, 7200]) {
      const res = await create(app, { ttlSeconds })
      expect(res.status).toBe(400)
      expect(await res.json()).toEqual({ error: 'bad_ttl' })
    }
  })

  it('counts unlimited rows toward the active-links cap', async () => {
    const { app } = await appWith()
    for (let i = 0; i < 15; i++) expect((await create(app, { ttlSeconds: 0 })).status).toBe(200)
    const res = await create(app, { ttlSeconds: 0 })
    expect(res.status).toBe(429)
    expect(await res.json()).toEqual({ error: 'rate_limited', scope: 'active_links' })
  })

  it('never purges an unlimited row, however old', async () => {
    const { app, db } = await appWith()
    const old = 'U'.repeat(22)
    await db.insert(watchLinks).values({
      id: old, licenseId: 'lic-1', joinKeyHash, expiresAt: null,
      createdAt: new Date(Date.now() - 30 * 24 * 3600_000)
    })
    expect((await create(app)).status).toBe(200) // a create runs the purge
    const rows = await db.select().from(watchLinks).where(eq(watchLinks.id, old))
    expect(rows).toHaveLength(1)
  })

  it('answers status live, joins, and is stopped by revoke and revoke-all', async () => {
    const { app, db } = await appWith()
    const { linkId } = (await (await create(app, { ttlSeconds: 0 })).json()) as { linkId: string }
    const status = await app.request(post(`/v1/watch-links/${linkId}/status`, { entitlement: ent() }))
    expect(await status.json()).toEqual({ state: 'live' })
    const join = await app.request(post(`/v1/watch-links/${linkId}/join`, { joinKey: joinKeyB64 }))
    expect(join.status).toBe(200)
    expect((await app.request(post('/v1/watch-links/revoke-all', { entitlement: ent() }))).status).toBe(204)
    const rows = await db.select().from(watchLinks).where(eq(watchLinks.id, linkId))
    expect(rows[0].revokedAt).toBeInstanceOf(Date)
  })

  it('revoke-all leaves an expired row reporting expired', async () => {
    const { app, db } = await appWith()
    const expired = 'E'.repeat(22)
    await db.insert(watchLinks).values({ id: expired, licenseId: 'lic-1', joinKeyHash, expiresAt: new Date(Date.now() - 1000) })
    await app.request(post('/v1/watch-links/revoke-all', { entitlement: ent() }))
    const rows = await db.select().from(watchLinks).where(eq(watchLinks.id, expired))
    expect(rows[0].revokedAt).toBeNull()
  })
})

Also update the existing watch_links table test so it still passes (it inserts a non-null expiresAt; leave it).

  • Step 2: Run the tests to verify they fail

Run: cd /root/nodeterm-server-watch && npx vitest run test/watch-links.test.ts -t "unlimited links" Expected: FAIL — the insert with expiresAt: null violates NOT NULL / TypeScript complains, and ttlSeconds: 0 answers bad_ttl.

  • Step 3: Make the column nullable and generate the migration

In src/db/schema.ts change the line to:

    expiresAt: timestamp('expires_at', { withTimezone: true }),

Then run npx drizzle-kit generate (offline; it diffs against meta/0016_snapshot.json). Check the generated SQL is exactly one statement:

ALTER TABLE "watch_links" ALTER COLUMN "expires_at" DROP NOT NULL;

If drizzle-kit asks an interactive question or emits anything else, stop and report — do not hand-edit snapshots. Keep the generated file name.

  • Step 4: Teach the route

In src/routes/watch-links.ts:

import { and, eq, gt, isNull, lt, or } from 'drizzle-orm'
...
export const WATCH_LINK_TTLS = [900, 3600, 28800, 86400] as const
/** The wire value for "no end time": the link lives until it is stopped. */
export const UNLIMITED_TTL = 0

export function linkState(row: Pick<LinkRow, 'revokedAt' | 'expiresAt'>, nowMs: number = Date.now()): LinkState {
  if (row.revokedAt) return 'revoked'
  // NULL = no end time. Expiry is inclusive: a link whose instant has come is over.
  if (row.expiresAt !== null && row.expiresAt.getTime() <= nowMs) return 'expired'
  return 'live'
}

Inside registerWatchLinks:

  const capConfigured = typeof deps.maxTtlSeconds === 'number' && deps.maxTtlSeconds > 0
  const maxTtl = capConfigured ? (deps.maxTtlSeconds as number) : 86400
  const allowedTtls: readonly number[] = WATCH_LINK_TTLS.filter((t) => t <= maxTtl)

  /** Seconds granted, `null` for "no end time", or `undefined` to refuse. */
  function grantedTtl(requested: number): number | null | undefined {
    if (requested === UNLIMITED_TTL) {
      if (!capConfigured) return null
      return allowedTtls.length === 0 ? undefined : Math.max(...allowedTtls)
    }
    if (!(WATCH_LINK_TTLS as readonly number[]).includes(requested)) return undefined
    if (allowedTtls.length === 0) return undefined
    return requested <= maxTtl ? requested : Math.max(...allowedTtls)
  }

  /** A row that is not over by time: no end time, or one still ahead. */
  const notExpired = (at: Date) => or(isNull(watchLinks.expiresAt), gt(watchLinks.expiresAt, at))

In the create handler: if (ttlSeconds === undefined) return c.json({ error: 'bad_ttl' }, 400); the active count uses and(eq(licenseId), isNull(revokedAt), notExpired(new Date(nowMs))); the insert and response become:

    const expiresAt = ttlSeconds === null ? null : new Date(nowMs + ttlSeconds * 1000)
    await db.insert(watchLinks).values({ id, licenseId: ent.licenseId, joinKeyHash, expiresAt })
    return c.json({ linkId: id, expiresAt: expiresAt === null ? null : Math.floor(expiresAt.getTime() / 1000) })

Revoke-all's where clause becomes and(eq(watchLinks.licenseId, ent.licenseId), isNull(watchLinks.revokedAt), notExpired(now)). Leave the purge (lt(watchLinks.expiresAt, …)) as it is — NULL never compares less, which the purge test pins. Update the file header's "Who may do what" comment: a link may have no end time; it lives until stopped.

  • Step 5: Run the whole file, then the whole suite and typecheck

Run: npx vitest run test/watch-links.test.ts && npm test && npx tsc --noEmit Expected: all PASS. If npx tsc --noEmit is not the repo's typecheck, use the script in package.json.

  • Step 6: Commit
git add src/db/schema.ts src/db/migrations src/routes/watch-links.ts test/watch-links.test.ts
git commit -m "feat(watch-links): unlimited links (ttlSeconds 0, nullable expires_at)"

Task 2: An unlimited link stops within a day of a lapsed Pro

Files:

  • Modify: src/routes/watch-links.ts (WatchLinkDeps, asOwner, the host-token route, a liveness cache)
  • Test: test/watch-links.test.ts

Interfaces:

  • Consumes: licenseLiveness(ent) (existing, inside registerWatchLinks), Task 1's nullable expiresAt.

  • Produces: WatchLinkDeps.now?: () => number (test seam; default Date.now); exported constants UNLIMITED_LIVENESS_LIVE_MS = 24 * 60 * 60_000 and UNLIMITED_LIVENESS_UNKNOWN_MS = 10 * 60_000.

  • Step 1: Write the failing tests

describe('unlimited host-token and Pro lapse', () => {
  async function unlimitedApp(over: Partial<KeygenClient>, now: { t: number }) {
    const calls: string[] = []
    const keygen: Partial<KeygenClient> = {
      ...over,
      validateLicense: async (id, fp) => {
        calls.push(`${id}/${fp}`)
        return over.validateLicense ? over.validateLicense(id, fp) : { valid: true }
      }
    }
    const { db } = await makeTestDb()
    const app = new Hono()
    registerWatchLinks(app, db, {
      entitlementPublicKey: publicKey,
      pairing: createPairingToken(privateKey),
      relayEndpoint: 'wss://relay.test',
      keygen: fakeKeygen(keygen),
      ipLimitPerMinute: 10_000,
      now: () => now.t
    })
    const { linkId } = (await (await create(app, { ttlSeconds: 0 })).json()) as { linkId: string }
    calls.length = 0 // the create's own validation is not what is measured here
    const mint = () => app.request(post(`/v1/watch-links/${linkId}/host-token`, { entitlement: ent() }))
    return { app, db, linkId, calls, mint }
  }

  it('asks keygen once per 24 h for an unlimited link', async () => {
    const now = { t: Date.now() }
    const { calls, mint } = await unlimitedApp({}, now)
    expect((await mint()).status).toBe(200)
    expect((await mint()).status).toBe(200)
    expect(calls).toHaveLength(1)
    now.t += 24 * 60 * 60_000 + 1
    expect((await mint()).status).toBe(200)
    expect(calls).toHaveLength(2)
  })

  it('refuses the mint with 402 when the license is no longer live, and never caches that', async () => {
    const now = { t: Date.now() }
    let valid = true
    const { calls, mint } = await unlimitedApp({ validateLicense: async () => (valid ? { valid: true } : { valid: false, code: 'EXPIRED' }) }, now)
    expect((await mint()).status).toBe(200)
    valid = false
    now.t += 24 * 60 * 60_000 + 1
    const res = await mint()
    expect(res.status).toBe(402)
    expect(await res.json()).toEqual({ error: 'not_entitled' })
    valid = true
    expect((await mint()).status).toBe(200) // a renewed license is not locked out by a cached "dead"
    expect(calls).toHaveLength(3)
  })

  it('allows the mint while keygen is unreachable and re-asks after 10 minutes', async () => {
    const now = { t: Date.now() }
    const { calls, mint } = await unlimitedApp({ validateLicense: async () => { throw new Error('down') } }, now)
    expect((await mint()).status).toBe(200)
    expect((await mint()).status).toBe(200)
    expect(calls).toHaveLength(1)
    now.t += 10 * 60_000 + 1
    expect((await mint()).status).toBe(200)
    expect(calls).toHaveLength(2)
  })

  it('never calls keygen for a finite link (unchanged rule)', async () => {
    const calls: string[] = []
    const { app } = await appWith({ validateLicense: async (id, fp) => { calls.push(`${id}/${fp}`); return { valid: true } } })
    const { linkId } = (await (await create(app)).json()) as { linkId: string }
    calls.length = 0
    expect((await app.request(post(`/v1/watch-links/${linkId}/host-token`, { entitlement: ent() }))).status).toBe(200)
    expect(calls).toEqual([])
  })

  it('keeps the verdict per license', async () => {
    const now = { t: Date.now() }
    const { app, calls, mint } = await unlimitedApp({}, now)
    expect((await mint()).status).toBe(200)
    // a second license with its own unlimited link must be asked about separately
    const other = (await (await app.request(post('/v1/watch-links', { entitlement: ent('lic-2'), joinKeyHash, ttlSeconds: 0 }))).json()) as { linkId: string }
    calls.length = 0
    expect((await app.request(post(`/v1/watch-links/${other.linkId}/host-token`, { entitlement: ent('lic-2') }))).status).toBe(200)
    expect(calls).toEqual(['lic-2/mac-a'])
  })

  it('refuses an entitlement without a device id with 402 and no keygen call', async () => {
    const now = { t: Date.now() }
    const { linkId, calls, app } = await unlimitedApp({}, now)
    const noDevice = entitlement.sign({ tier: 'pro', licenseId: 'lic-1', ttlSeconds: 3600 } as never)
    const res = await app.request(post(`/v1/watch-links/${linkId}/host-token`, { entitlement: noDevice }))
    expect(res.status).toBe(402)
    expect(calls).toEqual([])
  })
})

If entitlement.sign rejects a payload without deviceId at the type or runtime level, build that token the way the existing tests build a malformed one, or drop that one case and say so in the report — do not weaken the production check.

  • Step 2: Run to verify they fail

Run: npx vitest run test/watch-links.test.ts -t "Pro lapse" Expected: FAIL — now is not a dep, and the host-token route never asks keygen.

  • Step 3: Implement

In WatchLinkDeps add:

  /** Test seam for the liveness cache; defaults to Date.now. */
  now?: () => number

Inside registerWatchLinks:

  const now = deps.now ?? Date.now
  /** licenseId → the last liveness verdict that may stand in for a fresh one, and when it was taken. */
  const unlimitedLiveness = new Map<string, { verdict: 'live' | 'unknown'; at: number }>()
  async function unlimitedMayMint(ent: EntitlementPayload): Promise<boolean> {
    if (typeof ent.deviceId !== 'string') return false
    const hit = unlimitedLiveness.get(ent.licenseId)
    const t = now()
    if (hit) {
      const ttl = hit.verdict === 'live' ? UNLIMITED_LIVENESS_LIVE_MS : UNLIMITED_LIVENESS_UNKNOWN_MS
      if (t - hit.at < ttl) return true
    }
    const verdict = await licenseLiveness(ent)
    if (verdict === 'dead') {
      unlimitedLiveness.delete(ent.licenseId)
      return false
    }
    unlimitedLiveness.set(ent.licenseId, { verdict, at: t })
    return true
  }

Bound the map so a stream of forged licenses cannot grow it: before set, when unlimitedLiveness.size >= 10_000, delete the oldest key (unlimitedLiveness.keys().next().value). (Only a holder of a validly signed entitlement reaches this code, so the bound is belt and braces.)

Make asOwner return the verified entitlement as well: { ok: true; row: LinkRow; ent: EntitlementPayload }. In the host-token route, after the state !== 'live' check and BEFORE the per-link rate window:

    if (who.row.expiresAt === null && !(await unlimitedMayMint(who.ent))) {
      return c.json({ error: 'not_entitled' }, 402)
    }

Use now() (not Date.now()) for linkState(who.row, now()) in this route so the test clock is honoured consistently. Leave the other routes on Date.now() unless a test needs otherwise. Update the header comment: host-token for an unlimited link checks liveness at most once per 24 h per license (fail open on an outage, 10 min).

  • Step 4: Run the file, the suite and typecheck

Run: npx vitest run test/watch-links.test.ts && npm test && npx tsc --noEmit Expected: PASS. The existing "host-token never calls keygen" test (finite link) must still pass unchanged.

  • Step 5: Commit
git add src/routes/watch-links.ts test/watch-links.test.ts
git commit -m "feat(watch-links): an unlimited link re-checks the license daily at host-token mint"

After both tasks

Push feat/watch-links-unlimited and open a PR against main (title and body in English, following the pr-writing skill: what changed and why, how it was checked and what was not, deploy note "deploy before the desktop that sends ttlSeconds 0; the migration is one DROP NOT NULL, safe on a live table"). Do not merge; merging and deploying are enes's call.