forked from MetaMask/rpc-cap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaveats.ts
74 lines (64 loc) · 1.96 KB
/
caveats.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
import { JsonRpcMiddleware } from 'json-rpc-engine';
import { IOcapLdCaveat } from './@types/ocap-ld';
import { unauthorized } from './errors';
import equal from 'fast-deep-equal';
import isSubset from 'is-subset';
export type ICaveatFunction = JsonRpcMiddleware;
export type ICaveatFunctionGenerator = (caveat: IOcapLdCaveat) => ICaveatFunction;
/*
* Require that the request params match those specified by the caveat value.
*/
export const requireParams: ICaveatFunctionGenerator = function requireParams (serialized: IOcapLdCaveat) {
const { value } = serialized;
return (req, res, next, end): void => {
const permitted = isSubset(req.params, value);
if (!permitted) {
res.error = unauthorized({ data: req });
return end(res.error);
}
next();
};
};
/*
* Filters array results.
*/
export const filterResponse: ICaveatFunctionGenerator = function filterResponse (serialized: IOcapLdCaveat) {
const { value } = serialized;
return (_req, res, next, _end): void => {
next((done) => {
if (Array.isArray(res.result)) {
res.result = res.result.filter((item) => {
const findResult = value.find((v: any) => {
return equal(v, item);
});
return findResult !== undefined;
});
}
done();
});
};
};
/*
* Limits array results to a specific integer length.
*/
export const limitResponseLength: ICaveatFunctionGenerator = function limitResponseLength (serialized: IOcapLdCaveat) {
const { value } = serialized;
return (_req, res, next, _end): void => {
next((done) => {
if (Array.isArray(res.result)) {
res.result = res.result.slice(0, value);
}
done();
});
};
};
/*
* Forces the method to be called with given params.
*/
export const forceParams: ICaveatFunctionGenerator = function forceParams (serialized: IOcapLdCaveat) {
const { value } = serialized;
return (req, _, next): void => {
req.params = [...value];
next();
};
};