-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathws.ts
180 lines (152 loc) · 5.26 KB
/
ws.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
import WebSocket from 'ws'
import { v4 as uuid } from 'uuid'
import log from 'electron-log'
import store from '../store'
import provider from '../provider'
import accounts from '../accounts'
import windows from '../windows'
import {
updateOrigin,
isTrusted,
parseOrigin,
isKnownExtension,
FrameExtension,
parseFrameExtension
} from './origins'
import validPayload from './validPayload'
import protectedMethods from './protectedMethods'
import { IncomingMessage, Server } from 'http'
import { isHexString } from '@ethereumjs/util'
const logTraffic = process.env.LOG_TRAFFIC
const subs: Record<string, Subscription> = {}
const connectionMonitors: Record<string, NodeJS.Timeout> = {}
interface Subscription {
originId: string
socket: FrameWebSocket
}
interface FrameWebSocket extends WebSocket {
id: string
origin?: string
frameExtension?: FrameExtension
}
interface ExtensionPayload extends JSONRPCRequestPayload {
__frameOrigin?: string
__extensionConnecting?: boolean
}
function extendSession(originId: string) {
if (originId) {
clearTimeout(connectionMonitors[originId])
connectionMonitors[originId] = setTimeout(() => {
store.endOriginSession(originId)
}, 60 * 1000)
}
}
const handler = (socket: FrameWebSocket, req: IncomingMessage) => {
socket.id = uuid()
socket.origin = req.headers.origin
socket.frameExtension = parseFrameExtension(req)
const res = (payload: RPCResponsePayload) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(payload), (err) => {
if (err) log.info(err)
})
}
}
socket.on('message', async (data) => {
const rawPayload = validPayload<ExtensionPayload>(data.toString())
if (!rawPayload) return console.warn('Invalid Payload', data)
let requestOrigin = socket.origin
if (socket.frameExtension) {
if (!(await isKnownExtension(socket.frameExtension))) {
const error = {
message: `Permission denied, approve connection from Frame Companion with id ${socket.frameExtension.id} in Frame to continue`,
code: 4001
}
return res({ id: rawPayload.id, jsonrpc: rawPayload.jsonrpc, error })
}
// Request from extension, swap origin
if (rawPayload.__frameOrigin) {
requestOrigin = rawPayload.__frameOrigin
delete rawPayload.__frameOrigin
} else {
requestOrigin = 'frame-extension'
}
}
const origin = parseOrigin(requestOrigin)
if (logTraffic)
log.info(
`req -> | ${socket.frameExtension ? 'ext' : 'ws'} | ${origin} | ${rawPayload.method} | -> | ${
rawPayload.params
}`
)
const { payload, chainId } = updateOrigin(rawPayload, origin, rawPayload.__extensionConnecting)
if (!isHexString(chainId)) {
const error = {
message: `Invalid chain id (${rawPayload.chainId}), chain id must be hex-prefixed string`,
code: -1
}
return res({ id: rawPayload.id, jsonrpc: rawPayload.jsonrpc, error })
}
if (!rawPayload.__extensionConnecting) {
extendSession(payload._origin)
}
if (origin === 'frame-extension') {
// custom extension action for summoning Frame
if (rawPayload.method === 'frame_summon') return windows.toggleTray()
const { id, jsonrpc } = rawPayload
if (rawPayload.method === 'eth_chainId') return res({ id, jsonrpc, result: chainId })
if (rawPayload.method === 'net_version') return res({ id, jsonrpc, result: parseInt(chainId, 16) })
}
if (protectedMethods.indexOf(payload.method) > -1 && !(await isTrusted(payload))) {
let error = { message: 'Permission denied, approve ' + origin + ' in Frame to continue', code: 4001 }
// review
if (!accounts.getSelectedAddresses()[0]) error = { message: 'No Frame account selected', code: 4001 }
res({ id: payload.id, jsonrpc: payload.jsonrpc, error })
} else {
provider.send(payload, (response) => {
if (response && response.result) {
if (payload.method === 'eth_subscribe') {
subs[response.result] = { socket, originId: payload._origin }
} else if (payload.method === 'eth_unsubscribe') {
payload.params.forEach((sub) => {
if (subs[sub]) delete subs[sub]
})
}
}
if (logTraffic)
log.info(
`<- res | ${socket.frameExtension ? 'ext' : 'ws'} | ${origin} | ${
payload.method
} | <- | ${JSON.stringify(response.result || response.error)}`
)
res(response)
})
}
})
socket.on('error', (err) => log.error(err))
socket.on('close', (_) => {
Object.keys(subs).forEach((sub) => {
if (subs[sub].socket.id === socket.id) {
provider.send({
jsonrpc: '2.0',
id: 1,
method: 'eth_unsubscribe',
_origin: subs[sub].originId,
params: [sub]
})
delete subs[sub]
}
})
})
}
export default function (server: Server) {
const ws = new WebSocket.Server({ server })
ws.on('connection', handler)
provider.on('data:subscription', (payload: RPC.Susbcription.Response) => {
const subscription = subs[payload.params.subscription]
if (subscription) {
subscription.socket.send(JSON.stringify(payload))
}
})
return server
}