-
Notifications
You must be signed in to change notification settings - Fork 542
/
validation.ts
264 lines (237 loc) · 6.93 KB
/
validation.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
import { assert, assertStruct } from '@metamask/utils';
import {
array,
boolean,
coerce,
create,
enums,
Infer,
integer,
is,
literal,
object,
optional,
pattern,
refine,
size,
string,
Struct,
type,
union,
} from 'superstruct';
import { CronjobSpecificationArrayStruct } from '../cronjob';
import { RpcOriginsStruct } from '../json-rpc';
import { NamespacesStruct } from '../namespace';
import { normalizeRelative } from '../path';
import { NameStruct, NpmSnapFileNames } from '../types';
import { VersionStruct } from '../versions';
// 0xd36e6170 - 0x80000000
export const SIP_6_MAGIC_VALUE = `1399742832'` as `${number}'`;
// BIP-43 purposes that cannot be used for entropy derivation. These are in the
// string form, ending with `'`.
const FORBIDDEN_PURPOSES: string[] = [SIP_6_MAGIC_VALUE];
export type Base64Opts = {
/**
* Is the `=` padding at the end required or not.
*
* @default false
*/
// Padding is optional in RFC 4648, that's why the default value is false
paddingRequired?: boolean;
/**
* Which character set should be used.
* The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.
*
* @default 'base64'
*/
characterSet?: 'base64' | 'base64url';
};
/**
* Ensure that a provided string-based struct is valid base64.
*
* @param struct - The string based struct.
* @param opts - Optional options to specialize base64 validation. See {@link Base64Opts} documentation.
* @returns A superstruct validating base64.
*/
export const base64 = <T extends string, S>(
struct: Struct<T, S>,
opts: Base64Opts = {},
) => {
const paddingRequired = opts.paddingRequired ?? false;
const characterSet = opts.characterSet ?? 'base64';
let letters: string;
if (characterSet === 'base64') {
letters = String.raw`[A-Za-z0-9+\/]`;
} else {
assert(characterSet === 'base64url');
letters = String.raw`[-_A-Za-z0-9]`;
}
let re: RegExp;
if (paddingRequired) {
re = new RegExp(
`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,
'u',
);
} else {
re = new RegExp(
`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,
'u',
);
}
return pattern(struct, re);
};
const BIP32_INDEX_REGEX = /^\d+'?$/u;
export const Bip32PathStruct = refine(
array(string()),
'BIP-32 path',
(path) => {
if (path.length === 0) {
return 'Path must be a non-empty BIP-32 derivation path array';
}
if (path[0] !== 'm') {
return 'Path must start with "m".';
}
if (path.length < 3) {
return 'Paths must have a length of at least three.';
}
if (path.slice(1).some((part) => !BIP32_INDEX_REGEX.test(part))) {
return 'Path must be a valid BIP-32 derivation path array.';
}
if (FORBIDDEN_PURPOSES.includes(path[1])) {
return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
}
return true;
},
);
export const bip32entropy = <T extends { path: string[]; curve: string }, S>(
struct: Struct<T, S>,
) =>
refine(struct, 'BIP-32 entropy', (value) => {
if (
value.curve === 'ed25519' &&
value.path.slice(1).some((part) => !part.endsWith("'"))
) {
return 'Ed25519 does not support unhardened paths.';
}
return true;
});
// Used outside @metamask/snap-utils
export const Bip32EntropyStruct = bip32entropy(
type({
path: Bip32PathStruct,
curve: enums(['ed25519', 'secp256k1']),
}),
);
export type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;
export const SnapGetBip32EntropyPermissionsStruct = size(
array(Bip32EntropyStruct),
1,
Infinity,
);
/* eslint-disable @typescript-eslint/naming-convention */
export const PermissionsStruct = type({
'endowment:long-running': optional(object({})),
'endowment:network-access': optional(object({})),
'endowment:transaction-insight': optional(
object({
allowTransactionOrigin: optional(boolean()),
}),
),
'endowment:cronjob': optional(
object({ jobs: CronjobSpecificationArrayStruct }),
),
'endowment:rpc': optional(RpcOriginsStruct),
snap_confirm: optional(object({})),
snap_manageState: optional(object({})),
snap_notify: optional(object({})),
snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),
snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),
snap_getBip44Entropy: optional(
size(
array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),
1,
Infinity,
),
),
snap_getEntropy: optional(object({})),
'endowment:keyring': optional(
object({
namespaces: NamespacesStruct,
}),
),
});
/* eslint-enable @typescript-eslint/naming-convention */
const relativePath = <Type extends string>(struct: Struct<Type>) =>
coerce(struct, struct, (value) => normalizeRelative(value));
export type SnapPermissions = Infer<typeof PermissionsStruct>;
export const SnapManifestStruct = object({
version: VersionStruct,
description: size(string(), 1, 280),
proposedName: size(
pattern(
string(),
/^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,
),
1,
214,
),
repository: optional(
object({
type: size(string(), 1, Infinity),
url: size(string(), 1, Infinity),
}),
),
source: object({
shasum: size(base64(string(), { paddingRequired: true }), 44, 44),
location: object({
npm: object({
filePath: relativePath(size(string(), 1, Infinity)),
iconPath: optional(relativePath(size(string(), 1, Infinity))),
packageName: NameStruct,
registry: union([
literal('https://registry.npmjs.org'),
literal('https://registry.npmjs.org/'),
]),
}),
}),
}),
initialPermissions: PermissionsStruct,
manifestVersion: literal('0.1'),
});
export type SnapManifest = Infer<typeof SnapManifestStruct>;
/**
* Check if the given value is a valid {@link SnapManifest} object.
*
* @param value - The value to check.
* @returns Whether the value is a valid {@link SnapManifest} object.
*/
export function isSnapManifest(value: unknown): value is SnapManifest {
return is(value, SnapManifestStruct);
}
/**
* Assert that the given value is a valid {@link SnapManifest} object.
*
* @param value - The value to check.
* @throws If the value is not a valid {@link SnapManifest} object.
*/
export function assertIsSnapManifest(
value: unknown,
): asserts value is SnapManifest {
assertStruct(
value,
SnapManifestStruct,
`"${NpmSnapFileNames.Manifest}" is invalid`,
);
}
/**
* Creates a {@link SnapManifest} object from JSON.
*
*
* @param value - The value to check.
* @throws If the value cannot be coerced to a {@link SnapManifest} object.
* @returns The created {@link SnapManifest} object.
*/
export function createSnapManifest(value: unknown): SnapManifest {
// TODO: Add a utility to prefix these errors similar to assertStruct
return create(value, SnapManifestStruct);
}