├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── captcha.py
├── db
└── sqlite.py
├── init_sqlite.sh
├── main.py
├── minimd.py
├── password.py
├── requirements.txt
├── restart.sh
├── run_sqlite.sh
├── schema.txt
├── static
└── theme.css
├── templates
├── admin
│ ├── base.html
│ ├── index.html
│ └── query.html
├── base.html
├── comment.html
├── comments.html
├── confirm_delete_comment.html
├── confirm_delete_thread.html
├── edit_comment.html
├── edit_thread.html
├── forum.html
├── help.html
├── index.html
├── login.html
├── moderator.html
├── new_thread.html
├── register.html
├── thread.html
├── user_edit.html
└── user_info.html
├── test
├── all.sh
└── init_db.txt
├── tool.py
├── upgrade
└── sqlite
│ └── v0.1.sh
└── upgrade_sqlite.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | /venv
2 | __pycache__
3 | *.db
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | PYTHON = python3
2 | FLASK = flask
3 | SQLITE = sqlite3
4 |
5 | default: venv
6 |
7 | test: venv
8 | test/all.sh
9 |
10 | venv:
11 | $(PYTHON) -m venv $@
12 | . ./venv/bin/activate && pip3 install -r requirements.txt
13 |
14 | forum.db:
15 | $(SQLITE) $@ < schema.txt
16 |
17 | .PHONY: test
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Agreper - minimal, no-JS forum software
2 |
3 | **For security issues, please send a mail to agreper+security@demindiro.com**
4 |
5 | 
6 |
7 | Agreper is a forum board with a focus on being easy to set up and manage.
8 |
9 | ## Install & running
10 |
11 | ### Linux
12 |
13 | Ensure you have the necessary packages, e.g. for Debian:
14 |
15 | ```
16 | apt install git make sqlite3 python3-venv python3-pip
17 | ```
18 |
19 | First clone or [download the latest release](https://github.com/Demindiro/agreper/archive/refs/tags/v0.1.1.tar.gz).
20 |
21 | Then setup with:
22 |
23 | ```
24 | ./init_sqlite.sh forum.db
25 | ```
26 |
27 | Lastly, run with:
28 |
29 | ```
30 | ./run_sqlite.sh forum.db forum.pid
31 | ```
32 |
33 | You will need a proxy such as nginx to access the forum on the public internet.
34 |
35 | ## Upgrading
36 |
37 | To upgrade from a previous version, run ``upgrade_sqlite.sh``
38 |
39 | ## Screenshots
40 |
41 | 
42 | 
43 | 
44 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Only the latest version is supported.
6 |
7 | ## Reporting a Vulnerability
8 |
9 | Please send a mail to agreper+security@demindiro.com
10 |
11 | PGP key: [7897 2A80 BC74 A394 1C50 F060 A915 6EA5 E4B6 44FF](https://www.demindiro.com/pubkey.pgp.asc)
12 |
--------------------------------------------------------------------------------
/captcha.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | import hashlib, base64
3 |
4 | # FIXME hash can be reused
5 | def generate(key):
6 | '''
7 | Generate a simple CAPTCHA.
8 | It is based on a simple math expression which stops the simplest of bots.
9 | '''
10 | # The parameters are chosen such that they are simple to solve on paper.
11 | a = randint(1, 10)
12 | b = randint(1, 10)
13 | c = randint(10, 20)
14 | return f'{a} * {b} + {c} = ', _hash_answer(key, str(a * b + c))
15 |
16 | def verify(key, answer, hash):
17 | return _hash_answer(key, answer) == hash
18 |
19 | def _hash_answer(key, answer):
20 | return base64.b64encode(hashlib.sha256((key + answer).encode('utf-8')).digest()).decode('ascii')
21 |
--------------------------------------------------------------------------------
/db/sqlite.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 | class DB:
4 | def __init__(self, conn):
5 | self.conn = conn
6 | pass
7 |
8 | def get_config(self):
9 | return self._db().execute('''
10 | select version, name, description, secret_key, captcha_key, registration_enabled from config
11 | '''
12 | ).fetchone()
13 |
14 | def get_forums(self):
15 | return self._db().execute('''
16 | select f.forum_id, name, description, thread_id, title, update_time
17 | from forums f
18 | left join threads t
19 | on t.thread_id = (
20 | select tt.thread_id
21 | from threads tt
22 | where f.forum_id = tt.forum_id and not tt.hidden
23 | order by update_time desc
24 | limit 1
25 | )
26 | '''
27 | )
28 |
29 | def get_forum(self, forum_id):
30 | return self._db().execute('''
31 | select name, description
32 | from forums
33 | where forum_id = ?
34 | ''',
35 | (forum_id,)
36 | ).fetchone()
37 |
38 | def get_threads(self, forum_id, offset, limit, user_id):
39 | return self._db().execute('''
40 | select
41 | t.thread_id,
42 | title,
43 | t.create_time,
44 | t.update_time,
45 | t.author_id,
46 | name,
47 | count(c.thread_id),
48 | t.hidden
49 | from
50 | threads t,
51 | users
52 | left join
53 | comments c
54 | on
55 | t.thread_id = c.thread_id
56 | where forum_id = ?
57 | and user_id = t.author_id
58 | and (
59 | t.hidden = 0 or (
60 | select 1 from users
61 | where user_id = ?
62 | and (
63 | user_id = t.author_id
64 | -- 1 = moderator, 2 = admin
65 | or role in (1, 2)
66 | )
67 | )
68 | )
69 | group by t.thread_id
70 | order by t.update_time desc
71 | limit ?
72 | offset ?
73 | ''',
74 | (forum_id, user_id, limit, offset)
75 | )
76 |
77 | def get_thread(self, thread):
78 | db = self._db()
79 | title, text, author, author_id, create_time, modify_time, hidden = db.execute('''
80 | select title, text, name, author_id, create_time, modify_time, hidden
81 | from threads, users
82 | where thread_id = ? and author_id = user_id
83 | ''',
84 | (thread,)
85 | ).fetchone()
86 | comments = db.execute('''
87 | select
88 | comment_id,
89 | parent_id,
90 | author_id,
91 | name,
92 | text,
93 | create_time,
94 | modify_time,
95 | hidden
96 | from comments
97 | left join users
98 | on author_id = user_id
99 | where thread_id = ?
100 | ''',
101 | (thread,)
102 | )
103 | return title, text, author, author_id, create_time, modify_time, comments, hidden
104 |
105 | def get_thread_title(self, thread_id):
106 | return self._db().execute('''
107 | select title
108 | from threads
109 | where thread_id = ?
110 | ''',
111 | (thread_id,)
112 | ).fetchone()
113 |
114 | def get_thread_title_text(self, thread_id):
115 | return self._db().execute('''
116 | select title, text
117 | from threads
118 | where thread_id = ?
119 | ''',
120 | (thread_id,)
121 | ).fetchone()
122 |
123 | def get_recent_threads(self, limit):
124 | return self._db().execute('''
125 | select thread_id, title, modify_date
126 | from threads
127 | order by modify_date
128 | limit ?
129 | ''',
130 | (limit,)
131 | )
132 |
133 | def get_comment(self, comment_id):
134 | return self._db().execute('''
135 | select title, c.text
136 | from comments c, threads t
137 | where comment_id = ? and c.thread_id = t.thread_id
138 | ''',
139 | (comment_id,)
140 | ).fetchone()
141 |
142 | def get_subcomments(self, comment_id):
143 | db = self._db()
144 | thread_id, parent_id, title = db.execute('''
145 | select threads.thread_id, parent_id, title
146 | from threads, comments
147 | where comment_id = ? and threads.thread_id = comments.thread_id
148 | ''',
149 | (comment_id,)
150 | ).fetchone()
151 | # Recursive CTE, see https://www.sqlite.org/lang_with.html
152 | return thread_id, parent_id, title, db.execute('''
153 | with recursive
154 | descendant_of(id) as (
155 | select comment_id from comments where comment_id = ?
156 | union
157 | select comment_id from descendant_of, comments where id = parent_id
158 | )
159 | select
160 | id,
161 | parent_id,
162 | author_id,
163 | name,
164 | text,
165 | create_time,
166 | modify_time,
167 | hidden
168 | from
169 | descendant_of,
170 | comments,
171 | users
172 | where id = comment_id
173 | and user_id = author_id
174 | ''',
175 | (comment_id,)
176 | )
177 |
178 | def get_user_password(self, username):
179 | return self._db().execute('''
180 | select user_id, password
181 | from users
182 | where name = lower(?)
183 | ''',
184 | (username,)
185 | ).fetchone()
186 |
187 | def get_user_password_by_id(self, user_id):
188 | return self._db().execute('''
189 | select password
190 | from users
191 | where user_id = ?
192 | ''',
193 | (user_id,)
194 | ).fetchone()
195 |
196 | def set_user_password(self, user_id, password):
197 | return self.change_one('''
198 | update users
199 | set password = ?
200 | where user_id = ?
201 | ''',
202 | (password, user_id)
203 | )
204 |
205 | def get_user_public_info(self, user_id):
206 | return self._db().execute('''
207 | select name, about, banned_until
208 | from users
209 | where user_id = ?
210 | ''',
211 | (user_id,)
212 | ).fetchone()
213 |
214 | def get_user_private_info(self, user_id):
215 | return self._db().execute('''
216 | select about
217 | from users
218 | where user_id = ?
219 | ''',
220 | (user_id,)
221 | ).fetchone()
222 |
223 | def set_user_private_info(self, user_id, about):
224 | db = self._db()
225 | db.execute('''
226 | update users
227 | set about = ?
228 | where user_id = ?
229 | ''',
230 | (about, user_id)
231 | )
232 | db.commit()
233 |
234 | def get_user_name_role_banned(self, user_id):
235 | return self._db().execute('''
236 | select name, role, banned_until
237 | from users
238 | where user_id = ?
239 | ''',
240 | (user_id,)
241 | ).fetchone()
242 |
243 | def get_user_name(self, user_id):
244 | return self._db().execute('''
245 | select name
246 | from users
247 | where user_id = ?
248 | ''',
249 | (user_id,)
250 | ).fetchone()
251 |
252 | def add_thread(self, author_id, forum_id, title, text, time):
253 | db = self._db()
254 | c = db.cursor()
255 | c.execute('''
256 | insert into threads (author_id, forum_id, title, text,
257 | create_time, modify_time, update_time)
258 | select ?, ?, ?, ?, ?, ?, ?
259 | from users
260 | where user_id = ? and banned_until < ?
261 | ''',
262 | (author_id, forum_id, title, text, time, time, time, author_id, time)
263 | )
264 | rowid = c.lastrowid
265 | if rowid is None:
266 | return None
267 | db.commit()
268 | return db.execute('''
269 | select thread_id
270 | from threads
271 | where rowid = ?
272 | ''',
273 | (rowid,)
274 | ).fetchone()
275 |
276 | def delete_thread(self, user_id, thread_id):
277 | db = self._db()
278 | c = db.cursor()
279 | c.execute('''
280 | delete
281 | from threads
282 | -- 1 = moderator, 2 = admin
283 | where thread_id = ? and (
284 | author_id = ?
285 | or (select 1 from users where user_id = ? and (role = 1 or role = 2))
286 | )
287 | ''',
288 | (thread_id, user_id, user_id)
289 | )
290 | db.commit()
291 | return c.rowcount > 0
292 |
293 | def delete_comment(self, user_id, comment_id):
294 | db = self._db()
295 | c = db.cursor()
296 | c.execute('''
297 | delete
298 | from comments
299 | where comment_id = ?
300 | and (
301 | author_id = ?
302 | -- 1 = moderator, 2 = admin
303 | or (select 1 from users where user_id = ? and (role = 1 or role = 2))
304 | )
305 | -- Don't allow deleting comments with children
306 | and (select 1 from comments where parent_id = ?) is null
307 | ''',
308 | (comment_id, user_id, user_id, comment_id)
309 | )
310 | db.commit()
311 | return c.rowcount > 0
312 |
313 | def add_comment_to_thread(self, thread_id, author_id, text, time):
314 | db = self._db()
315 | c = db.cursor()
316 | c.execute('''
317 | insert into comments(thread_id, author_id, text, create_time, modify_time)
318 | select ?, ?, ?, ?, ?
319 | from threads, users
320 | where thread_id = ? and user_id = ? and banned_until < ?
321 | ''',
322 | (thread_id, author_id, text, time, time, thread_id, author_id, time)
323 | )
324 | if c.rowcount > 0:
325 | c.execute('''
326 | update threads
327 | set update_time = ?
328 | where thread_id = ?
329 | ''',
330 | (time, thread_id)
331 | )
332 | db.commit()
333 | return True
334 | return False
335 |
336 | def add_comment_to_comment(self, parent_id, author_id, text, time):
337 | db = self._db()
338 | c = db.cursor()
339 | c.execute('''
340 | insert into comments(thread_id, parent_id, author_id, text, create_time, modify_time)
341 | select thread_id, ?, ?, ?, ?, ?
342 | from comments, users
343 | where comment_id = ? and user_id = ? and banned_until < ?
344 | ''',
345 | (parent_id, author_id, text, time, time, parent_id, author_id, time)
346 | )
347 | if c.rowcount > 0:
348 | c.execute('''
349 | update threads
350 | set update_time = ?
351 | where threads.thread_id = (
352 | select c.thread_id
353 | from comments c
354 | where comment_id = ?
355 | )
356 | ''',
357 | (time, parent_id)
358 | )
359 | db.commit()
360 | return True
361 | return False
362 |
363 | def modify_thread(self, thread_id, user_id, title, text, time):
364 | db = self._db()
365 | c = db.cursor()
366 | c.execute('''
367 | update threads
368 | set title = ?, text = ?, modify_time = ?
369 | where thread_id = ? and (
370 | (author_id = ? and (select 1 from users where user_id = ? and banned_until < ?))
371 | -- 1 = moderator, 2 = admin
372 | or (select 1 from users where user_id = ? and (role = 1 or role = 2))
373 | )
374 | ''',
375 | (
376 | title, text, time,
377 | thread_id,
378 | user_id, user_id, time,
379 | user_id,
380 | )
381 | )
382 | if c.rowcount > 0:
383 | db.commit()
384 | return True
385 | return False
386 |
387 | def modify_comment(self, comment_id, user_id, text, time):
388 | db = self._db()
389 | c = db.cursor()
390 | c.execute('''
391 | update comments
392 | set text = ?, modify_time = ?
393 | where comment_id = ? and (
394 | (author_id = ? and (select 1 from users where user_id = ? and banned_until < ?))
395 | -- 1 = moderator, 2 = admin
396 | or (select 1 from users where user_id = ? and (role = 1 or role = 2))
397 | )
398 | ''',
399 | (
400 | text, time,
401 | comment_id,
402 | user_id, user_id, time,
403 | user_id,
404 | )
405 | )
406 | if c.rowcount > 0:
407 | db.commit()
408 | return True
409 | return False
410 |
411 | def register_user(self, username, password, time):
412 | '''
413 | Add a user if registrations are enabled.
414 | '''
415 | try:
416 | db = self._db()
417 | c = db.cursor()
418 | c.execute('''
419 | insert into users(name, password, join_time)
420 | select lower(?), ?, ?
421 | from config
422 | where registration_enabled = 1
423 | ''',
424 | (username, password, time)
425 | )
426 | if c.rowcount > 0:
427 | db.commit()
428 | # TODO find a way to get the (autoincremented) user ID without looking
429 | # up by name.
430 | # ROWID is *probably* not always consistent (race conditions).
431 | # Ideally we get the ID immediately on insert.
432 | return c.execute('''
433 | select user_id
434 | from users
435 | where name = lower(?)
436 | ''',
437 | (username,)
438 | ).fetchone()
439 | return None
440 | except sqlite3.IntegrityError:
441 | # User already exists, probably
442 | return None
443 |
444 | def add_user(self, username, password, time):
445 | '''
446 | Add a user without checking if registrations are enabled.
447 | '''
448 | try:
449 | db = self._db()
450 | c = db.cursor()
451 | c.execute('''
452 | insert into users(name, password, join_time)
453 | values (lower(?), ?, ?)
454 | ''',
455 | (username, password, time)
456 | )
457 | if c.rowcount > 0:
458 | db.commit()
459 | return True
460 | return False
461 | except sqlite3.IntegrityError:
462 | # User already exists, probably
463 | return False
464 |
465 | def get_users(self):
466 | return self._db().execute('''
467 | select user_id, name, join_time, role, banned_until
468 | from users
469 | ''',
470 | )
471 |
472 | def set_forum_name(self, forum_id, name):
473 | return self.change_one('''
474 | update forums
475 | set name = ?
476 | where forum_id = ?
477 | ''',
478 | (name, forum_id)
479 | )
480 |
481 | def set_forum_description(self, forum_id, description):
482 | return self.change_one('''
483 | update forums
484 | set description = ?
485 | where forum_id = ?
486 | ''',
487 | (description, forum_id)
488 | )
489 |
490 | def add_forum(self, name, description):
491 | db = self._db()
492 | db.execute('''
493 | insert into forums(name, description)
494 | values (?, ?)
495 | ''',
496 | (name, description)
497 | )
498 | db.commit()
499 |
500 | def set_config(self, server_name, server_description, registration_enabled):
501 | return self.change_one('''
502 | update config
503 | set name = ?, description = ?, registration_enabled = ?
504 | ''',
505 | (server_name, server_description, registration_enabled)
506 | )
507 |
508 | def set_config_secrets(self, secret_key, captcha_key):
509 | return self.change_one('''
510 | update config
511 | set secret_key = ?, captcha_key = ?
512 | ''',
513 | (secret_key, captcha_key)
514 | )
515 |
516 | def set_user_ban(self, user_id, until):
517 | return self.change_one('''
518 | update users
519 | set banned_until = ?
520 | where user_id = ?
521 | ''',
522 | (until, user_id)
523 | )
524 |
525 | def set_user_role(self, user_id, role):
526 | return self.change_one('''
527 | update users
528 | set role = ?
529 | where user_id = ?
530 | ''',
531 | (role, user_id)
532 | )
533 |
534 | def set_thread_hidden(self, thread_id, hide):
535 | return self.change_one('''
536 | update threads
537 | set hidden = ?
538 | where thread_id = ?
539 | ''',
540 | (hide, thread_id)
541 | )
542 |
543 | def set_comment_hidden(self, comment_id, hide):
544 | return self.change_one('''
545 | update comments
546 | set hidden = ?
547 | where comment_id = ?
548 | ''',
549 | (hide, comment_id)
550 | )
551 |
552 | def change_one(self, query, values):
553 | db = self._db()
554 | c = db.cursor()
555 | c.execute(query, values)
556 | if c.rowcount > 0:
557 | db.commit()
558 | return True
559 | return False
560 |
561 | def query(self, q):
562 | db = self._db()
563 | c = db.cursor()
564 | rows = c.execute(q)
565 | db.commit()
566 | return rows, c.rowcount
567 |
568 | def _db(self):
569 | return sqlite3.connect(self.conn, timeout=5)
570 |
--------------------------------------------------------------------------------
/init_sqlite.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | SQLITE=sqlite3
4 | PYTHON=python3
5 |
6 | set -e
7 |
8 | make
9 | . ./venv/bin/activate
10 |
11 | if [ $# -le 0 ]
12 | then
13 | echo "Usage: $0 [--no-admin]" >&2
14 | exit 1
15 | fi
16 |
17 | if [ -e "$1" ]
18 | then
19 | echo "Database '$1' already exists" >&2
20 | exit 1
21 | fi
22 |
23 | if [ "$2" != --no-admin ]
24 | then
25 | read -p 'Admin username: ' username
26 | read -sp 'Admin password: ' password
27 | fi
28 |
29 | password=$($PYTHON tool.py password "$password")
30 | time=$($PYTHON -c 'import time; print(time.time_ns())')
31 |
32 | $SQLITE "$1" -init schema.txt "insert into config (
33 | version,
34 | name,
35 | description,
36 | secret_key,
37 | captcha_key,
38 | registration_enabled
39 | )
40 | values (
41 | 'agreper-v0.1.1',
42 | 'Agreper',
43 | '',
44 | '$(head -c 30 /dev/urandom | base64)',
45 | '$(head -c 30 /dev/urandom | base64)',
46 | 0
47 | )"
48 | if [ "$2" != --no-admin ]
49 | then
50 | $SQLITE "$1" "
51 | insert into users (name, password, role, join_time)
52 | values (lower('$username'), '$password', 2, $time)
53 | "
54 | fi
55 |
56 | echo "Database '$1' created" >&2
57 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | VERSION = 'agreper-v0.1.1'
2 | # TODO put in config table
3 | THREADS_PER_PAGE = 50
4 |
5 | from flask import Flask, render_template, session, request, redirect, url_for, flash, g
6 | from db.sqlite import DB
7 | import os, sys, subprocess
8 | import passlib.hash, secrets
9 | import time
10 | import string
11 | from datetime import datetime
12 | import captcha, password, minimd
13 |
14 | app = Flask(__name__)
15 | db = DB(os.getenv('DB'))
16 |
17 | # This defaults to None, which allows CSRF attacks in FireFox
18 | # and older versions of Chrome.
19 | # 'Lax' is sufficient to prevent malicious POST requests.
20 | app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
21 |
22 | class Config:
23 | pass
24 | config = Config()
25 | config.version, config.server_name, config.server_description, app.config['SECRET_KEY'], config.captcha_key, config.registration_enabled = db.get_config()
26 |
27 | if config.version != VERSION:
28 | print(f'Incompatible version {config.version} (expected {VERSION})')
29 | sys.exit(1)
30 |
31 | class Role:
32 | USER = 0
33 | MODERATOR = 1
34 | ADMIN = 2
35 |
36 | @app.after_request
37 | def after_request(response):
38 | # This forbids other sites from embedding this site in an iframe,
39 | # preventing clickjacking attacks.
40 | response.headers['X-Frame-Options'] = 'DENY'
41 | return response
42 |
43 | @app.route('/')
44 | def index():
45 | return render_template(
46 | 'index.html',
47 | title = config.server_name,
48 | description = config.server_description,
49 | config = config,
50 | user = get_user(),
51 | forums = db.get_forums()
52 | )
53 |
54 | @app.route('/forum//')
55 | def forum(forum_id):
56 | title, description = db.get_forum(forum_id)
57 | offset = int(request.args.get('p', 0))
58 | user_id = session.get('user_id', -1)
59 | threads = [*db.get_threads(forum_id, offset, THREADS_PER_PAGE + 1, user_id)]
60 | if len(threads) == THREADS_PER_PAGE + 1:
61 | threads.pop()
62 | next_page = offset + THREADS_PER_PAGE
63 | else:
64 | next_page = None
65 | return render_template(
66 | 'forum.html',
67 | title = title,
68 | user = get_user(),
69 | config = config,
70 | forum_id = forum_id,
71 | description = description,
72 | threads = threads,
73 | next_page = next_page,
74 | prev_page = max(offset - THREADS_PER_PAGE, 0) if offset > 0 else None,
75 | )
76 |
77 | @app.route('/thread//')
78 | def thread(thread_id):
79 | user = get_user()
80 | title, text, author, author_id, create_time, modify_time, comments, hidden = db.get_thread(thread_id)
81 | comments = create_comment_tree(comments, user)
82 | return render_template(
83 | 'thread.html',
84 | title = title,
85 | config = config,
86 | user = user,
87 | text = text,
88 | author = author,
89 | author_id = author_id,
90 | thread_id = thread_id,
91 | hidden = hidden,
92 | create_time = create_time,
93 | modify_time = modify_time,
94 | comments = comments,
95 | )
96 |
97 | @app.route('/comment//')
98 | def comment(comment_id):
99 | user = get_user()
100 | thread_id, parent_id, title, comments = db.get_subcomments(comment_id)
101 | comments = create_comment_tree(comments, user)
102 | reply_comment, = comments
103 | comments = reply_comment.children
104 | reply_comment.children = []
105 | return render_template(
106 | 'comments.html',
107 | title = title,
108 | config = config,
109 | user = user,
110 | reply_comment = reply_comment,
111 | comments = comments,
112 | parent_id = parent_id,
113 | thread_id = thread_id,
114 | )
115 |
116 | @app.route('/login/', methods = ['GET', 'POST'])
117 | def login():
118 | if request.method == 'POST':
119 | v = db.get_user_password(request.form['username'])
120 | if v is not None:
121 | id, hash = v
122 | if password.verify(request.form['password'], hash):
123 | flash('Logged in', 'success')
124 | session['user_id'] = id
125 | session.permanent = True
126 | return redirect(url_for('index'))
127 | else:
128 | # Sleep to reduce effectiveness of bruteforce
129 | time.sleep(0.1)
130 | flash('Username or password is invalid', 'error')
131 | return render_template(
132 | 'login.html',
133 | title = 'Login',
134 | config = config,
135 | user = get_user()
136 | )
137 |
138 | @app.route('/logout/')
139 | def logout():
140 | session.pop('user_id')
141 | return redirect(url_for('index'))
142 |
143 | @app.route('/user/', methods = ['GET', 'POST'])
144 | def user_edit():
145 | user = get_user()
146 | if user is None:
147 | return redirect(url_for('login'))
148 |
149 | if request.method == 'POST':
150 | about = trim_text(request.form['about'])
151 | db.set_user_private_info(user.id, about)
152 | flash('Updated profile', 'success')
153 | else:
154 | about, = db.get_user_private_info(user.id)
155 |
156 | return render_template(
157 | 'user_edit.html',
158 | title = 'Edit profile',
159 | config = config,
160 | user = user,
161 | about = about
162 | )
163 |
164 | @app.route('/user/edit/password/', methods = ['POST'])
165 | def user_edit_password():
166 | user_id = session.get('user_id')
167 | if user_id is None:
168 | return redirect(url_for('login'))
169 |
170 | new = request.form['new']
171 | if len(new) < 8:
172 | flash('New password must be at least 8 characters long', 'error')
173 | else:
174 | hash, = db.get_user_password_by_id(user_id)
175 | if password.verify(request.form['old'], hash):
176 | if db.set_user_password(user_id, password.hash(new)):
177 | flash('Updated password', 'success')
178 | else:
179 | flash('Failed to update password', 'error')
180 | else:
181 | flash('Old password does not match', 'error')
182 | return redirect(url_for('user_edit'))
183 |
184 | @app.route('/user//')
185 | def user_info(user_id):
186 | name, about, banned_until = db.get_user_public_info(user_id)
187 | return render_template(
188 | 'user_info.html',
189 | title = 'Profile',
190 | config = config,
191 | user = get_user(),
192 | name = name,
193 | id = user_id,
194 | banned_until = banned_until,
195 | about = about
196 | )
197 |
198 | @app.route('/forum//new/', methods = ['GET', 'POST'])
199 | def new_thread(forum_id):
200 | user_id = session.get('user_id')
201 | if user_id is None and not config.registration_enabled:
202 | # Can't create a thread without an account
203 | return redirect(url_for('login'))
204 |
205 | if request.method == 'POST':
206 | if user_id is None:
207 | # Attempt to create a user account first
208 | if register_user(True):
209 | user_id = session['user_id']
210 |
211 | if user_id is not None:
212 | title, text = request.form['title'].strip(), trim_text(request.form['text'])
213 | title = title.strip()
214 | if title == '' or text == '':
215 | flash('Title and text may not be empty', 'error')
216 | return redirect(url_for('forum', forum_id = forum_id))
217 | id = db.add_thread(user_id, forum_id, title, text, time.time_ns())
218 | if id is None:
219 | flash('Failed to create thread', 'error')
220 | return redirect(url_for('forum', forum_id = forum_id))
221 | else:
222 | id, = id
223 | flash('Created thread', 'success')
224 | return redirect(url_for('thread', thread_id = id))
225 |
226 | return render_template(
227 | 'new_thread.html',
228 | title = 'Create new thread',
229 | config = config,
230 | user = get_user(),
231 | )
232 |
233 | @app.route('/thread//confirm_delete/')
234 | def confirm_delete_thread(thread_id):
235 | title, = db.get_thread_title(thread_id)
236 | return render_template(
237 | 'confirm_delete_thread.html',
238 | title = 'Delete thread',
239 | config = config,
240 | user = get_user(),
241 | thread_title = title,
242 | )
243 |
244 | @app.route('/thread//delete/', methods = ['POST'])
245 | def delete_thread(thread_id):
246 | user_id = session.get('user_id')
247 | if user_id is None:
248 | return redirect(url_for('login'))
249 |
250 | if db.delete_thread(user_id, thread_id):
251 | flash('Thread has been deleted', 'success')
252 | else:
253 | flash('Thread could not be removed', 'error')
254 | # TODO return 403, maybe?
255 | return redirect(url_for('index'))
256 |
257 | def _add_comment_check_user():
258 | user_id = session.get('user_id')
259 | if user_id is not None:
260 | return user_id
261 | if not config.registration_enabled:
262 | flash('Registrations are not enabled. Please log in to comment', 'error')
263 | if register_user(True):
264 | return session['user_id']
265 |
266 | @app.route('/thread//comment/', methods = ['POST'])
267 | def add_comment(thread_id):
268 | user_id = _add_comment_check_user()
269 | if user_id is not None:
270 | text = trim_text(request.form['text'])
271 | if text == '':
272 | flash('Text may not be empty', 'error')
273 | elif db.add_comment_to_thread(thread_id, user_id, text, time.time_ns()):
274 | flash('Added comment', 'success')
275 | else:
276 | flash('Failed to add comment', 'error')
277 | return redirect(url_for('thread', thread_id = thread_id))
278 |
279 | @app.route('/comment//comment/', methods = ['POST'])
280 | def add_comment_parent(comment_id):
281 | user_id = _add_comment_check_user()
282 | if user_id is not None:
283 | text = trim_text(request.form['text'])
284 | if text == '':
285 | flash('Text may not be empty', 'error')
286 | elif db.add_comment_to_comment(comment_id, user_id, text, time.time_ns()):
287 | flash('Added comment', 'success')
288 | else:
289 | flash('Failed to add comment', 'error')
290 | return redirect(url_for('comment', comment_id = comment_id))
291 |
292 | @app.route('/comment//confirm_delete/')
293 | def confirm_delete_comment(comment_id):
294 | title, text = db.get_comment(comment_id)
295 | return render_template(
296 | 'confirm_delete_comment.html',
297 | title = 'Delete comment',
298 | config = config,
299 | user = get_user(),
300 | thread_title = title,
301 | text = text,
302 | )
303 |
304 | @app.route('/comment//delete/', methods = ['POST'])
305 | def delete_comment(comment_id):
306 | user_id = session.get('user_id')
307 | if user_id is None:
308 | return redirect(url_for('login'))
309 |
310 | if db.delete_comment(user_id, comment_id):
311 | flash('Comment has been deleted', 'success')
312 | else:
313 | flash('Comment could not be removed', 'error')
314 | # TODO return 403, maybe?
315 | return redirect(url_for('index'))
316 |
317 | @app.route('/thread//edit/', methods = ['GET', 'POST'])
318 | def edit_thread(thread_id):
319 | user_id = session.get('user_id')
320 | if user_id is None:
321 | return redirect(url_for('login'))
322 |
323 | if request.method == 'POST':
324 | title, text = request.form['title'].strip(), trim_text(request.form['text'])
325 | if title == '' or text == '':
326 | flash('Title and text may not be empty', 'error')
327 | elif db.modify_thread(
328 | thread_id,
329 | user_id,
330 | title,
331 | text,
332 | time.time_ns(),
333 | ):
334 | flash('Thread has been edited', 'success')
335 | else:
336 | flash('Thread could not be edited', 'error')
337 | return redirect(url_for('thread', thread_id = thread_id))
338 |
339 | title, text = db.get_thread_title_text(thread_id)
340 |
341 | return render_template(
342 | 'edit_thread.html',
343 | title = 'Edit thread',
344 | config = config,
345 | user = get_user(),
346 | thread_title = title,
347 | text = text,
348 | )
349 |
350 | @app.route('/comment//edit/', methods = ['GET', 'POST'])
351 | def edit_comment(comment_id):
352 | user_id = session.get('user_id')
353 | if user_id is None:
354 | return redirect(url_for('login'))
355 |
356 | if request.method == 'POST':
357 | text = trim_text(request.form['text'])
358 | if text == '':
359 | flash('Text may not be empty', 'error')
360 | elif db.modify_comment(
361 | comment_id,
362 | user_id,
363 | trim_text(request.form['text']),
364 | time.time_ns(),
365 | ):
366 | flash('Comment has been edited', 'success')
367 | else:
368 | flash('Comment could not be edited', 'error')
369 | return redirect(url_for('comment', comment_id = comment_id))
370 |
371 | title, text = db.get_comment(comment_id)
372 |
373 | return render_template(
374 | 'edit_comment.html',
375 | title = 'Edit comment',
376 | config = config,
377 | user = get_user(),
378 | thread_title = title,
379 | text = text,
380 | )
381 |
382 | @app.route('/register/', methods = ['GET', 'POST'])
383 | def register():
384 | if request.method == 'POST':
385 | username, passwd = request.form['username'], request.form['password']
386 | if register_user(False):
387 | return redirect(url_for('index'))
388 |
389 | capt, answer = captcha.generate(config.captcha_key)
390 | return render_template(
391 | 'register.html',
392 | title = 'Register',
393 | config = config,
394 | user = get_user(),
395 | captcha = capt,
396 | answer = answer,
397 | )
398 |
399 | @app.route('/admin/')
400 | def admin():
401 | chk, user = _admin_check()
402 | if not chk:
403 | return user
404 |
405 | return render_template(
406 | 'admin/index.html',
407 | title = 'Admin panel',
408 | config = config,
409 | forums = db.get_forums(),
410 | users = db.get_users(),
411 | )
412 |
413 | @app.route('/admin/query/', methods = ['GET', 'POST'])
414 | def admin_query():
415 | chk, user = _admin_check()
416 | if not chk:
417 | return user
418 |
419 | try:
420 | rows, rowcount = db.query(request.form['q']) if request.method == 'POST' else []
421 | if rowcount > 0:
422 | flash(f'{rowcount} rows changed', 'success')
423 | except Exception as e:
424 | flash(e, 'error')
425 | rows = []
426 | return render_template(
427 | 'admin/query.html',
428 | title = 'Query',
429 | config = config,
430 | rows = rows,
431 | )
432 |
433 | @app.route('/admin/forum//edit//', methods = ['POST'])
434 | def admin_edit_forum(forum_id, what):
435 | chk, user = _admin_check()
436 | if not chk:
437 | return user
438 |
439 | try:
440 | if what == 'description':
441 | res = db.set_forum_description(forum_id, trim_text(request.form['description']))
442 | elif what == 'name':
443 | res = db.set_forum_name(forum_id, request.form['name'])
444 | else:
445 | flash(f'Unknown property "{what}"', 'error')
446 | res = None
447 | if res is True:
448 | flash(f'Updated {what}', 'success')
449 | elif res is False:
450 | flash(f'Failed to update {what}', 'error')
451 | except Exception as e:
452 | flash(e, 'error')
453 | return redirect(url_for('admin'))
454 |
455 | @app.route('/admin/forum/new/', methods = ['POST'])
456 | def admin_new_forum():
457 | chk, user = _admin_check()
458 | if not chk:
459 | return user
460 |
461 | try:
462 | db.add_forum(request.form['name'], trim_text(request.form['description']))
463 | flash('Added forum', 'success')
464 | except Exception as e:
465 | flash(str(e), 'error')
466 | return redirect(url_for('admin'))
467 |
468 | @app.route('/admin/config/edit/', methods = ['POST'])
469 | def admin_edit_config():
470 | chk, user = _admin_check()
471 | if not chk:
472 | return user
473 |
474 | try:
475 | db.set_config(
476 | request.form['server_name'],
477 | trim_text(request.form['server_description']),
478 | 'registration_enabled' in request.form,
479 | )
480 | flash('Updated config. Refresh the page to see the changes.', 'success')
481 | restart()
482 | except Exception as e:
483 | flash(str(e), 'error')
484 | return redirect(url_for('admin'))
485 |
486 | @app.route('/admin/config/new_secrets/', methods = ['POST'])
487 | def admin_new_secrets():
488 | chk, user = _admin_check()
489 | if not chk:
490 | return user
491 |
492 | secret_key = secrets.token_urlsafe(30)
493 | captcha_key = secrets.token_urlsafe(30)
494 | try:
495 | db.set_config_secrets(secret_key, captcha_key)
496 | flash('Changed secrets. You will be logged out.', 'success')
497 | restart()
498 | except Exception as e:
499 | flash(str(e), 'error')
500 | return redirect(url_for('admin'))
501 |
502 | def ban_user(user_id):
503 | chk, user = _moderator_check()
504 | if not chk:
505 | return user
506 |
507 | d, t = request.form['days'], request.form['time']
508 | d = 0 if d == '' else int(d)
509 | h, m = (0, 0) if t == '' else map(int, t.split(':'))
510 | until = time.time_ns() + (d * 24 * 60 + h * 60 + m) * (60 * 10**9)
511 | until = min(until, 0x7fff_ffff_ffff_ffff)
512 |
513 | try:
514 | if db.set_user_ban(user_id, until):
515 | flash('Banned user', 'success')
516 | else:
517 | flash('Failed to ban user', 'error')
518 | except Exception as e:
519 | flash(str(e), 'error')
520 |
521 | @app.route('/user//ban/', methods = ['POST'])
522 | def moderator_ban_user(user_id):
523 | return ban_user(user_id) or redirect(url_for('user_info', user_id = user_id))
524 |
525 | @app.route('/admin/user//ban/', methods = ['POST'])
526 | def admin_ban_user(user_id):
527 | return ban_user(user_id) or redirect(url_for('admin'))
528 |
529 | def unban_user(user_id):
530 | chk, user = _moderator_check()
531 | if not chk:
532 | return user
533 |
534 | try:
535 | if db.set_user_ban(user_id, 0):
536 | flash('Unbanned user', 'success')
537 | else:
538 | flash('Failed to unban user', 'error')
539 | except Exception as e:
540 | flash(str(e), 'error')
541 |
542 | @app.route('/user//unban/', methods = ['POST'])
543 | def moderator_unban_user(user_id):
544 | return unban_user(user_id) or redirect(url_for('user_info', user_id = user_id))
545 |
546 | @app.route('/admin/user//unban/', methods = ['POST'])
547 | def admin_unban_user(user_id):
548 | return unban_user(user_id) or redirect(url_for('admin'))
549 |
550 | @app.route('/admin/user/new/', methods = ['POST'])
551 | def admin_new_user():
552 | chk, user = _admin_check()
553 | if not chk:
554 | return user
555 |
556 | try:
557 | name, passwd = request.form['name'], request.form['password']
558 | if name == '' or passwd == '':
559 | flash('Name and password may not be empty')
560 | elif db.add_user(name, password.hash(passwd), time.time_ns()):
561 | flash('Added user', 'success')
562 | else:
563 | flash('Failed to add user', 'error')
564 | except Exception as e:
565 | flash(str(e), 'error')
566 | return redirect(url_for('admin'))
567 |
568 | @app.route('/admin/user//edit/role/', methods = ['POST'])
569 | def admin_set_role(user_id):
570 | chk, user = _admin_check()
571 | if not chk:
572 | return user
573 |
574 | try:
575 | role = request.form['role']
576 | if role not in ('0', '1', '2'):
577 | flash(f'Invalid role type ({role})', 'error')
578 | else:
579 | db.set_user_role(user_id, role)
580 | flash('Set user role', 'success')
581 | except Exception as e:
582 | flash(str(e), 'error')
583 | return redirect(url_for('admin'))
584 |
585 | @app.route('/admin/restart/', methods = ['POST'])
586 | def admin_restart():
587 | chk, user = _admin_check()
588 | if not chk:
589 | return user
590 |
591 | restart()
592 | return redirect(url_for('admin'))
593 |
594 | @app.route('/thread//hide/', methods = ['POST'])
595 | def set_hide_thread(thread_id):
596 | chk, user = _moderator_check()
597 | if not chk:
598 | return user
599 |
600 | try:
601 | hide = request.form['hide'] != '0'
602 | hide_str = 'Hidden' if hide else 'Unhidden'
603 | if db.set_thread_hidden(thread_id, hide):
604 | flash(f'{hide_str} thread', 'success')
605 | else:
606 | flash(f'Failed to {hide_str.lower()} thread', 'error')
607 | except Exception as e:
608 | flash(str(e), 'error')
609 |
610 | return redirect(request.form['redirect'])
611 |
612 | @app.route('/comment//hide/', methods = ['POST'])
613 | def set_hide_comment(comment_id):
614 | chk, user = _moderator_check()
615 | if not chk:
616 | return user
617 |
618 | try:
619 | hide = request.form['hide'] != '0'
620 | hide_str = 'Hidden' if hide else 'Unhidden'
621 | if db.set_comment_hidden(comment_id, hide):
622 | flash(f'{hide_str} comment', 'success')
623 | else:
624 | flash(f'Failed to {hide_str.lower()} comment', 'error')
625 | except Exception as e:
626 | flash(str(e), 'error')
627 |
628 | return redirect(request.form['redirect'])
629 |
630 | # TODO can probably be a static-esque page, maybe?
631 | @app.route('/help/')
632 | def help():
633 | return render_template(
634 | 'help.html',
635 | title = 'Help',
636 | user = get_user(),
637 | )
638 |
639 | def _moderator_check():
640 | user = get_user()
641 | if user is None:
642 | return False, redirect(url_for('login'))
643 | if not user.is_moderator():
644 | return False, ('
Forbidden
', 403)
645 | return True, user
646 |
647 | def _admin_check():
648 | user = get_user()
649 | if user is None:
650 | return False, redirect(url_for('login'))
651 | if not user.is_admin():
652 | return False, ('
Forbidden
', 403)
653 | return True, user
654 |
655 |
656 | class Comment:
657 | def __init__(self, id, parent_id, author_id, author, text, create_time, modify_time, hidden):
658 | self.id = id
659 | self.author_id = author_id
660 | self.author = author
661 | self.text = text
662 | self.children = []
663 | self.create_time = create_time
664 | self.modify_time = modify_time
665 | self.parent_id = parent_id
666 | self.hidden = hidden
667 |
668 | def create_comment_tree(comments, user):
669 | start = time.time();
670 | # Collect comments first, then build the tree in case we encounter a child before a parent
671 | comment_map = { v[0]: Comment(*v) for v in comments }
672 | root = []
673 | # We should keep showing hidden comments if the user replied to them, directly or indirectly.
674 | # To do that, keep track of user comments, then walk up the tree and insert hidden comments.
675 | user_comments = []
676 | # Build tree
677 | def insert(comment):
678 | parent = comment_map.get(comment.parent_id)
679 | if parent is not None:
680 | parent.children.append(comment)
681 | else:
682 | root.append(comment)
683 | for comment in comment_map.values():
684 | if comment.hidden and (not user or not user.is_moderator()):
685 | continue
686 | insert(comment)
687 | if user and (comment.author_id == user.id and not user.is_moderator()):
688 | user_comments.append(comment)
689 | # Insert replied-to hidden comments
690 | for c in user_comments:
691 | while c is not None:
692 | if c.hidden:
693 | insert(c)
694 | c = comment_map.get(c.parent_id)
695 | # Sort each comment based on create time
696 | def sort_time(l):
697 | l.sort(key=lambda c: c.modify_time, reverse=True)
698 | for c in l:
699 | sort_time(c.children)
700 | sort_time(root)
701 | return root
702 |
703 |
704 | class User:
705 | def __init__(self, id, name, role, banned_until):
706 | self.id = id
707 | self.name = name
708 | self.role = role
709 | self.banned_until = banned_until
710 |
711 | def is_moderator(self):
712 | return self.role in (Role.ADMIN, Role.MODERATOR)
713 |
714 | def is_admin(self):
715 | return self.role == Role.ADMIN
716 |
717 | def is_banned(self):
718 | return self.banned_until > time.time_ns()
719 |
720 | def get_user():
721 | id = session.get('user_id')
722 | if id is not None:
723 | name, role, banned_until = db.get_user_name_role_banned(id)
724 | return User(id, name, role, banned_until)
725 | return None
726 |
727 | def register_user(show_password):
728 | username, passwd = request.form['username'], request.form['password']
729 | if any(c in username for c in string.whitespace):
730 | # This error is more ergonomic in case someone tries to play tricks again :)
731 | flash('Username may not contain whitespace', 'error')
732 | elif len(username) < 3:
733 | flash('Username must be at least 3 characters long', 'error')
734 | elif len(passwd) < 8:
735 | flash('Password must be at least 8 characters long', 'error')
736 | elif not captcha.verify(
737 | config.captcha_key,
738 | request.form['captcha'],
739 | request.form['answer'],
740 | ):
741 | flash('CAPTCHA answer is incorrect', 'error')
742 | else:
743 | uid = db.register_user(username, password.hash(passwd), time.time_ns())
744 | if uid is None:
745 | flash('Failed to create account (username may already be taken)', 'error')
746 | else:
747 | s = 'Account has been created.'
748 | if show_password:
749 | s += f' Your password is {passwd} (hover to reveal).'
750 | flash(s, 'success')
751 | uid, = uid
752 | session['user_id'] = uid
753 | session.permanent = True
754 | return True
755 | return False
756 |
757 |
758 | @app.context_processor
759 | def utility_processor():
760 | def _format_time_delta(n, t):
761 | # Try the sane thing first
762 | dt = (n - t) // 10 ** 9
763 | if dt < 1:
764 | return "less than a second"
765 | if dt < 2:
766 | return f"1 second"
767 | if dt < 60:
768 | return f"{dt} seconds"
769 | if dt < 119:
770 | return f"1 minute"
771 | if dt < 3600:
772 | return f"{dt // 60} minutes"
773 | if dt < 3600 * 2:
774 | return f"1 hour"
775 | if dt < 3600 * 24:
776 | return f"{dt // 3600} hours"
777 | if dt < 3600 * 24 * 31:
778 | return f"{dt // (3600 * 24)} days"
779 |
780 | # Try some very rough estimate, whatever
781 | f = lambda x: datetime.utcfromtimestamp(x // 10 ** 9)
782 | n, t = f(n), f(t)
783 | def f(x, y, s):
784 | return f'{y - x} {s}{"s" if y - x > 1 else ""}'
785 | if t.year < n.year:
786 | return f(t.year, n.year, "year")
787 | if t.month < n.month:
788 | return f(t.month, n.month, "month")
789 | assert False, 'unreachable'
790 |
791 | def format_since(t):
792 | n = time.time_ns()
793 | if n < t:
794 | return 'in a distant future'
795 | return _format_time_delta(n, t) + ' ago'
796 |
797 | def format_until(t):
798 | n = time.time_ns()
799 | if t <= n:
800 | return 'in a distant past'
801 | return _format_time_delta(t, n)
802 |
803 | def format_time(t):
804 | return datetime.utcfromtimestamp(t / 10 ** 9).replace(microsecond=0)
805 |
806 | def rand_password():
807 | '''
808 | Generate a random password.
809 |
810 | The current implementation returns 12 random lower- and uppercase alphabet characters.
811 | This gives up to `log((26 * 2) ** 12) / log(2) = ~68` bits of entropy, which should be
812 | enough for the foreseeable future.
813 | '''
814 | return ''.join(string.ascii_letters[secrets.randbelow(52)] for _ in range(12))
815 |
816 | def gen_captcha():
817 | return captcha.generate(config.captcha_key)
818 |
819 | return {
820 | 'format_since': format_since,
821 | 'format_time': format_time,
822 | 'format_until': format_until,
823 | 'minimd': minimd.html,
824 | 'rand_password': rand_password,
825 | 'gen_captcha': gen_captcha,
826 | }
827 |
828 |
829 | def restart():
830 | '''
831 | Shut down *all* workers and spawn new ones.
832 | This is necessary on e.g. a configuration change.
833 |
834 | Since restarting workers depends is platform-dependent this task is delegated to an external
835 | program.
836 | '''
837 | r = subprocess.call(['./restart.sh'])
838 | if r == 0:
839 | flash('Restart script exited successfully', 'success')
840 | else:
841 | flash(f'Restart script exited with error (code {r})', 'error')
842 |
843 | def trim_text(s):
844 | '''
845 | Because browsers LOVE \\r, trailing whitespace etc.
846 | '''
847 | return s.replace('\r', '')
848 |
--------------------------------------------------------------------------------
/minimd.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import re
4 |
5 | # https://stackoverflow.com/a/6041965
6 | RE_URL = re.compile(r'(https?://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-]))')
7 | RE_EM = re.compile(r'\*(.*?)\*')
8 | RE_LIST = re.compile(r'(-|[0-9]\.) .*')
9 |
10 | def html(text):
11 | # Replace angle brackets to prevent XSS
12 | # Also replace ampersands to prevent surprises.
13 | text = text.replace('&', '&').replace('<', '<').replace('>', '>')
14 |
15 | html = ['
']
16 | lines = text.split('\n')
17 | in_code = False
18 | in_list = False
19 |
20 | for l in lines:
21 | if l == '':
22 | in_list = False
23 | if in_code:
24 | html.append('')
25 | in_code = False
26 | html.append('
')
27 | continue
28 | if l.startswith(' '):
29 | in_list = False
30 | l = l[2:]
31 | if not in_code:
32 | html.append('
36 | {%- for category, msg in get_flashed_messages(True) -%}
37 | {#-
38 | FIXME ensure all flash() messages are free of XSS vectors.
39 | In particular, check places where we flash error messages.
40 | -#}
41 |
{{ msg | safe }}
42 | {%- endfor -%}
43 | {%- block content %}{% endblock -%}
44 |
45 |
46 |
--------------------------------------------------------------------------------
/templates/comment.html:
--------------------------------------------------------------------------------
1 | {% from 'moderator.html' import moderate_comment with context -%}
2 |
3 | {%- macro author(id, name, ctime, mtime) -%}
4 | {{ name }} - {{ format_since(ctime) }}{% if ctime != mtime %} (last modified {{ format_since(mtime) }}){% endif %}
5 | {%- endmacro -%}
6 |
7 | {%- macro comment_author(comment, thread_id, can_delete) -%}
8 |
9 | {{- '[hidden]' if comment.hidden else '' }}
10 | {{ author(comment.author_id, comment.author, comment.create_time, comment.modify_time) }} |
11 | {# Suffixing a # prevents unnecessary reloads #}
12 | thread
13 | {%- if comment.parent_id is not none -%}
14 | parent
15 | {%- endif -%}
16 | {%- if user is not none and (comment.author_id == user.id or user.is_moderator()) and not user.is_banned() -%}
17 | edit
18 | {%- if can_delete -%}
19 | delete
20 | {%- endif -%}
21 | {%- if user.is_moderator() -%}
22 | {{ moderate_comment(comment.id, comment.hidden) }}
23 | {%- endif -%}
24 | {%- endif -%}
25 |
26 | {%- endmacro -%}
27 |
28 | {%- macro thread_author(author_id, name, ctime, mtime) -%}
29 |
30 | {{- author(author_id, name, ctime, mtime) -}}
31 | {%- if user is not none and (author_id == user.id or user.is_moderator()) and not user.is_banned() -%}
32 | edit
33 | delete
34 | {%- endif -%}
35 |
36 | {%- endmacro -%}
37 |
38 | {%- macro render_comment_pre(comment, thread_id, can_delete) -%}
39 |
6 | {%- if prev_page is not none %}prev{% endif -%}
7 | {%- if prev_page is not none and next_page is not none %} | {% endif -%}
8 | {%- if next_page is not none %}next{% endif -%}
9 |