Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sshEnvironment.ts

242 lines9.1 KB

1import {
2 bootstrapRemoteBearerSession,
3 fetchRemoteSessionState,
4 RemoteEnvironmentAuthUndeclaredStatusError,
5 type RemoteEnvironmentAuthError,
6} from "@t3tools/client-runtime/authorization";
7import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
8import {
9 EnvironmentAuthInvalidError,
10 DesktopDiscoveredSshHostSchema,
11 DesktopSshBearerBootstrapInputSchema,
12 DesktopSshBearerRequestInputSchema,
13 DesktopSshEnvironmentEnsureInputSchema,
14 DesktopSshEnvironmentEnsureResultSchema,
15 DesktopSshEnvironmentTargetSchema,
16 DesktopSshHttpBaseUrlInputSchema,
17 DesktopSshPasswordPromptCancelledType,
18 DesktopSshPasswordPromptResolutionInputSchema,
19 ExecutionEnvironmentDescriptor,
20 EnvironmentInternalError,
21 EnvironmentOperationForbiddenError,
22 EnvironmentRequestInvalidError,
23 EnvironmentScopeRequiredError,
24 AuthAccessTokenResult,
25 AuthSessionState,
26} from "@t3tools/contracts";
27import { SshHttpBridgeError } from "@t3tools/ssh/errors";
28import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";
29import * as Effect from "effect/Effect";
30import * as Schema from "effect/Schema";
31import * as Electron from "electron";
32​
33import * as IpcChannels from "../channels.ts";
34import * as DesktopIpc from "../DesktopIpc.ts";
35import * as SshOnboardingClaims from "../SshOnboardingClaims.ts";
36import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
37import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
38​
39const DesktopSshEnvironmentRequestOperation = Schema.Literals([
40 "fetch-environment-descriptor",
41 "bootstrap-bearer-session",
42 "fetch-session-state",
43]);
44type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type;
45​
46type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
47​
48const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
49const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
50const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
51const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
52const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
53const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is(
54 RemoteEnvironmentAuthUndeclaredStatusError,
55);
56const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
57​
58function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
59 if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) {
60 return cause.status ?? null;
61 }
62 if (isEnvironmentRequestInvalidError(cause)) {
63 return 400;
64 }
65 if (isEnvironmentAuthInvalidError(cause)) {
66 return 401;
67 }
68 if (isEnvironmentScopeRequiredError(cause)) {
69 return 403;
70 }
71 if (isEnvironmentOperationForbiddenError(cause)) {
72 return 403;
73 }
74 if (isEnvironmentInternalError(cause)) {
75 return 500;
76 }
77 return null;
79​
80export class DesktopSshEnvironmentRequestError extends Schema.TaggedError<DesktopSshEnvironmentRequestError>()(
81 "DesktopSshEnvironmentRequestError",
82 {
83 operation: DesktopSshEnvironmentRequestOperation,
84 cause: Schema.Defect(),
85 sshHttpStatus: Schema.NullOr(Schema.Number),
86 },
87) {
88 // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing.
89 override get message() {
90 const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `;
91 return `${prefix}SSH remote API request failed during ${this.operation}.`;
92 }
94​
95const withLoopbackSshApi =
96 <A, R>(
97 operation: DesktopSshEnvironmentRequestOperation,
98 use: (httpBaseUrl: string) => Effect.Effect<A, RemoteEnvironmentAuthError, R>,
99 ) =>
100 (httpBaseUrl: string): Effect.Effect<A, DesktopSshEnvironmentRequestError, R> =>
101 resolveLoopbackSshHttpBaseUrl(httpBaseUrl).pipe(
102 Effect.flatMap(use),
103 Effect.mapError(
104 (cause) =>
105 new DesktopSshEnvironmentRequestError({
106 operation,
107 cause,
108 sshHttpStatus: readSshHttpStatus(cause),
109 }),
110 ),
111 );
112​
113export const discoverSshHosts = DesktopIpc.makeIpcMethod({
114 channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
115 payload: Schema.Void,
116 result: Schema.Array(DesktopDiscoveredSshHostSchema),
117 handler: Effect.fn("desktop.ipc.sshEnvironment.discoverHosts")(function* () {
118 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
119 return yield* sshEnvironment.discoverHosts();
120 }),
121});
122​
123export const resolveSshHost = DesktopIpc.makeIpcMethod({
124 channel: IpcChannels.RESOLVE_SSH_HOST_CHANNEL,
125 payload: Schema.String,
126 result: DesktopSshEnvironmentTargetSchema,
127 handler: Effect.fn("desktop.ipc.sshEnvironment.resolveHost")(function* (alias) {
128 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
129 return yield* sshEnvironment.resolveHost(alias);
130 }),
131});
132​
133export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
134 channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
135 payload: DesktopSshEnvironmentEnsureInputSchema,
136 result: DesktopSshEnvironmentEnsureResultSchema,
137 handler: Effect.fn("desktop.ipc.sshEnvironment.ensureEnvironment")(function* (
138 { target, options },
139 event,
140 ) {
141 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
142 const renderer = event === undefined ? undefined : Electron.webContents.fromId(event.sender.id);
143 const document =
144 options?.claimTunnel === true && renderer !== undefined
145 ? SshOnboardingClaims.watchDocument(renderer)
146 : undefined;
147 return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
148 Effect.tap((bootstrap) => {
149 const token = bootstrap.tunnelClaim;
150 if (token === undefined) return Effect.void;
151 const finish = (retain: boolean) => sshEnvironment.finishTunnelClaim(token, retain);
152 return renderer === undefined || document === undefined
153 ? finish(false)
154 : SshOnboardingClaims.track(renderer, document, token, finish);
155 }),
156 Effect.catchIf(DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation, (error) =>
157 Effect.succeed({
158 type: DesktopSshPasswordPromptCancelledType,
159 message: error.message,
160 }),
161 ),
162 );
163 }),
164});
165​
166export const releaseSshTunnelClaim = DesktopIpc.makeIpcMethod({
167 channel: IpcChannels.RELEASE_SSH_TUNNEL_CLAIM_CHANNEL,
168 payload: Schema.String,
169 result: Schema.Void,
170 handler: Effect.fn("desktop.ipc.sshEnvironment.releaseTunnelClaim")(function* (claim, event) {
171 const renderer = event === undefined ? undefined : Electron.webContents.fromId(event.sender.id);
172 if (renderer !== undefined) yield* SshOnboardingClaims.finish(renderer, claim);
173 }),
174});
175​
176export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
177 channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
178 payload: DesktopSshEnvironmentTargetSchema,
179 result: Schema.Void,
180 handler: Effect.fn("desktop.ipc.sshEnvironment.disconnectEnvironment")(function* (target) {
181 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
182 yield* sshEnvironment.disconnectEnvironment(target);
183 }),
184});
185​
186export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
187 channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
188 payload: DesktopSshHttpBaseUrlInputSchema,
189 result: ExecutionEnvironmentDescriptor,
190 handler: Effect.fn("desktop.ipc.sshEnvironment.fetchDescriptor")(function* ({ httpBaseUrl }) {
191 return yield* withLoopbackSshApi("fetch-environment-descriptor", (resolvedHttpBaseUrl) =>
192 fetchRemoteEnvironmentDescriptor({ httpBaseUrl: resolvedHttpBaseUrl }),
193 )(httpBaseUrl);
194 }),
195});
196​
197export const bootstrapSshBearerSession = DesktopIpc.makeIpcMethod({
198 channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
199 payload: DesktopSshBearerBootstrapInputSchema,
200 result: AuthAccessTokenResult,
201 handler: Effect.fn("desktop.ipc.sshEnvironment.bootstrapBearerSession")(function* ({
202 httpBaseUrl,
203 credential,
204 }) {
205 return yield* withLoopbackSshApi("bootstrap-bearer-session", (resolvedHttpBaseUrl) =>
206 bootstrapRemoteBearerSession({
207 httpBaseUrl: resolvedHttpBaseUrl,
208 credential,
209 }),
210 )(httpBaseUrl);
211 }),
212});
213​
214export const fetchSshSessionState = DesktopIpc.makeIpcMethod({
215 channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
216 payload: DesktopSshBearerRequestInputSchema,
217 result: AuthSessionState,
218 handler: Effect.fn("desktop.ipc.sshEnvironment.fetchSessionState")(function* ({
219 httpBaseUrl,
220 bearerToken,
221 }) {
222 return yield* withLoopbackSshApi("fetch-session-state", (resolvedHttpBaseUrl) =>
223 fetchRemoteSessionState({
224 httpBaseUrl: resolvedHttpBaseUrl,
225 bearerToken,
226 }),
227 )(httpBaseUrl);
228 }),
229});
230​
231export const resolveSshPasswordPrompt = DesktopIpc.makeIpcMethod({
232 channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
233 payload: DesktopSshPasswordPromptResolutionInputSchema,
234 result: Schema.Void,
235 handler: Effect.fn("desktop.ipc.sshEnvironment.resolvePasswordPrompt")(function* ({
236 requestId,
237 password,
238 }) {
239 const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
240 yield* prompts.resolve({ requestId, password });
241 }),
242});