-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauthenticate.ts
More file actions
162 lines (145 loc) · 4.6 KB
/
authenticate.ts
File metadata and controls
162 lines (145 loc) · 4.6 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
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import type {
CancellationToken,
ExtensionContext,
LogOutputChannel,
} from "vscode";
import { env, Uri, window } from "vscode";
import { assertIsError } from "./assert.ts";
/**
* Registers a {@link UriHandler} that waits for an authentication token from the browser,
* and redirects the user to the LocalStack Website afterwards.
*
* The request can be cancelled with the `cancellationToken`.
*
* @returns A promise that resolves with the authentication token.
*/
export async function requestAuthentication(
context: ExtensionContext,
cancellationToken?: CancellationToken,
): Promise<
| { authToken: string; cancelled?: undefined }
| { authToken?: undefined; cancelled: true }
> {
return new Promise((resolve, reject) => {
const uriHandler = window.registerUriHandler({
handleUri: (uri: Uri) => {
uriHandler.dispose();
// Example: vscode://localstack.localstack?token=abc123
const params = new URLSearchParams(uri.query);
const authToken = params.get("token");
if (authToken) {
resolve({ authToken });
} else {
void window.showErrorMessage("No token found in URI.");
reject(new Error("No token found in URI"));
}
},
});
context.subscriptions.push(uriHandler);
cancellationToken?.onCancellationRequested(() => {
uriHandler.dispose();
resolve({ cancelled: true });
});
void redirectToLocalStack().then(({ cancelled }) => {
if (cancelled) {
uriHandler.dispose();
resolve({ cancelled: true });
}
});
});
}
async function redirectToLocalStack(): Promise<{ cancelled: boolean }> {
// You don't have to get the Uri from the `env.asExternalUri` API but it will add a query
// parameter (ex: "windowId%3D14") that will help VS Code decide which window to redirect to.
// If this query parameter isn't specified, VS Code will pick the last windows that was focused.
const redirectUri = await env.asExternalUri(
Uri.parse(`${env.uriScheme}://localstack.localstack`),
);
const redirectSearchParams = new URLSearchParams(redirectUri.query);
// TODO: Gather environment variables in a safer way - e.g. during extension activation
// biome-ignore lint/style/noNonNullAssertion: false positive
const url = new URL(process.env.LOCALSTACK_WEB_AUTH_REDIRECT!);
url.searchParams.set("windowId", redirectSearchParams.get("windowId") ?? "");
const selection = await window.showInformationMessage(
`LocalStack needs to open the browser to continue with the authentication process.`,
{ modal: true },
"Continue",
);
if (!selection) {
return { cancelled: true };
}
const openSuccessful = await env.openExternal(Uri.parse(url.toString()));
return { cancelled: !openSuccessful };
}
const LOCALSTACK_AUTH_FILENAME = `${os.homedir()}/.localstack/auth.json`;
const LOCALSTACK_AUTH_FILENAME_READABLE = LOCALSTACK_AUTH_FILENAME.replace(
`${os.homedir()}/`,
"~/",
);
const AUTH_TOKEN_KEY = "LOCALSTACK_AUTH_TOKEN";
export async function saveAuthToken(
token: string,
outputChannel: LogOutputChannel,
) {
try {
await fs.mkdir(path.dirname(LOCALSTACK_AUTH_FILENAME), { recursive: true });
await fs.writeFile(
LOCALSTACK_AUTH_FILENAME,
JSON.stringify({ [AUTH_TOKEN_KEY]: token }, null, 2),
);
// void window.showInformationMessage(
// `Auth token saved to ${LOCALSTACK_AUTH_FILENAME_READABLE}`,
// );
} catch (error) {
assertIsError(error);
outputChannel.error(
`Failed to save auth token to ${LOCALSTACK_AUTH_FILENAME_READABLE}`,
);
outputChannel.error(error);
window
.showErrorMessage(
`Failed to save auth token to ${LOCALSTACK_AUTH_FILENAME_READABLE}`,
"View Logs",
)
.then(() => {
outputChannel.show(true);
});
}
}
function isAuthTokenPresent(authObject: unknown) {
return (
typeof authObject === "object" &&
authObject !== null &&
AUTH_TOKEN_KEY in authObject
);
}
// Reads the auth token from the auth.json file for logging in the user
export async function readAuthToken(): Promise<string> {
try {
const authJson = await fs.readFile(LOCALSTACK_AUTH_FILENAME, "utf-8");
const authObject = JSON.parse(authJson) as unknown;
if (!isAuthTokenPresent(authObject)) {
return "";
}
const authToken = authObject[AUTH_TOKEN_KEY];
if (typeof authToken !== "string") {
return "";
}
return authToken;
} catch {
return "";
}
}
/**
* Checks if the user is authenticated by validating the stored auth token.
*
* License is validated separately
*
* @returns boolean indicating if the authentication is valid
*/
export async function checkIsAuthenticated() {
return (await readAuthToken()) !== "";
}