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
|
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import ci from 'ci-info';
import { green } from 'kleur/colors';
import ora from 'ora';
import {
MISSING_PROJECT_ID_ERROR,
MISSING_SESSION_ID_CI_ERROR,
MISSING_SESSION_ID_ERROR,
} from './errors.js';
import { getAstroStudioEnv, getAstroStudioUrl } from './utils.js';
export const SESSION_LOGIN_FILE = pathToFileURL(join(homedir(), '.astro', 'session-token'));
export const PROJECT_ID_FILE = pathToFileURL(join(process.cwd(), '.astro', 'link'));
export interface ManagedAppToken {
token: string;
renew(): Promise<void>;
destroy(): Promise<void>;
}
class ManagedLocalAppToken implements ManagedAppToken {
token: string;
constructor(token: string) {
this.token = token;
}
async renew() {}
async destroy() {}
}
class ManagedRemoteAppToken implements ManagedAppToken {
token: string;
session: string;
projectId: string;
ttl: number;
expires: Date;
renewTimer: NodeJS.Timeout | undefined;
static async create(sessionToken: string, projectId: string) {
const { token: shortLivedAppToken, ttl } = await this.createToken(sessionToken, projectId);
return new ManagedRemoteAppToken({
token: shortLivedAppToken,
session: sessionToken,
projectId,
ttl,
});
}
static async createToken(
sessionToken: string,
projectId: string,
): Promise<{ token: string; ttl: number }> {
const spinner = ora('Connecting to remote database...').start();
const response = await safeFetch(
new URL(`${getAstroStudioUrl()}/auth/cli/token-create`),
{
method: 'POST',
headers: new Headers({
Authorization: `Bearer ${sessionToken}`,
}),
body: JSON.stringify({ projectId }),
},
(res) => {
throw new Error(`Failed to create token: ${res.status} ${res.statusText}`);
},
);
spinner.succeed(green('Connected to remote database.'));
const { token, ttl } = await response.json();
return { token, ttl };
}
constructor(options: { token: string; session: string; projectId: string; ttl: number }) {
this.token = options.token;
this.session = options.session;
this.projectId = options.projectId;
this.ttl = options.ttl;
this.renewTimer = setTimeout(() => this.renew(), (1000 * 60 * 5) / 2);
this.expires = getExpiresFromTtl(this.ttl);
}
private async fetch(url: string, body: Record<string, unknown>) {
return safeFetch(
`${getAstroStudioUrl()}${url}`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${this.session}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
},
() => {
throw new Error(`Failed to fetch ${url}.`);
},
);
}
tokenIsValid() {
return new Date() > this.expires;
}
createRenewTimer() {
return setTimeout(() => this.renew(), (1000 * 60 * this.ttl) / 2);
}
async renew() {
clearTimeout(this.renewTimer);
delete this.renewTimer;
if (this.tokenIsValid()) {
const response = await this.fetch('/auth/cli/token-renew', {
token: this.token,
projectId: this.projectId,
});
if (response.status === 200) {
this.expires = getExpiresFromTtl(this.ttl);
this.renewTimer = this.createRenewTimer();
} else {
throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
}
} else {
try {
const { token, ttl } = await ManagedRemoteAppToken.createToken(
this.session,
this.projectId,
);
this.token = token;
this.ttl = ttl;
this.expires = getExpiresFromTtl(ttl);
this.renewTimer = this.createRenewTimer();
} catch {
// If we get here we couldn't create a new token. Since the existing token
// is expired we really can't do anything and should exit.
throw new Error(
`Token has expired and attempts to renew it have failed, please try again.`,
);
}
}
}
async destroy() {
try {
const response = await this.fetch('/auth/cli/token-delete', {
token: this.token,
projectId: this.projectId,
});
if (response.status !== 200) {
throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
}
} catch (error: any) {
// eslint-disable-next-line no-console
console.error('Failed to delete token.', error?.message);
}
}
}
export async function getProjectIdFromFile() {
try {
return await readFile(PROJECT_ID_FILE, 'utf-8');
} catch {
return undefined;
}
}
export async function getSessionIdFromFile() {
try {
return await readFile(SESSION_LOGIN_FILE, 'utf-8');
} catch {
return undefined;
}
}
export async function getManagedAppTokenOrExit(token?: string): Promise<ManagedAppToken> {
if (token) {
return new ManagedLocalAppToken(token);
}
if (process.env.ASTRO_INTERNAL_TEST_REMOTE) {
return new ManagedLocalAppToken('fake' /* token ignored in test */);
}
const { ASTRO_STUDIO_APP_TOKEN } = getAstroStudioEnv();
if (ASTRO_STUDIO_APP_TOKEN) {
return new ManagedLocalAppToken(ASTRO_STUDIO_APP_TOKEN);
}
const sessionToken = await getSessionIdFromFile();
if (!sessionToken) {
if (ci.isCI) {
// eslint-disable-next-line no-console
console.error(MISSING_SESSION_ID_CI_ERROR);
} else {
// eslint-disable-next-line no-console
console.error(MISSING_SESSION_ID_ERROR);
}
process.exit(1);
}
const projectId = await getProjectIdFromFile();
if (!projectId) {
// eslint-disable-next-line no-console
console.error(MISSING_PROJECT_ID_ERROR);
process.exit(1);
}
return ManagedRemoteAppToken.create(sessionToken, projectId);
}
function getExpiresFromTtl(ttl: number): Date {
// ttl is in minutes
return new Date(Date.now() + ttl * 60 * 1000);
}
/**
* Small wrapper around fetch that throws an error if the response is not OK. Allows for custom error handling as well through the onNotOK callback.
*/
async function safeFetch(
url: Parameters<typeof fetch>[0],
options: Parameters<typeof fetch>[1] = {},
onNotOK: (response: Response) => void | Promise<void> = () => {
throw new Error(`Request to ${url} returned a non-OK status code.`);
},
): Promise<Response> {
const response = await fetch(url, options);
if (!response.ok) {
await onNotOK(response);
}
return response;
}
|