-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.ts
More file actions
455 lines (416 loc) · 12.1 KB
/
Copy pathauth.ts
File metadata and controls
455 lines (416 loc) · 12.1 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import type { TRPCCombinedDataTransformer } from "@trpc/server";
import { serialize } from "superjson";
import open from "open";
import { encodeBase64 } from "@std/encoding";
import { green } from "@std/fmt/colors";
import {
createTRPCUntypedClient,
httpBatchStreamLink,
httpSubscriptionLink,
retryLink,
splitLink,
TRPCClientError,
type TRPCLink,
type TRPCUntypedClient,
} from "@trpc/client";
import { observable } from "@trpc/server/observable";
import { Spinner } from "@std/cli/unstable-spinner";
import { error, ExitCode, requireInteractive } from "./util.ts";
import { EventSourcePolyfill } from "event-source-polyfill";
import type { GlobalContext } from "./main.ts";
/** Map a tRPC error envelope (with `data.httpStatus` / `data.code`) to our taxonomy. */
function mapTrpcError(
err: unknown,
): { code: ExitCode; errorCode: string; hint?: string } {
// deno-lint-ignore no-explicit-any
const data = (err as any)?.data;
const httpStatus: number | undefined = data?.httpStatus;
const backendCode: string | undefined = data?.code;
if (
backendCode === "NOT_AUTHENTICATED" || backendCode === "TOKEN_EXPIRED" ||
httpStatus === 401 || httpStatus === 403
) {
return {
code: ExitCode.AUTH,
errorCode: backendCode ?? "AUTH",
hint: "Set DENO_DEPLOY_TOKEN or run `deno deploy login`.",
};
}
if (httpStatus === 404) {
return { code: ExitCode.NOT_FOUND, errorCode: backendCode ?? "NOT_FOUND" };
}
if (httpStatus === 409) {
const hint = backendCode === "SLUG_ALREADY_IN_USE"
? "A resource with that name already exists. Use a different name, " +
"or run the corresponding update/publish command against the existing one."
: undefined;
return {
code: ExitCode.CONFLICT,
errorCode: backendCode ?? "CONFLICT",
hint,
};
}
if (httpStatus !== undefined && httpStatus >= 500) {
return { code: ExitCode.NETWORK, errorCode: backendCode ?? "BACKEND" };
}
return { code: ExitCode.GENERIC, errorCode: backendCode ?? "GENERIC" };
}
// deno-lint-ignore no-explicit-any
export type TRPCClient = TRPCUntypedClient<any>;
export function createTrpcClient(
context: GlobalContext,
quiet: boolean = false,
) {
let storedAuth = tokenStorage.get();
// deno-lint-ignore no-explicit-any
const errorLink: TRPCLink<any> = () => {
return ({ next, op }) => {
return observable((observer) => {
return next(op).subscribe({
next(value) {
observer.next(value);
},
error(err) {
if (context.debug) {
console.error(err);
}
const mapped = mapTrpcError(err);
error(context, err.message || Deno.inspect(err), {
code: mapped.code,
errorCode: mapped.errorCode,
hint: mapped.hint,
response: err.meta?.response as Response | undefined,
});
},
complete() {
observer.complete();
},
});
});
};
};
const transformer: TRPCCombinedDataTransformer = {
input: {
serialize,
deserialize: (_) => {/* this is never called on the client */},
},
output: {
serialize: (_) => {/* this is never called on the client */},
deserialize: (object) => (0, eval)(`(${object})`),
},
};
let retryPromise: Promise<void> | undefined = undefined;
return createTRPCUntypedClient({
links: [
errorLink,
retryLink({
retry(opts) {
if (context.debug) {
console.error(opts);
}
if (
opts.error?.data?.httpStatus && opts.error.data.httpStatus !== 401
) {
return false;
}
if (tokenIsTemp) {
error(
context,
"The token specified via 'DENO_DEPLOY_TOKEN' or the '--token' flag is invalid or expired.",
{
code: ExitCode.AUTH,
errorCode: "AUTH_INVALID_TOKEN",
hint:
`Generate a new token at ${context.endpoint}/account/tokens and re-export DENO_DEPLOY_TOKEN.`,
},
);
}
if (typeof retryPromise !== "undefined") {
tokenStorage.remove();
error(
context,
"Already re-attempted authorization, please re-run this command",
{
code: ExitCode.AUTH,
errorCode: "AUTH_RETRY_EXHAUSTED",
},
);
}
tokenStorage.remove();
retryPromise = getAuth(context, quiet).then((auth) => {
storedAuth = auth;
});
return true;
},
}),
splitLink({
// uses the httpSubscriptionLink for subscriptions
condition: (op) => op.type === "subscription",
false: httpBatchStreamLink({
url: context.endpoint + "/api",
fetch: async (url, options) => {
// deno-lint-ignore no-explicit-any
const response = await fetch(url, options as any);
if (response.status === 401) {
throw TRPCClientError.from({
message: "Unauthorized",
code: -32004,
data: { httpStatus: 401, code: "NOT_AUTHENTICATED" },
});
} else if (response.status === 403) {
const body = await response.clone().json();
if (body.code === "TOKEN_EXPIRED") {
throw TRPCClientError.from({
message: "Token Expired",
code: -32004,
data: { httpStatus: 401, code: "TOKEN_EXPIRED" },
});
}
}
return response;
},
async headers() {
if (retryPromise) {
await retryPromise;
}
if (storedAuth) {
return {
cookie: `token=${storedAuth}; deno_auth_ghid=force`,
};
} else {
return {};
}
},
transformer,
}),
true: httpSubscriptionLink({
url: context.endpoint + "/api",
EventSource: EventSourcePolyfill,
async eventSourceOptions() {
if (retryPromise) {
await retryPromise;
retryPromise = undefined;
}
if (storedAuth) {
return {
headers: {
cookie: `token=${storedAuth}; deno_auth_ghid=force`,
},
};
} else {
return {};
}
},
transformer,
}),
}),
],
});
}
export async function getAuth(
context: GlobalContext,
quiet: boolean = false,
): Promise<string> {
const storedAuth = tokenStorage.get();
if (storedAuth) {
return storedAuth;
}
requireInteractive(
context,
"Set the DENO_DEPLOY_TOKEN environment variable or use --token.",
);
const { code, exchangeToken, verifier } = await interactive(context);
const authUrl = `${context.endpoint}/auth?code=${code}`;
const spinner = new Spinner({
message: "",
color: "yellow",
});
// Prompt-style message — goes to stderr so it doesn't pollute `--json` callers' stdout.
console.error(`Visit ${authUrl} to authorize deploying your project.`);
if (!quiet) {
spinner.start();
}
await open(authUrl);
return await tokenExchange(
context,
exchangeToken,
verifier,
spinner,
quiet,
);
}
export async function interactive(context: GlobalContext): Promise<
{ code: string; exchangeToken: string; verifier: string }
> {
const verifier = crypto.randomUUID();
const data = (new TextEncoder()).encode(verifier);
const hash = await crypto.subtle.digest("SHA-256", data);
const challenge = encodeBase64(hash);
const res = await fetch(`${context.endpoint}/auth/interactive`, {
method: "POST",
body: JSON.stringify({ challenge }),
});
if (!res.ok) {
error(
context,
"An error occurred during authentication, exiting...",
res,
);
}
const body = await res.json();
return {
code: body.code,
exchangeToken: body.exchangeToken,
verifier,
};
}
export function tokenExchange(
context: GlobalContext,
exchangeToken: string,
verifier: string,
spinner: Spinner,
quiet: boolean,
): Promise<string> {
return new Promise((resolve) => {
const interval = setInterval(async () => {
const res = await fetch(`${context.endpoint}/auth/exchange`, {
method: "POST",
body: JSON.stringify({
exchangeToken,
verifier,
}),
});
if (res.ok) {
const { token, user } = await res.json();
spinner.stop();
if (!quiet) {
// Status message — stderr so JSON callers' stdout stays clean.
console.error(
`${
green("✔")
} Authorization successful. Authenticated as ${user.name}\n`,
);
}
clearInterval(interval);
tokenStorage.set(token);
resolve(token);
} else {
const err = await res.json();
if (
!(err.code === "AUTHORIZATION_PENDING" &&
err.message.endsWith(
"The requested authorization has not been approved or denied yet.",
))
) {
clearInterval(interval);
spinner.stop();
error(context, err.message, res);
}
}
}, 2000);
});
}
export async function authedFetch(
context: GlobalContext,
endpoint: string,
init: RequestInit,
) {
let auth = tokenStorage.get();
if (!auth) {
auth = await getAuth(context);
}
const headers = new Headers(init.headers);
headers.set(
"cookie",
`token=${auth}; deno_auth_ghid=force`,
);
const url = new URL(endpoint, context.endpoint);
let fallbackBody: ReadableStream | undefined;
if (init.body instanceof ReadableStream) {
const [a, b] = init.body.tee();
init.body = a;
fallbackBody = b;
}
const res = await fetch(url, {
...init,
headers,
});
if (res.status === 401) {
// Diagnostic body — stderr only, and only when debugging.
if (context.debug) console.error(await res.text());
tokenStorage.remove();
auth = await getAuth(context);
const headers = new Headers(init.headers);
headers.set(
"cookie",
`token=${auth}; deno_auth_ghid=force`,
);
const retryRes = await fetch(url, {
...init,
headers,
body: init.body instanceof ReadableStream ? fallbackBody : init.body,
});
if (retryRes.status === 401) {
const err = await retryRes.json();
error(context, `unexpected authentication failure\n${err.message}`);
} else {
return retryRes;
}
} else {
return res;
}
}
let cachedToken: string | null = null;
export let tokenIsTemp = false;
let cannotInteractWithKeychain = false;
const KEYCHAIN_WARNING =
"Unable to interact with keychain.\nThe authentication will not be stored and will only work on this execution.";
export const tokenStorage = {
get(): string | null {
if (cachedToken) {
return cachedToken;
} else {
try {
// @ts-ignore deno internals
return Deno[Deno.internal].core.ops.op_deploy_token_get();
} catch {
if (!cannotInteractWithKeychain) {
cannotInteractWithKeychain = true;
console.error(KEYCHAIN_WARNING);
}
return null;
}
}
},
set(token: string, temp: boolean = false) {
cachedToken = token;
if (!temp) {
try {
// @ts-ignore deno internals
Deno[Deno.internal].core.ops.op_deploy_token_set(token);
} catch {
if (!cannotInteractWithKeychain) {
cannotInteractWithKeychain = true;
console.error(KEYCHAIN_WARNING);
}
}
} else {
tokenIsTemp = temp;
}
},
remove() {
if (tokenIsTemp) {
return;
}
cachedToken = null;
try {
// @ts-ignore deno internals
Deno[Deno.internal].core.ops.op_deploy_token_delete();
} catch {
if (!cannotInteractWithKeychain) {
cannotInteractWithKeychain = true;
console.log(KEYCHAIN_WARNING);
}
}
},
};