-
Notifications
You must be signed in to change notification settings - Fork 27.6k
/
Copy pathencryption-utils.ts
212 lines (182 loc) · 5.53 KB
/
encryption-utils.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
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
// Keep the key in memory as it should never change during the lifetime of the server in
// both development and production.
let __next_encryption_key_generation_promise: Promise<
[CryptoKey, string]
> | null = null
let __next_loaded_action_key: CryptoKey
let __next_internal_development_raw_action_key: string
export function arrayBufferToString(buffer: ArrayBuffer) {
const bytes = new Uint8Array(buffer)
const len = bytes.byteLength
// @anonrig: V8 has a limit of 65535 arguments in a function.
// For len < 65535, this is faster.
// https://github.com/vercel/next.js/pull/56377#pullrequestreview-1656181623
if (len < 65535) {
return String.fromCharCode.apply(null, bytes as unknown as number[])
}
let binary = ''
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return binary
}
export function stringToUint8Array(binary: string) {
const len = binary.length
const arr = new Uint8Array(len)
for (let i = 0; i < len; i++) {
arr[i] = binary.charCodeAt(i)
}
return arr
}
export function encrypt(key: CryptoKey, iv: Uint8Array, data: Uint8Array) {
return crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv,
},
key,
data
)
}
export function decrypt(key: CryptoKey, iv: Uint8Array, data: Uint8Array) {
return crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv,
},
key,
data
)
}
export async function generateEncryptionKeyBase64(dev?: boolean) {
// For development, we just keep one key in memory for all actions.
// This makes things faster.
if (dev) {
if (typeof __next_internal_development_raw_action_key !== 'undefined') {
return __next_internal_development_raw_action_key
}
}
// This avoids it being generated multiple times in parallel.
if (!__next_encryption_key_generation_promise) {
__next_encryption_key_generation_promise = new Promise(
async (resolve, reject) => {
try {
const key = await crypto.subtle.generateKey(
{
name: 'AES-GCM',
length: 256,
},
true,
['encrypt', 'decrypt']
)
const exported = await crypto.subtle.exportKey('raw', key)
const b64 = btoa(arrayBufferToString(exported))
resolve([key, b64])
} catch (error) {
reject(error)
}
}
)
}
const [key, b64] = await __next_encryption_key_generation_promise
__next_loaded_action_key = key
if (dev) {
__next_internal_development_raw_action_key = b64
}
return b64
}
// This is a global singleton that is used to encode/decode the action bound args from
// the closure. This can't be using a AsyncLocalStorage as it might happen on the module
// level. Since the client reference manifest won't be mutated, let's use a global singleton
// to keep it.
const SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(
'next.server.action-manifests'
)
export function setReferenceManifestsSingleton({
clientReferenceManifest,
serverActionsManifest,
serverModuleMap,
}: {
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
serverModuleMap: {
[id: string]: {
id: string
chunks: string[]
name: string
}
}
}) {
// @ts-ignore
globalThis[SERVER_ACTION_MANIFESTS_SINGLETON] = {
clientReferenceManifest,
serverActionsManifest,
serverModuleMap,
}
}
export function getServerModuleMap() {
const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
serverModuleMap: {
[id: string]: {
id: string
chunks: string[]
name: string
}
}
}
if (!serverActionsManifestSingleton) {
throw new Error(
'Missing manifest for Server Actions. This is a bug in Next.js'
)
}
return serverActionsManifestSingleton.serverModuleMap
}
export function getClientReferenceManifestSingleton() {
const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
}
if (!serverActionsManifestSingleton) {
throw new Error(
'Missing manifest for Server Actions. This is a bug in Next.js'
)
}
return serverActionsManifestSingleton.clientReferenceManifest
}
export async function getActionEncryptionKey() {
if (__next_loaded_action_key) {
return __next_loaded_action_key
}
const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
}
if (!serverActionsManifestSingleton) {
throw new Error(
'Missing manifest for Server Actions. This is a bug in Next.js'
)
}
const rawKey =
process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ||
serverActionsManifestSingleton.serverActionsManifest.encryptionKey
if (rawKey === undefined) {
throw new Error('Missing encryption key for Server Actions')
}
__next_loaded_action_key = await crypto.subtle.importKey(
'raw',
stringToUint8Array(atob(rawKey)),
'AES-GCM',
true,
['encrypt', 'decrypt']
)
return __next_loaded_action_key
}