-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.callback.machine.ts
471 lines (458 loc) · 20.4 KB
/
auth.callback.machine.ts
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { Context } from "hono";
import { setCookie } from "hono/cookie";
import { HTTPException } from "hono/http-exception";
import { assign, fromPromise, setup } from "xstate";
import { Bucket, GOOGLE_GDRIVE_SCOPES, Session, User } from "./const.ts";
import { Env } from "./env.ts";
import {
google_process_cb_data,
google_sign_in_url,
ResultGoogleCpDataProcessing,
} from "./google.service.ts";
import { kv } from "./kv.ts";
import { clean_auth_cookies } from "./x-actions.ts";
import { SECOND } from "@std/datetime/constants";
const machine = setup({
types: {
input: {} as tInput,
output: {} as tOutput,
context: {} as tCtx,
},
guards: {
is_new_refresh_token_present({ context }) {
return !!context.g?.payload.tokens.refresh_token;
},
is_session_active(
{
context,
},
) {
return context
.session!
._tag ===
"Session::normal";
},
},
actions: {
clean_auth_cookies({ context: { c } }) {
clean_auth_cookies(c);
},
},
actors: {
parse_google_code_and_state: fromPromise<
tActor["parse_google_code_and_state"]["output"],
tActor["parse_google_code_and_state"]["input"]
>(
async ({ input: { code, state } }) => {
const [g, maybeSession] = await Promise.all([
google_process_cb_data(code),
kv.get<Session>(["session", state]),
]);
const session = maybeSession.value;
if (!session) {
throw new Error(
"Unable to resolve <state> from google res",
);
}
return {
g,
session,
};
},
),
prepare_redirect_to_google_sign_in_with_gDrive_scopes_incremental:
fromPromise<
tActor[
"prepare_redirect_to_google_sign_in_with_gDrive_scopes_incremental"
]["output"],
tActor[
"prepare_redirect_to_google_sign_in_with_gDrive_scopes_incremental"
]["input"]
>(async ({ input: { session_id, g } }) => {
const redirect_for_gDrive = google_sign_in_url(
{
scope: GOOGLE_GDRIVE_SCOPES,
state: session_id,
include_granted_scopes: true,
login_hint: g.info.email!,
access_type: "offline",
},
);
return {
redirect_for_gDrive,
authorization_header: `Bearer ${g.payload.tokens
.access_token!}`,
};
}),
update_user_with_new_refresh: fromPromise<
tActor["update_user_with_new_refresh"]["output"],
tActor["update_user_with_new_refresh"]["input"]
>(async ({ input: { g, session } }) => {
const key = ["user", session.user_id!];
const user = await kv.get<User>(key);
if (!user.value) {
throw new Error(
"Unexpected fact that the user by session is not exist",
);
}
user.value.buckets.set(g.info.email!, {
__typename: "Bucket",
access_token: g.payload.tokens.access_token!,
refresh_token: g.payload.tokens.refresh_token!,
email: g.info.email!,
user_id: session.user_id!,
});
await kv.set(key, user.value satisfies User);
}),
create_user_and_update_session: fromPromise<
tActor["create_user_and_update_session"]["output"],
tActor["create_user_and_update_session"]["input"]
>(async ({ input: { g, session_id } }) => {
const user_id = crypto.randomUUID();
await Promise.all([
kv.set(
["user", user_id],
{
__typename: "User",
id: user_id,
buckets: new Map<string, Bucket>().set(g.info.email!, {
__typename: "Bucket",
access_token: g.payload.tokens.access_token!,
refresh_token: g.payload.tokens.refresh_token!,
email: g.info.email!,
user_id,
}),
} satisfies User,
),
kv.set(
["session", session_id],
{
__typename: "Session",
_tag: "Session::normal",
user_id,
email: g.info.email!,
id: session_id,
} satisfies Session,
),
]);
}),
},
})
.createMachine({
/** @xstate-layout N4IgpgJg5mDOIC5QGMCGAbdAjVyDWAdAAqoBOsYABFAPY1TpXI0RWoB2ElsALqj2ADEEGuzAEAluwBuNPOLSYc+YmQrU6DJizadufAQimy0PCaIDaABgC61m4lAAHGrAlnRjkAA9EATgBmABYAGhAAT0QAWgB2PwBfeLDFbFxCEnIqWnpGSmZWSg4uXn4hMFJSGlICJ3R+ADMqgFsCFOV0tSzNXPzdYoMwIxkaU3N2e3svFzcPdi9fBABGIIAmALDIhBjFghiY4ICYgFZE5IxUlSJK5Dg3dihuW7HCvWytSgh+VAIAYQALMD4SgSWCUMQAd0opDA9WhsD+Ly4UAAIqQJNIqLBmE44JQnHCwOweMD2BoclQnKhwugaKgIIJJkgQNN3GN5tEggAODaIYIANlOIDaaWI1ye90esDcokRZPenz4vwBQJBYLAkOhsLgCKK1FR6Mx2Nx+LghOJUjluUp1Np9IsiwcTJZs3ZCBWRz8PIQQT5nMFwsuYqlUgeFGDMt1b1yCu+ABUAWqNTC4X8Qnq0RjuEbQWQKQSiSTLRSqTS6UrAXhgaCw9LSRhoXT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5V6uJIqLlBpwWGsfMa-k6rBQamFVB8sohMUYjEPkC9AhUzdgA5WKxV4EHdOvQgPwJK1DACDLh51XQqw4oxViQj-D3XMTxRIQA */
id: "callback",
context({ input }) {
return {
...input,
refresh_token: "unknown",
};
},
initial: "Parse google code and state",
states: {
"Parse google code and state": {
invoke: {
src: "parse_google_code_and_state",
input: (
{ context: { gCode, state } },
) => ({
code: gCode,
state,
}),
onDone: {
target: "Processing session and google data",
actions: assign(({ event }) => {
return {
g: event.output
.g,
session: event
.output.session,
};
}),
},
onError: {
target: "Complete",
actions: [
"clean_auth_cookies",
assign(({ event }) => ({
output: {
exception: new HTTPException(
500,
{
message:
"Problem with parsing google data",
cause: event
.error,
},
),
},
})),
],
},
},
},
"Processing session and google data": {
initial:
"Check is new refresh and gDrive scopes present in google payload",
states: {
"Check is new refresh and gDrive scopes present in google payload":
{
always: [
{
target:
"The new refresh, gDrive scopes are present in google payload",
guard: "is_new_refresh_token_present",
},
{
target:
"There is NO refresh in google payload",
},
],
},
"The new refresh, gDrive scopes are present in google payload":
{
initial: "Check is session already active",
states: {
"Check is session already active": {
always: [
{
guard: "is_session_active",
target:
"Update user with new refresh",
},
"Create new user and update session",
],
},
"Update user with new refresh": {
invoke: {
src: "update_user_with_new_refresh",
input({ context: { g, session } }) {
return {
g: g!,
session: session!,
};
},
onDone: {
target: "#callback.Complete",
actions: assign(
(
{ context: { c, session } },
) => {
return {
output: {
success_complete_payload:
{
c,
session_id:
session!
.id,
email:
session!
.email!,
user_id:
session!
.user_id!,
},
},
};
},
),
},
onError: "#callback.Complete",
},
},
"Create new user and update session": {
invoke: {
src: "create_user_and_update_session",
input({ context: { g, session } }) {
return {
g: g!,
session_id: session!.id,
};
},
onDone: {
target: "#callback.Complete",
actions: assign(
(
{ context: { c, session } },
) => {
return {
output: {
success_complete_payload:
{
c,
session_id:
session!
.id,
email:
session!
.email!,
user_id:
session!
.user_id!,
},
},
};
},
),
},
onError: "#callback.Complete",
},
},
},
},
"There is NO refresh in google payload": {
initial: "Check is session already active",
states: {
"Check is session already active": {
always: [
{
target: "#callback.Complete",
guard: "is_session_active",
actions: assign(
{
output: {
exception:
new HTTPException(
400,
{
message:
"User is already has active session",
},
),
},
},
),
},
"#callback.Redirect someone to google with gDrive scopes (incremental)",
],
},
},
},
},
},
"Redirect someone to google with gDrive scopes (incremental)": {
invoke: {
src: "prepare_redirect_to_google_sign_in_with_gDrive_scopes_incremental",
input({ context: { g, session } }) {
return {
g: g!,
session_id: session!.id,
};
},
onDone: {
target: "Complete",
actions: assign(
({ event, context: { c, session } }) => {
const redirect = c.newResponse(null, {
status: 302,
headers: {
Location: event.output
.redirect_for_gDrive,
Authorization: event.output
.authorization_header,
},
});
setCookie(c, "session", session!.id, {
domain: Env.UI_URL!.split(".").splice(
1,
Infinity,
).join(
".",
),
httpOnly: true,
sameSite: "Lax",
path: '/',
maxAge: SECOND * 60 * 5,
secure: true,
});
return {
output: {
redirect,
},
};
},
),
},
onError: {
target: "Complete",
},
},
},
"Complete": {
type: "final",
},
},
output: ({ context }) => {
const result = context.output || {
exception: new HTTPException(500, {
message: "Something went wrong (x-callback)",
cause: "oops",
}),
};
return result;
},
});
type tInput = {
c: Context;
gCode: string;
state: string;
};
type tOutput = {
exception: HTTPException;
redirect?: never;
success_complete_payload?: never;
} | {
redirect: ReturnType<Context["redirect" | "newResponse"]>;
exception?: never;
success_complete_payload?: never;
} | {
redirect?: never;
exception?: never;
success_complete_payload: {
c: Context;
session_id: string;
user_id: string;
email: string;
};
};
type tCtx = tInput & {
output?: tOutput;
g?: ResultGoogleCpDataProcessing;
user?: User | undefined;
session?: Session | undefined;
refresh_token: "present" | "not-present" | "unknown";
};
type tActor = {
parse_google_code_and_state: {
input: {
code: string;
state: string;
};
output: { g: ResultGoogleCpDataProcessing; session: Session };
};
prepare_redirect_to_google_sign_in_with_gDrive_scopes_incremental: {
input: {
session_id: string;
g: ResultGoogleCpDataProcessing;
};
output: {
redirect_for_gDrive: string;
authorization_header: string;
};
};
update_user_with_new_refresh: {
input: {
g: ResultGoogleCpDataProcessing;
session: Session;
};
output: void;
};
create_user_and_update_session: {
input: {
g: ResultGoogleCpDataProcessing;
session_id: string;
};
output: void;
};
};
export const auth_callback_machine = machine;