@abide/bridge 0.5.2 → 0.6.0

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.
package/src/opened.ts CHANGED
@@ -1,15 +1,28 @@
1
1
  // WHAT RUNS WHEN A PAIRING LINK IS OPENED: the handler `abide-bridge install` bundles beside the app it
2
- // registers, started by that app with the link. It asks the visitor first (44.42), then runs the
3
- // release of the bridge the link names, as the command a site shows would — so a site is answered by
4
- // the bridge that speaks its relay, while what asks is the one the visitor installed.
2
+ // registers, started with the link. It asks the visitor first (44.42) — unless they always allow the
3
+ // site for whoever the link's code was minted for (44.62) — then runs the release of the bridge the
4
+ // link names, as the command a site shows would — so a site is answered by the bridge that speaks its
5
+ // relay, while what asks is the one the visitor installed.
5
6
  //
6
- // RUN BY THE APP, NOT A SHELL: nothing of the visitor's login is here, so `bun`, `claude` and the
7
+ // RUN BY THE DESKTOP, NOT A SHELL: nothing of the visitor's login is here, so `bun`, `claude` and the
7
8
  // `PATH` are what install found (`settings.json`) — an npm-installed `claude` is a `node` script, and
8
9
  // finds `node` only on the PATH it was installed from. Every line the bridge says is written to the
9
- // log the app opened and shown as a notification.
10
+ // log in the install directory and shown as a notification.
10
11
 
12
+ import { appendFile } from 'node:fs/promises' // bun has no append of its own
13
+
14
+ import {
15
+ allowAlways,
16
+ allowedIn,
17
+ allowedSites,
18
+ allowsUnasked,
19
+ } from './allowedSites.ts'
20
+ import { BRIDGE_PATH } from './bridge.ts'
21
+ import { type Answer, ask, notify } from './desktop.ts'
22
+ import { grantFor, serversNamed } from './grant.ts'
11
23
  import { type Pairing, pairingOf } from './pairingLink.ts'
12
24
  import { readLines } from './readLines.ts'
25
+ import { siteTls } from './siteTls.ts'
13
26
 
14
27
  /**
15
28
  * What install found, kept beside this file: `bun`, `claude`, and the `PATH` it was run on — and what
@@ -24,22 +37,29 @@ export type HandlerSettings = {
24
37
  }
25
38
 
26
39
  /**
27
- * What the visitor is asked before `pairing` runs. EVERY LINK IS ASKED (44.42): a code proves only
28
- * that the site minted it, never that this visitor's browser asked for it, so an answer kept for a
29
- * site would pair any page's link to whoever minted its code.
40
+ * What the visitor is asked before `pairing` runs, naming each MCP tool it asks for of a server their
41
+ * Claude Code is not configured with, `unserved` (44.65).
30
42
  */
31
- export function question(pairing: Pairing, settings: HandlerSettings): string {
43
+ export function question(
44
+ pairing: Pairing,
45
+ settings: HandlerSettings,
46
+ unserved: readonly string[] = [],
47
+ ): string {
32
48
  const tools =
33
49
  pairing.tools.length === 0
34
- ? 'It gets none of this Mac’s tools.'
35
- : `It also asks for these tools of this Mac’s: ${pairing.tools.join(', ')}.`
50
+ ? 'It gets none of this computer’s tools.'
51
+ : `It also asks for these tools of this computer’s: ${pairing.tools.join(', ')}.`
52
+ const missing =
53
+ unserved.length === 0
54
+ ? ''
55
+ : `\n\nYour Claude Code has no ${serversNamed(unserved)} MCP server, so it can’t give ${unserved.join(', ')}. Add it with \`claude mcp add --scope user\` before you ask.`
36
56
  // A variable's value is only named, never shown: it is as likely a token as a host.
37
57
  const names = Object.keys(settings.env)
38
58
  const kept =
39
59
  settings.claudeArgs.length === 0 && names.length === 0
40
60
  ? ''
41
61
  : `\n\nIt also gets what you gave install for every site: ${[...settings.claudeArgs, ...names].join(' ')}.`
42
- return `${pairing.site} wants to use your Claude Code as its assistant, with its own tools, on your Claude account.\n\n${tools}${kept}\n\nIt runs @abide/bridge ${pairing.version}. Allow it only if you just asked to pair on that site.`
62
+ return `${pairing.site} wants to use your Claude Code as its assistant, with its own tools, on your Claude account.\n\n${tools}${missing}${kept}\n\nIt runs @abide/bridge ${pairing.version}. Allow it only if you just asked to pair on that site.`
43
63
  }
44
64
 
45
65
  /**
@@ -50,9 +70,7 @@ export function bridgeArguments(
50
70
  pairing: Pairing,
51
71
  settings: HandlerSettings,
52
72
  ): string[] {
53
- const claudeArgs = [...settings.claudeArgs]
54
- if (pairing.tools.length > 0)
55
- claudeArgs.push('--tools', pairing.tools.join(','))
73
+ const claudeArgs = claudeArgsOf(pairing, settings)
56
74
  return [
57
75
  settings.bun,
58
76
  'x',
@@ -65,53 +83,115 @@ export function bridgeArguments(
65
83
  ]
66
84
  }
67
85
 
68
- /** The `PATH` the bridge runs on: the directories of `bun` and `claude`, then the one install was run on. */
69
- export function searchPath(settings: HandlerSettings): string {
86
+ /** The Claude Code options the bridge for `pairing` is run with: install's, then the link's tools. */
87
+ function claudeArgsOf(pairing: Pairing, settings: HandlerSettings): string[] {
88
+ const claudeArgs = [...settings.claudeArgs]
89
+ if (pairing.tools.length > 0)
90
+ claudeArgs.push('--tools', pairing.tools.join(','))
91
+ return claudeArgs
92
+ }
93
+
94
+ /**
95
+ * The `PATH` the bridge runs on: the directories of `bun` and `claude`, then the one install was run
96
+ * on, joined by `separator` — `;` on Windows.
97
+ */
98
+ export function searchPath(
99
+ settings: HandlerSettings,
100
+ separator = process.platform === 'win32' ? ';' : ':',
101
+ ): string {
70
102
  const directories: string[] = []
71
103
  for (const directory of [
72
- settings.bun.slice(0, settings.bun.lastIndexOf('/')),
73
- settings.claude.slice(0, settings.claude.lastIndexOf('/')),
74
- ...settings.path.split(':'),
104
+ directoryOf(settings.bun),
105
+ directoryOf(settings.claude),
106
+ ...settings.path.split(separator),
75
107
  ])
76
108
  if (directory !== '' && !directories.includes(directory))
77
109
  directories.push(directory)
78
- return directories.join(':')
110
+ return directories.join(separator)
79
111
  }
80
112
 
81
- /** Runs one AppleScript with `argument` as `item 1 of argv`, answering what it printed, or `undefined` where it failed. */
82
- async function appleScript(
83
- lines: string[],
84
- argument: string,
85
- ): Promise<string | undefined> {
86
- const script: string[] = ['-e', 'on run argv']
87
- for (const line of lines) script.push('-e', line)
88
- script.push('-e', 'end run')
89
- const child = Bun.spawn(['osascript', ...script, argument], {
90
- stdout: 'pipe',
91
- stderr: 'ignore',
92
- })
93
- const printed = (await new Response(child.stdout).text()).trim()
94
- return (await child.exited) === 0 ? printed : undefined
113
+ function directoryOf(file: string): string {
114
+ return file.slice(
115
+ 0,
116
+ Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\')),
117
+ )
95
118
  }
96
119
 
97
- /** Asks the visitor about `pairing` in a dialog; closing it is a no. */
98
- async function allowed(
120
+ /**
121
+ * Who `pairing`'s code was minted for, as `/__abide/bridge` names them (44.63), or `undefined` where the
122
+ * site names no one — a release before it did, or a code it did not mint.
123
+ */
124
+ export async function holderOf(pairing: Pairing): Promise<string | undefined> {
125
+ try {
126
+ const answer = await fetch(
127
+ `${pairing.site}${BRIDGE_PATH}?holder=${encodeURIComponent(pairing.code)}`,
128
+ { tls: siteTls(), signal: AbortSignal.timeout(10_000) },
129
+ )
130
+ if (!answer.ok) {
131
+ await answer.body?.cancel()
132
+ return undefined
133
+ }
134
+ const { holder } = (await answer.json()) as { holder?: unknown }
135
+ return typeof holder === 'string' && holder !== '' ? holder : undefined
136
+ } catch {
137
+ return undefined
138
+ }
139
+ }
140
+
141
+ /** The MCP tools `pairing` asks for whose server the visitor's Claude Code is not configured with. 44.65. */
142
+ export async function unservedOf(
143
+ pairing: Pairing,
144
+ settings: HandlerSettings,
145
+ ): Promise<string[]> {
146
+ // An unreadable config is no server here: the bridge says why when it runs.
147
+ const { grant } = await grantFor(
148
+ pairing.tools,
149
+ claudeArgsOf(pairing, settings),
150
+ () => {},
151
+ )
152
+ return grant.unserved
153
+ }
154
+
155
+ /**
156
+ * Whether `pairing` may pair: unasked where the visitor always allows its site for the holder its code
157
+ * was minted for and it asks for no tool beyond those allowed then (44.62), else as `askVisitor`
158
+ * answers — offering to always allow only where the site named a holder — keeping an always in
159
+ * `allowedFile`.
160
+ */
161
+ export async function consented(
99
162
  pairing: Pairing,
100
163
  settings: HandlerSettings,
164
+ allowedFile: string,
165
+ askVisitor: (question: string, offerAlways: boolean) => Promise<Answer>,
166
+ say: (line: string) => void,
101
167
  ): Promise<boolean> {
102
- const pressed = await appleScript(
103
- [
104
- 'display dialog (item 1 of argv) with title "abide bridge" buttons {"Don’t Allow", "Allow"} default button "Don’t Allow" cancel button "Don’t Allow" with icon caution',
105
- 'button returned of result',
106
- ],
107
- question(pairing, settings),
168
+ // None waits on another, and the holder is a round trip to the site.
169
+ const [holder, allowed, unserved] = await Promise.all([
170
+ holderOf(pairing),
171
+ allowedSites(allowedFile),
172
+ unservedOf(pairing, settings),
173
+ ])
174
+ if (
175
+ holder !== undefined &&
176
+ allowsUnasked(allowed, pairing.site, holder, pairing.tools)
177
+ ) {
178
+ say(
179
+ `Pairing with ${new URL(pairing.site).host}, which you always allow.`,
180
+ )
181
+ return true
182
+ }
183
+ const answer = await askVisitor(
184
+ question(pairing, settings, unserved),
185
+ holder !== undefined,
108
186
  )
109
- return pressed === 'Allow'
187
+ if (answer === 'always' && holder !== undefined)
188
+ await allowAlways(allowedFile, pairing.site, holder, pairing.tools)
189
+ return answer !== 'deny'
110
190
  }
111
191
 
112
192
  /**
113
- * Shows `line` as a notification, coalesced: one `osascript` at a time, and a line arriving while one
114
- * shows replaces any still waiting, so a burst on the bridge's stderr is never read at its pace.
193
+ * Shows `line` as a notification, coalesced: one at a time, and a line arriving while one shows
194
+ * replaces any still waiting, so a burst on the bridge's stderr is never read at its pace.
115
195
  */
116
196
  function notifier(): { show(line: string): void; settled(): Promise<void> } {
117
197
  let waiting: string | undefined
@@ -120,12 +200,7 @@ function notifier(): { show(line: string): void; settled(): Promise<void> } {
120
200
  while (waiting !== undefined) {
121
201
  const line = waiting
122
202
  waiting = undefined
123
- await appleScript(
124
- [
125
- 'display notification (item 1 of argv) with title "abide bridge"',
126
- ],
127
- line,
128
- )
203
+ await notify(line)
129
204
  }
130
205
  showing = undefined
131
206
  }
@@ -143,20 +218,55 @@ function notifier(): { show(line: string): void; settled(): Promise<void> } {
143
218
  /** Opens `link`: asks the visitor, then runs the bridge until it ends. Answers the exit code. */
144
219
  async function open(link: string): Promise<number> {
145
220
  const notifications = notifier()
221
+ const log = `${import.meta.dir}/../bridge.log`
222
+ let logged = Promise.resolve()
146
223
  function say(line: string): void {
147
224
  console.error(line)
225
+ logged = logged.then(() =>
226
+ appendFile(log, `${new Date().toISOString()} ${line}\n`).catch(
227
+ () => {},
228
+ ),
229
+ )
148
230
  notifications.show(line)
149
231
  }
232
+ async function settled(code: number): Promise<number> {
233
+ await notifications.settled()
234
+ await logged
235
+ return code
236
+ }
237
+ try {
238
+ return settled(await pairWith(link, say))
239
+ } catch (thrown) {
240
+ // The applet discards this process's output, so a throw is only seen if it is said.
241
+ say(
242
+ `The bridge could not open: ${thrown instanceof Error ? thrown.message : String(thrown)}`,
243
+ )
244
+ return settled(1)
245
+ }
246
+ }
247
+
248
+ async function pairWith(
249
+ link: string,
250
+ say: (line: string) => void,
251
+ ): Promise<number> {
150
252
  const pairing = pairingOf(link)
151
253
  if (pairing === undefined) {
152
254
  say('That link isn’t one this bridge can pair with.')
153
- await notifications.settled()
154
255
  return 1
155
256
  }
156
257
  const settings = (await Bun.file(
157
258
  `${import.meta.dir}/settings.json`,
158
259
  ).json()) as HandlerSettings
159
- if (!(await allowed(pairing, settings))) return 0
260
+ if (
261
+ !(await consented(
262
+ pairing,
263
+ settings,
264
+ allowedIn(import.meta.dir),
265
+ ask,
266
+ say,
267
+ ))
268
+ )
269
+ return 0
160
270
  const running = Bun.spawn(bridgeArguments(pairing, settings), {
161
271
  stdout: 'ignore',
162
272
  stderr: 'pipe',
@@ -169,9 +279,7 @@ async function open(link: string): Promise<number> {
169
279
  const said = line.trim()
170
280
  if (said !== '') say(said)
171
281
  }
172
- const code = await running.exited
173
- await notifications.settled()
174
- return code
282
+ return running.exited
175
283
  }
176
284
 
177
285
  if (import.meta.main) process.exit(await open(process.argv[2] ?? ''))
@@ -1,7 +1,7 @@
1
1
  // A PAIRING AS A LINK: what a site shows beside its command (44.40), opened by the handler
2
2
  // `abide-bridge install` registers. It carries what the command does — the site, the code, the bridge
3
- // release that speaks the site's relay and the built-in tools it asks for — and nothing more, and the
4
- // handler asks the visitor before it runs one (44.42).
3
+ // release that speaks the site's relay and the tools of this machine it asks for — and nothing more,
4
+ // and the handler asks the visitor before it runs one (44.42).
5
5
 
6
6
  // abide's `BRIDGE_SCHEME`, spelled out for `BRIDGE_PATH`'s reason — a test holds the two equal.
7
7
  export const PAIRING_SCHEME = 'abide-bridge'
@@ -18,8 +18,9 @@ export type Pairing = {
18
18
  const RELEASE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
19
19
  // abide's codes are base64url.
20
20
  const CODE = /^[\w-]+$/
21
- // A tool as `--tools` names one: `WebSearch`, `Bash`.
22
- const TOOL = /^[A-Za-z][A-Za-z0-9]*$/
21
+ // A tool as the bridge's `--tools` names one: a built-in, `WebSearch`, or an MCP server's,
22
+ // `mcp__calendar__meetings`, or all of one server's, `mcp__calendar` (44.29).
23
+ const TOOL = /^(?:[A-Za-z][A-Za-z0-9]*|mcp__[A-Za-z0-9_-]+)$/
23
24
  const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
24
25
 
25
26
  /**
@@ -62,9 +63,14 @@ export function pairingOf(link: string): Pairing | undefined {
62
63
  return undefined
63
64
  for (const tool of tools) if (!TOOL.test(tool)) return undefined
64
65
  return {
65
- site: `${siteUrl.origin}${siteUrl.pathname}`.replace(/\/+$/, ''),
66
+ site: siteOf(siteUrl),
66
67
  code,
67
68
  version,
68
69
  tools,
69
70
  }
70
71
  }
72
+
73
+ /** A site as the bridge keeps it: its origin and path, with no trailing slash. */
74
+ export function siteOf(url: URL): string {
75
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, '')
76
+ }
package/src/siteTls.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { getCACertificates } from 'node:tls' // bun's fetch reads this machine's trust store only under `--use-system-ca`, a flag `bun x` and the link handler's launch cannot pass
2
+
3
+ /**
4
+ * 44.47 — bun's own roots and this machine's, so a site whose certificate an organization's authority
5
+ * signed is reached as the browser reaches it. A `ca` replaces bun's roots rather than adding to them,
6
+ * so both are passed.
7
+ */
8
+ export function siteTls(): { ca: string[] } {
9
+ return {
10
+ ca: [
11
+ ...new Set([
12
+ ...getCACertificates('bundled'),
13
+ ...getCACertificates('system'),
14
+ ]),
15
+ ],
16
+ }
17
+ }