dsh-remote-go 0.2.0 → 0.3.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/README.md +11 -3
- package/{client.js → dist/client.js} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two prompts a connection can pause on (unknown host key, foreign DSH already running) and the answers the Client sends back; each settles exactly once.
|
|
3
|
+
*
|
|
4
|
+
* The status/phase/progress writes are transitions now (`hostkey.pending` / `hostkey.answered` /
|
|
5
|
+
* `hostkey.timeout` / `conflict.pending` / `conflict.answered`); this module only owns the two
|
|
6
|
+
* deferred slots and the fingerprint/conflict data.
|
|
7
|
+
*/
|
|
8
|
+
import { errors, toErrorView } from './errors.js';
|
|
9
|
+
import { dispatch, promptScopeFacts } from './runtime/dispatch.js';
|
|
10
|
+
import { createDecision, nowIso } from './util.js';
|
|
11
|
+
/**
|
|
12
|
+
* The effect owner of this module.
|
|
13
|
+
*
|
|
14
|
+
* A prompt transition publishes a frame and (for `conflict.answered`) clears the conflict card;
|
|
15
|
+
* it never arms a timer, touches the link or tears anything down. The heavy effects are declared so
|
|
16
|
+
* the interface stays one shape, and throw if a future rule ever asks this module to perform one
|
|
17
|
+
* (that would be a wiring bug: the prompt module has no deps slice).
|
|
18
|
+
* @param ctx - the prompt context (settings, reporter, store).
|
|
19
|
+
* @returns the effect owner for one prompt transition.
|
|
20
|
+
*/
|
|
21
|
+
function promptEffects(ctx) {
|
|
22
|
+
const noEffect = (name) => {
|
|
23
|
+
throw new Error(`dispatch: the prompt module cannot perform the ${name} effect`);
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
emit: () => ctx.emitState(),
|
|
27
|
+
log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
|
|
28
|
+
logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
|
|
29
|
+
arm: () => noEffect('arm'),
|
|
30
|
+
disarm: () => noEffect('disarm'),
|
|
31
|
+
settlePrompts: (runtime) => {
|
|
32
|
+
cancelHostKeyPrompt(runtime);
|
|
33
|
+
cancelConflict(runtime);
|
|
34
|
+
},
|
|
35
|
+
closeLink: () => noEffect('closeLink'),
|
|
36
|
+
teardown: async () => noEffect('teardown'),
|
|
37
|
+
apply: (runtime, patch) => {
|
|
38
|
+
if (patch.kind === 'clear-conflict') {
|
|
39
|
+
runtime.conflict = null;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
noEffect('apply');
|
|
43
|
+
},
|
|
44
|
+
flushLogs: () => {
|
|
45
|
+
// No prompt rule flushes the log ring.
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Park the SSH handshake until the user answers the fingerprint prompt.
|
|
51
|
+
*
|
|
52
|
+
* A jump host and the target are different machines with different keys: the `role`
|
|
53
|
+
* decides which context the answer belongs to, so a jump-host confirmation can never be
|
|
54
|
+
* mistaken for the target's (B1).
|
|
55
|
+
*
|
|
56
|
+
* @returns whether the user accepted the key.
|
|
57
|
+
*/
|
|
58
|
+
export function requestHostKey(ctx, runtime, info, options = {}) {
|
|
59
|
+
const role = options.role === 'jump' ? 'jump' : 'target';
|
|
60
|
+
const isJump = role === 'jump';
|
|
61
|
+
// A per-host policy describes the target the user saved. A jump host has its own
|
|
62
|
+
// security context, so only the global policy applies to it.
|
|
63
|
+
const policy = isJump
|
|
64
|
+
? (ctx.settings()?.hostKeyPolicy ?? 'first-use')
|
|
65
|
+
: (runtime.entry.hostKeyPolicy ?? ctx.settings()?.hostKeyPolicy ?? 'first-use');
|
|
66
|
+
if (policy === 'strict')
|
|
67
|
+
throw errors.hostKeyUnknown(info.sha256);
|
|
68
|
+
const hostLabel = isJump && options.host ? ` ${options.host}` : '';
|
|
69
|
+
ctx.progress.log(runtime, 'info', `waiting for the ${isJump ? `jump host${hostLabel}` : 'host'} key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`);
|
|
70
|
+
const pending = {
|
|
71
|
+
sha256: info.sha256,
|
|
72
|
+
keyType: info.keyType,
|
|
73
|
+
role,
|
|
74
|
+
host: typeof options.host === 'string' && options.host !== '' ? options.host : null,
|
|
75
|
+
port: Number(options.port) || 22,
|
|
76
|
+
resolve: null,
|
|
77
|
+
};
|
|
78
|
+
const decision = createDecision(ctx.timers.hostKeyConfirmMs, () => {
|
|
79
|
+
// A prompt whose link already went away must not overwrite the state of that teardown.
|
|
80
|
+
if (runtime.pendingHostKey !== pending)
|
|
81
|
+
return false;
|
|
82
|
+
if (runtime.desired !== 'connected' || runtime.closing === true)
|
|
83
|
+
return false;
|
|
84
|
+
// `hostkey.timeout` owns the `error` card and the "do not retry" flag; the slot itself is
|
|
85
|
+
// cleared here (the settle hook below is idempotent).
|
|
86
|
+
void dispatch(promptEffects(ctx), runtime, { type: 'hostkey.timeout', view: toErrorView(errors.hostKeyUnknown(info.sha256)) }, promptScopeFacts(runtime), { caller: 'timer' });
|
|
87
|
+
runtime.pendingHostKey = null;
|
|
88
|
+
return false;
|
|
89
|
+
}, () => {
|
|
90
|
+
if (runtime.pendingHostKey === pending)
|
|
91
|
+
runtime.pendingHostKey = null;
|
|
92
|
+
});
|
|
93
|
+
pending.resolve = decision.settle;
|
|
94
|
+
runtime.pendingHostKey = pending;
|
|
95
|
+
// The card shows this while the prompt is open: nothing is pinned yet, so `pinned` stays null.
|
|
96
|
+
const fingerprint = {
|
|
97
|
+
sha256: info.sha256,
|
|
98
|
+
keyType: info.keyType,
|
|
99
|
+
status: 'pending',
|
|
100
|
+
pinned: null,
|
|
101
|
+
};
|
|
102
|
+
if (isJump) {
|
|
103
|
+
// The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked
|
|
104
|
+
// against the previous machine's key (review blocker 3).
|
|
105
|
+
runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
|
|
106
|
+
// The Client's dialog renders `HostView.fingerprint`, so the key being confirmed right now
|
|
107
|
+
// has to be the one shown there - even though the pin it may produce stays separate (B1).
|
|
108
|
+
runtime.fingerprint = { ...fingerprint };
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
runtime.fingerprint = fingerprint;
|
|
112
|
+
}
|
|
113
|
+
// The dialog data is in place before the transition publishes the frame that shows it.
|
|
114
|
+
void dispatch(promptEffects(ctx), runtime, {
|
|
115
|
+
type: 'hostkey.pending',
|
|
116
|
+
info: { sha256: info.sha256, keyType: info.keyType },
|
|
117
|
+
role,
|
|
118
|
+
host: pending.host,
|
|
119
|
+
port: pending.port,
|
|
120
|
+
}, promptScopeFacts(runtime), { caller: 'callback' });
|
|
121
|
+
return decision.promise;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Answer the host-key prompt. Pinning is written straight through to the store so
|
|
125
|
+
* a failed first attempt still remembers the key the user accepted.
|
|
126
|
+
*
|
|
127
|
+
* A jump host's key is remembered in memory only (`runtime.jumpFingerprint`): the store's
|
|
128
|
+
* `pinnedFingerprint` describes the target, and writing a jump key there would pin the
|
|
129
|
+
* target to the wrong machine forever (B1).
|
|
130
|
+
*/
|
|
131
|
+
export async function confirmHostKey(ctx, runtime, decision) {
|
|
132
|
+
// `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingHostKey).
|
|
133
|
+
const pending = runtime.pendingHostKey;
|
|
134
|
+
if (!pending) {
|
|
135
|
+
throw errors.invalidInput('fingerprint', {
|
|
136
|
+
zh: '没有待确认的主机指纹。',
|
|
137
|
+
en: 'No host key is pending confirmation.',
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
// A prompt is only answerable while it is the live one: a timeout, a disconnect or a
|
|
141
|
+
// replacement attempt already settled it, and a late answer must not revive it (M1).
|
|
142
|
+
if (runtime.status !== 'fingerprint-pending') {
|
|
143
|
+
throw errors.invalidInput('fingerprint', {
|
|
144
|
+
zh: '这个指纹提示已经失效,请在下次连接时重新确认。',
|
|
145
|
+
en: 'This host-key prompt is no longer active; confirm the key on the next connection.',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
|
|
149
|
+
throw errors.invalidInput('fingerprint', {
|
|
150
|
+
zh: '确认的指纹与待确认的不一致。',
|
|
151
|
+
en: 'The confirmed fingerprint does not match the pending one.',
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (decision.accept && decision.remember && pending.role !== 'jump') {
|
|
155
|
+
await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 });
|
|
156
|
+
runtime.entry = { ...runtime.entry, pinnedFingerprint: pending.sha256 };
|
|
157
|
+
}
|
|
158
|
+
const fingerprint = {
|
|
159
|
+
sha256: pending.sha256,
|
|
160
|
+
keyType: pending.keyType,
|
|
161
|
+
status: 'pinned',
|
|
162
|
+
pinned: decision.remember ? pending.sha256 : null,
|
|
163
|
+
};
|
|
164
|
+
if (pending.role === 'jump') {
|
|
165
|
+
// Keep the identity with the pin: the same remembered pin may only be used for the same
|
|
166
|
+
// jump host and port (review blocker 3).
|
|
167
|
+
runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
|
|
168
|
+
// The dialog that asked about the jump host must not start describing the target as soon
|
|
169
|
+
// as it is answered: keep showing what was confirmed until the target is dialled.
|
|
170
|
+
runtime.fingerprint = { ...fingerprint };
|
|
171
|
+
ctx.progress.log(runtime, 'info', `jump host key accepted${decision.remember ? ' and remembered for this session' : ''} (${pending.host ?? 'jump host'}: ${pending.sha256})`);
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
runtime.fingerprint = fingerprint;
|
|
175
|
+
}
|
|
176
|
+
// `hostkey.answered` owns the `connecting` card and the "user said no" flag. The slot is still
|
|
177
|
+
// installed here (the rule's guard reads it) and is cleared right after, as before.
|
|
178
|
+
void dispatch(promptEffects(ctx), runtime, { type: 'hostkey.answered', accept: decision.accept === true }, promptScopeFacts(runtime), { caller: 'callback' });
|
|
179
|
+
runtime.pendingHostKey = null;
|
|
180
|
+
pending.resolve(decision.accept === true);
|
|
181
|
+
return { ok: true };
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Abandon a pending host-key prompt (teardown, host removal, lost transport). Resolving it
|
|
185
|
+
* with `false` makes the stalled `verifyHostKey` throw instead of holding the connect
|
|
186
|
+
* promise open until the prompt times out (M1).
|
|
187
|
+
*/
|
|
188
|
+
export function cancelHostKeyPrompt(runtime) {
|
|
189
|
+
// `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingHostKey).
|
|
190
|
+
const pending = runtime.pendingHostKey;
|
|
191
|
+
runtime.pendingHostKey = null;
|
|
192
|
+
if (pending)
|
|
193
|
+
pending.resolve(false);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Pause the pipeline for a decision about foreign remote processes.
|
|
197
|
+
* Mirrors the host-key prompt: a status, a promise, and a bounded timeout.
|
|
198
|
+
*/
|
|
199
|
+
export function askConflict(ctx, runtime, processes) {
|
|
200
|
+
// The card data is in place before the transition publishes the frame that renders it.
|
|
201
|
+
runtime.conflict = {
|
|
202
|
+
detectedAt: nowIso(),
|
|
203
|
+
processes: processes.slice(0, 20).map((process) => ({
|
|
204
|
+
pid: process.pid,
|
|
205
|
+
command: String(process.command ?? '').slice(0, 400),
|
|
206
|
+
})),
|
|
207
|
+
};
|
|
208
|
+
// A prompt the user never sees (the link was cancelled in the same tick) must not throw into
|
|
209
|
+
// the pipeline; the refusal is logged and the caller's own guard reports the cancellation.
|
|
210
|
+
void dispatch(promptEffects(ctx), runtime, { type: 'conflict.pending', count: processes.length }, promptScopeFacts(runtime), { caller: 'callback' });
|
|
211
|
+
const decision = createDecision(ctx.timers.conflictConfirmMs, () => ({ action: 'cancel', timedOut: true }), (value) => {
|
|
212
|
+
// The transition owns the `probing` card, the "user said no" flag and the conflict card.
|
|
213
|
+
// A settlement that arrives after the link was torn down has no state to publish (the
|
|
214
|
+
// teardown's own frame follows), so only the card is cleared here — the same guard today's
|
|
215
|
+
// `desired === 'connected'` test provided, expressed on the status the rule checks.
|
|
216
|
+
if (runtime.status === 'conflict-pending') {
|
|
217
|
+
void dispatch(promptEffects(ctx), runtime, {
|
|
218
|
+
type: 'conflict.answered',
|
|
219
|
+
action: value.action,
|
|
220
|
+
...(value.timedOut === true ? { timedOut: true } : {}),
|
|
221
|
+
}, promptScopeFacts(runtime), { caller: 'silent' });
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
runtime.conflict = null;
|
|
225
|
+
}
|
|
226
|
+
// `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
|
|
227
|
+
if (runtime.pendingConflict?.resolve === decision.settle) {
|
|
228
|
+
runtime.pendingConflict = null;
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
runtime.pendingConflict = { processes, resolve: decision.settle };
|
|
232
|
+
return decision.promise;
|
|
233
|
+
}
|
|
234
|
+
export function confirmConflict(runtime, decision) {
|
|
235
|
+
// `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
|
|
236
|
+
const pending = runtime.pendingConflict;
|
|
237
|
+
if (!pending) {
|
|
238
|
+
throw errors.invalidInput('conflict', {
|
|
239
|
+
zh: '没有待确认的远端 DSH 冲突。',
|
|
240
|
+
en: 'No remote DSH conflict is pending confirmation.',
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
const action = decision?.action;
|
|
244
|
+
if (action !== 'stop' && action !== 'alongside' && action !== 'cancel') {
|
|
245
|
+
throw errors.invalidInput('conflict', {
|
|
246
|
+
zh: '请选择停止手工实例、与它并存,或取消连接。',
|
|
247
|
+
en: 'Choose whether to stop the manual instance, keep it alongside, or cancel.',
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
// The three-way guard directly above is the runtime proof; `ConflictDecision.action` is
|
|
251
|
+
// `unknown` on purpose (it is the Client's body) and inequality cannot narrow `unknown`, so the
|
|
252
|
+
// assertion names the type the guard already established. It erases at emit time.
|
|
253
|
+
pending.resolve({ action });
|
|
254
|
+
return { ok: true };
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Abandon a pending conflict prompt (teardown). Resolving it with `cancel` makes
|
|
258
|
+
* the stalled `askConflict` call return instead of holding the pipeline open.
|
|
259
|
+
*/
|
|
260
|
+
export function cancelConflict(runtime) {
|
|
261
|
+
// `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
|
|
262
|
+
const pending = runtime.pendingConflict;
|
|
263
|
+
// The answer is delivered while the slot is still installed: the settlement hook's
|
|
264
|
+
// `conflict.answered` guard reads it. Both the hook and this function clear the slot, and both
|
|
265
|
+
// clears are idempotent (M1).
|
|
266
|
+
if (pending)
|
|
267
|
+
pending.resolve({ action: 'cancel' });
|
|
268
|
+
runtime.pendingConflict = null;
|
|
269
|
+
runtime.conflict = null;
|
|
270
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounds of one host's cookie jar. The remote decides what to set, so the jar needs a ceiling:
|
|
3
|
+
* 64 cookies of at most 4 KiB keep a hostile or simply broken remote from growing the process,
|
|
4
|
+
* and a cookie the remote marks `Secure` never lands in this plaintext, in-memory jar at all.
|
|
5
|
+
*/
|
|
6
|
+
export const MAX_JAR_COOKIES = 64;
|
|
7
|
+
export const MAX_COOKIE_VALUE = 4096;
|
|
8
|
+
export const MAX_COOKIE_NAME = 128;
|
|
9
|
+
/**
|
|
10
|
+
* Parse one `Set-Cookie` line into the jar entry it should replace.
|
|
11
|
+
* Only the attributes that decide whether and where the value is sent are kept.
|
|
12
|
+
* @param line - one Set-Cookie header value.
|
|
13
|
+
*/
|
|
14
|
+
export function parseSetCookie(line) {
|
|
15
|
+
const [pair, ...attributes] = String(line ?? '').split(';');
|
|
16
|
+
const equals = pair.indexOf('=');
|
|
17
|
+
if (equals <= 0)
|
|
18
|
+
return null;
|
|
19
|
+
const name = pair.slice(0, equals).trim();
|
|
20
|
+
const value = pair.slice(equals + 1).trim();
|
|
21
|
+
if (name === '' || name.length > MAX_COOKIE_NAME)
|
|
22
|
+
return null;
|
|
23
|
+
if (value.length > MAX_COOKIE_VALUE)
|
|
24
|
+
return null;
|
|
25
|
+
let cookiePath = '/';
|
|
26
|
+
let expiresAt = Number.POSITIVE_INFINITY;
|
|
27
|
+
let secure = false;
|
|
28
|
+
for (const attribute of attributes) {
|
|
29
|
+
const at = attribute.indexOf('=');
|
|
30
|
+
const key = (at === -1 ? attribute : attribute.slice(0, at)).trim().toLowerCase();
|
|
31
|
+
const raw = at === -1 ? '' : attribute.slice(at + 1).trim();
|
|
32
|
+
if (key === 'path' && raw.startsWith('/'))
|
|
33
|
+
cookiePath = raw;
|
|
34
|
+
if (key === 'secure')
|
|
35
|
+
secure = true;
|
|
36
|
+
if (key === 'max-age') {
|
|
37
|
+
const seconds = Number(raw);
|
|
38
|
+
if (Number.isFinite(seconds))
|
|
39
|
+
expiresAt = seconds <= 0 ? 0 : Date.now() + seconds * 1000;
|
|
40
|
+
}
|
|
41
|
+
if (key === 'expires' && expiresAt === Number.POSITIVE_INFINITY) {
|
|
42
|
+
const parsed = Date.parse(raw);
|
|
43
|
+
if (Number.isFinite(parsed))
|
|
44
|
+
expiresAt = parsed;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { name, value, path: cookiePath, expiresAt, secure };
|
|
48
|
+
}
|
|
49
|
+
/** One host's cookies, keyed by name; values never leave this process. */
|
|
50
|
+
function createCookieJar() {
|
|
51
|
+
return new Map();
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Store every non-expired cookie from one response and drop the ones it cleared.
|
|
55
|
+
* @param jar - host jar.
|
|
56
|
+
* @param setCookie - raw Set-Cookie value(s).
|
|
57
|
+
*/
|
|
58
|
+
export function storeCookies(jar, setCookie) {
|
|
59
|
+
if (setCookie === undefined)
|
|
60
|
+
return;
|
|
61
|
+
for (const line of Array.isArray(setCookie) ? setCookie : [setCookie]) {
|
|
62
|
+
const entry = parseSetCookie(line);
|
|
63
|
+
if (entry === null)
|
|
64
|
+
continue;
|
|
65
|
+
if (entry.value === '' || entry.expiresAt <= Date.now()) {
|
|
66
|
+
jar.delete(entry.name);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
// The tunnel is plain HTTP to 127.0.0.1, so a `Secure` cookie is not one this jar may
|
|
70
|
+
// keep: storing and replaying it would downgrade a flag the remote asked for.
|
|
71
|
+
if (entry.secure) {
|
|
72
|
+
jar.delete(entry.name);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (!jar.has(entry.name) && jar.size >= MAX_JAR_COOKIES)
|
|
76
|
+
continue;
|
|
77
|
+
jar.set(entry.name, { name: entry.name, value: entry.value, path: entry.path, expiresAt: entry.expiresAt });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Cookies whose path covers the upstream path, as one Cookie header value.
|
|
82
|
+
* @param jar - host jar.
|
|
83
|
+
* @param path - upstream request path.
|
|
84
|
+
*/
|
|
85
|
+
export function cookieHeader(jar, path) {
|
|
86
|
+
const now = Date.now();
|
|
87
|
+
const parts = [];
|
|
88
|
+
for (const [name, entry] of jar) {
|
|
89
|
+
if (entry.expiresAt <= now) {
|
|
90
|
+
jar.delete(name);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const covers = entry.path === '/' ||
|
|
94
|
+
path === entry.path ||
|
|
95
|
+
path.startsWith(`${entry.path.endsWith('/') ? entry.path.slice(0, -1) : entry.path}/`);
|
|
96
|
+
if (covers)
|
|
97
|
+
parts.push(`${name}=${entry.value}`);
|
|
98
|
+
}
|
|
99
|
+
return parts.join('; ');
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Create the per-host jar book.
|
|
103
|
+
*
|
|
104
|
+
* `authorityOf` is injected instead of imported: `remoteAuthority` is defined next to the header
|
|
105
|
+
* rewriting, and `headers.ts` already imports `cookieHeader` from here, so reaching back would
|
|
106
|
+
* make the two leaf modules import each other.
|
|
107
|
+
*/
|
|
108
|
+
export function createJarBook(authorityOf) {
|
|
109
|
+
const jars = new Map();
|
|
110
|
+
/**
|
|
111
|
+
* The per-host cookie jar is bound to the remote authority it was filled from: after a
|
|
112
|
+
* restart or a re-attach the remote comes back on a new random port, and cookies issued
|
|
113
|
+
* by the old instance must not be sent to the new one (nor kept after the host is gone).
|
|
114
|
+
*/
|
|
115
|
+
function jarFor(hostId, target) {
|
|
116
|
+
const authority = authorityOf(target);
|
|
117
|
+
let entry = jars.get(hostId);
|
|
118
|
+
if (entry === undefined || entry.authority !== authority) {
|
|
119
|
+
entry = { authority, jar: createCookieJar() };
|
|
120
|
+
jars.set(hostId, entry);
|
|
121
|
+
}
|
|
122
|
+
return entry.jar;
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
jarFor,
|
|
126
|
+
clear(hostId) {
|
|
127
|
+
if (hostId === undefined)
|
|
128
|
+
jars.clear();
|
|
129
|
+
else
|
|
130
|
+
jars.delete(hostId);
|
|
131
|
+
},
|
|
132
|
+
get(hostId) {
|
|
133
|
+
return jars.get(hostId)?.jar;
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Header rewriting for the same-origin proxy: an allowlist on the way out, a blocklist on the way
|
|
3
|
+
* back, and the two authority fields rewritten so the remote keeps seeing its own loopback seat.
|
|
4
|
+
*
|
|
5
|
+
* The proxy hands the browser a page from another origin without handing it a second origin, so
|
|
6
|
+
* `Host`/`Origin` are rewritten to the remote's own loopback authority (its authority-bound cookie
|
|
7
|
+
* and same-origin fence keep working), while the browser's own local credentials and the
|
|
8
|
+
* traffic-shaping headers of this hop stay here.
|
|
9
|
+
*/
|
|
10
|
+
import { REMOTE_VIEW_PREFIX } from '../constants.js';
|
|
11
|
+
import { cookieHeader } from './cookies.js';
|
|
12
|
+
/** Headers that describe one hop and must not be copied to the other connection. */
|
|
13
|
+
const HOP_BY_HOP = new Set([
|
|
14
|
+
'connection',
|
|
15
|
+
'keep-alive',
|
|
16
|
+
'proxy-authenticate',
|
|
17
|
+
'proxy-authorization',
|
|
18
|
+
'te',
|
|
19
|
+
'trailer',
|
|
20
|
+
'transfer-encoding',
|
|
21
|
+
'upgrade',
|
|
22
|
+
]);
|
|
23
|
+
/**
|
|
24
|
+
* The request headers this proxy forwards. This is an allowlist on purpose: the browser's own
|
|
25
|
+
* credentials belong to the *local* origin (`authorization`, `cookie`, `x-dsh-*`) and the
|
|
26
|
+
* traffic-shaping headers belong to this hop (`forwarded`, `x-forwarded-*`, `sec-fetch-*`).
|
|
27
|
+
* A blacklist forwarded them all to a host that the remote controls.
|
|
28
|
+
*/
|
|
29
|
+
const FORWARDED_REQUEST_HEADERS = new Set([
|
|
30
|
+
'accept',
|
|
31
|
+
'accept-encoding',
|
|
32
|
+
'accept-language',
|
|
33
|
+
'cache-control',
|
|
34
|
+
'content-length',
|
|
35
|
+
'content-type',
|
|
36
|
+
'range',
|
|
37
|
+
'user-agent',
|
|
38
|
+
'x-requested-with',
|
|
39
|
+
]);
|
|
40
|
+
/** Conditional-request headers: `if-match`, `if-none-match`, `if-modified-since`, `if-range`, … */
|
|
41
|
+
const FORWARDED_REQUEST_PREFIX = 'if-';
|
|
42
|
+
/** The fields a WebSocket handshake needs, forwarded only on an upgrade. */
|
|
43
|
+
const UPGRADE_REQUEST_HEADERS = new Set([
|
|
44
|
+
'connection',
|
|
45
|
+
'upgrade',
|
|
46
|
+
'sec-websocket-key',
|
|
47
|
+
'sec-websocket-version',
|
|
48
|
+
'sec-websocket-protocol',
|
|
49
|
+
'sec-websocket-extensions',
|
|
50
|
+
]);
|
|
51
|
+
/**
|
|
52
|
+
* Response headers a remote page may not set on the local origin. `clear-site-data` would let a
|
|
53
|
+
* compromised remote wipe this GUI's own cookies and storage, `access-control-*` would open the
|
|
54
|
+
* local origin to other sites, and `refresh` / `content-location` / `report-to` / `nel` /
|
|
55
|
+
* `permissions-policy` / `alt-svc` redirect or reshape the browser's view of a server it does
|
|
56
|
+
* not own.
|
|
57
|
+
*/
|
|
58
|
+
const BLOCKED_RESPONSE_HEADERS = new Set([
|
|
59
|
+
'clear-site-data',
|
|
60
|
+
'refresh',
|
|
61
|
+
'content-location',
|
|
62
|
+
'report-to',
|
|
63
|
+
'nel',
|
|
64
|
+
'permissions-policy',
|
|
65
|
+
'alt-svc',
|
|
66
|
+
]);
|
|
67
|
+
/** Every `access-control-*` response header belongs to the remote's origin, not this one. */
|
|
68
|
+
const BLOCKED_RESPONSE_PREFIX = 'access-control-';
|
|
69
|
+
/**
|
|
70
|
+
* Whether one browser request header may reach the remote.
|
|
71
|
+
* @param name - lowercase header name.
|
|
72
|
+
* @param preserveUpgrade - whether this is a WebSocket handshake.
|
|
73
|
+
*/
|
|
74
|
+
export function forwardableRequestHeader(name, preserveUpgrade = false) {
|
|
75
|
+
if (FORWARDED_REQUEST_HEADERS.has(name))
|
|
76
|
+
return true;
|
|
77
|
+
if (name.startsWith(FORWARDED_REQUEST_PREFIX))
|
|
78
|
+
return true;
|
|
79
|
+
return preserveUpgrade === true && UPGRADE_REQUEST_HEADERS.has(name);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Whether one upstream response header may reach the browser.
|
|
83
|
+
* @param name - lowercase header name.
|
|
84
|
+
*/
|
|
85
|
+
export function forwardableResponseHeader(name) {
|
|
86
|
+
if (BLOCKED_RESPONSE_HEADERS.has(name))
|
|
87
|
+
return false;
|
|
88
|
+
if (name.startsWith(BLOCKED_RESPONSE_PREFIX))
|
|
89
|
+
return false;
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
/** Absolute origin of the remote's own listener, as the remote sees itself through the tunnel. */
|
|
93
|
+
export function remoteOrigin(target) {
|
|
94
|
+
const port = Number(target.remotePort);
|
|
95
|
+
return `http://127.0.0.1:${Number.isInteger(port) && port > 0 ? port : target.localPort}`;
|
|
96
|
+
}
|
|
97
|
+
/** The remote's own `host:port`, as its `Host` header and its cookies are bound to it. */
|
|
98
|
+
export function remoteAuthority(target) {
|
|
99
|
+
return remoteOrigin(target).slice('http://'.length);
|
|
100
|
+
}
|
|
101
|
+
/** Rewrite an absolute URL from the local origin to the remote's origin, keeping its path. */
|
|
102
|
+
function rewriteSameOrigin(value, localOrigin, target) {
|
|
103
|
+
const local = typeof localOrigin === 'string' ? localOrigin.replace(/\/$/, '') : '';
|
|
104
|
+
const text = String(value);
|
|
105
|
+
if (local !== '' && (text === local || text.startsWith(`${local}/`))) {
|
|
106
|
+
return remoteOrigin(target) + text.slice(local.length);
|
|
107
|
+
}
|
|
108
|
+
return text;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Request headers for the upstream: only the allowlisted content headers are copied, the two
|
|
112
|
+
* authority fields are rewritten, and only this host's own cookies are added.
|
|
113
|
+
* @param rawHeaders - node raw header list.
|
|
114
|
+
*/
|
|
115
|
+
export function upstreamHeaders(rawHeaders, input) {
|
|
116
|
+
const out = {};
|
|
117
|
+
const preserveUpgrade = input.preserveUpgrade === true;
|
|
118
|
+
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
119
|
+
const name = String(rawHeaders[at]).toLowerCase();
|
|
120
|
+
const value = rawHeaders[at + 1];
|
|
121
|
+
if (name === 'host' || name === 'cookie')
|
|
122
|
+
continue;
|
|
123
|
+
if (name === 'origin') {
|
|
124
|
+
out.origin = remoteOrigin(input.target);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (name === 'referer') {
|
|
128
|
+
out.referer = rewriteSameOrigin(value, input.localOrigin, input.target);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!forwardableRequestHeader(name, preserveUpgrade))
|
|
132
|
+
continue;
|
|
133
|
+
out[name] = out[name] === undefined ? value : [].concat(out[name], value);
|
|
134
|
+
}
|
|
135
|
+
out.host = remoteAuthority(input.target);
|
|
136
|
+
const cookies = cookieHeader(input.jar, input.path);
|
|
137
|
+
if (cookies !== '')
|
|
138
|
+
out.cookie = cookies;
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Drop only the `frame-ancestors` directive of a CSP: the proxy exists to frame that one page,
|
|
143
|
+
* and a hostile-looking directive would otherwise make a hardened remote unusable in a browser.
|
|
144
|
+
* Every other directive stays exactly as the remote sent it.
|
|
145
|
+
* @param value - one Content-Security-Policy value.
|
|
146
|
+
*/
|
|
147
|
+
export function withoutFrameAncestors(value) {
|
|
148
|
+
return String(value)
|
|
149
|
+
.split(';')
|
|
150
|
+
.filter((directive) => !/^\s*frame-ancestors\b/i.test(directive))
|
|
151
|
+
.map((directive) => directive.trim())
|
|
152
|
+
.filter((directive) => directive !== '')
|
|
153
|
+
.join('; ');
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Rewrite one upstream `Location` for the browser.
|
|
157
|
+
*
|
|
158
|
+
* A redirect that names the remote's own loopback listener is folded back under the view
|
|
159
|
+
* prefix, so a form post or a token exchange stays inside the frame. Everything else that is an
|
|
160
|
+
* absolute URL — another host, another scheme, a protocol-relative `//evil.example`, or a
|
|
161
|
+
* different loopback port — is refused (`null`): the header is dropped, because navigation
|
|
162
|
+
* inside this same-origin frame must never leave the seat the user opened. A relative
|
|
163
|
+
* reference (`.`, `./next`, `/assets/app.js`) is already resolved against that seat, so it is
|
|
164
|
+
* passed through untouched.
|
|
165
|
+
* @param value - one upstream Location header value.
|
|
166
|
+
* @returns the header value to send, or null to drop the header.
|
|
167
|
+
*/
|
|
168
|
+
export function safeLocation(value, input = {}) {
|
|
169
|
+
const text = String(value ?? '')
|
|
170
|
+
.replace(/[\r\n]/g, '')
|
|
171
|
+
.trim();
|
|
172
|
+
if (text === '')
|
|
173
|
+
return null;
|
|
174
|
+
if (input.hostId && input.remoteOrigin) {
|
|
175
|
+
if (text === input.remoteOrigin)
|
|
176
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}/`;
|
|
177
|
+
if (text.startsWith(`${input.remoteOrigin}/`)) {
|
|
178
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}${text.slice(input.remoteOrigin.length)}`;
|
|
179
|
+
}
|
|
180
|
+
if (text.startsWith(`${input.remoteOrigin}?`) || text.startsWith(`${input.remoteOrigin}#`)) {
|
|
181
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}/${text.slice(input.remoteOrigin.length)}`;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Any scheme (`https:`, `javascript:`, `data:`…) is an absolute target.
|
|
185
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(text))
|
|
186
|
+
return null;
|
|
187
|
+
// A backslash is a slash to the URL parser for special schemes: `/\evil.example/x` and
|
|
188
|
+
// `\/evil.example` both resolve to `http://evil.example/`, so a surviving backslash in what
|
|
189
|
+
// looks like a relative reference is an off-origin escape. (`%5c` stays percent-encoded and is
|
|
190
|
+
// not a separator, so it is not caught here.)
|
|
191
|
+
if (text.includes('\\'))
|
|
192
|
+
return null;
|
|
193
|
+
// `//host/…`: a browser reads it as protocol-relative, i.e. off-origin.
|
|
194
|
+
if (text.startsWith('//'))
|
|
195
|
+
return null;
|
|
196
|
+
return text;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Response headers to hand the browser: drop hop-by-hop fields, this connection's framing, the
|
|
200
|
+
* remote's cookies (they go to the jar), any frame denial the remote inherited from another
|
|
201
|
+
* deployment, and browser-policy headers the remote must not set on the local origin. A
|
|
202
|
+
* `Location` that names the remote's own listener is folded back under the view prefix; any
|
|
203
|
+
* other absolute target is dropped so a redirect cannot slip out of the frame.
|
|
204
|
+
* @param rawHeaders - upstream raw header list.
|
|
205
|
+
* @returns flat [name, value, …] pairs.
|
|
206
|
+
*/
|
|
207
|
+
export function responseHeaders(rawHeaders, input = {}) {
|
|
208
|
+
const out = [];
|
|
209
|
+
const preserveUpgrade = input.preserveUpgrade === true;
|
|
210
|
+
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
211
|
+
const name = String(rawHeaders[at]).toLowerCase();
|
|
212
|
+
// `Connection`/`Upgrade` are hop-by-hop, except in the response to a WebSocket handshake:
|
|
213
|
+
// dropping them there would turn a valid 101 into a protocol error.
|
|
214
|
+
if (HOP_BY_HOP.has(name) && !(preserveUpgrade && (name === 'connection' || name === 'upgrade')))
|
|
215
|
+
continue;
|
|
216
|
+
if (name === 'set-cookie' || name === 'x-frame-options')
|
|
217
|
+
continue;
|
|
218
|
+
if (!forwardableResponseHeader(name))
|
|
219
|
+
continue;
|
|
220
|
+
if (name === 'content-security-policy') {
|
|
221
|
+
out.push(rawHeaders[at], withoutFrameAncestors(String(rawHeaders[at + 1])));
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (name === 'location') {
|
|
225
|
+
const location = safeLocation(rawHeaders[at + 1], input);
|
|
226
|
+
if (location === null)
|
|
227
|
+
continue;
|
|
228
|
+
out.push(rawHeaders[at], location);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
out.push(rawHeaders[at], rawHeaders[at + 1]);
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Rewrite one raw upstream response head (status line + headers, without the final blank line).
|
|
237
|
+
*
|
|
238
|
+
* The upgrade path forwards a 101 byte-for-byte if left alone, which also forwarded
|
|
239
|
+
* `Set-Cookie` and every browser-policy header the remote chose to attach to the handshake. The
|
|
240
|
+
* same policy as `responseHeaders` applies here; only the status line and the header block are
|
|
241
|
+
* touched, never the frames that follow.
|
|
242
|
+
* @param headText - latin1-decoded head, `HTTP/1.1 101 …\r\nkey: value…`.
|
|
243
|
+
* @returns the filtered head (without the trailing blank line), or '' when unparseable.
|
|
244
|
+
*/
|
|
245
|
+
export function filterResponseHead(headText, input = {}) {
|
|
246
|
+
const lines = String(headText ?? '').split('\r\n');
|
|
247
|
+
const statusLine = lines.shift() ?? '';
|
|
248
|
+
if (!/^HTTP\/1\.[01] \d{3}(?: .*)?$/.test(statusLine))
|
|
249
|
+
return '';
|
|
250
|
+
const raw = [];
|
|
251
|
+
for (const line of lines) {
|
|
252
|
+
const colon = line.indexOf(':');
|
|
253
|
+
if (colon <= 0)
|
|
254
|
+
continue;
|
|
255
|
+
raw.push(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
|
|
256
|
+
}
|
|
257
|
+
const filtered = responseHeaders(raw, { ...input, preserveUpgrade: true });
|
|
258
|
+
let out = `${statusLine}\r\n`;
|
|
259
|
+
for (let at = 0; at < filtered.length; at += 2)
|
|
260
|
+
out += `${filtered[at]}: ${filtered[at + 1]}\r\n`;
|
|
261
|
+
return out;
|
|
262
|
+
}
|