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
|
/*
GoToSocial
Copyright (C) GoToSocial Authors admin@gotosocial.org
SPDX-License-Identifier: AGPL-3.0-or-later
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {
ParseConfig as CSVParseConfig,
parse as csvParse
} from "papaparse";
import { nanoid } from "nanoid";
import { isValidDomainPermission, hasBetterScope } from "../../../util/domain-permission";
import { gtsApi } from "../../gts-api";
import {
validateDomainPerms,
type DomainPerm,
} from "../../../types/domain-permission";
/**
* Parse the given string of domain permissions and return it as an array.
* Accepts input as a JSON array string, a CSV, or newline-separated domain names.
* Will throw an error if input is invalid.
* @param list
* @returns
* @throws
*/
function parseDomainList(list: string): DomainPerm[] {
if (list.startsWith("[")) {
// Assume JSON array.
const data = JSON.parse(list);
const validateRes = validateDomainPerms(data);
if (!validateRes.success) {
throw `parsed JSON was not array of DomainPermission: ${JSON.stringify(validateRes.errors)}`;
}
return data;
} else if (list.startsWith("#domain") || list.startsWith("domain,severity")) {
// Assume Mastodon-style CSV.
const csvParseCfg: CSVParseConfig = {
// Key by header.
header: true,
// Remove leading '#' from headers if present.
transformHeader: (header) => header.startsWith("#") ? header.slice(1) : header,
// Massage weird boolean values.
transform: (value, _field) => {
if (value == "False" || value == "True") {
return value.toLowerCase();
} else {
return value;
}
},
skipEmptyLines: true,
// Only dynamic type boolean values,
// leave the rest as strings.
dynamicTyping: {
"domain": false,
"severity": false,
"reject_media": true,
"reject_reports": true,
"public_comment": false,
"obfuscate": true,
}
};
const { data, errors } = csvParse(list, csvParseCfg);
if (errors.length > 0) {
let error = "";
errors.forEach((err) => {
error += `${err.message} (line ${err.row})`;
});
throw error;
}
const validateRes = validateDomainPerms(data);
if (!validateRes.success) {
throw `parsed CSV was not array of DomainPermission: ${JSON.stringify(validateRes.errors)}`;
}
return data;
} else {
// Fallback: assume newline-separated
// list of simple domain strings.
const data: DomainPerm[] = [];
list.split("\n").forEach((line) => {
let domain = line.trim();
let valid = true;
if (domain.startsWith("http")) {
try {
domain = new URL(domain).hostname;
} catch (e) {
valid = false;
}
}
if (domain.length > 0) {
data.push({ domain, valid });
}
});
return data;
}
}
function deduplicateDomainList(list: DomainPerm[]): DomainPerm[] {
let domains = new Set();
return list.filter((entry) => {
if (domains.has(entry.domain)) {
return false;
} else {
domains.add(entry.domain);
return true;
}
});
}
function validateDomainList(list: DomainPerm[]) {
list.forEach((entry) => {
if (entry.domain.startsWith("*.")) {
// A domain permission always includes
// all subdomains, wildcard is meaningless here
entry.domain = entry.domain.slice(2);
}
entry.valid = (entry.valid !== false) && isValidDomainPermission(entry.domain);
if (entry.valid) {
entry.suggest = hasBetterScope(entry.domain);
}
entry.checked = entry.valid;
});
return list;
}
const extended = gtsApi.injectEndpoints({
endpoints: (build) => ({
processDomainPermissions: build.mutation<DomainPerm[], any>({
async queryFn(formData, _api, _extraOpts, _fetchWithBQ) {
if (formData.domains == undefined || formData.domains.length == 0) {
throw "No domains entered";
}
// Parse + tidy up the form data.
const permissions = parseDomainList(formData.domains);
const deduped = deduplicateDomainList(permissions);
const validated = validateDomainList(deduped);
validated.forEach((entry) => {
// Set unique key that stays stable
// even if domain gets modified by user.
entry.key = nanoid();
});
return { data: validated };
}
})
})
});
/**
* useProcessDomainPermissionsMutation uses the RTK Query API without actually
* hitting the GtS API, it's purely an internal function for our own convenience.
*
* It returns the validated and deduplicated domain permission list.
*/
const useProcessDomainPermissionsMutation = extended.useProcessDomainPermissionsMutation;
export { useProcessDomainPermissionsMutation };
|