@abide/bridge 0.3.5 → 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @abide/bridge
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2af648d: a pairing link beside the command — abide-bridge install registers a macOS app that opens it and asks before it pairs (RULEBOOK 44.40-44.43) ([`409d5ac`](https://github.com/briancray/abide/commit/409d5ac7f95338cb3f44a21cc76cd977387eab42))
8
+
3
9
  ## 0.3.5
4
10
 
5
11
  ### Patch Changes
@@ -3,8 +3,13 @@
3
3
  // you to connect your Claude Code to its assistant. `--claude <path>` names the executable where `claude`
4
4
  // is not on PATH; whatever follows `--` is passed to Claude Code as you wrote it, and is how you give a
5
5
  // site what reaches this machine — `-- --tools WebSearch,WebFetch` for the built-in tools it asks for.
6
+ //
7
+ // `abide-bridge install [--claude <path>]` builds and registers, on macOS, the app that opens the pairing
8
+ // link a site shows beside its command, so a click pairs instead of a terminal; `abide-bridge uninstall`
9
+ // takes it away.
6
10
 
7
11
  import { bridge } from '../src/bridge.ts'
12
+ import { install, installDirectory, uninstall } from '../src/install.ts'
8
13
 
9
14
  const all = process.argv.slice(2)
10
15
  const split = all.indexOf('--')
@@ -16,26 +21,46 @@ const [site, code] = args.filter(
16
21
  (_arg, index) => flag === -1 || (index !== flag && index !== flag + 1),
17
22
  )
18
23
 
19
- if (site === undefined || code === undefined) {
24
+ if (
25
+ site === undefined ||
26
+ (site !== 'uninstall' && site !== 'install' && code === undefined)
27
+ ) {
20
28
  console.error(
21
- 'usage: abide-bridge <site> <code> [--claude <path>] [-- <claude options>]',
29
+ 'usage: abide-bridge <site> <code> [--claude <path>] [-- <claude options>]\n abide-bridge install [--claude <path>]\n abide-bridge uninstall',
22
30
  )
23
31
  process.exit(2)
24
32
  }
25
- if (claude === undefined && Bun.which('claude') === null) {
26
- console.error(
27
- 'Claude Code is not installed here: `claude` is not on PATH. Install it, sign in, and run this again.',
28
- )
29
- process.exit(1)
30
- }
31
33
 
32
34
  try {
33
- await bridge({
34
- site,
35
- code,
36
- claudeArgs,
37
- ...(claude === undefined ? {} : { claude }),
38
- })
35
+ if (site === 'uninstall') {
36
+ await uninstall()
37
+ console.error(`Removed ${installDirectory()}.`)
38
+ } else {
39
+ // Absolute, because an installed handler runs from no directory of the visitor's and on no shell's PATH.
40
+ const found = Bun.which(claude ?? 'claude')
41
+ if (found === null)
42
+ throw new Error(
43
+ claude === undefined
44
+ ? 'Claude Code is not installed here: `claude` is not on PATH. Install it, sign in, or name it with --claude <path>, and run this again.'
45
+ : `--claude ${claude} is no executable here. Name the path to Claude Code, and run this again.`,
46
+ )
47
+ if (site === 'install') {
48
+ const app = await install({
49
+ bun: process.execPath,
50
+ claude: found,
51
+ path: Bun.env.PATH ?? '',
52
+ })
53
+ console.error(
54
+ `Installed ${app}. A site's pairing link now opens here, and asks you before it pairs. \`abide-bridge uninstall\` removes it.`,
55
+ )
56
+ } else
57
+ await bridge({
58
+ site,
59
+ code: code as string,
60
+ claudeArgs,
61
+ claude: found,
62
+ })
63
+ }
39
64
  process.exit(0)
40
65
  } catch (thrown) {
41
66
  console.error(thrown instanceof Error ? thrown.message : String(thrown))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abide/bridge",
3
- "version": "0.3.5",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Connects the Claude Code on your machine to the assistant on an abide site",
6
6
  "license": "MIT",
package/src/install.ts ADDED
@@ -0,0 +1,142 @@
1
+ // `abide-bridge install`: AN APP THAT OPENS PAIRING LINKS, built on this Mac rather than downloaded. A
2
+ // URL reaches a macOS app as an Apple Event, never as an argument, so the app is an AppleScript applet
3
+ // (`osacompile`, on every Mac) whose `open location` starts the handler (`opened.ts`, bundled into one
4
+ // file so nothing it imports can be left behind) with the link. Built here, it carries no quarantine and Gatekeeper never reads it; ad-hoc signed whole after
5
+ // its `Info.plist` is changed, as `abide bundle` signs its own, since an edited bundle whose signature
6
+ // no longer matches is one macOS reads as damaged.
7
+ //
8
+ // IN APPLICATION SUPPORT, NOT AN APPLICATIONS FOLDER (44.43): it is nothing to open by hand, and Launch
9
+ // Services finds a handler there only once it is registered, so install registers it and uninstall
10
+ // takes it away again.
11
+
12
+ import { rm } from 'node:fs/promises' // bun has no recursive remove of its own
13
+
14
+ import type { HandlerSettings } from './opened.ts'
15
+ import { PAIRING_SCHEME } from './pairingLink.ts'
16
+
17
+ const APP_NAME = 'abide bridge'
18
+ export const IDENTIFIER = 'abide.bridge'
19
+ const LAUNCH_SERVICES =
20
+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister'
21
+ /** The handler install bundles into `directory`, which the applet starts. */
22
+ export function handlerIn(directory: string): string {
23
+ return `${directory}/handler/opened.js`
24
+ }
25
+
26
+ /** Where install writes, under the visitor's home. */
27
+ export function installDirectory(): string {
28
+ return `${Bun.env.HOME ?? ''}/Library/Application Support/abide-bridge`
29
+ }
30
+
31
+ /** The app install writes into `directory`. */
32
+ export function appIn(directory: string): string {
33
+ return `${directory}/${APP_NAME}.app`
34
+ }
35
+
36
+ /** `text` as an AppleScript string literal. */
37
+ function appleScriptString(text: string): string {
38
+ return `"${text.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
39
+ }
40
+
41
+ /** The applet's source: a link opened starts the handler with it, in the background, into the log. */
42
+ function appletSource(bun: string, directory: string): string {
43
+ const handler = appleScriptString(handlerIn(directory))
44
+ const log = appleScriptString(`${directory}/bridge.log`)
45
+ return `on open location theURL
46
+ \tdo shell script quoted form of ${appleScriptString(bun)} & " " & quoted form of ${handler} & " " & quoted form of theURL & " >> " & quoted form of ${log} & " 2>&1 &"
47
+ end open location
48
+
49
+ on run
50
+ \tdisplay dialog "abide bridge opens the pairing links abide sites show, so your Claude Code can be their assistant. There is nothing to do here." buttons {"OK"} default button "OK" with title "abide bridge"
51
+ end run
52
+ `
53
+ }
54
+
55
+ /** Runs one of macOS's own tools, throwing with what it wrote where it fails. */
56
+ async function tool(command: string[]): Promise<void> {
57
+ const child = Bun.spawn(command, { stdout: 'ignore', stderr: 'pipe' })
58
+ const [code, said] = await Promise.all([
59
+ child.exited,
60
+ new Response(child.stderr).text(),
61
+ ])
62
+ if (code !== 0) throw new Error(`${command[0]} failed: ${said.trim()}`)
63
+ }
64
+
65
+ /** Throws where this is not macOS, the one place a pairing link opens. */
66
+ function onMac(): void {
67
+ if (process.platform !== 'darwin')
68
+ throw new Error(
69
+ `pairing links open on macOS, and this is ${process.platform}. The command a site shows pairs from any terminal.`,
70
+ )
71
+ }
72
+
73
+ /** Where install and uninstall work, and whether they touch Launch Services — a test's own directory, unregistered. */
74
+ type Placement = { directory?: string; register?: boolean }
75
+
76
+ /**
77
+ * Builds the app that opens pairing links into `directory`, with the handler it starts beside it, and
78
+ * registers it with Launch Services unless `register` is false.
79
+ */
80
+ export async function install(
81
+ settings: HandlerSettings,
82
+ options: Placement = {},
83
+ ): Promise<string> {
84
+ onMac()
85
+ const directory = options.directory ?? installDirectory()
86
+ const app = appIn(directory)
87
+ const bundled = await Bun.build({
88
+ entrypoints: [`${import.meta.dir}/opened.ts`],
89
+ outdir: `${directory}/handler`,
90
+ target: 'bun',
91
+ })
92
+ if (!bundled.success)
93
+ throw new Error(
94
+ `the link handler did not bundle: ${bundled.logs.join('\n')}`,
95
+ )
96
+ await Bun.write(
97
+ `${directory}/handler/settings.json`,
98
+ JSON.stringify(settings, null, 4),
99
+ )
100
+ const source = `${directory}/handler/applet.applescript`
101
+ await Bun.write(source, appletSource(settings.bun, directory))
102
+ await rm(app, { recursive: true, force: true })
103
+ await tool(['osacompile', '-o', app, source])
104
+ const plist = `${app}/Contents/Info.plist`
105
+ for (const [key, type, value] of [
106
+ ['CFBundleIdentifier', '-string', IDENTIFIER],
107
+ ['LSUIElement', '-bool', 'YES'],
108
+ [
109
+ 'CFBundleURLTypes',
110
+ '-json',
111
+ JSON.stringify([
112
+ {
113
+ CFBundleURLName: 'abide bridge pairing',
114
+ CFBundleURLSchemes: [PAIRING_SCHEME],
115
+ },
116
+ ]),
117
+ ],
118
+ ] as const)
119
+ await tool(['plutil', '-replace', key, type, value, plist])
120
+ await tool(['codesign', '--force', '--sign', '-', app])
121
+ if (options.register !== false) await tool([LAUNCH_SERVICES, '-f', app])
122
+ return app
123
+ }
124
+
125
+ /**
126
+ * Unregisters the app install built in `directory` and removes everything install wrote there — the
127
+ * removal runs even where Launch Services refuses, and the refusal is thrown after it.
128
+ */
129
+ export async function uninstall(options: Placement = {}): Promise<void> {
130
+ onMac()
131
+ const directory = options.directory ?? installDirectory()
132
+ const app = appIn(directory)
133
+ try {
134
+ if (
135
+ options.register !== false &&
136
+ (await Bun.file(`${app}/Contents/Info.plist`).exists())
137
+ )
138
+ await tool([LAUNCH_SERVICES, '-u', app])
139
+ } finally {
140
+ await rm(directory, { recursive: true, force: true })
141
+ }
142
+ }
package/src/opened.ts ADDED
@@ -0,0 +1,154 @@
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.
5
+ //
6
+ // RUN BY THE APP, NOT A SHELL: nothing of the visitor's login is here, so `bun`, `claude` and the
7
+ // `PATH` are what install found (`settings.json`) — an npm-installed `claude` is a `node` script, and
8
+ // 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
+
11
+ import { type Pairing, pairingOf } from './pairingLink.ts'
12
+ import { readLines } from './readLines.ts'
13
+
14
+ /** What install found, kept beside this file: `bun`, `claude`, and the `PATH` it was run on. */
15
+ export type HandlerSettings = { bun: string; claude: string; path: string }
16
+
17
+ /**
18
+ * What the visitor is asked before `pairing` runs. EVERY LINK IS ASKED (44.42): a code proves only
19
+ * that the site minted it, never that this visitor's browser asked for it, so an answer kept for a
20
+ * site would pair any page's link to whoever minted its code.
21
+ */
22
+ export function question(pairing: Pairing): string {
23
+ const tools =
24
+ pairing.tools.length === 0
25
+ ? 'It gets none of this Mac’s tools.'
26
+ : `It also asks for these tools of this Mac’s: ${pairing.tools.join(', ')}.`
27
+ return `${pairing.site} wants to use your Claude Code as its assistant, with its own tools, on your Claude account.\n\n${tools}\n\nIt runs @abide/bridge ${pairing.version}. Allow it only if you just asked to pair on that site.`
28
+ }
29
+
30
+ /** The bridge the link names, run as the command a site shows would run it. 44.32. */
31
+ export function bridgeArguments(
32
+ pairing: Pairing,
33
+ settings: HandlerSettings,
34
+ ): string[] {
35
+ return [
36
+ settings.bun,
37
+ 'x',
38
+ `@abide/bridge@${pairing.version}`,
39
+ pairing.site,
40
+ pairing.code,
41
+ '--claude',
42
+ settings.claude,
43
+ ...(pairing.tools.length === 0
44
+ ? []
45
+ : ['--', '--tools', pairing.tools.join(',')]),
46
+ ]
47
+ }
48
+
49
+ /** The `PATH` the bridge runs on: the directories of `bun` and `claude`, then the one install was run on. */
50
+ export function searchPath(settings: HandlerSettings): string {
51
+ const directories: string[] = []
52
+ for (const directory of [
53
+ settings.bun.slice(0, settings.bun.lastIndexOf('/')),
54
+ settings.claude.slice(0, settings.claude.lastIndexOf('/')),
55
+ ...settings.path.split(':'),
56
+ ])
57
+ if (directory !== '' && !directories.includes(directory))
58
+ directories.push(directory)
59
+ return directories.join(':')
60
+ }
61
+
62
+ /** Runs one AppleScript with `argument` as `item 1 of argv`, answering what it printed, or `undefined` where it failed. */
63
+ async function appleScript(
64
+ lines: string[],
65
+ argument: string,
66
+ ): Promise<string | undefined> {
67
+ const script: string[] = ['-e', 'on run argv']
68
+ for (const line of lines) script.push('-e', line)
69
+ script.push('-e', 'end run')
70
+ const child = Bun.spawn(['osascript', ...script, argument], {
71
+ stdout: 'pipe',
72
+ stderr: 'ignore',
73
+ })
74
+ const printed = (await new Response(child.stdout).text()).trim()
75
+ return (await child.exited) === 0 ? printed : undefined
76
+ }
77
+
78
+ /** Asks the visitor about `pairing` in a dialog; closing it is a no. */
79
+ async function allowed(pairing: Pairing): Promise<boolean> {
80
+ const pressed = await appleScript(
81
+ [
82
+ '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',
83
+ 'button returned of result',
84
+ ],
85
+ question(pairing),
86
+ )
87
+ return pressed === 'Allow'
88
+ }
89
+
90
+ /**
91
+ * Shows `line` as a notification, coalesced: one `osascript` at a time, and a line arriving while one
92
+ * shows replaces any still waiting, so a burst on the bridge's stderr is never read at its pace.
93
+ */
94
+ function notifier(): { show(line: string): void; settled(): Promise<void> } {
95
+ let waiting: string | undefined
96
+ let showing: Promise<void> | undefined
97
+ async function drain(): Promise<void> {
98
+ while (waiting !== undefined) {
99
+ const line = waiting
100
+ waiting = undefined
101
+ await appleScript(
102
+ [
103
+ 'display notification (item 1 of argv) with title "abide bridge"',
104
+ ],
105
+ line,
106
+ )
107
+ }
108
+ showing = undefined
109
+ }
110
+ return {
111
+ show(line) {
112
+ waiting = line
113
+ showing ??= drain()
114
+ },
115
+ async settled() {
116
+ await showing
117
+ },
118
+ }
119
+ }
120
+
121
+ /** Opens `link`: asks the visitor, then runs the bridge until it ends. Answers the exit code. */
122
+ async function open(link: string): Promise<number> {
123
+ const notifications = notifier()
124
+ function say(line: string): void {
125
+ console.error(line)
126
+ notifications.show(line)
127
+ }
128
+ const pairing = pairingOf(link)
129
+ if (pairing === undefined) {
130
+ say('That link is not a pairing this bridge opens.')
131
+ await notifications.settled()
132
+ return 1
133
+ }
134
+ const settings = (await Bun.file(
135
+ `${import.meta.dir}/settings.json`,
136
+ ).json()) as HandlerSettings
137
+ if (!(await allowed(pairing))) return 0
138
+ const running = Bun.spawn(bridgeArguments(pairing, settings), {
139
+ stdout: 'ignore',
140
+ stderr: 'pipe',
141
+ env: { ...Bun.env, PATH: searchPath(settings) },
142
+ })
143
+ for await (const line of readLines(
144
+ running.stderr as ReadableStream<Uint8Array>,
145
+ )) {
146
+ const said = line.trim()
147
+ if (said !== '') say(said)
148
+ }
149
+ const code = await running.exited
150
+ await notifications.settled()
151
+ return code
152
+ }
153
+
154
+ if (import.meta.main) process.exit(await open(process.argv[2] ?? ''))
@@ -0,0 +1,70 @@
1
+ // A PAIRING AS A LINK: what a site shows beside its command (44.40), opened by the handler
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).
5
+
6
+ // abide's `BRIDGE_SCHEME`, spelled out for `BRIDGE_PATH`'s reason — a test holds the two equal.
7
+ export const PAIRING_SCHEME = 'abide-bridge'
8
+
9
+ /** One pairing a link asks for. */
10
+ export type Pairing = {
11
+ site: string
12
+ code: string
13
+ version: string
14
+ tools: string[]
15
+ }
16
+
17
+ // A release on npm, never a range, a tag or a path: the version is laid into `bun x`'s package spec.
18
+ const RELEASE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
19
+ // abide's codes are base64url.
20
+ const CODE = /^[\w-]+$/
21
+ // A tool as `--tools` names one: `WebSearch`, `Bash`.
22
+ const TOOL = /^[A-Za-z][A-Za-z0-9]*$/
23
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
24
+
25
+ /**
26
+ * The pairing `link` asks for, or `undefined` where it is not one this bridge opens: another scheme,
27
+ * a site that is neither https nor loopback, or any part that would be read as more than it is. 44.41.
28
+ */
29
+ export function pairingOf(link: string): Pairing | undefined {
30
+ let url: URL
31
+ try {
32
+ url = new URL(link)
33
+ } catch {
34
+ return undefined
35
+ }
36
+ if (url.protocol !== `${PAIRING_SCHEME}:` || url.host !== 'pair')
37
+ return undefined
38
+ const site = url.searchParams.get('site') ?? ''
39
+ const code = url.searchParams.get('code') ?? ''
40
+ const version = url.searchParams.get('version') ?? ''
41
+ const tools = (url.searchParams.get('tools') ?? '')
42
+ .split(',')
43
+ .filter((tool) => tool !== '')
44
+ let siteUrl: URL
45
+ try {
46
+ siteUrl = new URL(site)
47
+ } catch {
48
+ return undefined
49
+ }
50
+ const secure =
51
+ siteUrl.protocol === 'https:' ||
52
+ (siteUrl.protocol === 'http:' && LOOPBACK.has(siteUrl.hostname))
53
+ if (
54
+ !secure ||
55
+ siteUrl.username !== '' ||
56
+ siteUrl.password !== '' ||
57
+ siteUrl.search !== '' ||
58
+ siteUrl.hash !== '' ||
59
+ !CODE.test(code) ||
60
+ !RELEASE.test(version)
61
+ )
62
+ return undefined
63
+ for (const tool of tools) if (!TOOL.test(tool)) return undefined
64
+ return {
65
+ site: `${siteUrl.origin}${siteUrl.pathname}`.replace(/\/+$/, ''),
66
+ code,
67
+ version,
68
+ tools,
69
+ }
70
+ }