-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ts
More file actions
233 lines (208 loc) · 7.87 KB
/
install.ts
File metadata and controls
233 lines (208 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* @file Install the Socket native messaging host manifest so Chrome can find
* and launch the host when the extension calls connectNative(). Native host
* manifest paths (Chrome): macOS ~/Library/Application
* Support/Google/Chrome/NativeMessagingHosts/<name>.json
* ~/Library/Application Support/Chromium/NativeMessagingHosts/<name>.json
* Linux ~/.config/google-chrome/NativeMessagingHosts/<name>.json
* ~/.config/chromium/NativeMessagingHosts/<name>.json Windows
* HKCU\Software\Google\Chrome\NativeMessagingHosts<name> → path to .json The
* manifest points to a small wrapper shell script (POSIX) or .cmd (Windows)
* that invokes `node /path/to/socket-lib/src/native-messaging/run.ts` with
* the `--native-messaging` flag so the host can detect its context even when
* the extension origin arg is absent (e.g. during local testing). Strip-types
* flag policy: Node 24+ no flag needed (default-on). Node 22.6–23 pass
* `--strip-types` (stable since 22.6). Node < 22.6 refuse to install;
* assertNodeStripTypesSupported throws. The flag decision is baked into the
* wrapper at install time. If the user later switches Node versions (e.g. via
* nvm) the host enforces the same floor at runtime via
* assertNodeStripTypesSupported.
*/
import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
import { spawnSync } from '@socketsecurity/lib-stable/process/spawn/child'
import {
getNodeVersion,
supportsNodeStripTypes,
supportsNodeStripTypesDefault,
} from '../constants/node'
import { DARWIN, WIN32 } from '../constants/platform'
import { getAppdata } from '../env/windows'
import { getHome } from '../env/home'
import {
detectActiveNodeManager,
nodeManagerUpgradeHint,
} from '../env/node-version-managers'
import { ErrorCtor } from '../primordials/error'
export const HOST_NAME = 'dev.socket.trusted_publisher_host'
export const MIN_NODE_VERSION_FOR_STRIP_TYPES = '22.6.0'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// Absolute path to the run.ts entry point in this package.
const HOST_SCRIPT = path.resolve(__dirname, 'run.ts')
export interface InstallOptions {
/**
* List of Chrome extension origin URLs that are allowed to connect to this
* host. Each entry is `chrome-extension://<extension-id>/`. Pass `['*']`
* during development to allow any extension (not for production).
*/
allowedOrigins: string[]
/**
* When `true`, reject wildcard origins (`['*']`) — production installs must
* pin to specific extension IDs.
*/
production?: boolean | undefined
/**
* Directory to write the wrapper script. Defaults to the same directory as
* this file (`src/native-messaging/`).
*/
wrapperDir?: string | undefined
}
export interface InstallResult {
manifestPaths: string[]
wrapperPath: string
}
/**
* Throw a clear, actionable error if the current Node runtime is too old to
* strip TypeScript types (i.e. < 22.6). Use at install time + host startup.
*
* The error message names the active Node version manager (nvm / fnm / volta /
* asdf / n / corepack / system) and gives the exact one-liner to upgrade — so
* the user can copy-paste the fix rather than searching docs.
*/
export function assertNodeStripTypesSupported(): void {
if (supportsNodeStripTypes()) {
return
}
const manager = detectActiveNodeManager()
const hint = nodeManagerUpgradeHint(manager, MIN_NODE_VERSION_FOR_STRIP_TYPES)
throw new ErrorCtor(
`Node ${getNodeVersion()} cannot run TypeScript directly. The Socket ` +
`native-messaging host needs Node ${MIN_NODE_VERSION_FOR_STRIP_TYPES}+ ` +
`(type-stripping is stable in Node 22.6 and default-on in Node 24).\n` +
`Detected Node manager: ${manager}\n` +
`To upgrade: ${hint}`,
)
}
export function buildManifest(
wrapperPath: string,
allowedOrigins: string[],
): object {
return {
name: HOST_NAME,
description:
'Socket Security — API token bridge for the Trusted Publisher extension',
path: wrapperPath,
type: 'stdio',
allowed_origins: allowedOrigins,
}
}
export function chromeManifestDirs(): string[] {
const home = getHome()
if (!home) {
throw new ErrorCtor('Cannot determine home directory.')
}
if (DARWIN) {
const lib = path.join(home, 'Library', 'Application Support')
return [
path.join(lib, 'Google', 'Chrome', 'NativeMessagingHosts'),
path.join(lib, 'Chromium', 'NativeMessagingHosts'),
]
}
if (WIN32) {
// On Windows we write the manifest file and then add the registry key.
// getAppdata() goes through the env rewire so tests can override.
const appData = getAppdata() ?? path.join(home, 'AppData', 'Roaming')
return [
path.join(
appData,
'Google',
'Chrome',
'User Data',
'NativeMessagingHosts',
),
]
}
// Linux (XDG)
const config = process.env['XDG_CONFIG_HOME'] ?? path.join(home, '.config')
return [
path.join(config, 'google-chrome', 'NativeMessagingHosts'),
path.join(config, 'chromium', 'NativeMessagingHosts'),
]
}
export function installNativeHost(opts: InstallOptions): InstallResult {
// Refuse to install on a Node too old to run the TypeScript host. The
// host's own runtime check is defensive (handles nvm switches between
// install and Chrome-exec); this one catches the obvious case where
// the installer is itself on a stale Node.
assertNodeStripTypesSupported()
const { allowedOrigins, production = false, wrapperDir = __dirname } = opts
if (production && allowedOrigins.includes('*')) {
throw new ErrorCtor(
"production mode rejects allowedOrigins '*' — pin to specific chrome-extension://<id>/ origins",
)
}
if (allowedOrigins.length === 0) {
throw new ErrorCtor(
"allowedOrigins must contain at least one origin; pass ['*'] for development",
)
}
const wrapperName = WIN32 ? `${HOST_NAME}.cmd` : `${HOST_NAME}.sh`
const wrapperPath = path.join(wrapperDir, wrapperName)
if (WIN32) {
writeWrapperWindows(wrapperPath)
} else {
writeWrapperPosix(wrapperPath)
}
const manifest = buildManifest(wrapperPath, allowedOrigins)
const dirs = chromeManifestDirs()
const written: string[] = []
for (const dir of dirs) {
mkdirSync(dir, { recursive: true })
const manifestPath = path.join(dir, `${HOST_NAME}.json`)
writeFileSync(
manifestPath,
JSON.stringify(manifest, null, 2) + '\n',
'utf8',
)
written.push(manifestPath)
}
if (WIN32 && written[0]) {
registerWindows(written[0])
}
return { manifestPaths: written, wrapperPath }
}
export function registerWindows(manifestPath: string): void {
const key = `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST_NAME}`
// Array-arg spawnSync (no shell, no injection surface). reg.exe is on
// every Windows install at %SystemRoot%\System32\reg.exe and on PATH.
spawnSync(
'reg',
['add', key, '/ve', '/t', 'REG_SZ', '/d', manifestPath, '/f'],
{
stdio: 'ignore',
shell: WIN32,
},
)
}
export function stripTypesFlag(): string {
// Empty string when no flag is needed (Node 24+); the wrapper template
// collapses adjacent spaces away naturally.
return supportsNodeStripTypesDefault() ? '' : '--strip-types '
}
export function writeWrapperPosix(wrapperPath: string): void {
const nodeBin = process.execPath
const flag = stripTypesFlag()
const script =
['#!/bin/sh', `exec "${nodeBin}" ${flag}"${HOST_SCRIPT}" "$@"`].join('\n') +
'\n'
writeFileSync(wrapperPath, script, { encoding: 'utf8' })
chmodSync(wrapperPath, 0o755)
}
export function writeWrapperWindows(wrapperPath: string): void {
const nodeBin = process.execPath
const flag = stripTypesFlag()
const script = `@echo off\r\n"${nodeBin}" ${flag}"${HOST_SCRIPT}" %*\r\n`
writeFileSync(wrapperPath, script, { encoding: 'utf8' })
}