-
Notifications
You must be signed in to change notification settings - Fork 22
/
LoginServer.ts
185 lines (156 loc) · 5.04 KB
/
LoginServer.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
import asyncRetry from 'async-retry'
import coBody from 'co-body'
import detectPort from 'detect-port'
import { Server } from 'http'
import Koa from 'koa'
import { ErrorKinds, logger } from '../../../../api'
import { VTEXID } from '../../../../api/clients/IOClients/external/VTEXID'
import { ErrorReport } from '../../../../api/error/ErrorReport'
const SUCCESS_PAGE = `
<!doctype html>
<html>
<head>
<title>Success</title>
<meta charset="utf-8">
</head>
<body>
<p> Você já pode fechar essa janela. </p>
<p> You may now close this window. </p>
<p> Ahora puedes cerrar esta ventana. </p>
</body>
</html>`
export class LoginServer {
private static readonly LOGIN_CALLBACK_PATH = '/login_callback'
private static readonly SERVER_START_RETRIES = 1
private static readonly HOSTNAME = '127.0.0.1'
public static async create(loginConfig: LoginConfig) {
const loginServer = new LoginServer(loginConfig)
await loginServer.start()
return loginServer
}
private app: Koa
private port: number
private server: Server
private loginState?: string
private tokenPromise: Promise<string>
private resolveTokenPromise: (val: string) => void
private rejectTokenPromise: (err: any) => void
constructor(private loginConfig: LoginConfig) {
this.app = new Koa()
this.registerLoginHandler()
this.tokenPromise = new Promise((resolve, reject) => {
this.resolveTokenPromise = resolve
this.rejectTokenPromise = reject
})
}
get token() {
return this.tokenPromise
}
get loginCallbackUrl() {
if (!this.port) {
throw new Error('LoginServer not initialized')
}
return `http://${LoginServer.HOSTNAME}:${this.port}${LoginServer.LOGIN_CALLBACK_PATH}`
}
public setLoginState(val: string) {
this.loginState = val
}
public start() {
return asyncRetry(
async (bail, attemptNumber) => {
try {
// detectPort will get the specified port or, if it's in use, another ramdom unnused port
this.port = await detectPort(3000)
this.server = await this.initServer(this.port)
logger.debug(`LoginServer started on http://${LoginServer.HOSTNAME}:${this.port}`)
} catch (err) {
logger.debug(`LoginServer failed to start on port:${this.port}. Reason: ${err.message}.`)
if (err.code !== 'EADDRINUSE') {
return bail(err)
}
if (attemptNumber < LoginServer.SERVER_START_RETRIES + 1) {
logger.debug(`Retrying to start LoginServer...`)
}
throw ErrorReport.createAndMaybeRegisterOnTelemetry({
originalError: err,
kind: ErrorKinds.LOGIN_SERVER_START_ERROR,
details: { attemptNumber },
})
}
},
{ retries: LoginServer.SERVER_START_RETRIES, maxTimeout: 100, minTimeout: 100 }
)
}
public close() {
this.server.unref()
this.server.close()
}
private initServer(port: number): Promise<Server> {
return new Promise((resolve, reject) => {
const server = this.app.listen(port, LoginServer.HOSTNAME, () => {
server.on('connection', socket => {
socket.unref()
})
server.removeListener('error', reject)
resolve(server)
})
server.on('error', reject)
})
}
private registerLoginHandler() {
this.app.use(async ctx => {
ctx.set('connection', 'close')
if (ctx.path !== LoginServer.LOGIN_CALLBACK_PATH) {
ctx.status = 404
ctx.body = 'Not found'
return
}
ctx.socket.ref()
logger.debug(`Received ${ctx.method} login callback`)
if (!this.loginState) {
return this.handleError(ctx, new Error('Received login callback before setting login state'))
}
let body
if (ctx.method.toLowerCase() === 'post') {
try {
body = await coBody(ctx.req)
} catch (err) {
return this.handleError(ctx, err)
}
} else {
body = { ott: ctx.query?.ott }
}
if (!body.ott) {
return this.handleError(ctx, new Error('Missing ott on VTEX ID callback call'), { body })
}
const vtexId = VTEXID.createClient({ account: this.loginConfig.account })
try {
const { token } = await vtexId.validateToolbeltLogin({
account: this.loginConfig.account,
secret: this.loginConfig.secret,
ott: body.ott,
state: this.loginState,
})
this.resolveTokenPromise(token)
ctx.status = 200
ctx.set('content-type', 'text/html')
ctx.body = SUCCESS_PAGE
} catch (err) {
return this.handleError(ctx, err)
}
})
}
private handleError(ctx: Koa.ParameterizedContext, err: any, details?: Record<string, any>) {
const errReport = ErrorReport.createAndMaybeRegisterOnTelemetry({ originalError: err, details })
ctx.status = 500
ctx.body = {
errorId: errReport.metadata.errorId,
message: errReport.message,
}
this.rejectTokenPromise(errReport)
}
}
interface LoginConfig {
account: string
secret: string
}