@pairdraw/mcp 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/dist/connect.d.mts +1 -0
  4. package/dist/connect.mjs +192 -0
  5. package/dist/connect.mjs.map +1 -0
  6. package/dist/discovery-CB2Bv5WA.mjs +167 -0
  7. package/dist/discovery-CB2Bv5WA.mjs.map +1 -0
  8. package/dist/discovery.d.mts +59 -0
  9. package/dist/discovery.mjs +2 -0
  10. package/dist/index.d.mts +1 -0
  11. package/dist/index.mjs +95 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/metadata-DVz00c8R.d.mts +26 -0
  14. package/dist/paths-BpcXnrbP.mjs +168 -0
  15. package/dist/paths-BpcXnrbP.mjs.map +1 -0
  16. package/dist/policy-B8Ka4WRH.mjs +206 -0
  17. package/dist/policy-B8Ka4WRH.mjs.map +1 -0
  18. package/dist/rolldown-runtime-ClRpJifh.mjs +3 -0
  19. package/dist/root-BzmoiT2g.mjs +9 -0
  20. package/dist/root-BzmoiT2g.mjs.map +1 -0
  21. package/dist/scope-D2LTTsDw.mjs +66 -0
  22. package/dist/scope-D2LTTsDw.mjs.map +1 -0
  23. package/dist/scope-DJ9hsBYV.d.mts +31 -0
  24. package/dist/server-BdiJUhSs.mjs +3261 -0
  25. package/dist/server-BdiJUhSs.mjs.map +1 -0
  26. package/dist/server.d.mts +265 -0
  27. package/dist/server.mjs +2 -0
  28. package/dist/stdio.d.mts +1 -0
  29. package/dist/stdio.mjs +411 -0
  30. package/dist/stdio.mjs.map +1 -0
  31. package/dist/tools.d.mts +17 -0
  32. package/dist/tools.mjs +33 -0
  33. package/dist/tools.mjs.map +1 -0
  34. package/dist/transport.d.mts +59 -0
  35. package/dist/transport.mjs +2 -0
  36. package/package.json +78 -4
  37. package/src/agents/acp.ts +110 -0
  38. package/src/agents/claude-cloud.ts +99 -0
  39. package/src/agents/filter.ts +85 -0
  40. package/src/agents/index.ts +299 -0
  41. package/src/agents/install.ts +44 -0
  42. package/src/agents/link.ts +79 -0
  43. package/src/agents/lookup.ts +136 -0
  44. package/src/agents/pairing.ts +182 -0
  45. package/src/agents/path.ts +85 -0
  46. package/src/agents/process.ts +88 -0
  47. package/src/agents/registry.ts +36 -0
  48. package/src/agents/schema.ts +77 -0
  49. package/src/agents/sign-in.ts +106 -0
  50. package/src/agents/socket.ts +79 -0
  51. package/src/auth.ts +21 -0
  52. package/src/browser-rpc.ts +440 -0
  53. package/src/connect.ts +170 -0
  54. package/src/global.d.ts +5 -0
  55. package/src/http-options.ts +14 -0
  56. package/src/index.ts +179 -0
  57. package/src/json.ts +1 -0
  58. package/src/result.ts +37 -0
  59. package/src/root.ts +5 -0
  60. package/src/rpc-types.ts +5 -0
  61. package/src/server/connections.ts +58 -0
  62. package/src/server/files.ts +49 -0
  63. package/src/server/install-command.ts +24 -0
  64. package/src/server/lifecycle.ts +389 -0
  65. package/src/server/origin.ts +53 -0
  66. package/src/server/pending-requests.ts +62 -0
  67. package/src/server/sessions.ts +335 -0
  68. package/src/server.ts +597 -0
  69. package/src/skill/content.ts +40 -0
  70. package/src/skill/instructions.ts +69 -0
  71. package/src/skill/register.ts +77 -0
  72. package/src/stdio/bridge.ts +460 -0
  73. package/src/stdio.ts +130 -0
  74. package/src/tool/browser.ts +183 -0
  75. package/src/tool/index.ts +12 -0
  76. package/src/tool/manifest.ts +221 -0
  77. package/src/tool/metadata.ts +44 -0
  78. package/src/tool/output.ts +336 -0
  79. package/src/tool/policy.ts +37 -0
  80. package/src/tool/registration.ts +523 -0
  81. package/src/tool/scope.ts +71 -0
  82. package/src/transport/discovery.ts +235 -0
  83. package/src/transport/origins.ts +85 -0
  84. package/src/transport/paths.ts +179 -0
@@ -0,0 +1,182 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
2
+
3
+ /** How long a printed link may be opened. */
4
+ export const PAIRING_CODE_TTL_MS = 2 * 60_000
5
+ /** A paired tab that sends nothing this long is signed out; an open tab checks in every 10 s. */
6
+ export const SESSION_IDLE_TIMEOUT_MS = 30 * 60_000
7
+ /** Wrong codes allowed in a window before `/pair` refuses everything until it ends. */
8
+ const MAX_FAILED_ATTEMPTS = 10
9
+ const ATTEMPT_WINDOW_MS = 60_000
10
+ /** Tabs paired at once; the oldest is forgotten when another pairs. */
11
+ const MAX_SESSIONS = 16
12
+
13
+ type PairingResult =
14
+ | { ok: true; token: string; agentToken: string }
15
+ | { ok: false; reason: 'rejected' | 'rate-limited' }
16
+
17
+ /** The two tokens of a session that exists without `/pair`. */
18
+ export interface TrustedSession {
19
+ token: string
20
+ agentToken: string
21
+ }
22
+
23
+ export interface PairingOptions {
24
+ ttlMs?: number
25
+ idleTimeoutMs?: number
26
+ now?: () => number
27
+ /**
28
+ * Sessions the process that started the server set up for its own tab, as `bun run dev` does
29
+ * through the environment. They never sit idle too long, are never forgotten for newer tabs,
30
+ * and cannot be revoked; they end with the server.
31
+ */
32
+ trusted?: readonly TrustedSession[]
33
+ }
34
+
35
+ function digest(value: string): Buffer {
36
+ return createHash('sha256').update(value, 'utf8').digest()
37
+ }
38
+
39
+ function key(token: string): string {
40
+ return digest(token).toString('hex')
41
+ }
42
+
43
+ /**
44
+ * Six characters derived from a pairing code, shown by the companion and by the tab that opens
45
+ * its link, so the person can tell the link is the one their terminal printed. The app derives
46
+ * the same characters (`companionFingerprint` in `src/app/automation/companion/`).
47
+ */
48
+ export function pairingFingerprint(code: string): string {
49
+ const hex = key(code).slice(0, 6).toUpperCase()
50
+ return `${hex.slice(0, 3)}-${hex.slice(3)}`
51
+ }
52
+
53
+ interface Session {
54
+ lastUsed: number
55
+ /** The digest of the token this tab hands its agents for Pairdraw's MCP server. */
56
+ agentKey: string
57
+ }
58
+
59
+ /**
60
+ * One-time codes and the tokens they buy. A code is printed in the link the companion opens,
61
+ * works once, and expires. Pairing returns two tokens: the tab's session token, which reaches
62
+ * the agent routes, and an agent token, which reaches only the MCP server and is what the tab
63
+ * hands the agents it starts. Both live only in this process and the tab's memory, so
64
+ * restarting the companion signs every tab out. Trusted sessions skip the code: the process that
65
+ * started the server made their tokens and gave them to its own tab.
66
+ */
67
+ export function createPairing({
68
+ ttlMs = PAIRING_CODE_TTL_MS,
69
+ idleTimeoutMs = SESSION_IDLE_TIMEOUT_MS,
70
+ now = Date.now,
71
+ trusted = []
72
+ }: PairingOptions = {}) {
73
+ let code: { digest: Buffer; expiresAt: number } | null = null
74
+ // Keyed by the token's digest, so a lookup never compares the secret itself.
75
+ const sessions = new Map<string, Session>()
76
+ const agentTokens = new Map<string, string>()
77
+ const trustedSessions = new Set(trusted.map((session) => key(session.token)))
78
+ const trustedAgentTokens = new Set(trusted.map((session) => key(session.agentToken)))
79
+ // A token that is both would let the agents a tab starts reach the routes that start programs.
80
+ if (
81
+ trusted.some((session) => !session.token || !session.agentToken) ||
82
+ [...trustedSessions].some((sessionKey) => trustedAgentTokens.has(sessionKey))
83
+ ) {
84
+ throw new RangeError('A trusted session needs a session token and a different agent token')
85
+ }
86
+ let failures = 0
87
+ let windowStart = now()
88
+
89
+ /**
90
+ * Issues a new code and invalidates the previous one. It also lifts a lockout, since the person
91
+ * at the terminal asked for it, so a local program spending attempts cannot keep them out.
92
+ */
93
+ function issueCode(): string {
94
+ const value = randomBytes(16).toString('hex')
95
+ code = { digest: digest(value), expiresAt: now() + ttlMs }
96
+ failures = 0
97
+ windowStart = now()
98
+ return value
99
+ }
100
+
101
+ function rateLimited(): boolean {
102
+ if (now() - windowStart >= ATTEMPT_WINDOW_MS) {
103
+ windowStart = now()
104
+ failures = 0
105
+ }
106
+ return failures >= MAX_FAILED_ATTEMPTS
107
+ }
108
+
109
+ function drop(sessionKey: string) {
110
+ const session = sessions.get(sessionKey)
111
+ if (session) agentTokens.delete(session.agentKey)
112
+ sessions.delete(sessionKey)
113
+ }
114
+
115
+ /** Trades a code for the tokens: once, before it expires, compared in constant time. */
116
+ function exchange(candidate: string): PairingResult {
117
+ if (rateLimited()) return { ok: false, reason: 'rate-limited' }
118
+ const current = code
119
+ const matches =
120
+ current !== null &&
121
+ timingSafeEqual(digest(candidate), current.digest) &&
122
+ now() < current.expiresAt
123
+ if (!matches) {
124
+ failures++
125
+ return { ok: false, reason: 'rejected' }
126
+ }
127
+ code = null
128
+ const token = randomBytes(32).toString('hex')
129
+ const agentToken = randomBytes(32).toString('hex')
130
+ const sessionKey = key(token)
131
+ sessions.set(sessionKey, { lastUsed: now(), agentKey: key(agentToken) })
132
+ agentTokens.set(key(agentToken), sessionKey)
133
+ while (sessions.size > MAX_SESSIONS) {
134
+ const oldest = sessions.keys().next().value
135
+ if (oldest === undefined) break
136
+ drop(oldest)
137
+ }
138
+ return { ok: true, token, agentToken }
139
+ }
140
+
141
+ /** The live session a token names, after dropping it if it sat idle too long. */
142
+ function live(sessionKey: string): Session | null {
143
+ const session = sessions.get(sessionKey)
144
+ if (!session) return null
145
+ if (now() - session.lastUsed >= idleTimeoutMs) {
146
+ drop(sessionKey)
147
+ return null
148
+ }
149
+ return session
150
+ }
151
+
152
+ /** Whether a token is a paired tab's session token; using it keeps the session alive. */
153
+ function isSession(token: string | null | undefined): boolean {
154
+ if (!token) return false
155
+ const sessionKey = key(token)
156
+ if (trustedSessions.has(sessionKey)) return true
157
+ const session = live(sessionKey)
158
+ if (session) session.lastUsed = now()
159
+ return session !== null
160
+ }
161
+
162
+ /** Whether a token is an agent token of a live session; it reaches only the MCP server. */
163
+ function isAgentToken(token: string | null | undefined): boolean {
164
+ if (!token) return false
165
+ const agentKey = key(token)
166
+ if (trustedAgentTokens.has(agentKey)) return true
167
+ const sessionKey = agentTokens.get(agentKey)
168
+ return sessionKey !== undefined && live(sessionKey) !== null
169
+ }
170
+
171
+ /**
172
+ * Signs a tab out: its session and agent tokens stop working at once. A trusted session stays,
173
+ * since its tab cannot pair again.
174
+ */
175
+ function revoke(token: string): void {
176
+ const sessionKey = key(token)
177
+ if (trustedSessions.has(sessionKey)) return
178
+ drop(sessionKey)
179
+ }
180
+
181
+ return { issueCode, exchange, isSession, isAgentToken, revoke }
182
+ }
@@ -0,0 +1,85 @@
1
+ import { accessSync, constants, statSync } from 'node:fs'
2
+ import { homedir, platform } from 'node:os'
3
+ import { delimiter, isAbsolute, join } from 'node:path'
4
+
5
+ const isWindows = platform() === 'win32'
6
+
7
+ /**
8
+ * Folders that commonly hold a globally installed Node or Bun CLI, which a terminal started
9
+ * without the person's shell profile may not have on PATH. Mirrors `desktop/src/agents/path.rs`.
10
+ */
11
+ function candidateDirs(home = homedir(), runtimePlatform = platform()): string[] {
12
+ const dirs = [
13
+ join(home, '.bun', 'bin'),
14
+ join(home, '.local', 'bin'),
15
+ join(home, '.npm-global', 'bin'),
16
+ join(home, '.volta', 'bin'),
17
+ join(home, 'n', 'bin'),
18
+ join(home, '.local', 'share', 'mise', 'shims')
19
+ ]
20
+ if (runtimePlatform === 'darwin')
21
+ dirs.push('/opt/homebrew/bin', '/usr/local/bin', '/opt/local/bin')
22
+ if (runtimePlatform === 'linux') dirs.push('/usr/local/bin', '/home/linuxbrew/.linuxbrew/bin')
23
+ if (runtimePlatform === 'win32' && process.env.APPDATA)
24
+ dirs.push(join(process.env.APPDATA, 'npm'))
25
+ return dirs
26
+ }
27
+
28
+ function isDirectory(path: string): boolean {
29
+ try {
30
+ return statSync(path).isDirectory()
31
+ } catch {
32
+ return false
33
+ }
34
+ }
35
+
36
+ /**
37
+ * The absolute folders of a PATH. A relative entry, such as `.` or an empty one, would resolve
38
+ * against whatever folder a program runs in, so a file there could pose as an agent or npm.
39
+ */
40
+ function absoluteEntries(path: string): string[] {
41
+ return path.split(delimiter).filter((entry) => entry.length > 0 && isAbsolute(entry))
42
+ }
43
+
44
+ /** Keeps the current PATH's absolute folders and appends the candidates that exist and it lacks. */
45
+ export function augmentPath(path: string, candidates: readonly string[] = candidateDirs()): string {
46
+ const entries = absoluteEntries(path)
47
+ for (const candidate of candidates) {
48
+ if (!entries.includes(candidate) && isDirectory(candidate)) entries.push(candidate)
49
+ }
50
+ return entries.join(delimiter)
51
+ }
52
+
53
+ function isExecutableFile(path: string): boolean {
54
+ try {
55
+ if (!statSync(path).isFile()) return false
56
+ if (isWindows) return true
57
+ accessSync(path, constants.X_OK)
58
+ return true
59
+ } catch {
60
+ return false
61
+ }
62
+ }
63
+
64
+ /** Extensions Windows runs a bare command name with, as `PATHEXT` lists them. */
65
+ function windowsExtensions(): string[] {
66
+ const listed = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
67
+ .split(';')
68
+ .map((extension) => extension.trim().toLowerCase())
69
+ .filter((extension) => extension.startsWith('.'))
70
+ return listed.length > 0 ? listed : ['.exe', '.cmd']
71
+ }
72
+
73
+ /** The full path `command` runs from on `searchPath`, as `which` finds it, or null. */
74
+ export function which(command: string, searchPath: string): string | null {
75
+ // Only bare names are looked up; a path or a name with separators is never resolved.
76
+ if (!/^[\w.@-]+$/.test(command)) return null
77
+ const extensions = isWindows ? windowsExtensions() : ['']
78
+ for (const dir of absoluteEntries(searchPath)) {
79
+ for (const extension of extensions) {
80
+ const candidate = join(dir, `${command}${extension}`)
81
+ if (isExecutableFile(candidate)) return candidate
82
+ }
83
+ }
84
+ return null
85
+ }
@@ -0,0 +1,88 @@
1
+ import { spawn, type ChildProcess, type StdioOptions } from 'node:child_process'
2
+ import { platform } from 'node:os'
3
+
4
+ import { which } from './path'
5
+
6
+ const isWindows = platform() === 'win32'
7
+
8
+ /** How long a process may take to exit after SIGTERM before it is killed outright. */
9
+ const KILL_GRACE_MS = 2_000
10
+
11
+ export class ProgramNotFoundError extends Error {
12
+ constructor(readonly command: string) {
13
+ super(`Program not found: ${command}`)
14
+ this.name = 'ProgramNotFoundError'
15
+ }
16
+ }
17
+
18
+ /** Variables of the companion's own that the programs it starts must not inherit. */
19
+ function childEnvironment(searchPath: string): NodeJS.ProcessEnv {
20
+ const env: NodeJS.ProcessEnv = {}
21
+ for (const [name, value] of Object.entries(process.env)) {
22
+ if (name.startsWith('PAIRDRAW_')) continue
23
+ env[name] = value
24
+ }
25
+ env.PATH = searchPath
26
+ return env
27
+ }
28
+
29
+ export interface FixedCommandOptions {
30
+ searchPath: string
31
+ cwd?: string
32
+ stdio: StdioOptions
33
+ }
34
+
35
+ /**
36
+ * Starts a program from a fixed command line, never through a shell. Windows runs npm's `.cmd`
37
+ * shims only through `cmd.exe`, so those go through it with the resolved path quoted; the
38
+ * arguments are the registry's own constants, never text from a client.
39
+ */
40
+ export function spawnFixed(
41
+ command: string,
42
+ args: readonly string[],
43
+ options: FixedCommandOptions
44
+ ): ChildProcess {
45
+ const resolved = which(command, options.searchPath)
46
+ if (!resolved) throw new ProgramNotFoundError(command)
47
+ const env = childEnvironment(options.searchPath)
48
+ if (isWindows && /\.(cmd|bat)$/i.test(resolved)) {
49
+ if (/["%^&|<>]/.test(resolved) || args.some((arg) => /["%^&|<>\s]/.test(arg))) {
50
+ throw new ProgramNotFoundError(command)
51
+ }
52
+ return spawn(
53
+ process.env.ComSpec ?? 'cmd.exe',
54
+ ['/d', '/s', '/c', `"${[`"${resolved}"`, ...args].join(' ')}"`],
55
+ {
56
+ cwd: options.cwd,
57
+ env,
58
+ stdio: options.stdio,
59
+ windowsHide: true,
60
+ windowsVerbatimArguments: true
61
+ }
62
+ )
63
+ }
64
+ return spawn(resolved, [...args], {
65
+ cwd: options.cwd,
66
+ env,
67
+ stdio: options.stdio,
68
+ windowsHide: true
69
+ })
70
+ }
71
+
72
+ /** Stops a child: SIGTERM first, then SIGKILL if it is still running after a grace period. */
73
+ export function terminate(child: ChildProcess): Promise<void> {
74
+ if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
75
+ return Promise.resolve()
76
+ }
77
+ return new Promise((resolve) => {
78
+ const timer = setTimeout(() => {
79
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
80
+ }, KILL_GRACE_MS)
81
+ timer.unref()
82
+ child.once('exit', () => {
83
+ clearTimeout(timer)
84
+ resolve()
85
+ })
86
+ child.kill('SIGTERM')
87
+ })
88
+ }
@@ -0,0 +1,36 @@
1
+ import { ACP_AGENTS } from '@pairdraw/core/constants'
2
+
3
+ /**
4
+ * An agent the companion may start. Every command line is fixed here: a client names an agent
5
+ * by its id and never sends a program, arguments, or environment.
6
+ */
7
+ export interface CompanionAgent {
8
+ id: string
9
+ /** The ACP program the bridge starts. */
10
+ command: string
11
+ args: readonly string[]
12
+ /** The agent's own CLI, when the ACP program is a separate adapter for it. */
13
+ cliCommand?: string
14
+ /** The npm package `install` puts on the computer, when the ACP program is an adapter. */
15
+ adapterPackage?: string
16
+ /** Arguments of a sign-in the agent runs in a terminal, such as Claude's browser login. */
17
+ terminalSignIn?: readonly string[]
18
+ }
19
+
20
+ /** The agents the app offers, as `ACP_AGENTS` in Core defines them. */
21
+ export const COMPANION_AGENTS: readonly CompanionAgent[] = ACP_AGENTS.map((agent) => ({
22
+ id: agent.id,
23
+ command: agent.command,
24
+ args: [...agent.args],
25
+ cliCommand: agent.cliCommand,
26
+ adapterPackage: agent.adapterPackage,
27
+ terminalSignIn: agent.signIn?.via === 'terminal' ? [...agent.signIn.args] : undefined
28
+ }))
29
+
30
+ /** The agent a route names, or undefined for an id the companion does not know. */
31
+ export function findCompanionAgent(
32
+ registry: readonly CompanionAgent[],
33
+ id: string
34
+ ): CompanionAgent | undefined {
35
+ return registry.find((agent) => agent.id === id)
36
+ }
@@ -0,0 +1,77 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** `POST /pair`: the one-time code from the link the companion printed. */
4
+ export const pairRequestSchema = v.object({
5
+ code: v.pipe(v.string(), v.minLength(1), v.maxLength(128))
6
+ })
7
+
8
+ /** The first message on an agent socket, since browsers cannot set headers on a WebSocket. */
9
+ export const socketAuthSchema = v.pipe(
10
+ v.string(),
11
+ v.maxLength(1024),
12
+ v.parseJson(),
13
+ v.strictObject({
14
+ type: v.literal('auth'),
15
+ token: v.pipe(v.string(), v.minLength(1), v.maxLength(256))
16
+ })
17
+ )
18
+
19
+ /** What the app sends on a sign-in socket after authenticating: the code the sign-in page shows. */
20
+ export const signInMessageSchema = v.pipe(
21
+ v.string(),
22
+ v.maxLength(1024),
23
+ v.parseJson(),
24
+ v.strictObject({
25
+ type: v.literal('code'),
26
+ // Printable ASCII without spaces or line breaks, so it cannot inject further input lines.
27
+ code: v.pipe(v.string(), v.minLength(1), v.maxLength(512), v.regex(/^[\x21-\x7E]+$/))
28
+ })
29
+ )
30
+
31
+ /** A JSON-RPC message the app sends an agent; its params, when present, are an object. */
32
+ export const acpClientMessageSchema = v.pipe(
33
+ v.string(),
34
+ v.parseJson(),
35
+ v.looseObject({
36
+ jsonrpc: v.literal('2.0'),
37
+ params: v.optional(v.record(v.string(), v.unknown()))
38
+ })
39
+ )
40
+
41
+ /** The one `_meta` entry the app sends: the tools Claude's adapter may use without asking. */
42
+ export const acpAllowedMetaSchema = v.object({
43
+ claudeCode: v.object({
44
+ options: v.object({
45
+ allowedTools: v.pipe(v.array(v.pipe(v.string(), v.maxLength(256))), v.maxLength(64))
46
+ })
47
+ })
48
+ })
49
+
50
+ /** An MCP server entry in `session/new` that names a URL rather than a command. */
51
+ export const acpHTTPServerSchema = v.looseObject({
52
+ type: v.picklist(['http', 'sse']),
53
+ url: v.pipe(v.string(), v.maxLength(2048))
54
+ })
55
+
56
+ /** A token the development server makes with 32 random bytes, as lowercase hex. */
57
+ const devTokenSchema = v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/))
58
+
59
+ /**
60
+ * The tab session `bun run dev` gives the MCP server it starts, in the environment, so its own
61
+ * tab reaches the agent bridge without pairing. The two tokens must differ: the agent token
62
+ * reaches only `/mcp`, and agents hold it.
63
+ */
64
+ export const devAgentSessionEnvSchema = v.pipe(
65
+ v.object({
66
+ PAIRDRAW_MCP_AGENT_SESSION: devTokenSchema,
67
+ PAIRDRAW_MCP_AGENT_TOKEN: devTokenSchema
68
+ }),
69
+ v.check(
70
+ (env) => env.PAIRDRAW_MCP_AGENT_SESSION !== env.PAIRDRAW_MCP_AGENT_TOKEN,
71
+ 'The session and agent tokens must differ'
72
+ ),
73
+ v.transform((env) => ({
74
+ token: env.PAIRDRAW_MCP_AGENT_SESSION,
75
+ agentToken: env.PAIRDRAW_MCP_AGENT_TOKEN
76
+ }))
77
+ )
@@ -0,0 +1,106 @@
1
+ import type { ChildProcess } from 'node:child_process'
2
+
3
+ import * as v from 'valibot'
4
+ import type { RawData, WebSocket } from 'ws'
5
+
6
+ import type { AgentProcessContext } from './acp'
7
+ import { ProgramNotFoundError, spawnFixed, terminate } from './process'
8
+ import type { CompanionAgent } from './registry'
9
+ import { signInMessageSchema } from './schema'
10
+ import { CLOSE_CODES, rawBytes, sendJSON } from './socket'
11
+
12
+ /** Long enough to sign in from a fresh browser, short enough not to leave a login waiting. */
13
+ const SIGN_IN_TIMEOUT_MS = 5 * 60_000
14
+ const MAX_URL_LENGTH = 2_048
15
+ const MAX_LINE_BUFFER = 16_384
16
+
17
+ // eslint-disable-next-line no-control-regex -- Escape sequences are what it removes.
18
+ const TERMINAL_CODES = /\u001B\]8;[^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B\[[0-9;?]*[A-Za-z]/g
19
+
20
+ /** The first https address in the login's output, without terminal codes, or null. */
21
+ function findSignInURL(text: string): string | null {
22
+ const candidate = /https:\/\/\S+/.exec(text.replace(TERMINAL_CODES, ''))?.[0]
23
+ if (!candidate || candidate.length > MAX_URL_LENGTH) return null
24
+ try {
25
+ return new URL(candidate).protocol === 'https:' ? candidate : null
26
+ } catch {
27
+ return null
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Runs an agent's terminal sign-in, such as Claude's browser login, for one authenticated
33
+ * socket. The login opens the browser itself; the socket hears the page to open by hand
34
+ * (`url`), may send the code the page shows (`code`), and hears how it ended (`done`). Closing
35
+ * the socket cancels the login.
36
+ */
37
+ export function runSignIn(
38
+ ws: WebSocket,
39
+ agent: CompanionAgent,
40
+ context: AgentProcessContext
41
+ ): void {
42
+ const args = agent.terminalSignIn
43
+ // The socket may have closed while the workspace was prepared; nothing would stop the login.
44
+ if (ws.readyState !== ws.OPEN) return
45
+ if (!args) {
46
+ ws.close(CLOSE_CODES.unsupported, 'This agent signs in inside its own session')
47
+ return
48
+ }
49
+ let child: ChildProcess
50
+ try {
51
+ child = spawnFixed(agent.command, args, {
52
+ cwd: context.workspace,
53
+ searchPath: context.searchPath,
54
+ stdio: ['pipe', 'pipe', 'ignore']
55
+ })
56
+ } catch (error) {
57
+ const notFound = error instanceof ProgramNotFoundError
58
+ ws.close(notFound ? CLOSE_CODES.notFound : CLOSE_CODES.failed, 'Sign-in did not start')
59
+ return
60
+ }
61
+ context.track(child)
62
+ let finished = false
63
+ let urlSent = false
64
+ let pending = ''
65
+ const timer = setTimeout(() => finish(false), SIGN_IN_TIMEOUT_MS)
66
+ timer.unref()
67
+
68
+ function finish(ok: boolean) {
69
+ if (finished) return
70
+ finished = true
71
+ clearTimeout(timer)
72
+ sendJSON(ws, { type: 'done', ok })
73
+ if (ws.readyState === ws.OPEN) ws.close(1000, 'Sign-in ended')
74
+ void terminate(child)
75
+ }
76
+
77
+ child.stdin?.on('error', () => undefined)
78
+ child.stdout?.on('data', (chunk: Buffer) => {
79
+ if (urlSent) return
80
+ pending = (pending + chunk.toString('utf8')).slice(-MAX_LINE_BUFFER)
81
+ const url = findSignInURL(pending)
82
+ if (!url) return
83
+ urlSent = true
84
+ sendJSON(ws, { type: 'url', url })
85
+ })
86
+ // The app sends a code only after this, so none arrives before the socket listens for it.
87
+ child.once('spawn', () => sendJSON(ws, { type: 'ready' }))
88
+ child.once('error', () => finish(false))
89
+ child.once('close', (code) => finish(code === 0))
90
+
91
+ ws.on('message', (data: RawData, isBinary: boolean) => {
92
+ const message = isBinary
93
+ ? null
94
+ : v.safeParse(signInMessageSchema, rawBytes(data).toString('utf8'))
95
+ if (!message?.success) {
96
+ ws.close(CLOSE_CODES.unsupported, 'Unexpected message')
97
+ return
98
+ }
99
+ child.stdin?.write(`${message.output.code}\n`)
100
+ })
101
+ ws.once('close', () => {
102
+ clearTimeout(timer)
103
+ finished = true
104
+ void terminate(child)
105
+ })
106
+ }
@@ -0,0 +1,79 @@
1
+ import * as v from 'valibot'
2
+ import type { RawData, WebSocket } from 'ws'
3
+
4
+ import { socketAuthSchema } from './schema'
5
+
6
+ /** Close codes the app reads; 4000–4999 are free for applications. */
7
+ export const CLOSE_CODES = {
8
+ unsupported: 1003,
9
+ unauthorized: 4401,
10
+ notFound: 4404,
11
+ conflict: 4409,
12
+ busy: 4429,
13
+ failed: 4500
14
+ } as const
15
+
16
+ const AUTH_TIMEOUT_MS = 5_000
17
+ const HEARTBEAT_INTERVAL_MS = 15_000
18
+
19
+ export function rawBytes(data: RawData): Buffer {
20
+ if (Buffer.isBuffer(data)) return data
21
+ if (Array.isArray(data)) return Buffer.concat(data)
22
+ return Buffer.from(data)
23
+ }
24
+
25
+ export function sendJSON(ws: WebSocket, message: Record<string, unknown>): void {
26
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message))
27
+ }
28
+
29
+ /**
30
+ * Waits for the socket's first message, which must be `{type: 'auth', token}` with a token
31
+ * `authorize` accepts. Anything else, or nothing in time, closes the socket.
32
+ */
33
+ export function authenticate(
34
+ ws: WebSocket,
35
+ authorize: (token: string) => boolean
36
+ ): Promise<boolean> {
37
+ return new Promise((resolve) => {
38
+ const timer = setTimeout(() => finish(false), AUTH_TIMEOUT_MS)
39
+ function finish(ok: boolean) {
40
+ clearTimeout(timer)
41
+ ws.off('message', onMessage)
42
+ ws.off('close', onClose)
43
+ if (!ok && ws.readyState === ws.OPEN) ws.close(CLOSE_CODES.unauthorized, 'Unauthorized')
44
+ resolve(ok)
45
+ }
46
+ function onMessage(data: RawData, isBinary: boolean) {
47
+ if (isBinary) return finish(false)
48
+ const parsed = v.safeParse(socketAuthSchema, rawBytes(data).toString('utf8'))
49
+ finish(parsed.success && authorize(parsed.output.token))
50
+ }
51
+ function onClose() {
52
+ finish(false)
53
+ }
54
+ ws.on('message', onMessage)
55
+ ws.once('close', onClose)
56
+ })
57
+ }
58
+
59
+ /** Pings the socket and terminates it when a ping goes unanswered, so a vanished tab frees its process. */
60
+ export function keepAlive(ws: WebSocket): void {
61
+ let alive = true
62
+ ws.on('pong', () => {
63
+ alive = true
64
+ })
65
+ const timer = setInterval(() => {
66
+ if (!alive) {
67
+ ws.terminate()
68
+ return
69
+ }
70
+ alive = false
71
+ try {
72
+ ws.ping()
73
+ } catch {
74
+ ws.terminate()
75
+ }
76
+ }, HEARTBEAT_INTERVAL_MS)
77
+ timer.unref()
78
+ ws.once('close', () => clearInterval(timer))
79
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto'
2
+
3
+ export function bearerToken(header: string | undefined | null): string | null {
4
+ return header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : null
5
+ }
6
+
7
+ export function mcpRequestToken(
8
+ authorization: string | undefined | null,
9
+ headerToken: string | undefined | null
10
+ ): string | null {
11
+ return bearerToken(authorization) ?? headerToken ?? null
12
+ }
13
+
14
+ export function isAuthorized(provided: string | null, expected: string | null): boolean {
15
+ if (expected === null) return true
16
+ if (provided === null) return false
17
+
18
+ const providedDigest = createHash('sha256').update(provided, 'utf8').digest()
19
+ const expectedDigest = createHash('sha256').update(expected, 'utf8').digest()
20
+ return timingSafeEqual(providedDigest, expectedDigest)
21
+ }