forked from nanoboard/nanoboard
/
PostsValidator.cs
283 lines (243 loc) · 9.68 KB
/
PostsValidator.cs
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
using Newtonsoft.Json;
using NDB;
using System.Collections.Generic;
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions; //to check is Base64 and to unescape JSON-special characters
namespace NDB
{
static class PostsValidator
{
/*
Validate Base64-string
*/
public static bool IsBase64String(this string s)
{
s = s.Trim();
return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
}
public static string EscapeJSONSpecialCharacters(string str)
{
//https://www.tutorialspoint.com/json_simple/json_simple_escape_characters.htm
// Just 7 special characters must to be escaped with backslash in JSON-values:
//string str = "\b\f\n\r\t\"\\";
string str2 = str
.Replace("\\","\\\\") // "\\" -> "\\\\" (at first, because else one slash will be replaced to two)
.Replace("\b","\\b") // "\b" -> "\\b"
.Replace("\f","\\f") // "\f" -> "\\f"
.Replace("\n","\\n") // "\n" -> "\\n"
.Replace("\r","\\r") // "\r" -> "\\r"
.Replace("\t","\\t") // "\t" -> "\\t"
.Replace("\"","\\\"") // "\"" -> "\\""
;
//Console.WriteLine("\n\n"+"Escape into JSON:\n"+str2);
return str2;
}
public static string UnescapeJSONSpecialCharacters(string str2){
string str = Regex.Unescape(str2);
//Console.WriteLine("\n\n"+"Raw string from JSON:\n"+str);
return str;
}
/*
This extension methods are used everywhere to return raw-message from Post.message if this encoded.
Variants of Post.message:
1. (raw_message):
"message": "raw_post_message_Text_Without_7_JSON_Special_Characters"
//(7 JSON special characters): ('\b', '\f', '\n', '\r', '\t' '\"', '\\')
2. (escaped_message):
"message": "Escaped_post_message_with_escaped_By_backslash_for_7_JSON_Special_Characters"
//(7 JSON special characters) -> ('\\b', '\\f', '\\n', '\\r', '\\t' '\\"', '\\\\') (just add backslash before slash, and 2 slashes before 1 slash)
3. (encoded_message):
"message": "console.log(encodeURIComponent('raw_post_message_with_JSON_special_characters'))"
4. (base64encoded_message)"message": "console.log(btoa('raw_post_message_with_JSON_special_characters'))"
Encoding:
1. raw_message (if this not contains 7 JSON special characers) - leave this as is.
(This is Human-readable)
2. escaped_message (if raw_message cointains 7 JSON special characters) - escaped_message.
(This is still human-reabable, but JSON-special characters are replaced)
3. encoded_message (just use javascript function encodeURIComponent('raw_message')) -> encoded_message.
(This is still human-readable, but "\n" replaced to "\\n", and this is one string in JSON.)
4. base64encoded_message (just use javascript function btoa('raw_message')) -> base64encoded_message
Decode:
if base64encoded_message
try to return decoded base64
error
try to return decoded encoded_message
error
try to return unescaped escaped_message
error
return raw_message as is.
*/
public static string FromB64(this string s)
{
//1. return a raw message, as is the "Raw_Message_Without_JSON_Special_Characters"
//2. or return a raw message, as an unesaped "Message_With_JSON_Special_Characters_escaped_by_backslash" ("\")
//3. or return a raw message, as a decoded "JavaScript_Function_encodeURIComponent(Message_with_JSON_Special_Characters)"
//4. or return a raw message, as a decoded "JavaScript_Function_btoa_to_encode_Text_in_base64(Message_With_JSON_Special_Characters)"
//if base64, then try return (4); else try return (3), or try (2), or return (1) as is.
if(s == "" || s == null){
//if string is null or empty
return "PostValidator.cs. FromB64. Source string is empty or null.";
}
if(!IsBase64String(s)){
//if string not base64 encoded
//Console.WriteLine("This is not base64 string: "+s);
try {
//try to unescape this if this was been encodeURIComponent, and return result
return System.Uri.UnescapeDataString(s);
}
catch{ //on catch
try{
//try to unescape this if JSON special characters was been escaped only
return Regex.Unescape(s);
}
catch{ //on catch
return s; //return string as is
}
}
}
//else if string was been base64-encoded string, decode this from base64, and return UTF8 string.
return Encoding.UTF8.GetString(Convert.FromBase64String(s));
}
/*
See above. Inverse operation.
*/
public static string ToB64(this string s)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
}
/*
Rewrites post hash.
Checks if post meets rules:
max message size in utf-8 bytes is 65536,
replyTo should be valid hash
returns false if rules violated
*/
public static bool Validate(NDB.Post p, bool bypassValidation = false)
{
// var message = p.message.FromB64();
string message = null;
try{
message = p.message.FromB64();
}catch(Exception ex){
Console.WriteLine("PostsValidator. Validate. Fail to decode base64-encoded p.message. "+ex+"\nMaybe this is not encoded. message = p.message, now.");
message = p.message;
}
var bytes = Encoding.UTF8.GetBytes(message);
if (bytes.Length > 65536)
{
return false;
}
p.hash = HashCalculator.Calculate(p.replyto + message);
if (p.replyto.Length != 32)
return false;
foreach (var ch in p.replyto)
{
if (!((ch >= 'a' && ch <= 'f') || (ch >= '0' && ch <= '9')))
{
return false;
}
}
var post = p.replyto + message;
if (!bypassValidation && !captcha.Captcha.PostHasValidPOW(post))
{
return false;
}
if (!captcha.Captcha.PostHasSolvedCaptcha(post, bypassValidation))
{
return false;
}
return true;
}
/*
Validates range of posts in a batch.
*/
public static Post[] Validate(NDB.Post[] posts)
{
var res = new List<Post>();
foreach (var p in posts)
{
if (Validate(p))
{
res.Add(p);
}
}
return res.ToArray();
}
/*
Rewrites post hash.
Checks if post meets rules:
max message size in utf-8 bytes is 65536,
replyTo should be valid hash
returns false if rules violated
*/
public static bool Validate(nbpack.Post p, bool bypassValidation = false) //one post
{
string message = null;
try{
message = p.message.FromB64();
}catch(Exception ex){
Console.WriteLine("PostsValidator.Validate. p.message: "+p.message+", ex: "+ex);
}
var bytes = Encoding.UTF8.GetBytes(message);
if (bytes.Length > 65536)
{
return false;
}
p.hash = HashCalculator.Calculate(p.replyto + message);
if (p.replyto.Length != 32)
return false;
foreach (var ch in p.replyto)
{
if (!((ch >= 'a' && ch <= 'f') || (ch >= '0' && ch <= '9')))
{
return false;
}
}
var post = p.replyto + message;
if (!captcha.Captcha.PostHasValidPOW(post) && !bypassValidation)
{
return false;
}
if (!captcha.Captcha.PostHasSolvedCaptcha(post, bypassValidation))
{
return false;
}
return true;
}
/*
Validates range of posts in a batch.
*/
public static nbpack.Post[] Validate(nbpack.Post[] posts, bool bypassValidation = false) //return array with many valid posts
{
var res = new List<nbpack.Post>();
//Console.WriteLine("fix_posts.Count: "+fix_posts.Count);
foreach (var p in posts)
{
if((nbpack.NBPackMain.fix_posts).ContainsKey(p.hash)){
if((nbpack.NBPackMain.fix_posts)[p.hash][0] == "deleted" && (nbpack.NBPackMain.fix_posts)[p.hash][1] == "forever"){continue;}
p.replyto = (nbpack.NBPackMain.fix_posts)[p.hash][0]; //replyTo
p.message = Convert.ToBase64String(
Encoding.UTF8.GetBytes(
(
nbpack.NBPackMain.fix_posts //from dictionary form fix_posts.json
[p.hash] //for this post.hash
[1] //take message
.FromB64() //and get raw-message from this
)
)
)
; //Replace message to the fixed message
p.hash = (nbpack.NBPackMain.fix_posts)[p.hash][2]; //new post hash
}
if (Validate(p, bypassValidation))
{
res.Add(p);
}
}
return res.ToArray();
}
}
}