Oasis 0.9.5 con Karvan para escritorio

Rama de desarrollo experimental sobre el Oasis de epsylon, sin afiliacion con el
proyecto original. Base: 0.9.5.

Trae el modulo Karvan —salas efimeras en memoria con autodestruccion por TTL, chat
que funciona sin JavaScript y llamadas de audio y video sobre WebRTC— con el enlace
en el menu lateral por el mismo patron que el resto de modulos: renderKarvanLink
calcado de renderPollsLink, entrada en modules_view y en la lista de /modules.

Los estilos del modulo van en su propia hoja, styles/karvan.css, siguiendo el patron
de highlight.css: asi se ve igual con cualquier tema, sin depender del tema movil.

Sin servidores ICE de terceros: no hay STUN de fabrica, porque un STUN aprende la IP
publica y el momento de cada llamada. Solo candidatos host salvo que se configure un
TURN propio en oasis-config.json, con credenciales efimeras por el mecanismo REST de
coturn.

El codigo propio vive separado —views/fork/, backend/fork_routes.js,
models/karvan_model.js y translations/fork/— de modo que sobre los ficheros de
upstream solo hay enganches de una linea y cada version nueva se integra sin
arrastrar nada.

Respecto al arbol de Android: fuera el wrapper y main.js, que es su arranque; el
tema vuelve a Dark-SNH y se restauran los modulos que en movil se recortan por peso.

Verificado arrancando sin OASIS_MOBILE: nueve rutas OK, menu lateral de upstream con
27 grupos y el enlace de Karvan, cero rastro de la interfaz movil (ni hexagonos, ni
topbar, ni barra inferior), y una sala creada y servida.
This commit is contained in:
SITO 2026-08-19 00:35:08 +02:00
commit ddd2787b73
286 changed files with 157145 additions and 0 deletions

15
.gitignore vendored Normal file
View file

@ -0,0 +1,15 @@
node_modules/
packages/
*.gguf
*.onnx
*.tar.gz
src/AI/embeddings/
src/AI/.cache/
.update_required
cache/
src/configs/*
!src/configs/config-manager.js
!src/configs/shared-state.js
!src/configs/server-config.json
!src/configs/content_favorites.json
test/results/

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

78
README.md Normal file
View file

@ -0,0 +1,78 @@
# OASIS_LINUX — rama de desarrollo experimental
> ## ⚠ ESTO NO ES OASIS OFICIAL
>
> Esta es una **rama de desarrollo experimental** mantenida por el hacklab, no
> afiliada al proyecto original.
>
> **El repositorio oficial de Oasis es el de epsylon: https://github.com/epsylon/oasis**
>
> Si quieres **usar Oasis de verdad**, instala el oficial. Lo que hay aquí puede
> romperse, cambiar de forma incompatible o desaparecer sin aviso. No está auditado
> y no tiene garantía de ninguna clase.
>
> Los fallos de esta rama **se reportan aquí, nunca a epsylon**.
Versión base: **Oasis 0.9.5**.
## Qué añade esta rama
### Karvan — salas efímeras
Salas de chat que **viven solo en memoria** y se autodestruyen solas:
- TTL de inactividad (30 min) y absoluto (2 h), configurables al crear la sala.
- Nada se escribe en disco ni en el log SSB: al vencer el plazo, la sala y sus
mensajes desaparecen.
- Anillo de 250 mensajes, 100 salas simultáneas, 50 miembros por sala.
- El identificador de sala son **72 bits** y es la única credencial: **quien tiene
el enlace, entra**. No hay lista de miembros que valga.
- Invitación a un contacto por mensaje privado SSB.
- **Funciona sin JavaScript**: enviar y recibir van por formulario y recarga. Con
JavaScript se añade un canal directo entre pares.
### Llamadas de audio y vídeo
Sobre el mismo WebRTC del chat. En escritorio el navegador pide los permisos de
cámara y micrófono directamente.
**Sin servidores de terceros**: no hay ningún STUN de fábrica. Un servidor STUN
aprende la IP pública y el momento de cada llamada, así que no se pone ninguno.
Por defecto solo hay candidatos host, que funcionan en la misma red y con NAT
amable. Si tu nodo tiene TURN propio, se configura en `oasis-config.json`:
```json
"rtc": {
"stun": ["stun:tu.pub:3478"],
"turn": { "urls": ["turn:tu.pub:3478"], "secret": "<static-auth-secret>", "ttlSec": 3600 },
"relayOnly": false
}
```
Con `secret` se emiten credenciales efímeras por el mecanismo REST de coturn. Con
`relayOnly` toda la media pasa por el TURN y ningún par ve la IP del otro.
## Qué NO tiene respecto al oficial
- **Módulo de IA**: fuera. El modelo son unos 4 GB.
- **housing**: portado pero apagado por defecto.
## Instalación
Igual que el oficial:
```sh
cd src/server && npm install
cd ../.. && ./oasis.sh
```
## Relación con upstream
Esta rama sigue las versiones de epsylon de cerca. El código propio vive separado
(`src/views/fork/`, `src/backend/fork_routes.js`, `src/models/karvan_model.js` y las
traducciones en `translations/fork/`) para que integrar cada versión nueva no arrastre
la interfaz de la rama. Sobre los ficheros de upstream solo hay enganches de una línea.
## Licencia
AGPL-3.0, la misma que el proyecto original.

17
docs/AI/info.md Normal file
View file

@ -0,0 +1,17 @@
# Oasis AI General Info
Collective Artificial Intelligence (CAI) model called "42" is based into: llama-2-7b-chat.Q4_K_M.
https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF
This is a static model trained in English on an offline dataset with a size of: 3,8 GiB (4.081.004.224 bytes).
---
The main idea behind this implementation of an GGUF/LLM in the OASIS network is to enable distributed learning generated through the collective action of many individuals, with the goal of redistributing the necessary processing load, as well as the ecological footprint and corporate bias.
Our AI will be trained with content from the OASIS network and its purpose is to take action and obtain answers to individual, but also global, problems.
Future versions of the tuned model will be released as we improve model safety with community feedback.
---

View file

@ -0,0 +1,69 @@
# Connect your Mastodon account
The **Fediverse** module lets you use your Mastodon account from inside Oasis: read your timeline, publish posts (text, images or video), reply, boost and favourite — all in one place.
This short guide shows you how to connect your account.
---
## 1) Create an access token in Mastodon
1. Log in to your Mastodon server (for example `mastodon.social`).
2. Go to **Preferences → Development → New application**.
3. Fill in:
- **Application name**: `Oasis`
- **Application website**: optional, leave blank if you want.
- **Redirect URI**: leave the value that's already there.
4. Under **Scopes**, tick these (and nothing else):
```
read:accounts
read:statuses
write:statuses
write:media
write:favourites
```
5. Click **Submit**. Open the new **Oasis** application and copy **"Your access token"**.
> Keep this token private — it lets you post to your account. You can delete it any time from the same Development page.
---
## 2) Connect it in Oasis
1. In Oasis, open **Settings**.
2. Find the **Fediverse** section (the **Mastodon** box).
3. Enter:
- **Address**: your server, e.g. `mastodon.social`.
- **Access token**: the token you just copied.
4. Click **Connect it**.
That's it. Oasis checks the token and opens your timeline. From now on you'll find **Fediverse** in the main menu.
To stop using it, go back to **Settings → Fediverse** and click **Disconnect**.
---
## 3) Using it
Open **Fediverse → Timelines**:
- **Read** your timeline, newest first. Use **Load more** to see older posts.
- **Post**: write in the box, optionally **Attach media** (images or video), **Preview**, then **Publish**.
- **Reply**: open a post's thread and answer from there.
- **Boost** and **Favourite** any post with its buttons.
---
## Show "via Oasis" on your posts (optional)
If you'd like your posts to show that they were sent from Oasis, go to **Preferences → Privacy** in Mastodon and enable **"Display from which app you sent a post"**. Since your application is named `Oasis`, your posts will then show *"via Oasis"*.
---
## If something doesn't work
- **Invalid or expired token** — create the token again and make sure the scopes above are ticked.
- **Invalid instance URL** — use your server's domain, e.g. `mastodon.social`.
- **Couldn't publish / upload** — your token is missing `write:statuses` or `write:media`; re-create it with the right scopes.

17
docs/MANIFESTO Normal file
View file

@ -0,0 +1,17 @@
"""
Im tired of watching injustice prevail while the echoes of despair roam the halls of a world that is burning out. Indifference is the cloak under which those who delight in the suffering of others hide. Reality, with all its weight, crushes us—but within us, there is a flame that refuses to go out, a hope that persists despite the shadows.
Yes, we are tired. Tired of the systems that diminish us, of the lies that divide us, of the structures that tell us we cannot change. But havent we witnessed the transformative power of human connection? Havent we seen what happens when ideas flow without barriers, when a group of souls comes together in a shared purpose, when digital empathy turns into concrete action?
Today, in the midst of this chaos, within the social network that connects the most willing minds and hearts, we have the power to give life to new worlds. Worlds where justice is non-negotiable, where collaboration replaces destructive competition, where knowledge is not a privilege but a universal right.
Projects like OASIS are not just virtual spaces; they are seeds we plant today to harvest tomorrow: a place where voices rise together to build the future we dream of. A space where each piece of code, each line of thought, each project is born with the intention to heal, to learn, to change. We dont have all the answers, but we are certain that the act of building begins here, in this community of dreamers and doers—creators who understand that the future is forged by hands that reach out to collaborate, not to destroy.
So even if today the shadows are long and impunity still reigns, tomorrow the sun of hope will rise—and it will rise with the strength of an army of ideas and projects born in this Oasis of infinite possibilities. May our voices never go silent, may our hands never stop working, may our eyes never stop gazing toward the horizon—where new worlds await to be created by us. Because in the end, if we dont dream the future, who will?
The revolution is in our hands, and its strength lies in the connection between all of us. Together, I still believe—we can create something truly worthwhile ...
.- by psy (03c8.net)
"""

221
docs/PUB/deploy.md Normal file
View file

@ -0,0 +1,221 @@
# Oasis PUB Deployment Guide
This guide walks you through deploying an **Oasis PUB** on a VPS using the Oasis launcher (`sh oasis.sh server`). A PUB needs a static, publicly-reachable IP address and an open TCP port (default `8008`).
---
## 1) Prepare the server
Install the basics:
```
sudo apt-get update
sudo apt-get install -y git curl build-essential
```
Install Node.js (Oasis is tested on Node 22; older LTS versions also work for server-only mode):
```
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22
nvm alias default 22
```
## 2) Clone Oasis
```
cd ~
git clone https://code.03c8.net/krakenslab/oasis oasis
cd oasis
```
## 3) Install dependencies
The `install.sh` script installs Node deps and applies the bundled patches. **You can skip the AI model download** — a PUB does not need it.
```
bash install.sh
```
If the AI model download fails or you skipped it, that's fine. The PUB will run without it.
## 4) Configure the PUB
Two example config files live in `docs/PUB/`:
- [`server-config.json.example`](./server-config.json.example) — the Oasis Sbot config (cap, friends graph, gossip, incoming/outgoing ports). Goes into `src/configs/server-config.json`.
- [`oasis-config.json.example`](./oasis-config.json.example) — the GUI/module config tuned for a PUB (AI/wallet/market/jobs/shops off; LAN broadcasting off). Goes into `src/configs/oasis-config.json` if you ever run the GUI on the same host.
Copy them:
```sh
cp docs/PUB/server-config.json.example src/configs/server-config.json
cp docs/PUB/oasis-config.json.example src/configs/oasis-config.json # only if you run the GUI here
```
The reference `server-config.json`:
```json
{
"logging": { "level": "notice" },
"caps": { "shs": "H5EC+V5BU9s0lWxCkt4z8a095Sj8a6TgiLKPYi1JD7s=" },
"pub": true,
"local": false,
"friends": { "dunbar": 300, "hops": 3 },
"gossip": {
"connections": 50,
"local": false,
"friends": true,
"seed": true,
"global": true
},
"replicationScheduler": {
"autostart": true,
"partialReplication": null
},
"autofollow": {
"enabled": true,
"feeds": [
"@0qSCyK3xyL71X4qKkmf84Cb2riP6OeUqxCvbP2Z6HWs=.ed25519"
]
},
"connections": {
"seeds": [],
"incoming": {
"net": [
{
"scope": ["device", "local", "public"],
"transform": "shs",
"port": 8008,
"external": "pub.example.com"
}
],
"unix": [
{
"scope": ["device", "local", "private"],
"transform": "noauth"
}
]
},
"outgoing": {
"net": [{ "transform": "shs" }],
"tunnel": [],
"onion": [],
"ws": []
}
}
}
```
**Three values to know:**
- **`connections.incoming.net[].external`** — the externally-reachable hostname of this PUB (e.g. `pub.example.com`). This is what gets embedded into invite codes generated by `sh oasis.sh invite` and into pub announce messages for the `public` scope. If it's missing, multiserver falls back to the first non-loopback IPv4 address it finds, which means invites will hand out the raw VPS IP instead of your domain. Set it on the public listener before you generate any invites. Note: this is a per-listener field — the top-level `host` does **not** affect invite codes.
- **`caps.shs`** — the network-level secret handshake cap. The Oasis network uses `H5EC+V5BU9s0lWxCkt4z8a095Sj8a6TgiLKPYi1JD7s=` (set in the example above). All PUBs and clients on this network must hold the **same** value — nodes with a different cap silently can't connect. If you're bootstrapping a separate isolated network instead, generate your own with:
```sh
node scripts/generate_shs.js
```
- **`autofollow.feeds`** — the upstream PUB(s) this node will automatically follow on first boot. The example seeds from `solarnethub.com`'s PUB (`@0qSCyK3xyL71X4qKkmf84Cb2riP6OeUqxCvbP2Z6HWs=.ed25519`), the default seed of the Oasis network. Once your PUB connects to it, gossip propagates the rest of the network's pub list. Replace this id only if you're bootstrapping from a different network root.
Everything else is the standard PUB shape: `pub: true`, no LAN discovery, dunbar 300, three friend hops, replication scheduler running on autostart, port `8008` open for SHS on every scope (device/local/public), and a `noauth` unix socket for the CLI.
## 5) Launch the PUB (server-only)
In server-only mode Oasis runs **only the Oasis Sbot**, not the web GUI or AI service. `aiMod` is forced off automatically when launched this way.
The repo ships a ready-to-use systemd unit at `docs/PUB/oasis-pub.service`. Copy it, edit the `YOUR_USER` placeholder, then enable it:
```
sudo cp ~/oasis/docs/PUB/oasis-pub.service /etc/systemd/system/oasis-pub.service
sudo nano /etc/systemd/system/oasis-pub.service # replace YOUR_USER
sudo systemctl daemon-reload
sudo systemctl enable --now oasis-pub
sudo journalctl -u oasis-pub -f
```
Data is written to `~/.ssb/`.
## 6) PUB admin: `sh oasis.sh <command>`
All admin actions go through the launcher itself, which talks to the running Oasis Sbot via the local unix socket (`~/.ssb/socket`). No external CLI install is needed — just keep the systemd unit `oasis-pub` active.
```
sh oasis.sh whoami # print this PUB id
sh oasis.sh invite [N] # create invite code (N = uses, default 1)
sh oasis.sh name "<text>" # set PUB display name
sh oasis.sh announce <host> [port] # publish pub address (default port 8008)
sh oasis.sh follow <feedId> # follow another PUB / feed
sh oasis.sh status # peer / replication overview
sh oasis.sh gossip # known gossip peers
```
## 7) Get your PUB ID
```
sh oasis.sh whoami
```
Example response:
```
{ "id": "@mGrevRCSX4E5dLgmflWBc50Qkn/1RXUAtDaGHOJ8xB4=.ed25519" }
```
## 8) Set the PUB profile name
```
sh oasis.sh name "My PUB Name"
```
## 9) Create invite codes
```
sh oasis.sh invite # uses=1 (default)
sh oasis.sh invite 500 # uses=500 (open PUB)
```
The output is a single-use (or N-use) invite code you can hand out. Clients redeem it in their `/invites` page.
## 10) Announce the PUB
So peers can discover the PUB by hostname:
```
sh oasis.sh announce mypub.example.com
sh oasis.sh announce mypub.example.com 8008
```
## 11) Follow another PUB (federation)
Federate so both replicate each other:
```
sh oasis.sh follow "@mGrevRCSX4E5dLgmflWBc50Qkn/1RXUAtDaGHOJ8xB4=.ed25519"
```
## 12) Health checks
```
sh oasis.sh status # peer / replication overview
sh oasis.sh gossip # known gossip peers with state
ls -la ~/.ssb/ # confirm flume/, blobs/, gossip.json, conn.json exist
sudo journalctl -u oasis-pub -f # tail service logs
```
## 13) Disabling the AI module (only relevant if also running the GUI)
`sh oasis.sh server` does **not** load the GUI or AI service, so `oasis-config.json` is ignored in server-only mode. Only `server-config.json` matters.
If you also run the GUI on the same VPS (`sh oasis.sh` without `server`), set `aiMod` to `off` in `src/configs/oasis-config.json` to skip the AI model:
```
sed -i 's/"aiMod": *"on"/"aiMod": "off"/' src/configs/oasis-config.json
```
## 14) Joining the Oasis network
The default seed PUB at `solarnethub.com` is included in `autofollow.feeds` above. As soon as your PUB connects to it (or to any peer that knows about it), gossip propagates the rest of the network's pub list.

View file

@ -0,0 +1,78 @@
{
"themes": {
"current": "Dark-SNH"
},
"ux": {
"current": "blocks"
},
"modules": {
"popularMod": "on",
"topicsMod": "on",
"summariesMod": "on",
"latestMod": "on",
"threadsMod": "on",
"multiverseMod": "on",
"invitesMod": "on",
"walletMod": "off",
"legacyMod": "off",
"cipherMod": "off",
"bookmarksMod": "on",
"videosMod": "on",
"docsMod": "on",
"audiosMod": "on",
"tagsMod": "on",
"imagesMod": "on",
"trendingMod": "on",
"eventsMod": "on",
"tasksMod": "on",
"marketMod": "off",
"votesMod": "on",
"tribesMod": "on",
"reportsMod": "on",
"opinionsMod": "on",
"padsMod": "on",
"calendarsMod": "on",
"transfersMod": "off",
"feedMod": "on",
"pixeliaMod": "on",
"melodyMod": "on",
"agendaMod": "on",
"aiMod": "off",
"aiNavMod": "off",
"forumMod": "on",
"gamesMod": "on",
"jobsMod": "off",
"shopsMod": "off",
"projectsMod": "off",
"bankingMod": "off",
"parliamentMod": "on",
"courtsMod": "on",
"favoritesMod": "on",
"logsMod": "on",
"mapsMod": "on",
"chatsMod": "on",
"torrentsMod": "on",
"graphosMod": "on",
"larpMod": "on"
},
"wallet": {
"url": "http://localhost:7474",
"user": "",
"pass": "",
"fee": "5"
},
"walletPub": {
"pubId": ""
},
"ai": {
"prompt": "Provide an informative and precise response."
},
"ssbLogStream": {
"limit": 2000
},
"homePage": "activity",
"language": "en",
"wish": "whole",
"pmVisibility": "whole",
"lanBroadcasting": false
}

View file

@ -0,0 +1,26 @@
[Unit]
Description=Oasis PUB
Documentation=https://wiki.solarnethub.com/socialnet/snh-pub
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=YOUR_USER
WorkingDirectory=/home/YOUR_USER/oasis
ExecStart=/bin/sh /home/YOUR_USER/oasis/oasis.sh server
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=30
StandardOutput=journal
StandardError=journal
SyslogIdentifier=oasis-pub
NoNewPrivileges=yes
ProtectSystem=full
ProtectHome=read-only
ReadWritePaths=/home/YOUR_USER/.ssb /home/YOUR_USER/oasis
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1,65 @@
{
"logging": {
"level": "notice"
},
"caps": {
"shs": "H5EC+V5BU9s0lWxCkt4z8a095Sj8a6TgiLKPYi1JD7s="
},
"pub": true,
"local": false,
"friends": {
"dunbar": 300,
"hops": 3
},
"gossip": {
"connections": 50,
"local": false,
"friends": true,
"seed": true,
"global": true
},
"replicationScheduler": {
"autostart": true,
"partialReplication": null
},
"autofollow": {
"enabled": true,
"feeds": [
"@0qSCyK3xyL71X4qKkmf84Cb2riP6OeUqxCvbP2Z6HWs=.ed25519"
]
},
"connections": {
"seeds": [
],
"incoming": {
"net": [
{
"scope": ["device", "local", "public"],
"transform": "shs",
"port": 8008,
"external": "pub.example.com"
}
],
"unix": [
{
"scope": [
"device",
"local",
"private"
],
"transform": "noauth"
}
]
},
"outgoing": {
"net": [
{
"transform": "shs"
}
],
"tunnel": [],
"onion": [],
"ws": []
}
}
}

View file

@ -0,0 +1,62 @@
# Guía de desarrollo de Oasis
Esta carpeta documenta cómo está construido Oasis por dentro, para que puedas
entenderlo y extenderlo (por ejemplo, creando un **módulo de juegos** nuevo).
Está pensada para leerse en orden, pero cada archivo es autónomo.
## Índice
1. **[01-red-ssb.md](01-red-ssb.md)** — Cómo funciona Oasis **a nivel de red**:
Secure Scuttlebutt (SSB), secret-stack, multiserver, muxrpc, EBT, blobs,
federación P2P, puertos y cifrado.
2. **[02-arquitectura-software.md](02-arquitectura-software.md)** — La
**arquitectura de software** del backend: el patrón MVC casero
(models / views / backend.js), el stack de dependencias, el "cooler", el
flujo de una petición y cómo se interrelacionan los archivos.
3. **[03-modulos-y-juegos.md](03-modulos-y-juegos.md)** — Cómo está construido
el **módulo de juegos** actual y la anatomía de un módulo en general.
4. **[04-tutorial-modulo-desde-cero.md](04-tutorial-modulo-desde-cero.md)** —
**Tutorial paso a paso** para crear un módulo nuevo desde cero (caso práctico:
un módulo de juegos propio), con todos los puntos de integración.
5. **[05-mapa-funciones.txt](05-mapa-funciones.txt)** — **Gran mapa ASCII** de
cómo se relacionan las funciones lógicas entre archivos, la persistencia
(SSB) y la media (blobs).
## Conceptos en 30 segundos
Oasis es un **cliente web de Secure Scuttlebutt (SSB)**. SSB es un protocolo
social **P2P, distribuido y federado**: no hay servidor central; cada nodo tiene
una copia local de un *log append-only* firmado criptográficamente, y los nodos
se replican entre sí por *gossip*.
Oasis se compone de **dos procesos**:
```
┌─────────────────────────┐ ┌──────────────────────────┐
│ SBOT (nodo de red SSB) │ <─────> │ FRONTEND WEB (Koa/HTML) │
│ src/server/SSB_server │ unix │ src/backend/backend.js │
│ habla con otros peers │ socket │ habla con tu navegador │
└─────────────────────────┘ └──────────────────────────┘
puerto 8008 (SSB) puerto 3000 (HTTP)
```
- El **sbot** (`src/server/SSB_server.js`) es el nodo SSB: se conecta a otros
peers, replica feeds, sirve y descarga blobs. → [01-red-ssb.md](01-red-ssb.md)
- El **frontend** (`src/backend/backend.js`) es un servidor HTTP en Koa que
renderiza HTML puro (sin JS de navegador) y se conecta al sbot como **cliente
muxrpc** por un socket Unix local. → [02-arquitectura-software.md](02-arquitectura-software.md)
El patrón para **cada funcionalidad** ("módulo") es siempre el mismo:
```
navegador → backend.js (ruta) → *_model.js (lee/escribe SSB) → *_view.js (HTML) → navegador
```
> Las rutas, líneas y nombres citados en estos documentos corresponden a la
> versión 0.8.1 del código. Si editas el código, vuelve a comprobar los números
> de línea con `grep`.

View file

@ -0,0 +1,243 @@
# 1. Oasis a nivel de red (Secure Scuttlebutt)
Oasis es un cliente/servidor de **Secure Scuttlebutt (SSB)**. Toda la "red" de
Oasis se construye sobre la pila clásica del ecosistema SSB:
`secret-stack` + `ssb-db` + un montón de plugins.
Hay una separación clara en **dos procesos**:
- **Backend SSB (sbot)**`src/server/SSB_server.js`: el nodo de red propiamente
dicho. Es quien habla con otros peers.
- **Frontend web (GUI Koa)**`src/backend/backend.js`: un servidor HTTP que
actúa como **cliente muxrpc** del sbot, conectándose por un socket Unix local.
```
RED SSB (otros peers Oasis, misma SHS cap)
net:IP:8008~shs:<pubkey> · ssb-lan (UDP) · ssb-onion (Tor)
┌─────────────────────────────────────────────┐
│ SBOT (src/server/SSB_server.js) │
│ peer <-> MULTISERVER <-> SECRET-STACK (SHS) │
<-> MUXRPC <-> PLUGINS │
└─────────────────────────┬───────────────────┘
│ unix socket ~noauth (muxrpc local, sin SHS)
┌─────────────────────────────────────────────┐
│ FRONTEND (src/backend/backend.js, Koa) │
│ cooler = src/client/gui.js → ssb-client │
│ app.listen({host, port:3000}) │
└─────────────────────────┬───────────────────┘
Navegador http://localhost:3000
```
---
## 1.1 Arranque de red
### Scripts de arranque
- **`install.sh`**: instala Node 22 y hace `npm install` en `src/server`
(línea 23). Opcionalmente descarga modelos de IA. No toca la red.
- **`oasis.sh`** es el lanzador. Modos relevantes:
- `server` / `pub` (líneas 61-69): ejecuta `node SSB_server.js start` — **solo
el sbot headless**, sin interfaz web.
- `gui` o por defecto (líneas 73-81): ejecuta `node backend.js` — el frontend.
- comandos pub `whoami|invite|name|announce|follow|status|gossip`
(líneas 70-72) → delegan en `scripts/oasis-pub.js`.
- **`src/server/package.json`**, script `start`:
`npm run start:ssb && sleep 10 && npm run start:backend`.
Arranca el sbot en segundo plano, **espera 10 s** (para que el socket Unix
exista) y luego arranca el frontend.
### Qué hace `SSB_server.js` paso a paso
(`src/server/SSB_server.js`)
1. **Líneas 7-11**: carga `secret-stack`, `ssb-caps` (la capability SHS),
`ssb-db`, la config (`./ssb_config`) y utilidades de metadatos.
2. **Líneas 13-52** (IIFE): *monkey-patch* de `console.error`/`console.warn`
para silenciar ruido de red — rechazos de handshake por SHS cap incorrecta,
excepciones EBT, etc. Un rechazo se convierte en un log limpio:
`[ts] REJECTED <ip:port> (wrong SHS cap)`.
3. **Líneas 56-81**: construye el servidor con
`SecretStack({ caps }).use(plugin).use(plugin)...` encadenando todos los
plugins (ver tabla abajo).
4. **Líneas 83-86**: si **no** es pub, carga `ssb-lan` (descubrimiento LAN por
UDP) y el router LAN local `./lanRouter`.
5. **Líneas 88-98**: lógica de `autofollow`; carga `ssb-autofollow` si hay feeds.
6. **Líneas 123-196** (`argv[0] === 'start'`): instancia el servidor, escribe
`manifest.json` (el catálogo de métodos muxrpc remotos), monta una barra de
progreso de replicación, imprime metadatos y **escucha eventos del hub de
conexiones** (`server.conn.hub().listen()`) para loguear `CONNECTED` /
`DISCONNECTED`.
7. **Líneas 198-202**: exporta `{ config, server, open() }` — esto permite a la
GUI reusar el servidor **in-process** si corre en el mismo proceso.
### Plugins secret-stack cargados (líneas 56-98)
| Plugin | Función de red |
|---|---|
| `ssb-db` | base de datos *append-only* de feeds |
| `ssb-master` | identidad maestra / auth local |
| `ssb-gossip` | gossip clásico (legacy) de peers |
| `ssb-ebt` | **Epidemic Broadcast Trees** — replicación gossip eficiente |
| `ssb-friends` | grafo social: hops, follows/blocks |
| `ssb-blobs` | transferencia de ficheros binarios |
| `ssb-meme` | blobs de imágenes/memes |
| `ssb-conn` | gestor de conexiones moderno (hub, db, staging) |
| `ssb-box` | cifrado de mensajes privados (box1) |
| `ssb-search`, `ssb-private`, `ssb-friend-pub` | búsqueda, PM, pub de amigos |
| `ssb-invite` / `ssb-invite-client` | invites (servidor si es pub, cliente si no) |
| `ssb-replication-scheduler`, `ssb-partial-replication` | planificación de replicación |
| `ssb-onion` | transporte Tor |
| `ssb-unix-socket` | **socket Unix local** para clientes (la GUI) |
| `ssb-no-auth` | conexiones locales sin handshake SHS |
| `ssb-about`, `ssb-backlinks`, `ssb-links`, `ssb-tangle`, `ssb-query` | índices de vistas |
| `ssb-lan` + `lanRouter` | descubrimiento LAN (solo si no es pub) |
> Nota: la replicación NO usa `ssb-replicate` directamente; la orquestan
> `ssb-ebt` + `ssb-replication-scheduler` + `ssb-friends`.
---
## 1.2 El protocolo SSB en términos del proyecto
- **secret-stack + handshake SHS (capability).** `SecretStack({ caps })` crea el
nodo. La `caps.shs` está **fijada en `src/configs/server-config.json`**
(líneas 5-7): `"H5EC+V5BU9s0lWxCkt4z8a095Sj8a6TgiLKPYi1JD7s="`. Es la **clave
de capacidad de red** (Secret Handshake): dos peers solo completan el
handshake si comparten *exactamente* esta cap. Actúa como "contraseña de red":
**Oasis forma su propia red SSB privada**, distinta de la red SSB pública.
- **multiserver (transportes).** Capa de transporte abstracta. La config
`connections` (`server-config.json`, líneas 29-60) define:
- **incoming.net**: `transform: "shs"`, `port: 8008` → TCP cifrado con SHS.
- **incoming.unix**: `transform: "noauth"` → socket Unix local sin handshake,
para que el frontend se conecte como cliente privilegiado.
- **outgoing.net**: `transform: "shs"`.
- Una dirección multiserver típica: `net:IP:8008~shs:<pubkey-base64>`.
- **muxrpc (RPC sobre el stream).** Una vez establecido el stream SHS, `muxrpc`
multiplexa llamadas RPC asíncronas y *pull-streams* sobre la misma conexión.
El `manifest.json` describe qué métodos remotos existen (`sync`/`async`/
`source`). Es como el frontend invoca `ssb.publish(...)`, `ssb.blobs.get(...)`,
etc.
- **EBT (`epidemic-broadcast-trees` + `ssb-ebt`).** El algoritmo de replicación
gossip. Cada peer anuncia el `seq` (reloj vectorial) de los feeds que tiene;
el otro envía solo los mensajes que faltan, formando árboles de difusión
epidémica que evitan duplicados.
- **Identidad de los peers.** Cada peer es un **feed id ed25519**:
`@<base64>.ed25519`. En las direcciones multiserver, el sufijo
`~shs:<pubkey>` identifica criptográficamente al peer durante el handshake.
---
## 1.3 Federación / P2P
- **Descubrimiento LAN** (`src/server/lanRouter.js`): plugin local custom.
`startRouter` (líneas 55-64) arranca `ssb.lan.start()` (broadcast UDP) y
consume `ssb.lan.discoveredPeers()`. Cada peer descubierto pasa por
`handleDiscovery``stagePeer` (líneas 15-45): lo *stagea* en
`ssb.conn.stage(...)` (vía moderna) con fallback a `ssb.gossip.add(...)`
(legacy); si `eagerReplicate`, fuerza `ebt.request`. Respeta el flag
`lanBroadcasting` de `oasis-config.json`.
- **Pubs / invites.** En modo pub se carga `ssb-invite` (servidor); en cliente,
`ssb-invite-client`. Los comandos `oasis.sh invite|announce|follow`
(→ `scripts/oasis-pub.js`) permiten a un pub publicar su dirección y generar
códigos de invitación. Un invite contiene `host:port:pubkey~seed`; al
canjearlo, el peer se conecta y el pub le sigue de vuelta (`ssb-friend-pub`).
- **Replicación por hops.** `ssb-friends` define el grafo social.
`server-config.json` fija `friends.hops: 2` → el nodo replica los feeds de la
gente que sigues y de la gente que ellos siguen (amigos de amigos). El
`ssb-replication-scheduler` decide qué feeds pedir por EBT según ese grafo.
- **"Distributed not decentralized".** No hay servidor central ni DHT global.
Cada nodo Oasis tiene su **propia copia local** de la base de datos
(logs *append-only* firmados con ed25519) y solo replica los feeds dentro de
su radio social (hops) más los descubiertos por LAN. La red se federa por
gossip entre peers que comparten la misma SHS cap. Es **distribuida** (datos
replicados en muchos nodos autónomos, funciona offline) pero **no
descentralizada** como una blockchain (no hay consenso global ni vista única;
cada quien ve solo su subgrafo). El flag `wish` de `oasis-config.json`
(`whole` / `mutuals` / `only-lan`) controla el alcance de replicación deseado.
---
## 1.4 Puertos y endpoints
| Qué | Dónde | Puerto / dirección |
|---|---|---|
| muxrpc SSB (sbot) — otros peers se conectan aquí | `server-config.json` incoming.net | **8008/TCP** transform `shs` |
| Socket Unix local — para el frontend | incoming.unix | `unix:<ssb.path>/socket~noauth:<pubkey>` |
| Frontend web (Koa) — tu navegador | `oasis_client.js` / `middleware.js:180` | **3000** host `localhost` (configurable con `--host`/`--port`) |
**Cómo se conecta el frontend al sbot** (el "cooler", `src/client/gui.js`):
1. Intenta `require('../server/SSB_server')` y reusar el `server` **in-process**
si existe (sin socket, uso directo del objeto).
2. Si no, construye `remote = unix:<path>/socket~noauth:<pubkey>` y se conecta
con **`ssb-client`** (muxrpc por el socket Unix `noauth`).
3. `attemptConnectionWithBackoff`: reintentos con backoff exponencial (de ahí el
`sleep 10` del arranque).
4. Expone `cooler.open()` / `cooler.close()`. **Todos los modelos** del backend
reciben este `cooler` y hacen `await cooler.open()` para obtener el cliente
muxrpc.
> Para exponer la GUI en un VPS se usa `--host=0.0.0.0`.
---
## 1.5 Blobs (ficheros / imágenes)
- Plugin `ssb-blobs` (+ `ssb-meme`). Tamaño máximo en `ssb_config.js`: 50 MB.
- Un blob se referencia por hash: `&<sha256-base64>.sha256`. **Los mensajes del
log solo llevan el hash**, no el binario.
- Flujo en `src/backend/blobHandler.js`:
- **Subida**: `ssbClient.blobs.add(...)` recibe el contenido por pull-stream y
devuelve el ref `&...sha256`.
- **Descarga por red**: `blobs.has(id)` comprueba si ya está local; si no,
`blobs.want(id)` **lo pide a los peers conectados** (gossip de "want/has"
sobre muxrpc), y `blobs.get(id)` lo lee como stream.
Los blobs viajan sobre la misma conexión SHS/muxrpc, fuera del log append-only.
---
## 1.6 Caps / cifrado
- **`ssb-caps`** define las capabilities de protocolo (shs, sign, invite). La
**shs cap real** está fijada en `server-config.json` → red privada de Oasis.
- **Handshake SHS**: autenticación mutua por ed25519 + confidencialidad del
stream de transporte.
- **`ssb-box`**: cifrado de **mensajes privados box1** (hasta ~7 destinatarios,
cifrado por clave pública de cada feed). `ssb-private` expone publish/read.
- **Grupos privados ("tribes").** No se usa `box2`/`ssb-tribes`. En su lugar
Oasis implementa cifrado **propio a nivel de aplicación** en
`src/models/crypto.js`, instanciado por dominio en `backend.js`
(`tribeCrypto`, `chatCrypto`, `padCrypto`, `mapCrypto`, `calendarCrypto`,
`eventCrypto`, `forumCrypto`). Los grupos se cifran con esas claves derivadas
y se almacenan/replican como mensajes normales del feed.
---
## 1.7 Archivos clave de la capa de red
| Archivo | Rol |
|---|---|
| `src/server/SSB_server.js` | Construye el sbot y carga los plugins (56-98) |
| `src/server/ssb_config.js` | Fusiona `server-config.json`; fija `blobs.max=50MB` |
| `src/server/ssb_metadata.js` | Deriva e imprime puerto SSB, hops, LAN, feed ID |
| `src/server/lanRouter.js` | Descubrimiento/staging de peers LAN |
| `src/configs/server-config.json` | `caps.shs`, `pub`, `friends.hops`, `connections` (puertos) |
| `src/configs/oasis-config.json` | `lanBroadcasting`, `wish`, `pmVisibility`, módulos |
| `src/client/gui.js` | El "cooler": cliente muxrpc por socket Unix noauth |
| `src/backend/blobHandler.js` | add/has/want/get de blobs |
| `scripts/oasis-pub.js` | Comandos pub (invite/announce/follow) |
Siguiente: **[02-arquitectura-software.md](02-arquitectura-software.md)**.

View file

@ -0,0 +1,350 @@
# 2. Arquitectura de software del backend
Oasis usa un patrón **MVC casero** (sin framework MVC):
```
src/backend/backend.js → el ROUTER monolítico (Koa, ~7250 líneas, ~472 rutas)
src/models/*_model.js → la lógica de DATOS (lee/escribe SSB)
src/views/*_view.js → el RENDER de HTML (con hyperaxe)
```
Flujo de una funcionalidad:
```
navegador → backend.js (ruta) → xModel.metodo() (SSB) → xView(data) (HTML) → ctx.body
```
---
## 2.1 Stack de software (dependencias clave)
Todas las dependencias están en `src/server/package.json`. Importante: casi
todos los `require` usan **ruta relativa explícita** al node_modules del
servidor, p.ej. `require("../server/node_modules/@koa/router")`.
**Capa web / HTTP**
- **`koa`** — servidor HTTP base. Se instancian varias apps Koa en
`src/client/middleware.js` (principal + sub-apps para estáticos).
- **`@koa/router`** — enrutado. `backend.js:442` instancia
`const router = new koaRouter()`. Toda la API es **una única cadena fluida**
`router.param(...).get(...).post(...)` (líneas ~1270-7124).
- **`koa-static` / `koa-mount`** — sirven assets estáticos (`/assets`,
`/maptiles`, `/game-assets`, `/js`...) montados en `middleware.js`.
- **`koa-body`** — parseo de `multipart/form-data` y POST. Se aplica por ruta:
`.post('/votes/create', koaBody(), ...)`.
- `express` y `cors` figuran como dependencias pero **el flujo principal es
Koa**; Express no se usa en el router.
**Motor de plantillas (vistas)**
- **`hyperaxe`** — hyperscript → HTML. **No hay archivos `.html`**; el HTML se
construye programáticamente desde JS: `div(...)`, `nav(...)`, `form(...)`...
Cada elemento expone `.outerHTML`.
- **`ssb-markdown` + `ssb-msgs` + `ssb-ref`** — render de Markdown SSB con
resolución de menciones/enlaces internos (`src/views/markdown.js`).
- **`highlight.js`, `qrcode`, `moment`, `pretty-ms`** — sintaxis, QR, fechas.
- **`dompurify` + `jsdom` + `is-svg`** — saneado anti-XSS
(`src/backend/sanitizeHtml.js`).
**Streams SSB**
- **`pull-stream`** — el paradigma de streams de SSB. Es el mecanismo central de
lectura: `pull(source, pull.filter(...), pull.collect(cb))`.
- Auxiliares: `pull-paramap` (map asíncrono), `pull-sort`, `pull-abortable`
(cancelar streams `live`), `pull-cat`, `pull-many`, `pull-pushable`.
**Cliente / servidor SSB**
- **`ssb-client`** — cliente RPC muxrpc para conectar al sbot (en `gui.js`).
- **`ssb-config`, `ssb-keys`, `ssb-ref`** — config, claves ed25519, validación
de identificadores (`@feed`, `%msg`, `&blob`).
- **`secret-stack` + `ssb-caps` + `ssb-db`** y los plugins SSB → ver
[01-red-ssb.md](01-red-ssb.md).
**Otros**: `module-alias`, `lodash`, `minimist`, `open`, `archiver`,
`file-type`, `pdfjs-dist`, `openpgp`, `axios`, `node-llama-cpp` +
`@xenova/transformers` (módulo IA local).
---
## 2.2 Flujo de una petición
**a) Construcción del servidor** — `src/client/middleware.js`: la función
exportada `({host, port, middleware, allowHost})` crea la app Koa, monta
estáticos, fija cabeceras de seguridad (CSP, `X-Frame-Options`...), valida el
host, aplica los middlewares recibidos y finalmente `app.listen({host, port})`
(línea 180). En `backend.js:7239`:
`const app = http({ host, port, middleware, allowHost: config.allowHost })`.
**b) Cadena de middleware** — `backend.js:7126-7238`: incluye (1) bloqueo de
no-GET en modo público, (2) `setLanguage(...)` por cookie, (3) gate de
indexación (muestra `indexingView` si la base no está sincronizada), (4) refresco
de estado compartido cada 60 s, y por último `routes` (las rutas del router).
**c) Ruta GET — ejemplo agenda** (`backend.js:1977-1982`):
```js
.get('/agenda', async (ctx) => {
const filter = qf(ctx);
let data = await agendaModel.listAgenda(filter); // MODELO: lee SSB
if (Array.isArray(data)) data = await applyListFilters(data, ctx);
ctx.body = await agendaView(data, filter); // VISTA: genera HTML
})
```
`agendaModel.listAgenda` abre el cliente (`cooler.open()`), lee el log
(`createLogStream`), agrega ítems y devuelve datos. `agendaView` los recibe y
construye HTML con hyperaxe, envuelto en `template(...)`. El HTML se asigna a
`ctx.body` y Koa lo sirve.
**d) Ruta POST — ejemplo votos** (`backend.js:5572`):
```js
.post('/votes/create', koaBody(), async ctx => {
const b = ctx.request.body;
const parsedOptions = b.options ? b.options.split(',')... : defaultOptions;
await votesModel.createVote(stripDangerousTags(b.question), b.deadline, parsedOptions, ...);
ctx.redirect(safeReturnTo(ctx, '/votes?filter=mine', ['/votes']));
})
```
El POST **sanea** la entrada (`stripDangerousTags`), llama al modelo que
**publica un mensaje SSB**, y **redirige** (patrón Post/Redirect/Get). El GET
posterior vuelve a leer del modelo y renderiza.
---
## 2.3 Conexión al servidor SSB: el "cooler"
El **cooler** es la abstracción que gestiona la conexión al sbot. Se define en
`src/client/gui.js` (importado en `backend.js:441` como
`const ssb = require("../client/gui")`) y se instancia en `backend.js:540`:
```js
const cooler = ssb({ offline: config.offline, port: config.port,
host: config.host, isPublic: config.public });
```
- Si existe un sbot **en el mismo proceso** (`internalSSB`), `cooler.open()` lo
devuelve directamente sin RPC.
- Si no, conecta por muxrpc vía socket Unix `noauth` con backoff exponencial.
**Patrón de uso en todo el código**:
`const ssb = await cooler.open();` y luego se usan los métodos muxrpc:
| Método | Para qué |
|---|---|
| `ssb.createUserStream({id, reverse, limit})` | feed de un usuario |
| `ssb.createLogStream({reverse, limit})` | log global (lo más usado) |
| `ssb.query.read({query:[{$filter:{...}}]})` | consultas ssb-query |
| `ssb.messagesByType({type, private})` | mensajes por tipo |
| `ssb.backlinks.read({query})` | referencias/backlinks |
| `ssb.get(id, cb)` | un mensaje por id |
| `ssb.publish(content, cb)` | **publicar un mensaje** |
| `ssb.blobs.want/get/add` | blobs |
| `ssb.friends.isFollowing/isBlocking/graph` | grafo social |
| `ssb.conn.peers / ssb.status() / ssb.progress()` | estado de red |
---
## 2.4 Patrón de un MODELO
Todos los modelos siguen la **factory pattern**:
`module.exports = ({ cooler, isPublic, ...deps }) => ({ ...métodos })`. Reciben
el `cooler` por inyección desde `backend.js` (líneas 553-602). Muchos cachean el
cliente:
```js
let ssb;
const openSsb = async () => { if (!ssb) ssb = await cooler.open(); return ssb; };
```
**Publicar (escribir)** — `ssb.publish(content, cb)` con un campo `type`.
Ejemplo `votes_model.js` (`createVote`):
```js
const content = {
type: 'votes', question, options, deadline, createdBy: userId,
status: 'OPEN', votes: {...}, totalVotes: 0, createdAt: new Date().toISOString()
};
return new Promise((res, rej) =>
ssbClient.publish(content, (err, msg) => err ? rej(err) : res(msg)));
```
**Leer** — `pull-stream` + `collect`:
```js
pull(
ssbClient.createLogStream({ limit: logLimit }),
pull.collect((err, results) => err ? reject(err) : resolve(results))
);
```
Luego se procesa en memoria: se construye un índice, se filtra por `type`, se
ordena.
**Borrar / editar — modelo de tombstone** (el log es *append-only*: nada se
borra físicamente):
- **Borrado lógico**: se publica `{ type:'tombstone', target:<msgId>, deletedAt,
author }`.
- **Validación** (`src/models/tombstone_validator.js`,
`buildValidatedTombstoneSet`): solo acepta el tombstone si **el autor del
tombstone coincide con el autor del mensaje objetivo** — evita borrados por
terceros.
- **Edición**: se publica una versión nueva con `replaces: <idAnterior>` y se
lapida la anterior, formando una cadena de versiones; al leer se sigue la
cadena hasta la "punta".
- Las comprobaciones de autoría (`if (c.createdBy !== userId) throw`) se hacen en
el modelo.
**Tipos de mensaje SSB** (campo `content.type`): los nativos SSB `post`, `vote`
(likes), `contact` (follow/block), `about` (perfil), y los **propios de Oasis**:
`votes`, `tombstone`, `task`, `event`, `calendar`, `transfer`, `tribe`,
`market`, `report`, `job`, `project`, `gameScore`, etc.
> **`main_models.js`** es el modelo núcleo: exporta `about`, `blob`, `friend`,
> `meta`, `post`, `vote`, `spreads`, `lifetime`. Su función `transform()`
> enriquece cada mensaje con metadatos (autor, avatar, votos, timestamps) antes
> de pasarlo a las vistas.
---
## 2.5 Patrón de una VISTA
Las vistas exportan funciones que reciben datos del modelo y devuelven HTML.
Patrón típico:
```js
const { div, h2, p, section, button, form } = require("../server/node_modules/hyperaxe");
const { template, i18n, userLink } = require('./main_views');
exports.agendaView = async (data, filter) =>
template(i18n.agendaTitle, section( h2(i18n.agendaTitle), /* ... */ ));
```
**Layout común — `main_views.js`**:
- `template(titlePrefix, ...elements)` construye el documento completo:
`html → head (title, CSS, favicon) → body (header, sidebar de navegación,
main-content)`. Se exporta como `exports.template`.
- **Navegación**: helper `navLink({href, emoji, text, current})` genera cada
`<li><a>`. `navGroup({id, emoji, title})` agrupa enlaces en secciones
colapsables del menú lateral. Cada módulo tiene su `renderXxxLink()` que solo
emite el enlace si el módulo está activo en config.
- **i18n**: `i18n` es un objeto compartido importado por todas las vistas.
`setLanguage(lang)` lo muta in-place (11 idiomas:
`en, es, fr, eu, de, it, pt, zh, ar, hi, ru` en
`src/client/assets/translations/`). El middleware llama `setLanguage(...)` en
cada petición. Las cadenas se referencian como `i18n.agendaTitle`, con
fallback `i18n.x || 'Default'`. **Nunca texto literal en las vistas.**
- **Temas**: `const theme = currentConfig.themes.current || "Dark-SNH"`
`<link href="/assets/themes/${theme}.css">`.
- **Helpers reutilizables** exportados por `main_views`: `userLink`,
`renderStateChip`, `renderVisibilityChip`, `renderSpreadButton`, `errorView`,
`formatCarbon`, `markdown(input, mentions)`.
---
## 2.6 Configuración
**`src/configs/config-manager.js`** — gestor central de `oasis-config.json`:
- Si el archivo no existe, escribe un `defaultConfig`.
- `getConfig()` lee y parsea el JSON **en cada llamada** (sin caché → cambios en
caliente).
- `saveConfig(newConfig)` reescribe el archivo.
Qué controla **`oasis-config.json`**:
- `themes.current` — tema CSS activo.
- `ux.current` — modo de interfaz (`"blocks"` o `"ainav"`).
- **`modules`** — ~50 flags `<nombre>Mod: "on"|"off"` que activan/desactivan cada
módulo. En backend se comprueba con `checkMod(ctx, mod)` (líneas 170-177): si
está `off`, redirige a `/modules`.
- `wallet`/`walletPub`, `ai.prompt`, `ssbLogStream.limit` (límite de mensajes
leídos del log), `homePage`, `language`, `wish`, `pmVisibility`,
`lanBroadcasting`.
**`src/configs/shared-state.js`** — estado en memoria (no persistente):
contador de inbox, huella de carbono, nº de peers online, valor eco, etc.
Lo actualiza el middleware periódico y lo consume `template`.
---
## 2.7 Tabla de módulos (modelo ↔ vista)
| Modelo | Vista | Notas |
|---|---|---|
| `main_models.js` | `main_views.js` | Núcleo: layout, i18n, temas, about/blob/friend |
| `activity_model` | `activity_view` | Feed de actividad |
| `agenda_model` | `agenda_view` | Agrega tasks/events/transfers/market/... |
| `audios_model` | `audio_view` | |
| `banking_model` | `banking_views` | ECOin, epochs |
| `blockchain_model` | `blockchain_view` | |
| `bookmarking_model` | `bookmark_view` | |
| `calendars_model` | `calendars_view` | Cifrado |
| `chats_model` | `chats_view` | Cifrado |
| `cipher_model` | `cipher_view` | |
| `courts_model` | `courts_view` | |
| `cv_model` | `cv_view` | |
| `documents_model` | `document_view` | |
| `events_model` | `event_view` | |
| `favorites_model` | `favorites_view` | Agrega favoritos |
| `feed_model` | `feed_view` | |
| `forum_model` | `forum_view` | Cifrado |
| **`games_model`** | **`games_view`** | Hall of fame + shell de juegos |
| `images_model` | `image_view` | |
| `inhabitants_model` | `inhabitants_view` | Perfiles |
| `jobs_model` | `jobs_view` | |
| `larp_model` | `larp_view` | |
| `legacy_model` | `legacy_view` | |
| `logs_model` | `logs_view` | |
| `maps_model` | `maps_view` | Cifrado |
| `market_model` | `market_view` | |
| `melody_model` | `melody_view` | |
| `opinions_model` | `opinions_view` | |
| `pads_model` | `pads_view` | Cifrado |
| `parliament_model` | `parliament_view` | |
| `pixelia_model` | `pixelia_view` | |
| `pm_model` | `pm_view` | Mensajería privada |
| `projects_model` | `projects_view` | |
| `reports_model` | `report_view` | |
| `search_model` | `search_view` | |
| `shops_model` | `shops_view` | |
| `stats_model` | `stats_view` | |
| `tags_model` | `tags_view` | |
| `tasks_model` | `task_view` | |
| `torrents_model` | `torrents_view` | |
| `transfers_model` | `transfer_view` | |
| `trending_model` | `trending_view` | |
| `tribes_model` + `tribes_content_model` | `tribes_view` | Cifrado |
| `videos_model` | `video_view` | |
| `votes_model` | `vote_view` | |
| `wallet_model` | `wallet_view` | |
| (sin modelo) | `AI_view` | Lógica en `src/AI/*` |
| `crypto.js`/`tribe_crypto.js` | — | Cifrado simétrico por dominio |
---
## 2.8 Mapa de dependencias entre archivos
**`backend.js` → modelos** (líneas 541-602): importa `main_models` y **todos**
los `*_model.js` como factories invocadas con `{ cooler, isPublic, ...deps }`.
Hay **inyección de dependencias entre modelos**: p.ej. `agenda_model` recibe
`{calendarsModel, eventsModel, tasksModel, marketModel, jobsModel,
projectsModel}`; `favorites_model` recibe casi todos los modelos de contenido.
**`backend.js` → vistas** (líneas ~1162-1216 + `require` inline): importa las
funciones de render de cada `*_view.js`. Algunas se cargan diferidas dentro de
los handlers (`require('../views/...')`).
**Modelos → importan**: `pull-stream`, `moment`, `./tombstone_validator`,
`../configs/config-manager`, helpers, y reciben `cooler` por parámetro (no
importan `gui` directamente). `tombstone_validator.js` no tiene dependencias
(función pura).
**Vistas → importan**: hyperaxe, `{template, i18n, userLink, ...}` de
`main_views`, `moment`, y a veces `../server/SSB_server` para obtener
`config.keys.id` (el feedId propio).
**Estado compartido**: `config-manager.js` (lee/escribe `oasis-config.json`) y
`shared-state.js` (memoria) son importados por backend, modelos y vistas; son
los puntos de coordinación transversal. `nameCache.js` (un Map en memoria) lo
alimenta `main_models` y lo consume `main_views`.
Siguiente: **[03-modulos-y-juegos.md](03-modulos-y-juegos.md)**.

View file

@ -0,0 +1,216 @@
# 3. El módulo de juegos y la anatomía de un módulo
> **Hallazgo clave que cambia las expectativas:** el módulo de juegos de Oasis
> **NO es un sistema multijugador asíncrono por SSB**. Es mucho más simple:
>
> - Cada juego es un **único `index.html` autocontenido** (HTML + CSS + JS
> inline), 100% client-side, servido como archivo estático y embebido en un
> `<iframe>`. No hay JS externos, ni sprites, ni carpetas de assets: cada
> carpeta de juego tiene **solo 2 archivos**: `index.html` + `thumbnail.svg`.
> - La **única integración con SSB** es publicar un mensaje tipo `gameScore`
> (puntuación individual) para un **Hall of Fame** (ranking global). No hay
> retos, ni partidas, ni movimientos sincronizados. El "multijugador" se
> reduce a comparar las puntuaciones de distintos autores leyendo el log SSB.
---
## 3.1 El modelo: `src/models/games_model.js` (67 líneas)
Minimalista. Solo gestiona puntuaciones. Patrón factory estándar:
`module.exports = ({ cooler }) => {...}`.
- **Líneas 5-9**: lista blanca `VALID_GAMES` (Set de ids permitidos). ⚠️ Incluye
14 juegos pero **NO** `rockpaperscissors` ni `audiopendulum` (que sí están en
la vista): esos dos **no pueden enviar score** (el modelo los rechaza).
- **Líneas 18-25** `readAll()`: vuelca todo el log con `createLogStream`.
- **Líneas 28-38** `submitScore(game, score)` — único método de escritura:
```js
async submitScore(game, score) {
if (!VALID_GAMES.has(game)) throw new Error('invalid game');
const n = Number(score);
if (!Number.isFinite(n) || n < 0 || n > 9999999) throw new Error('invalid score');
const ssbClient = await openSsb();
return new Promise((resolve, reject) => {
ssbClient.publish({ type: 'gameScore', game, score: Math.round(n) },
(err, msg) => err ? reject(err) : resolve(msg));
});
}
```
El mensaje SSB resultante: `{ type: 'gameScore', game: '<id>', score: <int> }`.
- **Líneas 40-65** `getHallOfFame()`: recorre el log, filtra
`content.type === 'gameScore'`, y por cada par `game:author` guarda **solo la
mejor puntuación**. Devuelve `hall[game] = [{author, score, game, ts}, ...]`
ordenado descendente y truncado a top-10 por juego.
---
## 3.2 La vista: `src/views/games_view.js` (151 líneas)
- **Líneas 5-22** `getGames()`: catálogo hardcodeado de **16 juegos**. Cada
entrada es `{ id, title: () => i18n.<key>, desc: () => i18n.<key> }`. Es el
registro maestro de la vista.
- **Línea 58** `VALID_GAME_IDS`: un **tercer** Set, usado para validar la ruta
del shell. Incluye los 16.
- **Líneas 26-56** `renderHallOfFame(hall)`: tabla por juego con thumbnail
(`/game-assets/${id}/thumbnail.svg`), título, descripción y filas (posición,
`userLink(author)`, score, fecha).
- **Líneas 60-93** `gameShellView(name)`: así se **embebe cada juego**. Valida
`name` contra `VALID_GAME_IDS` y renderiza un iframe:
```js
iframe({
src: `/game-assets/${name}/index.html`,
class: `game-iframe game-iframe-${name}`,
scrolling: 'no',
allowfullscreen: true
})
```
- **Líneas 95-151** `gamesView(filter, hall)`: el **lobby**. Barra de filtros
(`all` / `scoring`). En modo `all` lista cada juego con thumbnail, título,
récord top y botón PLAY → `/games/${id}`. En modo `scoring` invoca
`renderHallOfFame`.
> ⚠️ Hay **TRES listas** que deben mantenerse sincronizadas: `getGames()` y
> `VALID_GAME_IDS` (vista) + `VALID_GAMES` (modelo). La inconsistencia de
> `rockpaperscissors`/`audiopendulum` lo demuestra.
---
## 3.3 Estructura de un juego: `src/games/<nombre>/`
17 carpetas: `8ball, arkanoid, artillery, asteroids, audiopendulum, cocoland,
cocoman, ecoinflow, flipflop, labyrinth, neoninfiltrator, pingpong,
rockpaperscissors, spaceinvaders, tetris, tiktaktoe`.
**TODOS los juegos tienen exactamente 2 archivos**:
- `index.html` (6-10 KB): documento completo y autosuficiente, con `<style>` y
`<script>` inline. Sin dependencias externas, sin CDN.
- `thumbnail.svg` (~1-2 KB): miniatura SVG vectorial (viewBox ~`0 0 400 220`).
No existe distinción "arcade" vs "social SSB": todos son arcade HTML5/canvas o
DOM puro, client-side, en iframe. La única diferencia es si **envían score** o
no.
**Mecanismo de envío de score** (idéntico en todos los juegos puntuables;
ejemplo `tiktaktoe/index.html`):
```html
<div id="scoreSubmit" style="display:none">
<form method="POST" action="/games/submit-score" target="_top">
<input type="hidden" name="game" value="tiktaktoe">
<input type="hidden" id="scoreInput" name="score" value="0">
<button type="submit">Submit Score to Hall of Fame</button>
</form>
</div>
```
Claves del patrón:
- `target="_top"` → el POST **rompe el iframe** y navega la ventana superior
(necesario porque el juego corre sandboxeado dentro de `/games/<name>`).
- El JS del juego rellena `#scoreInput` al terminar
(`document.getElementById('scoreInput').value = score;`) y muestra el `div`.
- Cada juego tiene una topbar con `<a href="/games" target="_top">← Back</a>`.
El resto del `index.html` es lógica de juego propia en JS vanilla (tiktaktoe usa
minimax con poda alfa-beta; tetris usa canvas).
`gameScore` además es un tipo SSB de primera clase **indexado en búsqueda**
(`src/views/search_view.js` lo mapea a `/games/<game>` y lo renderiza con su
thumbnail).
---
## 3.4 Cómo se sirve y enruta
**Servido estático** — `src/client/middleware.js` (líneas 109-111):
```js
const gamesStatic = new Koa();
gamesStatic.use(koaStatic(join(__dirname, "..", "games")));
app.use(mount("/game-assets", gamesStatic));
```
Sub-app Koa con `koa-static` sobre `src/games/`, montada en `/game-assets`. Por
eso `/game-assets/tetris/index.html` sirve `src/games/tetris/index.html`.
**Independiente del router principal** → una carpeta nueva queda servida
automáticamente.
**Rutas dinámicas** — `src/backend/backend.js`:
- **Línea 598**: `const gamesModel = require('../models/games_model')({ cooler });`
- **Línea 1168**: `const { gamesView } = require("../views/games_view");`
- **Líneas 1358-1373**:
```js
.get('/games', async (ctx) => {
if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
const filter = ctx.query.filter === 'scoring' ? 'scoring' : 'all';
const hall = await gamesModel.getHallOfFame();
ctx.body = gamesView(filter, hall);
})
.get('/games/:name', async (ctx) => {
if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
const { gameShellView } = require('../views/games_view');
ctx.body = gameShellView(ctx.params.name);
})
.post('/games/submit-score', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
const { game, score } = ctx.request.body;
try { await gamesModel.submitScore(game, score); } catch (_) {}
ctx.redirect('/games?filter=scoring');
})
```
Flujo completo:
```
/games (lobby)
└─ PLAY → /games/:name (shell con iframe)
└─ iframe carga /game-assets/:name/index.html
└─ al terminar: POST /games/submit-score (target="_top")
└─ redirect /games?filter=scoring (Hall of Fame)
```
El guard `checkMod(ctx, 'gamesMod')` (líneas 170-177) revisa la config del
servidor + una cookie por-usuario; default `on`. Si está off → `/modules`.
---
## 3.5 Cómo se registra el módulo (puntos de integración)
| Lugar | Archivo | Qué hay |
|---|---|---|
| **Menú** | `src/views/main_views.js:898` | `renderGamesLink()` (emite el `navLink` si `gamesMod==="on"`); se invoca en línea 1280 dentro del `navGroup` "creative" |
| **Config** | `src/configs/oasis-config.json` | `"gamesMod": "on"` dentro de `modules` |
| **Página /modules** | `src/views/modules_view.js:23` | `{ name: 'games', label, description }` |
| **Listas de backend** | `src/backend/backend.js` | `'games'` en línea 1346 (GET /modules), 7054 (POST /save-modules), 7038 (`ALL_MODULES`) y presets (7040-7042) |
| **i18n** | `src/client/assets/translations/oasis_*.js` (×11) | `gamesTitle`, `gamesDescription`, `modulesGamesLabel/Description`, y por juego `games<Nombre>Title` + `games<Nombre>Desc` |
> El nombre del módulo está **hardcodeado y duplicado en muchos sitios**; no hay
> un registro central único. Por eso, al crear un módulo, cada punto es
> obligatorio. → [04-tutorial-modulo-desde-cero.md](04-tutorial-modulo-desde-cero.md)
---
## 3.6 Receta rápida: añadir un juego NUEVO al sistema existente
Para añadir un juego `foobar`:
1. **`src/games/foobar/index.html`** — HTML autocontenido (CSS+JS inline).
Incluir la topbar `← Back` y, si puntúa, el form oculto a
`/games/submit-score` con `target="_top"` y `name="game" value="foobar"`.
2. **`src/games/foobar/thumbnail.svg`** — miniatura.
3. **`src/views/games_view.js`**:
- Añadir a `getGames()`:
`{ id: 'foobar', title: () => i18n.gamesFoobarTitle, desc: () => i18n.gamesFoobarDesc }`.
- Añadir `'foobar'` a `VALID_GAME_IDS`.
4. **`src/models/games_model.js`** — añadir `'foobar'` a `VALID_GAMES`
(**obligatorio si puntúa**, o `submitScore` lo rechaza).
5. **i18n** — añadir `gamesFoobarTitle` y `gamesFoobarDesc` en TODOS los
`oasis_*.js`.
No hay que tocar el backend ni el static serving (la carpeta nueva ya se sirve
por `/game-assets/`).

View file

@ -0,0 +1,361 @@
# 4. Tutorial: crear un módulo desde cero
Vamos a crear un módulo nuevo, **paso a paso**, tomando `games` como plantilla.
Como caso práctico crearemos un módulo `arena` (un módulo de juegos propio: un
lobby de juegos con su propio ranking). Sustituye `arena` por el nombre de tu
módulo.
> **Idea clave**: en Oasis no existe un "registro central" de módulos. Crear un
> módulo = crear 2 archivos nuevos (model + view) y **tocar ~7 sitios** de
> integración. Esta guía los enumera todos. Si te saltas uno, el módulo
> funcionará a medias (p.ej. la ruta existe pero no aparece en el menú).
## Mapa de lo que vamos a tocar
```
NUEVO src/models/arena_model.js ← lógica de datos (SSB)
NUEVO src/views/arena_view.js ← render HTML (hyperaxe)
EDITA src/backend/backend.js ← instanciar modelo + rutas + 4 listas
EDITA src/views/main_views.js ← enlace en el menú lateral
EDITA src/configs/oasis-config.json ← flag arenaMod: "on"
EDITA src/views/modules_view.js ← entrada en la página /modules
EDITA src/client/assets/translations/oasis_*.js (×11) ← i18n
(opc) src/client/middleware.js ← static mount si sirves archivos (juegos)
```
---
## Paso 1 — El modelo: `src/models/arena_model.js`
El modelo encapsula **toda la lógica de datos**: publicar y leer mensajes SSB.
Sigue el patrón factory `({ cooler }) => ({...})`.
```js
const pull = require('../server/node_modules/pull-stream');
const { getConfig } = require('../configs/config-manager.js');
const logLimit = getConfig().ssbLogStream?.limit || 5000;
const VALID_GAMES = new Set(['snake', 'breakout']); // tus juegos puntuables
module.exports = ({ cooler }) => {
let ssb;
const openSsb = async () => {
if (!ssb) ssb = await cooler.open();
return ssb;
};
function readAll(ssbClient) {
return new Promise((resolve, reject) => {
pull(
ssbClient.createLogStream({ limit: logLimit }),
pull.collect((err, res) => (err ? reject(err) : resolve(res)))
);
});
}
return {
// ESCRITURA: publica un mensaje SSB tipado
async submitScore(game, score) {
if (!VALID_GAMES.has(game)) throw new Error('invalid game');
const n = Number(score);
if (!Number.isFinite(n) || n < 0 || n > 9999999) throw new Error('invalid score');
const ssbClient = await openSsb();
return new Promise((resolve, reject) => {
ssbClient.publish({ type: 'arenaScore', game, score: Math.round(n) },
(err, msg) => (err ? reject(err) : resolve(msg)));
});
},
// LECTURA: lee el log, filtra por type, agrega
async getRanking() {
const ssbClient = await openSsb();
const messages = await readAll(ssbClient);
const best = {};
for (const m of messages) {
const c = m.value && m.value.content;
if (!c || c.type !== 'arenaScore') continue;
if (!VALID_GAMES.has(c.game)) continue;
const key = `${c.game}:${m.value.author}`;
const score = Number(c.score);
if (!Number.isFinite(score)) continue;
if (!best[key] || score > best[key].score) {
best[key] = { author: m.value.author, score, game: c.game, ts: m.value.timestamp || 0 };
}
}
const ranking = {};
for (const g of VALID_GAMES) ranking[g] = [];
for (const e of Object.values(best)) if (ranking[e.game]) ranking[e.game].push(e);
for (const g of VALID_GAMES) ranking[g] = ranking[g].sort((a, b) => b.score - a.score).slice(0, 10);
return ranking;
}
};
};
```
Reglas del patrón de modelo:
- **Conexión SSB lazy** con `openSsb()` cacheado.
- **Escritura** siempre con `ssb.publish({ type: '<algo>', ... })`. El `type` es
el discriminador de tus mensajes en el log global compartido — elige un nombre
único (`arenaScore`, no `score`).
- **Lectura** con `createLogStream` + `pull.collect`, luego filtras por `type` en
memoria.
- **Borrado/edición** (si lo necesitas): publica
`{ type:'tombstone', target, author }` y usa
`src/models/tombstone_validator.js` al leer. Para editar, publica una versión
nueva con `replaces: <idAnterior>`.
---
## Paso 2 — La vista: `src/views/arena_view.js`
La vista recibe los datos del modelo y devuelve HTML con **hyperaxe**. Siempre se
envuelve en `template(...)` y se usan claves `i18n` (nunca texto literal).
```js
const { div, h2, p, section, form, input, button, a, img, table, tr, td, th, iframe }
= require("../server/node_modules/hyperaxe");
const { template, i18n, userLink } = require('./main_views');
const moment = require("../server/node_modules/moment");
const getGames = () => [
{ id: 'snake', title: () => i18n.arenaSnakeTitle, desc: () => i18n.arenaSnakeDesc },
{ id: 'breakout', title: () => i18n.arenaBreakoutTitle, desc: () => i18n.arenaBreakoutDesc },
];
const VALID_GAME_IDS = new Set(['snake', 'breakout']);
// Lobby
exports.arenaView = (filter = 'all', ranking = null) => {
const games = getGames();
const filterBar = div({ class: 'filter-group' },
form({ method: 'GET', action: '/arena' },
input({ type: 'hidden', name: 'filter', value: 'all' }),
button({ type: 'submit', class: filter === 'all' ? 'filter-btn active' : 'filter-btn' }, i18n.arenaFilterAll)),
form({ method: 'GET', action: '/arena' },
input({ type: 'hidden', name: 'filter', value: 'scoring' }),
button({ type: 'submit', class: filter === 'scoring' ? 'filter-btn active' : 'filter-btn' }, i18n.arenaFilterScoring))
);
const content = filter === 'scoring' && ranking
? div({ class: 'arena-scoring' },
getGames().filter(g => ranking[g.id] && ranking[g.id].length).map(g =>
div({ class: 'arena-section' },
h2(g.title()),
table({ class: 'ranking-table' },
tr(th('#'), th(i18n.arenaPlayer), th(i18n.arenaScore)),
...ranking[g.id].map((e, i) =>
tr(td(String(i + 1)), td(userLink(e.author)), td(String(e.score))))))))
: div({ class: 'arena-list' },
games.map(g =>
div({ class: 'game-row' },
img({ src: `/arena-assets/${g.id}/thumbnail.svg`, loading: 'lazy' }),
div(h2(g.title()), p(g.desc())),
a({ href: `/arena/${g.id}`, class: 'filter-btn' }, i18n.arenaPlayButton))));
return template(i18n.arenaTitle, section(h2(i18n.arenaTitle), filterBar), section(content));
};
// Shell: embebe el juego en un iframe
exports.arenaShellView = (name) => {
if (!VALID_GAME_IDS.has(name)) return template(i18n.arenaTitle, section(p(i18n.notFound || 'Not found')));
const game = getGames().find(g => g.id === name);
return template(game ? game.title() : name,
section({ class: 'game-shell-section' },
iframe({ src: `/arena-assets/${name}/index.html`, class: `game-iframe game-iframe-${name}`,
scrolling: 'no', allowfullscreen: true })));
};
```
Reglas del patrón de vista:
- `template(titulo, ...secciones)` siempre como envoltorio (te da head, menú
lateral, tema, etc.).
- Helpers de `main_views`: `userLink(feedId)`, `markdown(texto, mentions)`,
chips, `errorView`...
- Si tu módulo no es de juegos, simplemente no uses iframe/static: renderiza tus
datos directamente (listas, formularios POST a tus rutas).
---
## Paso 3 — Backend: `src/backend/backend.js`
**3a. Instanciar el modelo** (junto a la línea ~598, donde están los demás):
```js
const arenaModel = require('../models/arena_model')({ cooler });
```
**3b. Importar la vista** (junto a la línea ~1168):
```js
const { arenaView } = require("../views/arena_view");
```
**3c. Añadir las rutas** (dentro de la cadena `router....`, junto a las de
games en ~1358). Cada ruta empieza con el guard `checkMod`:
```js
.get('/arena', async (ctx) => {
if (!checkMod(ctx, 'arenaMod')) { ctx.redirect('/modules'); return; }
const filter = ctx.query.filter === 'scoring' ? 'scoring' : 'all';
const ranking = await arenaModel.getRanking();
ctx.body = arenaView(filter, ranking);
})
.get('/arena/:name', async (ctx) => {
if (!checkMod(ctx, 'arenaMod')) { ctx.redirect('/modules'); return; }
const { arenaShellView } = require('../views/arena_view');
ctx.body = arenaShellView(ctx.params.name);
})
.post('/arena/submit-score', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'arenaMod')) { ctx.redirect('/modules'); return; }
const { game, score } = ctx.request.body;
try { await arenaModel.submitScore(game, score); } catch (_) {}
ctx.redirect('/arena?filter=scoring');
})
```
**3d. Añadir `'arena'` a las cuatro listas de módulos** (si no lo haces, el
módulo no aparecerá en la página `/modules` ni se podrá activar/desactivar):
- Línea **1346** — array `modules` del GET `/modules`.
- Línea **7054** — array `modules` del POST `/save-modules`.
- Línea **7038**`ALL_MODULES`.
- Líneas **7040-7042** — los presets (`minimal`/`social`/`economy`/`full`) donde
quieras que aparezca por defecto.
---
## Paso 4 — Menú lateral: `src/views/main_views.js`
**4a. Crear `renderArenaLink()`** (copia el patrón de `renderGamesLink`,
línea ~898):
```js
const renderArenaLink = () => {
const arenaMod = getConfig().modules.arenaMod === "on";
return arenaMod
? [navLink({ href: "/arena", emoji: "🎮", text: i18n.arenaTitle, class: "arena-link enabled" })]
: "";
};
```
**4b. Invocarlo dentro de un `navGroup`** (junto a `renderGamesLink()` en la
línea ~1280, grupo "creative", o el grupo que prefieras):
```js
renderGamesLink(),
renderArenaLink(), // ← añadir
```
---
## Paso 5 — Config: `src/configs/oasis-config.json`
Añadir el flag dentro de `modules` (junto a `"gamesMod": "on"`):
```json
"arenaMod": "on",
```
`config-manager.js` también tiene un `defaultConfig`; si quieres que el módulo
exista en instalaciones nuevas, añade el flag ahí también.
---
## Paso 6 — Página `/modules`: `src/views/modules_view.js`
Añadir una entrada al array `modules` (línea ~23). El toggle on/off lo renderiza
el código genérico (`${name}Mod` / `${name}Form`):
```js
{ name: 'arena', label: i18n.modulesArenaLabel, description: i18n.modulesArenaDescription },
```
---
## Paso 7 — i18n: `src/client/assets/translations/oasis_*.js`
En **todos** los archivos de idioma (×11) añade, como mínimo:
```js
arenaTitle: 'Arena',
arenaDescription: 'Play and compete in your network.',
arenaFilterAll: 'All',
arenaFilterScoring: 'Ranking',
arenaPlayButton: 'PLAY',
arenaPlayer: 'Player',
arenaScore: 'Score',
modulesArenaLabel: 'Arena',
modulesArenaDescription: 'A games arena with rankings.',
// y por cada juego:
arenaSnakeTitle: 'Snake', arenaSnakeDesc: 'Classic snake.',
arenaBreakoutTitle: 'Breakout', arenaBreakoutDesc: 'Break the bricks.',
```
Empieza por `oasis_en.js` (es el fallback). Si una clave falta en un idioma,
usa el patrón `i18n.x || 'Default'` en la vista para evitar `undefined`.
---
## Paso 8 (opcional) — Servir archivos estáticos (juegos)
Solo si tu módulo sirve archivos (como hace games con sus `index.html`). En
`src/client/middleware.js`, replica el bloque de games (líneas 109-111):
```js
const arenaStatic = new Koa();
arenaStatic.use(koaStatic(join(__dirname, "..", "arena-games")));
app.use(mount("/arena-assets", arenaStatic));
```
Y crea tus juegos en `src/arena-games/<id>/index.html` + `thumbnail.svg`. Cada
`index.html` autocontenido; si puntúa, el form oculto apunta a
`/arena/submit-score` con `target="_top"`:
```html
<form method="POST" action="/arena/submit-score" target="_top">
<input type="hidden" name="game" value="snake">
<input type="hidden" id="scoreInput" name="score" value="0">
<button type="submit">Submit Score</button>
</form>
```
---
## Checklist final
```
[ ] src/models/arena_model.js (factory {cooler}, publish/read SSB)
[ ] src/views/arena_view.js (hyperaxe + template + i18n)
[ ] backend.js: instancia modelo (~598)
[ ] backend.js: import vista (~1168)
[ ] backend.js: rutas GET/POST con checkMod(ctx,'arenaMod')
[ ] backend.js: 'arena' en las 4 listas (1346, 7054, 7038, presets)
[ ] main_views.js: renderArenaLink() + llamada en navGroup
[ ] oasis-config.json: "arenaMod": "on"
[ ] modules_view.js: entrada en array modules
[ ] oasis_*.js (×11): claves i18n
[ ] (opc) middleware.js: static mount + carpeta de juegos
```
## Cómo probarlo
```bash
# Arranca sbot + frontend
cd src/server && npm run start
# o por separado (sbot ya levantado):
node ../backend/backend.js
```
Abre `http://localhost:3000/arena`. Si redirige a `/modules`, activa el módulo
ahí (o revisa `arenaMod` en `oasis-config.json`). Comprueba:
1. El enlace aparece en el menú lateral.
2. `/arena` muestra el lobby.
3. `/arena/snake` embebe el juego.
4. Al enviar score, redirige a `/arena?filter=scoring` y aparece en el ranking.
> Errores típicos: `submitScore` lanza `invalid game` → falta el id en
> `VALID_GAMES` (modelo). El juego no carga en el iframe → ruta de
> `/arena-assets/...` mal o falta el static mount. La vista peta con `undefined`
> → falta una clave i18n; añade el fallback `|| '...'`.
Siguiente: **[05-mapa-funciones.txt](05-mapa-funciones.txt)** — el mapa ASCII de
relaciones entre funciones, persistencia y media.

View file

@ -0,0 +1,262 @@
================================================================================
OASIS · MAPA DE FUNCIONES Y FLUJO
Cómo se relacionan las funciones lógicas entre archivos,
la persistencia (SSB) y la media (blobs)
versión 0.8.1
================================================================================
LEYENDA
[proc] proceso ( ) función / método
--> llamada / flujo === límite de proceso ~~~ red / disco
*.js archivo #NNN número de línea aprox.
================================================================================
0. VISIÓN GLOBAL: DOS PROCESOS
================================================================================
NAVEGADOR OTROS PEERS SSB
(HTML puro, (misma SHS cap)
sin JS) |
| HTTP :3000 | net:IP:8008~shs
v v ~~~~~~~~~~~~~
============================[proc gui]== ==============[proc sbot]======
| src/backend/backend.js (Koa router) | | src/server/SSB_server.js |
| | | SecretStack({caps}).use(..)|
| cooler = src/client/gui.js | | ssb-db (log append-only) |
| | | <-> | ssb-ebt / ssb-friends |
| | cooler.open() |unix | ssb-blobs / ssb-conn |
| v |sock | ssb-box / ssb-private |
| ssb (cliente muxrpc) ---------------|~noauth-> muxrpc API (publish,get, |
| | | createLogStream,...) |
========================================= ===============================
modelos + vistas replicación P2P por gossip
================================================================================
1. CADENA DE UNA PETICIÓN (el patrón de TODO módulo)
================================================================================
navegador
| GET /modulo (o POST /modulo/accion)
v
middleware.js (#43..#209) ── app.listen({host,port})
| setLanguage(cookie) · gate indexación · refresco shared-state(60s)
v
backend.js router.get('/modulo') #1270..#7124 (~472 rutas)
| checkMod(ctx,'moduloMod') #170 ── off? --> redirect /modules
|
+--> xModel.metodo(filtro) [ LECTURA / ESCRITURA SSB ] -----+
| (src/models/xxx_model.js) |
| v
| <------------------ datos JS ------------------------ cooler.open()
| (gui.js)
+--> xView(datos, filtro) [ RENDER HTML ] |
| (src/views/xxx_view.js) v
| template(i18n.titulo, section(...)) ssb muxrpc
v
ctx.body = "<html>...</html>" --> Koa --> navegador
POST: koaBody() -> stripDangerousTags() -> xModel.crear() -> ctx.redirect()
(patrón Post/Redirect/Get; el GET siguiente re-renderiza)
================================================================================
2. PERSISTENCIA: cómo el MODELO habla con SSB (pull-stream + publish)
================================================================================
src/models/xxx_model.js = module.exports = ({cooler, ...deps}) => ({...})
openSsb() ............ if(!ssb) ssb = await cooler.open(); // lazy, cacheado
|
v
ESCRIBIR (persistir):
ssb.publish({ type:'<tipo>', ...campos }, cb)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+--> ssb-db: añade mensaje FIRMADO (ed25519) al log append-only
| del feed propio @miclave.ed25519
+--> ssb-ebt replica el mensaje a los peers (hops<=2) ~~~~>
LEER (consultar):
pull(
ssb.createLogStream({limit}) <-- lee el log local (todos los feeds
pull.filter(m => m.value.content.type === '<tipo>') replicados)
pull.collect((err,res)=>...)
)
(variantes: ssb.messagesByType, ssb.query.read, ssb.backlinks.read,
ssb.createUserStream{id})
BORRAR (lógico; el log NO se borra):
ssb.publish({ type:'tombstone', target:<msgId>, author })
|
+--> tombstone_validator.js :: buildValidatedTombstoneSet(msgs)
acepta SOLO si author(tombstone) === author(target) [autoría]
EDITAR:
ssb.publish({ ...nuevo, replaces:<idAnterior> }) + tombstone del viejo
|
+--> al leer, se sigue la cadena replaces -> hasta la "punta"
----------------------------------------------------------------------------
TIPOS DE MENSAJE (content.type) = el discriminador en el log compartido
----------------------------------------------------------------------------
nativos SSB : post · vote(like) · contact(follow/block) · about(perfil)
Oasis : votes · tombstone · task · event · calendar · transfer ·
tribe · market · report · job · project · gameScore · ...
================================================================================
3. MEDIA: cómo viajan los ficheros (BLOBS, fuera del log)
================================================================================
El log solo guarda el HASH. El binario viaja aparte por la red SSB.
SUBIR:
navegador --(multipart)--> backend.js --> blobHandler.js
ssb.blobs.add(pull-stream) --> &<sha256>.sha256 (ref = hash)
(luego se publica un mensaje con ese ref dentro de content)
MOSTRAR / DESCARGAR:
vista genera <img src="/blob/&xxx.sha256"> ó markdown.js resuelve menciones
|
v
backend.js ruta /blob/:id --> blobHandler.js
ssb.blobs.has(id)? --- no ---> ssb.blobs.want(id) ~~~~~~~~~~~~~~~~~>
| (gossip "want/has" a los peers)
+-- si ---> ssb.blobs.get(id) -> pull-stream -> ctx.body (bytes)
límite: 50 MB (ssb_config.js #17-19)
================================================================================
4. RENDER: cómo la VISTA construye HTML (hyperaxe, sin .html)
================================================================================
src/views/xxx_view.js
require("../server/node_modules/hyperaxe") -> div(), form(), section()...
require('./main_views') -> { template, i18n, userLink, markdown, chips }
exports.xView(datos) =
template( i18n.xTitle, // <- LAYOUT global
section( h2(i18n.xTitle), ...lista... ) )
|
v
main_views.js :: template(titulo, ...elems) #1017..#1321
html
+- head: <title> · CSS · /assets/themes/<tema>.css (oasis-config.themes)
+- body
+- header (logo, inbox badge <- shared-state, publish, search)
+- sidebar-left = navGroup(...) { renderXxxLink() por módulo }
| navLink({href,emoji,text}) #327
| renderGamesLink() #898 -> si gamesMod==='on' (config-manager)
+- main-content = tus secciones
i18n: objeto compartido mutado por setLanguage(lang) (11 idiomas)
backend middleware lo fija por cookie en cada request
markdown.js: ssb-markdown -> resuelve @feed,%msg,&blob,#hashtag a rutas /...
================================================================================
5. GRAFO DE DEPENDENCIAS ENTRE ARCHIVOS
================================================================================
src/backend/backend.js (orquestador central)
|--require--> ../client/gui.js .................. cooler (conexión SSB)
|--require--> ../client/middleware.js ........... http server Koa
|--require--> ../configs/config-manager.js ...... getConfig/saveConfig
|--require--> ../configs/shared-state.js ........ estado en memoria
|--require--> ./sanitizeHtml.js / ./blobHandler.js
|--require--> ../server/SSB_server.js ........... config + (sbot in-process)
|--require--> ../models/*_model.js (factories: ({cooler,deps}))
| |--inyecta--> otros modelos (agenda<-tasks,events,market..)
| |--inyecta--> *Crypto (crypto.js por dominio)
|--require--> ../views/*_view.js (funciones de render)
src/models/xxx_model.js
|--require--> pull-stream · moment
|--require--> ./tombstone_validator.js (función pura, sin deps)
|--require--> ../configs/config-manager.js
|--recibe----> cooler (NO importa gui directamente)
src/views/xxx_view.js
|--require--> hyperaxe
|--require--> ./main_views.js { template, i18n, userLink, helpers }
|--require--> moment · (a veces) ../server/SSB_server (feedId propio)
src/views/main_views.js (el "framework" de vistas)
|--require--> hyperaxe · lodash · highlight.js · qrcode · moment
|--require--> ./markdown.js · ../backend/renderUrl.js · ./sanitizeHtml?
|--require--> ../backend/nameCache.js (Map nombres <- main_models warmup)
|--require--> ../client/gui.js · ../configs/{config-manager,shared-state}
|--require--> ../client/assets/translations/i18n.js (11 idiomas)
src/server/SSB_server.js (sbot)
|--require--> secret-stack · ssb-caps · ssb-db · plugins ssb-*
|--require--> ./ssb_config.js (<- server-config.json) · ./ssb_metadata.js
|--require--> ./lanRouter.js (descubrimiento LAN)
================================================================================
6. EL MÓDULO GAMES, DE PRINCIPIO A FIN (ejemplo concreto)
================================================================================
MENU main_views.js #898 renderGamesLink() --(gamesMod==on)--> /games
|
LOBBY backend.js #1358 GET /games |
checkMod #170 -> gamesModel.getHallOfFame() #40 ----------+
| pull(createLogStream) |
| filter type==='gameScore' |
| best[game:author]=max(score) |
gamesView(filter,hall) #95 -> HTML |
|
PLAY GET /games/:name #1364 -> gameShellView(name) #60 |
<iframe src="/game-assets/<name>/index.html"> |
| |
STATIC middleware.js #109 mount('/game-assets', src/games/) ~~disk~+
|
JUEGO src/games/<name>/index.html (HTML+CSS+JS inline, canvas)
al terminar: form POST -> /games/submit-score target=_top
|
SCORE POST /games/submit-score #1369
gamesModel.submitScore(game,score) #28
ssb.publish({type:'gameScore',game,score}) ~~> SSB log
redirect /games?filter=scoring -> Hall of Fame
LISTAS A SINCRONIZAR (sin registro central):
games_view.js getGames() #5 + VALID_GAME_IDS #58 (16 juegos)
games_model.js VALID_GAMES #5 (14 -> falta rps,audio)
backend.js listas módulos #1346 #7038 #7054 #7040 ('games')
oasis-config.json modules.gamesMod
modules_view.js array modules #23
oasis_*.js gamesTitle, games<Nombre>Title/Desc (x11 idiomas)
================================================================================
7. CONFIG Y ESTADO (puntos de coordinación transversal)
================================================================================
oasis-config.json <--getConfig()/saveConfig()--> config-manager.js
| modules.{xMod:on/off} themes.current ux.current language
| wish pmVisibility lanBroadcasting ssbLogStream.limit wallet
+--leen--> backend.js (checkMod) · main_views (render links/tema) · modelos
server-config.json <-- ssb_config.js --> SSB_server.js
| caps.shs (red privada) friends.hops=2 connections (puerto 8008, unix)
shared-state.js (memoria, NO persistente)
| inboxCount carbon peersOnline ecoValue lastRefresh
+--escribe--> middleware refresco 60s +--lee--> main_views (badges)
nameCache.js (Map en memoria)
+--alimenta--> main_models._startNameWarmup (escucha 'about' en live)
+--consume---> main_models.about · main_views (mostrar nombres)
================================================================================
RESUMEN EN UNA FRASE
================================================================================
backend.js enruta -> el MODELO persiste/lee mensajes tipados en el log SSB
(replicado P2P por hops) y los blobs por want/has -> la VISTA (hyperaxe)
los pinta dentro de template() con i18n y tema -> y todo módulo se activa con
un flag xMod en oasis-config.json comprobado por checkMod().
================================================================================

View file

@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at <solarnethub@riseup.net>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

125
docs/devs/contract.md Normal file
View file

@ -0,0 +1,125 @@
# Collective Code Construction Contract - Oasis Implementation
The Collective Code Construction Contract (C4) is an evolution of the github.com [Fork + Pull Model](https://help.github.com/articles/about-pull-requests/), aimed at providing an optimal collaboration model for free software projects.
This is the Oasis-specific implementation, based on [revision 2 of C4](https://github.com/zeromq/rfc/blob/63024673f19ad136652ff7b3bfb3a6547811e006/42/README.md).
## Summary
Thank you for contributing to Oasis! Here we try capture how we collaborate, and why we do it this way.
This entire document is open for changes, if there is anything that is confusing or can be improved, please start a discussion with us!
## License
Copyright (c) 2009-2016 Pieter Hintjens.
This Specification is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This Specification is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses>.
## Abstract
C4 provides a standard process for contributing, evaluating and discussing improvements on software projects. It defines specific technical requirements for projects like a style guide, unit tests, `git` and similar platforms. It also establishes different personas for projects, with clear and distinct duties. C4 specifies a process for documenting and discussing issues including seeking consensus and clear descriptions, use of "pull requests" and systematic reviews.
## Language
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](http://tools.ietf.org/html/rfc2119).
## 1. Goals
C4 is meant to provide a reusable optimal collaboration model for open source software projects. It has these specific goals:
1. To maximize the scale and diversity of the community around a project, by reducing the friction for new Contributors and creating a scaled participation model with strong positive feedbacks;
1. To relieve dependencies on key individuals by separating different skill sets so that there is a larger pool of competence in any required domain;
1. To allow the project to develop faster and more accurately, by increasing the diversity of the decision making process;
1. To support the natural life cycle of project versions from experimental through to stable, by allowing safe experimentation, rapid failure, and isolation of stable code;
1. To reduce the internal complexity of project repositories, thus making it easier for Contributors to participate and reducing the scope for error;
1. To enforce collective ownership of the project, which increases economic incentive to Contributors and reduces the risk of hijack by hostile entities.
## 2. Design
### 2.1. Preliminaries
1. The project MUST use the git distributed revision control system.
1. The project MUST be hosted on github.com or equivalent, herein called the "Platform".
1. The project MUST use the Platform issue tracker.
1. The project SHOULD have clearly documented guidelines for code style.
1. A "Contributor" is a person who wishes to provide a patch, being a set of commits that solve some clearly identified problem.
1. A "Maintainer" is a person who merges patches to the project. Maintainers are not developers; their job is to enforce process.
1. Contributors MUST NOT have commit access to the repository unless they are also Maintainers.
1. Maintainers MUST have commit access to the repository.
1. Everyone, without distinction or discrimination, MUST have an equal right to become a Contributor under the terms of this contract.
### 2.2. Licensing and Ownership
1. The project MUST use a share-alike license such as the MPLv2, or a GPLv3 variant thereof (GPL, LGPL, AGPL).
1. All contributions to the project source code ("patches") MUST use the same license as the project.
1. All patches are owned by their authors. There MUST NOT be any copyright assignment process.
1. Each Contributor MUST be responsible for identifying themselves in the project Contributor list.
### 2.3. Patch Requirements
1. Maintainers and Contributors MUST have a Platform account and SHOULD use their real names or a well-known alias.
1. A patch SHOULD be a minimal and accurate answer to exactly one identified and agreed problem.
1. A patch MUST adhere to the code style guidelines of the project if these are defined.
1. A patch MUST adhere to the "Evolution of Public Contracts" guidelines defined below.
1. A patch MUST NOT include non-trivial code from other projects unless the Contributor is the original author of that code.
1. A patch MUST compile cleanly and pass project self-tests on at least the principal target platform.
1. A patch commit message SHOULD consist of a single short (less than 50 characters) line stating the problem ("Problem: ...") being solved, followed by a blank line and then the proposed solution ("Solution: ...").
1. A "Correct Patch" is one that satisfies the above requirements.
### 2.4. Development Process
1. Change on the project MUST be governed by the pattern of accurately identifying problems and applying minimal, accurate solutions to these problems.
1. To request changes, a user SHOULD log an issue on the project Platform issue tracker.
1. The user or Contributor SHOULD write the issue by describing the problem they face or observe.
1. The user or Contributor SHOULD seek consensus on the accuracy of their observation, and the value of solving the problem.
1. Users MUST NOT log feature requests, ideas, suggestions, or any solutions to problems that are not explicitly documented and provable.
1. Thus, the release history of the project MUST be a list of meaningful issues logged and solved.
1. To work on an issue, a Contributor MUST fork the project repository and then work on their forked repository.
1. To submit a patch, a Contributor MUST create a Platform pull request back to the project.
1. A Contributor MUST NOT commit changes directly to the project.
1. If the Platform implements pull requests as issues, a Contributor MAY directly send a pull request without logging a separate issue.
1. To discuss a patch, people MAY comment on the Platform pull request, on the commit, or elsewhere.
1. To accept or reject a patch, a Maintainer MUST use the Platform interface.
1. Maintainers SHOULD NOT merge their own patches except in exceptional cases, such as non-responsiveness from other Maintainers for an extended period (more than 1-2 days).
1. Maintainers MUST NOT make value judgments on correct patches.
1. Maintainers MUST merge correct patches from other Contributors rapidly.
1. Maintainers MAY merge incorrect patches from other Contributors with the goals of (a) ending fruitless discussions, (b) capturing toxic patches in the historical record, (c) engaging with the Contributor on improving their patch quality.
1. The user who created an issue SHOULD close the issue after checking the patch is successful.
1. Any Contributor who has value judgments on a patch SHOULD express these via their own patches.
1. Maintainers SHOULD close user issues that are left open without action for an uncomfortable period of time.
### 2.5. Branches and Releases
1. The project MUST have one branch ("master") that always holds the latest in-progress version and SHOULD always build.
1. The project MUST NOT use topic branches for any reason. Personal forks MAY use topic branches.
1. To make a stable release a Maintainer must tag the repository. Stable releases MUST always be released from the repository master.
### 2.6. Evolution of Public Contracts
1. All Public Contracts (APIs or protocols) MUST be documented.
1. All Public Contracts SHOULD have space for extensibility and experimentation.
1. A patch that modifies a stable Public Contract SHOULD not break existing applications unless there is overriding consensus on the value of doing this.
1. A patch that introduces new features SHOULD do so using new names (a new contract).
1. New contracts SHOULD be marked as "draft" until they are stable and used by real users.
1. Old contracts SHOULD be deprecated in a systematic fashion by marking them as "deprecated" and replacing them with new contracts as needed.
1. When sufficient time has passed, old deprecated contracts SHOULD be removed.
1. Old names MUST NOT be reused by new contracts.
### 2.7. Project Administration
1. The project founders MUST act as Administrators to manage the set of project Maintainers.
1. The Administrators MUST ensure their own succession over time by promoting the most effective Maintainers.
1. A new Contributor who makes correct patches, who clearly understands the project goals, and the process SHOULD be invited to become a Maintainer.
1. Administrators SHOULD remove Maintainers who are inactive for an extended period of time, or who repeatedly fail to apply this process accurately.
1. Administrators SHOULD block or ban "bad actors" who cause stress and pain to others in the project. This should be done after public discussion, with a chance for all parties to speak. A bad actor is someone who repeatedly ignores the rules and culture of the project, who is needlessly argumentative or hostile, or who is offensive, and who is unable to self-correct their behavior when asked to do so by others.
## Further Reading
- [Argyris' Models 1 and 2](http://en.wikipedia.org/wiki/Chris_Argyris) - the goals of C4 are consistent with Argyris' Model 2.
- [Toyota Kata](http://en.wikipedia.org/wiki/Toyota_Kata) - covering the Improvement Kata (fixing problems one at a time) and the Coaching Kata (helping others to learn the Improvement Kata).

68
docs/devs/contributing.md Normal file
View file

@ -0,0 +1,68 @@
# Contributing
If you want to dive into the details, please see the [contract](./contract.md)
that defines the contributor role in this project. If you're comfortable with
a top-level summary, you can start here first.
Our workflow is basically [GitHub Flow][github-flow] with specific roles:
- **Contributor:** Write patches that reduce the number of problems.
- **Maintainers:** Merge patches that reduce the number of problems.
If you have an issue, it's best to open an issue to describe the problem and
discuss solutions, but don't worry if you've already skipped that step.
Assuming you already have a [developer install](./install.md) you should be
able to start editing source code. There are a few useful commands you should
know about:
- **`npm install`**: Ensure that software dependencies are installed.
- **`npm test`**: Ensure that all automated tests pass.
- **`npm run fix`**: If an automated test failed, this may fix it.
Please run `npm test` before writing a commit, because if there are errors then
maintainers won't be able to merge your patch. Please ask for help if `npm test`
is giving you any trouble.
**Note:** `npm run fix` is run automatically as a pre-commit hook. You always
have the option to disable pre-commit hooks with `git commit --no-verify`.
## Frequently Failed Tests
### Unknown word
<!-- spell-checker:disable -->
```
/src/index.js:10:42 - Unknown word (Scuttlebtut)
```
<!-- spell-checker:enable -->
If this word is a typo, please fix the typo. If this error is a mistake, and
you're sure that this is a word, please add the word to `.cspell.json`.
### Code style issues found
```
Checking formatting...
src/index.js
README.md
Code style issues found in the above file(s). Forgot to run Prettier?
```
You can use `npm run fix` to resolve inconsistent code style. Please remember to
add those changes with `git add` or similar before you commit.
## Tips
### TypeScript opportunities
If you're looking for places where TypeScript would enjoy more detail, you can
run the TypeScript linter with `--noImplicitAny`:
```sh
npx tsc --allowJs --resolveJsonModule --lib es2018,dom --checkJs --noEmit --skipLibCheck --noImplicitAny src/index.js
```
[github-flow]: https://guides.github.com/introduction/flow/

86
docs/devs/install.md Normal file
View file

@ -0,0 +1,86 @@
# Developer Install
To deploy the development environment:
```shell
git clone https://code.03c8.net/KrakensLab/oasis
cd oasis
bash install.sh
cd src/server
npm run dev
```
Once Oasis is started in dev mode, visit [http://localhost:3000](http://localhost:3000).
The backend restarts automatically (via [nodemon](https://nodemon.io)) whenever you save changes to `.js` or `.json` files in `src/backend/`, `src/models/`, `src/views/`, or `src/client/`. Static assets (`src/client/assets/`) do not trigger a restart. Page autoreload is not available because we avoid using JavaScript in the browser — reload the page manually to display your changes.
## Two-process architecture
Oasis runs as two cooperating Node processes:
- **`SSB_server.js`** — boots the local Secure Scuttlebutt sbot (gossip, EBT, friends, blobs, LAN, search, box, query, tangle, links, backlinks). Owns `~/.ssb`.
- **`backend.js`** — Koa HTTP server that connects to the sbot through `ssb-client` and renders pages with hyperaxe. Serves `http://localhost:3000`.
The backend talks to the sbot over a local Unix socket. If you only restart the backend (the default in `npm run dev`), the sbot keeps running. If you change anything under `src/server/` or anything that holds an SSB handle inside a model, restart the sbot too (kill the `SSB_server.js` process and re-run `npm start`).
## npm scripts
Run these from `src/server/`:
- **`npm start`** — boots the SSB sbot in the background, waits ~10 s, then starts the HTTP backend. Use this for an end-to-end local run.
- **`npm run start:ssb`** — start only the SSB sbot.
- **`npm run start:backend`** — start only the HTTP backend (assumes sbot is already running).
- **`npm run dev`** — backend under nodemon watch (auto-restart on file change). Sbot is **not** watched.
The launcher script at the repo root (`oasis.sh`) wraps these and detects whether to start in `server`, `pub`, or `gui` mode.
## Tests
Unit and integration tests live under `test/` at the repo root, grouped per module in `test/mods/`. Coverage spans **40+ modules** including tribes, feed, banking, parliament, courts, jobs, market, shops, media (audio/video/image/document/torrent), maps, pads, calendars, events, tasks, votes, transfers, reports, projects, opinions, activity, AI, CV, LARP, melody, and more.
Run the full suite from the `oasis/` directory:
```sh
# All modules, each in a subprocess with safe ~/.ssb isolation
bash test/run.sh
# Same, but skip the confirmation prompt
bash test/run.sh --yes
# All modules in a single Node process (no isolation, faster but mixes state)
node test/run.js
# A single module
node test/run.js mods/tribes
node test/run.js mods/media/audios
# Per-module shortcut (no isolation, fast iteration)
bash test/mods/<module>/run.sh
```
`test/run.sh` moves your live `~/.ssb` to a timestamped backup (`~/.ssb-bak-YYYYMMDD_HHMMSS`) before the run and creates a fresh empty `~/.ssb` for the tests. **Stop any running Oasis instance first** — only one process can hold `~/.ssb` open at a time. Pass `--restore` to restore the original `~/.ssb` after the run finishes (CI uses this).
What the tests cover, how to add a new module suite, and a record of bugs the test harness has caught are documented in [`test/README.md`](../../test/README.md). When you change a model, add or update its test under `test/mods/<module>/` so the change comes with a regression net.
## Useful commands while developing
- **`npm install`** — install / refresh dependencies.
- **`npm test`** — run automated tests (calls into the `test/` harness).
- **`npm run fix`** — auto-fix formatting and lint issues (also runs as a pre-commit hook).
## Directory map (cheat sheet)
- `src/server/` — SSB sbot entry, ssb-config, secret-stack plugin wiring, vendored `packages/ssb-server`.
- `src/backend/` — Koa HTTP entry (`backend.js`), middleware, blob handler, URL renderer, sanitizer.
- `src/models/` — per-module data access. Factory functions that receive `cooler` (and sometimes `tribeCrypto`, `tribesModel`) and return query/publish methods.
- `src/views/` — hyperaxe view functions. Pure HTML builders.
- `src/AI/` — local LLM service (`ai_service.mjs` on port 4001) and context assembler.
- `src/configs/``oasis-config.json` (module toggles, themes, language) and `config-manager.js`.
- `src/client/assets/` — CSS, theme files, translations (11 languages), static images.
- `docs/` — user and developer documentation (this folder).
- `test/` — test harness (`run.sh`, `run.js`, `seed.js`, `helpers/`) and per-module test suites in `mods/`.
- `scripts/` — build helpers (`build-deb.sh`, node_modules patcher).
## Pre-commit checks
The pre-commit hook runs `cspell` and `prettier`. See [`contributing.md`](./contributing.md) for what to do when a check fails (typos go in `.cspell.json`; formatting via `npm run fix`).

35
docs/devs/maintaining.md Normal file
View file

@ -0,0 +1,35 @@
# Maintaining
Please read the [contract](./contract) that defines the maintainer role in this
project. In short:
- Please merge any patches that reduce the number of problems in this project.
- If you have small nitpicks about a patch, please merge the patch and write a
new patch with your preferred improvements.
- **Take care of yourself and don't burn out.** Please don't sacrifice your
health to improve this project, and know that there are much more important
things in life than merging pull requests quickly.
## Tips
### Checking out a patch
If you want to check out pull request number 42 and you're comfortable running
the code on your local device.
```sh
remote="https://code.03c8.net/krakenlabs/oasis.git"
git fetch "$remote"
git reset --hard $remote master
git pull "$remote" pull/42/head
npm ci && npm test && npm start
```
No need to add their fork as a remote.
Or for ultimate convenience (and github lock-in), use the [github cli tool](https://cli.github.com):
```sh
gh pr list
gh pr checkout 42
```

34
docs/install/install.md Normal file
View file

@ -0,0 +1,34 @@
# Oasis Installation Guide
This guide will walk you through the process of installing **Oasis** on your device.
You can either use the automated installation script or manually download the source code.
---
## 1) Automated Installation (Recommended)
To install **Oasis** with a single command, run:
sh install.sh
---
## 2) Manual Installation
Try to execute the following steps (from a shell):
sudo apt-get install git curl
curl -sL http://deb.nodesource.com/setup_22.x | sudo bash -
sudo apt-get install -y nodejs
git clone https://code.03c8.net/KrakensLab/oasis
cd oasis
npm install .
---
## 3) Run Oasis
To run **Oasis** just launch:
sh oasis.sh

33
docs/security.md Normal file
View file

@ -0,0 +1,33 @@
# Security Policy
## Security Model
Oasis is experimental software, please don't trust it with your life.
If everything is working correctly, it's likely that:
- Only your computer can access Oasis.
- Only you can publish a message to your feed.
- Only the recipients of private messages can read the message.
- Only basic HTML is supported in blobs, which can't access the rest of Oasis.
It's important to know that this is not a silver bullet:
- Your public messages can be read by anyone on the network.
- Your IP address can be seen by anyone that peers with you.
- Your private messages can be read by anyone with access to your private key.
You should also know:
- Information that others can read can be saved, without your permission.
- Encryption techniques that are unbreakable today may become compromised in the future; maybe in dozens or hundreds of years.
- Don't trust your smartphone.
- Oasis is designed to run in a safe environment (SNH kit).
## Supported Versions
Only the latest release is supported.
## Reporting a Vulnerability
Send an email to epsylon@riseup.net to report any security problems. Please do not use the public issue tracker.

128
install.sh Normal file
View file

@ -0,0 +1,128 @@
#!/bin/bash
cd src/server
printf "==========================\n"
printf "|| OASIS Installer v0.5 ||\n"
printf "==========================\n"
sudo apt-get install -y git curl tar
curl -sL http://deb.nodesource.com/setup_22.x | sudo bash -
sudo apt-get install -y nodejs
GREEN=$'\e[32m'
DIM=$'\e[2m'
RESET=$'\e[0m'
echo ""
echo "Installing Node.js packages..."
echo ""
NPM_LOG=$(mktemp)
if ! npm install . --silent --no-audit --no-fund --no-progress --loglevel=error >"$NPM_LOG" 2>&1; then
echo "npm install failed. Output:"
cat "$NPM_LOG"
rm -f "$NPM_LOG"
exit 1
fi
rm -f "$NPM_LOG"
DEPS=$(node -e "const p=require('./package.json'); console.log(Object.keys({...(p.dependencies||{}), ...(p.devDependencies||{})}).sort().join('\n'))" 2>/dev/null)
for dep in $DEPS; do
if [ -d "node_modules/$dep" ]; then
printf " ${GREEN}[✓]${RESET} %s\n" "$dep"
fi
done
echo ""
npm audit fix --silent --no-fund --no-progress >/dev/null 2>&1 || true
MODEL_DIR="../AI"
LLM_FILE="oasis-42-1-chat.Q4_K_M.gguf"
LLM_TAR="$LLM_FILE.tar.gz"
LLM_URL="https://solarnethub.com/code/models/$LLM_TAR"
EMB_DIR="$MODEL_DIR/embeddings"
EMB_TAR="oasis-embeddings.tar.gz"
EMB_URL="https://solarnethub.com/code/models/$EMB_TAR"
EMB_FILE="$EMB_DIR/onnx/model_quantized.onnx"
CONFIG_PATH="../configs/oasis-config.json"
CHOICE="${OASIS_AI:-}"
if [ -z "$CHOICE" ] && [ -t 0 ]; then
echo ""
echo "Do you want to enable AI features in Oasis?"
echo ""
echo " [1] Full AI: chat assistant (42) + smart navigation prompt (~3.9 GB)"
echo " [2] Smart navigation only (~150 MB)"
echo " [3] No AI features (no downloads, AI tabs hidden)"
echo ""
read -p "Choose [1/2/3] (default 3): " ANS
case "$ANS" in
1) CHOICE="full" ;;
2) CHOICE="nav" ;;
*) CHOICE="none" ;;
esac
fi
if [ -z "$CHOICE" ]; then
CHOICE="none"
fi
case "$CHOICE" in
full)
WANT_LLM=1
WANT_EMB=1
;;
nav)
WANT_LLM=0
WANT_EMB=1
;;
*)
WANT_LLM=0
WANT_EMB=0
;;
esac
if [ "$WANT_LLM" = "1" ] && [ ! -f "$MODEL_DIR/$LLM_FILE" ]; then
echo ""
echo "downloading AI model [size: 3,8 GiB (4.081.004.224 bytes)] ..."
curl -L -o "$MODEL_DIR/$LLM_TAR" "$LLM_URL"
echo ""
echo "extracting package: $LLM_TAR..."
echo ""
tar -xzf "$MODEL_DIR/$LLM_TAR" -C "$MODEL_DIR"
rm "$MODEL_DIR/$LLM_TAR"
fi
if [ "$WANT_EMB" = "1" ] && [ ! -f "$EMB_FILE" ]; then
echo ""
echo "downloading embeddings model [size: ~60 MiB] ..."
curl -L -o "$MODEL_DIR/$EMB_TAR" "$EMB_URL"
echo ""
echo "extracting package: $EMB_TAR..."
echo ""
tar -xzf "$MODEL_DIR/$EMB_TAR" -C "$MODEL_DIR"
rm "$MODEL_DIR/$EMB_TAR"
fi
if [ -f "$CONFIG_PATH" ]; then
AI_VAL="off"; NAV_VAL="off"
[ "$WANT_LLM" = "1" ] && AI_VAL="on"
[ "$WANT_EMB" = "1" ] && NAV_VAL="on"
node -e "
const fs = require('fs');
const p = '$CONFIG_PATH';
const cfg = JSON.parse(fs.readFileSync(p, 'utf8'));
cfg.modules = cfg.modules || {};
cfg.modules.aiMod = '$AI_VAL';
cfg.modules.aiNavMod = '$NAV_VAL';
fs.writeFileSync(p, JSON.stringify(cfg, null, 2) + '\n');
"
fi
printf "==========================\n"
printf "\nOASIS has been correctly deployed! ;)\n\n"
printf "Run: 'sh oasis.sh' to start ...\n\n"

84
oasis.sh Normal file
View file

@ -0,0 +1,84 @@
#!/bin/sh
CURRENT_DIR=$(pwd)
MODE=$1
MODEL_PATH="$CURRENT_DIR/src/AI/oasis-42-1-chat.Q4_K_M.gguf"
CONFIG_FILE="$CURRENT_DIR/src/configs/oasis-config.json"
case " $* " in *" --debug "*) export OASIS_DEBUG=1 ;; esac
show_help() {
cat <<'EOF'
Usage: sh oasis.sh [mode] [-- <option>=<value> ...]
Modes:
gui Launch the Oasis web GUI (default).
server Launch only the Oasis backend in headless / pub mode.
help, -h Show this help message.
PUB admin commands (require the sbot to be running: sh oasis.sh server):
whoami Print this PUB id
invite [N] Create an invite code (default uses=1)
name <text> Set this PUB display name
announce <host> [port] Publish a pub address (default port=8008)
follow <feedId> Follow another PUB / feed
status Show peer / replication status
gossip List known gossip peers
GUI options (forwarded to the backend):
--host=<ip> Hostname / IP the web UI listens on (default: localhost).
Use 0.0.0.0 to expose on a VPS.
--port=<n> Port for the web UI (default: 3000).
--allow-host=<host> Extra hostname allowed when behind a reverse proxy.
--public Public-hosting mode: disables POST and redacts content
from people who haven't opted in to public hosting.
--offline Don't try to connect to Oasis peers / pubs.
--no-open Don't auto-open a browser tab on launch (useful on a VPS).
--debug Verbose logging.
Examples:
sh oasis.sh
sh oasis.sh server
sh oasis.sh invite 100
sh oasis.sh name "My PUB"
sh oasis.sh announce mypub.example.com
sh oasis.sh --host=0.0.0.0 --port=8080 --no-open
EOF
}
if [ -f "$CONFIG_FILE" ]; then
if [ -f "$MODEL_PATH" ]; then
sed -i.bak 's/"aiMod": *"off"/"aiMod": "on"/' "$CONFIG_FILE"
else
sed -i.bak 's/"aiMod": *"on"/"aiMod": "off"/' "$CONFIG_FILE"
fi
rm -f "$CONFIG_FILE.bak"
fi
case "$MODE" in
help|-h|--help)
show_help
exit 0
;;
server|pub)
if [ -f "$CONFIG_FILE" ]; then
sed -i.bak 's/"aiMod": *"on"/"aiMod": "off"/' "$CONFIG_FILE"
sed -i.bak 's/"aiNavMod": *"on"/"aiNavMod": "off"/' "$CONFIG_FILE"
rm -f "$CONFIG_FILE.bak"
fi
cd "$CURRENT_DIR/src/server" || exit 1
exec node SSB_server.js start
;;
whoami|invite|name|announce|follow|status|gossip)
exec node "$CURRENT_DIR/scripts/oasis-pub.js" "$@"
;;
gui)
shift
cd "$CURRENT_DIR/src/backend" || exit 1
exec node backend.js "$@"
;;
*)
cd "$CURRENT_DIR/src/backend" || exit 1
exec node backend.js "$@"
;;
esac

159
package.json Normal file
View file

@ -0,0 +1,159 @@
{
"name": "@krakenslab/oasis",
"version": "0.9.1",
"description": "Oasis - Social Networking Utopia",
"repository": {
"type": "git",
"url": "git+ssh://git@code.03c8.net/krakenlabs/oasis.git"
},
"license": "AGPL-3.0",
"author": "psy <epsylon@riseup.net>",
"main": "src/index.js",
"bin": {
"oasis": "npm run start"
},
"scripts": {
"start": "npm run start:ssb && sleep 10 && npm run start:backend",
"start:backend": "node ../backend/backend.js",
"start:ssb": "node SSB_server.js start &",
"dev": "npm run dev:backend",
"dev:backend": "nodemon",
"postinstall": "node ../../scripts/patch-node-modules.js"
},
"dependencies": {
"@koa/router": "^13.1.0",
"@open-rpc/client-js": "^1.8.1",
"@xenova/transformers": "^2.17.2",
"abstract-level": "^2.0.1",
"archiver": "^7.0.1",
"axios": "^1.10.0",
"cors": "^2.8.5",
"debug": "^4.3.1",
"dompurify": "^3.3.1",
"env-paths": "^2.2.1",
"epidemic-broadcast-trees": "^9.0.4",
"express": "^5.1.0",
"file-type": "^16.5.4",
"highlight.js": "11.0.0",
"hyperaxe": "^2.0.1",
"ip": "https://registry.npmjs.org/neoip/-/neoip-3.0.0.tgz",
"is-svg": "^4.4.0",
"jsdom": "^28.0.0",
"koa": "^2.7.0",
"koa-body": "^6.0.1",
"koa-mount": "^4.0.0",
"koa-static": "^5.0.0",
"lodash": "^4.17.21",
"minimist": "^1.2.8",
"module-alias": "^2.2.3",
"moment": "^2.30.1",
"multiblob": "^1.13.0",
"multiserver": "^3.3.1",
"multiserver-address": "^1.0.1",
"muxrpc": "^8.0.0",
"muxrpc-validation": "^3.0.2",
"muxrpcli": "^3.1.2",
"node-llama-cpp": "^3.10.0",
"non-private-ip": "^2.2.0",
"open": "^8.4.2",
"openpgp": "^6.3.0",
"packet-stream": "^2.0.6",
"packet-stream-codec": "^1.2.0",
"pdfjs-dist": "^5.2.133",
"pretty-ms": "^7.0.1",
"pull-abortable": "^4.1.1",
"pull-cat": "~1.1.5",
"pull-file": "^1.0.0",
"pull-many": "~1.0.6",
"pull-paramap": "^1.2.2",
"pull-pushable": "^2.2.0",
"pull-sort": "^1.0.2",
"pull-stream": "^3.7.0",
"punycode.js": "^2.3.1",
"qrcode": "^1.5.4",
"secret-stack": "^6.3.1",
"ssb-about": "^2.0.1",
"ssb-autofollow": "^1.1.0",
"ssb-backlinks": "^2.1.1",
"ssb-blobs": "^2.0.1",
"ssb-box": "^1.0.1",
"ssb-caps": "^1.0.1",
"ssb-client": "^4.9.0",
"ssb-config": "^3.4.4",
"ssb-conn": "6.0.3",
"ssb-conn-db": "^1.0.5",
"ssb-conn-hub": "^1.2.0",
"ssb-conn-staging": "^1.0.0",
"ssb-db": "^20.4.1",
"ssb-device-address": "^1.1.6",
"ssb-ebt": "^9.1.2",
"ssb-friend-pub": "^1.0.7",
"ssb-friends": "^5.0.0",
"ssb-gossip": "^1.1.1",
"ssb-invite": "^3.0.3",
"ssb-invite-client": "^1.3.3",
"ssb-keys": "^8.0.0",
"ssb-lan": "^1.0.0",
"ssb-legacy-conn": "^1.0.17",
"ssb-links": "^3.0.10",
"ssb-logging": "^1.0.0",
"ssb-markdown": "^3.6.0",
"ssb-master": "^1.0.3",
"ssb-meme": "^1.1.0",
"ssb-mentions": "^0.5.2",
"ssb-msgs": "^5.2.0",
"ssb-no-auth": "^1.0.0",
"ssb-onion": "^1.0.0",
"ssb-partial-replication": "^3.0.1",
"ssb-plugins": "^1.0.2",
"ssb-private": "^1.1.0",
"ssb-query": "^2.4.5",
"ssb-ref": "^2.16.0",
"ssb-replication-scheduler": "^3.0.0",
"ssb-search": "^1.3.0",
"ssb-server": "file:packages/ssb-server",
"ssb-tangle": "^1.0.1",
"ssb-thread-schema": "^1.1.1",
"ssb-threads": "^10.0.4",
"ssb-unix-socket": "^1.0.0",
"ssb-ws": "^6.2.3",
"util": "^0.12.5",
"yargs": "^17.7.2"
},
"overrides": {
"caller-path": "^4.0.0",
"highlight.js": "11.0.0",
"@babel/traverse": "7.23.2",
"trim": "0.0.3",
"json5": "2.2.2",
"debug": "^4.3.1",
"postcss": "8.4.31",
"punycode": "2.3.1",
"ejs": "3.1.10",
"babel-traverse": "7.0.0-alpha.1",
"ssb-conn": "6.0.3",
"ssb-ref": "^2.16.0",
"secret-stack": "^6.3.1",
"ip": "https://registry.npmjs.org/neoip/-/neoip-3.0.0.tgz",
"lodash.set": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"
},
"optionalDependencies": {
"fsevents": "^2.3.2",
"sharp": "^0.33.5"
},
"devDependencies": {
"nodemon": "^3.1.0"
},
"bugs": {
"url": "https://github.com/epsylon/oasis/issues"
},
"homepage": "https://github.com/epsylon/oasis",
"directories": {
"doc": "docs"
},
"keywords": [],
"engines": {
"node": "^10.0.0 || >=12.0.0"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}

192
scripts/build-deb.sh Executable file
View file

@ -0,0 +1,192 @@
#!/bin/bash
set -e
VERSION="0.7.8"
PKG_NAME="oasis"
ARCH=$(dpkg --print-architecture)
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BUILD_DIR="/tmp/oasis-deb-build"
DEB_ROOT="${BUILD_DIR}/${PKG_NAME}_${VERSION}_${ARCH}"
INSTALL_DIR="/opt/oasis"
if [ "$1" = "--arm64" ]; then
ARCH="arm64"
DEB_ROOT="${BUILD_DIR}/${PKG_NAME}_${VERSION}_${ARCH}"
fi
echo "=== Building Oasis ${VERSION} .deb (${ARCH}) ==="
rm -rf "${DEB_ROOT}"
mkdir -p "${DEB_ROOT}/DEBIAN"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/server"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/backend"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/views"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/models"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/client"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/configs"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/src/AI"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/scripts"
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/docs"
mkdir -p "${DEB_ROOT}/usr/bin"
mkdir -p "${DEB_ROOT}/usr/share/applications"
mkdir -p "${DEB_ROOT}/usr/share/doc/${PKG_NAME}"
mkdir -p "${DEB_ROOT}/lib/systemd/system"
echo "Copying application files..."
cp -r "${SRC_DIR}/src/server/package.json" "${DEB_ROOT}${INSTALL_DIR}/src/server/"
cp -r "${SRC_DIR}/src/server/package-lock.json" "${DEB_ROOT}${INSTALL_DIR}/src/server/" 2>/dev/null || true
cp "${SRC_DIR}/src/server/"*.js "${DEB_ROOT}${INSTALL_DIR}/src/server/"
if [ -d "${SRC_DIR}/src/server/packages" ]; then
cp -r "${SRC_DIR}/src/server/packages" "${DEB_ROOT}${INSTALL_DIR}/src/server/"
find "${DEB_ROOT}${INSTALL_DIR}/src/server/packages" -name "node_modules" -type d -exec rm -rf {} + 2>/dev/null || true
fi
cp "${SRC_DIR}/src/backend/"*.js "${DEB_ROOT}${INSTALL_DIR}/src/backend/"
cp -r "${SRC_DIR}/src/views/"*.js "${DEB_ROOT}${INSTALL_DIR}/src/views/"
cp -r "${SRC_DIR}/src/models/"*.js "${DEB_ROOT}${INSTALL_DIR}/src/models/"
cp -r "${SRC_DIR}/src/client" "${DEB_ROOT}${INSTALL_DIR}/src/"
find "${DEB_ROOT}${INSTALL_DIR}/src/client" -name "*.py" -delete 2>/dev/null
find "${DEB_ROOT}${INSTALL_DIR}/src/client" -name ".ruff_cache" -type d -exec rm -rf {} + 2>/dev/null || true
for f in oasis-config.json server-config.json snh-invite-code.json config-manager.js shared-state.js; do
cp "${SRC_DIR}/src/configs/${f}" "${DEB_ROOT}${INSTALL_DIR}/src/configs/"
done
cp "${SRC_DIR}/src/AI/"*.js "${DEB_ROOT}${INSTALL_DIR}/src/AI/" 2>/dev/null || true
cp "${SRC_DIR}/src/AI/"*.mjs "${DEB_ROOT}${INSTALL_DIR}/src/AI/" 2>/dev/null || true
if [ -d "${SRC_DIR}/src/AI/embeddings" ]; then
cp -r "${SRC_DIR}/src/AI/embeddings" "${DEB_ROOT}${INSTALL_DIR}/src/AI/"
fi
cp -r "${SRC_DIR}/scripts" "${DEB_ROOT}${INSTALL_DIR}/"
if [ -d "${SRC_DIR}/docs/PUB" ]; then
mkdir -p "${DEB_ROOT}${INSTALL_DIR}/docs/PUB"
cp "${SRC_DIR}/docs/PUB/"* "${DEB_ROOT}${INSTALL_DIR}/docs/PUB/" 2>/dev/null || true
fi
cp "${SRC_DIR}/oasis.sh" "${DEB_ROOT}${INSTALL_DIR}/"
cp "${SRC_DIR}/install.sh" "${DEB_ROOT}${INSTALL_DIR}/" 2>/dev/null || true
cp "${SRC_DIR}/LICENSE" "${DEB_ROOT}${INSTALL_DIR}/"
cp "${SRC_DIR}/README.md" "${DEB_ROOT}${INSTALL_DIR}/" 2>/dev/null || true
cat > "${DEB_ROOT}/DEBIAN/control" << EOF
Package: ${PKG_NAME}
Version: ${VERSION}
Architecture: ${ARCH}
Maintainer: SolarNET.HuB <solarnethub@riseup.net>
Depends: nodejs (>= 18)
Recommends: npm
Installed-Size: $(du -sk "${DEB_ROOT}${INSTALL_DIR}" | cut -f1)
Section: net
Priority: optional
Homepage: https://solarnethub.com
Description: Oasis P2P Social Network
Oasis is a P2P encrypted social network built on Secure Scuttlebutt (SSB).
Zero browser JavaScript — all rendering is server-side HTML+CSS.
Part of the SolarNET.HuB ecosystem.
EOF
cat > "${DEB_ROOT}/DEBIAN/postinst" << 'POSTINST'
#!/bin/bash
INSTALL_DIR="/opt/oasis"
echo "Installing Node.js dependencies..."
cd "${INSTALL_DIR}/src/server"
npm install --production 2>&1 | tail -10
node ../../scripts/patch-node-modules.js 2>/dev/null || true
if ! id -u oasis >/dev/null 2>&1; then
useradd --system --home-dir /var/lib/oasis --create-home --shell /usr/sbin/nologin oasis
fi
mkdir -p /var/lib/oasis/.ssb
chown -R oasis:oasis /var/lib/oasis
chown -R oasis:oasis "${INSTALL_DIR}"
systemctl daemon-reload 2>/dev/null || true
echo ""
echo "=== Oasis installed ==="
echo "Start: systemctl start oasis"
echo "Enable: systemctl enable oasis"
echo "Open: http://localhost:3000"
echo ""
POSTINST
chmod 755 "${DEB_ROOT}/DEBIAN/postinst"
cat > "${DEB_ROOT}/DEBIAN/prerm" << 'PRERM'
#!/bin/bash
set -e
systemctl stop oasis 2>/dev/null || true
systemctl disable oasis 2>/dev/null || true
PRERM
chmod 755 "${DEB_ROOT}/DEBIAN/prerm"
cat > "${DEB_ROOT}/DEBIAN/postrm" << 'POSTRM'
#!/bin/bash
set -e
if [ "$1" = "purge" ]; then
rm -rf /opt/oasis
userdel oasis 2>/dev/null || true
rm -rf /var/lib/oasis
fi
systemctl daemon-reload 2>/dev/null || true
POSTRM
chmod 755 "${DEB_ROOT}/DEBIAN/postrm"
cat > "${DEB_ROOT}/lib/systemd/system/oasis.service" << EOF
[Unit]
Description=Oasis P2P Social Network
After=network.target
[Service]
Type=simple
User=oasis
Group=oasis
WorkingDirectory=${INSTALL_DIR}
ExecStart=/bin/sh ${INSTALL_DIR}/oasis.sh
Restart=on-failure
RestartSec=10
Environment=HOME=/var/lib/oasis
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
EOF
cat > "${DEB_ROOT}/usr/bin/oasis" << 'LAUNCHER'
#!/bin/sh
exec /bin/sh /opt/oasis/oasis.sh "$@"
LAUNCHER
chmod 755 "${DEB_ROOT}/usr/bin/oasis"
cat > "${DEB_ROOT}/usr/share/applications/oasis.desktop" << EOF
[Desktop Entry]
Name=Oasis
GenericName=P2P Social Network
Exec=xdg-open http://localhost:3000
Icon=applications-internet
Terminal=false
Type=Application
Categories=Network;Chat;InstantMessaging;
EOF
cat > "${DEB_ROOT}/usr/share/doc/${PKG_NAME}/copyright" << EOF
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Oasis
Source: https://code.03c8.net/KrakensLab/snh-oasis
Files: *
Copyright: 2022-2026 SolarNET.HuB / psy <epsylon@riseup.net>
License: AGPL-3.0
EOF
echo "Building .deb package..."
DEB_FILE="${BUILD_DIR}/${PKG_NAME}_${VERSION}_${ARCH}.deb"
dpkg-deb --build "${DEB_ROOT}" "${DEB_FILE}"
echo ""
echo "=== Package built: ${DEB_FILE} ==="
echo "Size: $(du -h "${DEB_FILE}" | cut -f1)"
echo ""
echo "Install: sudo dpkg -i ${DEB_FILE}"
echo " sudo apt-get install -f"

4
scripts/generate_shs.js Normal file
View file

@ -0,0 +1,4 @@
const crypto = require('crypto');
const cap = crypto.randomBytes(32).toString('base64');
console.log('New SHS cap:', cap);

91
scripts/oasis-pub.js Normal file
View file

@ -0,0 +1,91 @@
#!/usr/bin/env node
const path = require('path');
const ssbConfig = require(path.join(__dirname, '..', 'src', 'server', 'ssb_config'));
const ssbClient = require(path.join(__dirname, '..', 'src', 'server', 'node_modules', 'ssb-client'));
const socketPath = path.join(ssbConfig.path, 'socket');
const publicInteger = (ssbConfig.keys.public || '').replace('.ed25519', '');
const remote = `unix:${socketPath}~noauth:${publicInteger}`;
const cmd = process.argv[2];
const args = process.argv.slice(3);
const usage = () => {
console.error('Usage: sh oasis.sh <command> [args]');
console.error('');
console.error('PUB admin commands (sbot must be running: sh oasis.sh server):');
console.error(' whoami Print this PUB id');
console.error(' invite [N] Create an invite code (default uses=1)');
console.error(' name <text> Set PUB display name');
console.error(' announce <host> [port] Publish a pub address (default port=8008)');
console.error(' follow <feedId> Follow another PUB');
console.error(' status Show peer / replication status');
console.error(' gossip List known gossip peers');
process.exit(1);
};
if (!cmd) usage();
const call = (fn, ...a) => new Promise((res, rej) => fn(...a, (e, r) => e ? rej(e) : res(r)));
ssbClient(ssbConfig.keys, { remote, caps: ssbConfig.caps }).then(async (ssb) => {
try {
switch (cmd) {
case 'whoami': {
const r = await call(ssb.whoami.bind(ssb));
console.log(JSON.stringify(r, null, 2));
break;
}
case 'invite': {
const uses = Math.max(1, parseInt(args[0] || '1', 10));
const code = await call(ssb.invite.create.bind(ssb.invite), uses);
console.log(code);
break;
}
case 'name': {
const text = String(args[0] || '');
if (!text) { console.error('Missing name'); process.exit(1); }
const me = await call(ssb.whoami.bind(ssb));
const r = await call(ssb.publish.bind(ssb), { type: 'about', about: me.id, name: text });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'announce': {
const host = args[0];
const port = parseInt(args[1] || '8008', 10);
if (!host) { console.error('Missing host'); process.exit(1); }
const me = await call(ssb.whoami.bind(ssb));
const r = await call(ssb.publish.bind(ssb), { type: 'pub', address: { key: me.id, host, port } });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'follow': {
const feedId = args[0];
if (!feedId) { console.error('Missing feedId'); process.exit(1); }
const r = await call(ssb.publish.bind(ssb), { type: 'contact', contact: feedId, following: true });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'status': {
const r = await call(ssb.status.bind(ssb));
console.log(JSON.stringify(r, null, 2));
break;
}
case 'gossip': {
const r = await call(ssb.conn.dbPeers.bind(ssb.conn));
console.log(JSON.stringify(r, null, 2));
break;
}
default:
usage();
}
ssb.close();
} catch (e) {
console.error('Error:', e.message || e);
process.exit(1);
}
}).catch((e) => {
console.error('Connection error:', e.message || e);
console.error('Is the Oasis sbot running? (sh oasis.sh server)');
process.exit(1);
});

View file

@ -0,0 +1,79 @@
const fs = require('fs');
const path = require('path');
const log = (msg) => console.log(`[OASIS] [PATCH] ${msg}`);
// === Patch ssb-ref ===
const ssbRefPath = path.resolve(__dirname, '../src/server/node_modules/ssb-ref/index.js');
if (fs.existsSync(ssbRefPath)) {
const data = fs.readFileSync(ssbRefPath, 'utf8');
const alreadyClean = /exports\.parseAddress\s*=\s*parseAddress/.test(data);
if (!alreadyClean) {
const patched = data.replace(
/exports\.parseAddress\s*=\s*deprecate\(\s*['"][^'"]*['"]\s*,\s*parseAddress\s*\)/,
'exports.parseAddress = parseAddress'
);
if (patched !== data) {
fs.writeFileSync(ssbRefPath, patched);
log('Patched ssb-ref to remove deprecated usage of parseAddress');
} else {
log('ssb-ref patch skipped: unexpected parseAddress export format');
}
}
} else {
log('ssb-ref patch skipped: file not found at ' + ssbRefPath);
}
// === Patch ssb-blobs ===
const ssbBlobsPath = path.resolve(__dirname, '../src/server/node_modules/ssb-blobs/inject.js');
if (fs.existsSync(ssbBlobsPath)) {
let data = fs.readFileSync(ssbBlobsPath, 'utf8');
const marker = 'want: function (id, cb)';
const startIndex = data.indexOf(marker);
if (startIndex !== -1) {
const endIndex = data.indexOf('},', startIndex);
if (endIndex !== -1) {
const before = data.slice(0, startIndex);
const after = data.slice(endIndex + 2);
const replacement = `
want: function (id, cb) {
id = toBlobId(id);
if (!isBlobId(id)) return cb(new Error('invalid id:' + id));
if (blobStore.isEmptyHash(id)) return cb(null, true);
if (wantCallbacks[id]) {
if (!Array.isArray(wantCallbacks[id])) wantCallbacks[id] = [];
wantCallbacks[id].push(cb);
} else {
wantCallbacks[id] = [cb];
blobStore.size(id, function (err, size) {
if (err) return cb(err);
if (size != null) {
while (wantCallbacks[id].length) {
const fn = wantCallbacks[id].shift();
if (typeof fn === 'function') fn(null, true);
}
delete wantCallbacks[id];
}
});
}
const peerId = findPeerWithBlob(id);
if (peerId) get(peerId, id);
if (wantCallbacks[id]) registerWant(id);
},`;
const finalData = before + replacement + after;
fs.writeFileSync(ssbBlobsPath, finalData);
log('Patched ssb-blobs to fix wantCallbacks handling');
} else {
log('ssb-blobs patch skipped: end of want function not found');
}
} else {
log('ssb-blobs patch skipped: want function not found');
}
}

9743
src/backend/backend.js Normal file

File diff suppressed because it is too large Load diff

308
src/backend/blobHandler.js Normal file
View file

@ -0,0 +1,308 @@
const pull = require('../server/node_modules/pull-stream');
const FileType = require("../server/node_modules/file-type");
const promisesFs = require('fs').promises;
const ssb = require("../client/gui");
const config = require("../server/SSB_server").config;
const cooler = ssb({ offline: config.offline });
let sharp;
try {
sharp = require("sharp");
} catch (e) {
}
const stripImageMetadata = async (buffer) => {
if (typeof sharp !== "function") return buffer;
try {
return await sharp(buffer).rotate().toBuffer();
} catch {
return buffer;
}
};
const PDF_METADATA_KEYS = [
'/Title', '/Author', '/Subject', '/Keywords',
'/Creator', '/Producer', '/CreationDate', '/ModDate'
];
const stripPdfMetadata = (buffer) => {
try {
let str = buffer.toString('binary');
for (const key of PDF_METADATA_KEYS) {
const keyBytes = key;
const regex = new RegExp(
keyBytes.replace(/\//g, '\\/') + '\\s*\\([^)]*\\)',
'g'
);
str = str.replace(regex, keyBytes + ' ()');
const hexRegex = new RegExp(
keyBytes.replace(/\//g, '\\/') + '\\s*<[^>]*>',
'g'
);
str = str.replace(hexRegex, keyBytes + ' <>');
}
return Buffer.from(str, 'binary');
} catch {
return buffer;
}
};
const MAX_BLOB_SIZE = 50 * 1024 * 1024;
class FileTooLargeError extends Error {
constructor(fileName, fileSize) {
super(`File too large: ${fileName} (${(fileSize / 1024 / 1024).toFixed(1)} MB)`);
this.name = 'FileTooLargeError';
this.fileName = fileName;
this.fileSize = fileSize;
}
}
const OGG_VIDEO_MARKERS = ['theora', 'VP80', 'OggDS', 'Dirac'];
const OGG_AUDIO_MARKERS = ['vorbis', 'OpusHead', 'FLAC', 'Speex'];
const oggMime = (buffer) => {
const head = buffer.slice(0, 65536);
for (const marker of OGG_VIDEO_MARKERS) if (head.includes(Buffer.from(marker))) return 'video/ogg';
for (const marker of OGG_AUDIO_MARKERS) if (head.includes(Buffer.from(marker))) return 'audio/ogg';
return 'video/ogg';
};
const storeUploadedFile = async function (blobUpload) {
if (!blobUpload || !blobUpload.filepath) return null;
let data = await promisesFs.readFile(blobUpload.filepath);
if (data.length === 0) return null;
if (data.length > MAX_BLOB_SIZE) {
throw new FileTooLargeError(blobUpload.originalFilename || blobUpload.name || 'file', data.length);
}
const EXTENSION_MIME_MAP = {
'.mp4': 'video/mp4', '.webm': 'video/webm', '.ogg': 'video/ogg',
'.ogv': 'video/ogg', '.oga': 'audio/ogg', '.mkv': 'video/x-matroska', '.avi': 'video/x-msvideo', '.mov': 'video/quicktime',
'.mp3': 'audio/mpeg', '.wav': 'audio/wav',
'.flac': 'audio/flac', '.aac': 'audio/aac', '.opus': 'audio/opus',
'.pdf': 'application/pdf', '.png': 'image/png', '.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
'.svg': 'image/svg+xml', '.bmp': 'image/bmp',
'.torrent': 'application/x-bittorrent'
};
const blob = { name: blobUpload.originalFilename || blobUpload.name || 'file' };
try {
const fileType = await FileType.fromBuffer(data);
blob.mime = (fileType && fileType.mime) ? fileType.mime : null;
} catch {
blob.mime = null;
}
if (blob.mime === 'application/ogg') blob.mime = oggMime(data);
const GENERIC_MIMES = new Set(['application/octet-stream', 'video/x-matroska']);
if ((!blob.mime || GENERIC_MIMES.has(blob.mime)) && blob.name) {
const ext = (blob.name.match(/\.[^.]+$/) || [''])[0].toLowerCase();
blob.mime = EXTENSION_MIME_MAP[ext] || blob.mime || 'application/octet-stream';
}
if (!blob.mime) {
blob.mime = 'application/octet-stream';
}
if (blob.mime.startsWith('image/') && blob.mime !== 'image/gif') {
data = await stripImageMetadata(data);
} else if (blob.mime === 'application/pdf') {
data = stripPdfMetadata(data);
}
const ssbClient = await cooler.open();
blob.id = await new Promise((resolve, reject) => {
pull(
pull.values([data]),
ssbClient.blobs.add((err, ref) => (err ? reject(err) : resolve(ref)))
);
});
if (blob.mime.startsWith("image/")) return `\n![image:${blob.name}](${blob.id})`;
if (blob.mime.startsWith("audio/")) return `\n[audio:${blob.name}](${blob.id})`;
if (blob.mime.startsWith("video/")) return `\n[video:${blob.name}](${blob.id})`;
if (blob.mime === "application/pdf") return `[pdf:${blob.name}](${blob.id})`;
if (blob.mime === "application/x-bittorrent") return `\n[torrent:${blob.name}](${blob.id})`;
return `\n[${blob.name}](${blob.id})`;
};
const handleBlobUpload = async function (ctx, fileFieldName) {
if (!ctx.request.files || !ctx.request.files[fileFieldName]) return null;
const entry = ctx.request.files[fileFieldName];
const first = Array.isArray(entry) ? entry[0] : entry;
return storeUploadedFile(first);
};
const handleBlobUploads = async function (ctx, fileFieldName, max = 8) {
if (!ctx.request.files || !ctx.request.files[fileFieldName]) return [];
const entry = ctx.request.files[fileFieldName];
const files = (Array.isArray(entry) ? entry : [entry]).slice(0, Math.max(0, max));
const out = [];
for (const file of files) {
const stored = await storeUploadedFile(file);
if (stored) out.push(stored);
}
return out;
};
function waitForBlob(ssbClient, blobId, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
let done = false;
const finishOk = () => {
if (done) return;
done = true;
clearTimeout(timer);
resolve();
};
const finishErr = (err) => {
if (done) return;
done = true;
clearTimeout(timer);
reject(err);
};
const timer = setTimeout(() => {
finishErr(new Error(`Timeout waiting for blob ${blobId}`));
}, timeoutMs);
if (!ssbClient.blobs || typeof ssbClient.blobs.has !== 'function') {
return finishErr(new Error('ssb.blobs.has is not available'));
}
ssbClient.blobs.has(blobId, (err, has) => {
if (err) return finishErr(err);
if (has) return finishOk();
if (typeof ssbClient.blobs.want !== 'function') {
return finishErr(new Error('ssb.blobs.want is not available'));
}
ssbClient.blobs.want(blobId, (err2) => {
if (err2) return finishErr(err2);
finishOk();
});
});
});
}
const serveBlob = async function (ctx) {
const encodedParam = (ctx.params.id || ctx.params.blobId || '').trim();
const raw = decodeURIComponent(encodedParam);
if (!raw) {
ctx.status = 400;
ctx.body = 'Invalid blob id';
return;
}
const blobId = raw.startsWith('&') ? raw : `&${raw}`;
const ssbClient = await cooler.open();
try {
await waitForBlob(ssbClient, blobId, 8000);
} catch (err) {
ctx.status = 504;
ctx.body = 'Blob not available';
return;
}
let buffer;
try {
buffer = await new Promise((resolve, reject) => {
pull(
ssbClient.blobs.get(blobId),
pull.collect((err, chunks) => {
if (err) return reject(err);
resolve(Buffer.concat(chunks));
})
);
});
} catch (err) {
ctx.status = 500;
ctx.body = 'Error reading blob';
return;
}
const size = buffer.length;
let mime = 'application/octet-stream';
try {
const ft = await FileType.fromBuffer(buffer);
if (ft && ft.mime) mime = ft.mime;
} catch {}
if (mime === 'application/octet-stream' && buffer.length > 10 && buffer[0] === 0x64) {
const head = buffer.slice(0, 128).toString('ascii');
if (head.includes('announce') || head.includes('8:announce') || head.includes('4:info')) mime = 'application/x-bittorrent';
}
if (mime === 'application/octet-stream' || mime === 'text/plain' || mime === 'application/xml' || mime === 'text/xml') {
let head = buffer.slice(0, 512).toString('utf8');
if (head.charCodeAt(0) === 0xFEFF) head = head.slice(1);
const trimmed = head.replace(/^\s+/, '').toLowerCase();
if (trimmed.startsWith('<?xml') || trimmed.startsWith('<svg')) {
if (trimmed.includes('<svg')) mime = 'image/svg+xml';
}
}
if (mime === 'application/ogg') mime = oggMime(buffer);
const isSvg = mime === 'image/svg+xml';
const qName = ctx.query.name ? String(ctx.query.name).replace(/["\r\n\\]/g, '').trim() : '';
const safeRaw = String(raw).replace(/["\r\n\\]/g, '');
const filename = qName || (mime === 'application/x-bittorrent' ? 'download.torrent' : safeRaw);
const disposition = isSvg ? 'attachment' : 'inline';
ctx.type = mime;
ctx.set('Content-Disposition', `${disposition}; filename="${filename}"`);
ctx.set('Cache-Control', 'public, max-age=31536000, immutable');
const range = ctx.headers.range;
if (range) {
const match = /^bytes=(\d*)-(\d*)$/.exec(range);
if (!match) {
ctx.status = 416;
ctx.set('Content-Range', `bytes */${size}`);
return;
}
let start = match[1] ? parseInt(match[1], 10) : 0;
let end = match[2] ? parseInt(match[2], 10) : size - 1;
if (Number.isNaN(start) || start < 0) start = 0;
if (Number.isNaN(end) || end >= size) end = size - 1;
if (start > end || start >= size) {
ctx.status = 416;
ctx.set('Content-Range', `bytes */${size}`);
return;
}
const chunk = buffer.slice(start, end + 1);
ctx.status = 206;
ctx.set('Content-Range', `bytes ${start}-${end}/${size}`);
ctx.set('Accept-Ranges', 'bytes');
ctx.set('Content-Length', String(chunk.length));
ctx.body = chunk;
} else {
ctx.status = 200;
ctx.set('Accept-Ranges', 'bytes');
ctx.set('Content-Length', String(size));
ctx.body = buffer;
}
};
module.exports = { handleBlobUpload, handleBlobUploads, serveBlob, oggMime, FileTooLargeError };

View file

@ -0,0 +1,66 @@
const { mergeDuplicatesBy, norm } = require('./dedupe');
const identitySignature = (x) => (x && x.author && x.createdAt) ? norm(x.author) + '|' + norm(x.createdAt) : null;
const openInviteOf = (item) => {
if (!item || !Array.isArray(item.invites)) return null;
const pub = item.invites.find((inv) => inv && typeof inv === 'object' && inv.public === true && inv.code);
return pub ? { code: pub.code } : null;
};
const collabContent = (opts = {}) => {
const membersField = opts.membersField || 'members';
const undecField = opts.undecField || 'undecryptable';
const contentFields = Array.isArray(opts.contentFields) ? opts.contentFields : [];
const listFields = Array.isArray(opts.listFields) ? opts.listFields : [];
const arr = (v) => (Array.isArray(v) ? v : []);
const freshestMembers = (base, dup) => {
const bt = new Date(base.updatedAt || base.createdAt || 0).getTime();
const dt = new Date(dup.updatedAt || dup.createdAt || 0).getTime();
const fresh = dt >= bt ? dup : base;
return arr(fresh[membersField]).length ? fresh[membersField]
: (arr(base[membersField]).length ? base[membersField] : arr(dup[membersField]));
};
const mergePair = (base, dup) => {
const out = { ...base, [membersField]: freshestMembers(base, dup) };
for (const f of contentFields) out[f] = base[f] || dup[f];
for (const f of listFields) out[f] = arr(base[f]).length ? base[f] : arr(dup[f]);
out[undecField] = !!(base[undecField] && dup[undecField]);
return out;
};
const orderForMerge = (a, b) => {
const c = new Date(a.createdAt || 0) - new Date(b.createdAt || 0);
if (c !== 0) return c;
return ((a[undecField] || !a.title) ? 1 : 0) - ((b[undecField] || !b.title) ? 1 : 0);
};
const collapse = (items) =>
mergeDuplicatesBy(arr(items).slice().sort(orderForMerge), identitySignature, mergePair);
const fold = (base, all) => {
const sig = identitySignature(base);
if (!sig) return base;
const group = arr(all).filter((x) => identitySignature(x) === sig);
if (group.length <= 1) return base;
const canonical = collapse(group)[0];
const out = { ...base, [membersField]: canonical[membersField] };
for (const f of contentFields) out[f] = base[f] || canonical[f];
for (const f of listFields) out[f] = arr(base[f]).length ? base[f] : arr(canonical[f]);
return out;
};
const isVisible = (item, viewerId) => {
if (!item[undecField]) return true;
return item.author === viewerId || arr(item[membersField]).includes(viewerId);
};
const visibleThenCollapsed = (items, viewerId) =>
collapse(arr(items).filter((x) => isVisible(x, viewerId)));
return { identitySignature, mergePair, collapse, fold, isVisible, visibleThenCollapsed };
};
module.exports = { collabContent, identitySignature, openInviteOf };

280
src/backend/contentPdf.js Normal file
View file

@ -0,0 +1,280 @@
const { buildDocumentPdf } = require('./pdfDocument');
const fmtDate = v => {
if (!v) return '';
const d = new Date(v);
return isNaN(d.getTime()) ? String(v) : d.toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
};
const fmtDay = v => {
if (!v) return '';
const d = new Date(v);
return isNaN(d.getTime()) ? String(v) : d.toISOString().slice(0, 10);
};
const asList = v => (Array.isArray(v) ? v : []);
const txt = v => (v == null ? '' : String(v));
const humanLabel = (key) => String(key || '')
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/^./, c => c.toUpperCase());
const pushMeta = (out, item) => {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'METADATA' });
if (item.id) out.push({ kind: 'kv', label: 'Content ID', value: item.id });
const author = item.author || item.organizer || item.createdBy || item.from || '';
if (author) out.push({ kind: 'kv', label: 'Author', value: author });
if (item.createdAt) out.push({ kind: 'kv', label: 'Created At', value: fmtDate(item.createdAt) });
if (item.updatedAt) out.push({ kind: 'kv', label: 'Updated At', value: fmtDate(item.updatedAt) });
};
const pushOpinions = (out, item) => {
const op = item.opinions && typeof item.opinions === 'object' ? item.opinions : {};
const entries = Object.entries(op).filter(([, n]) => Number(n) > 0);
if (!entries.length) return;
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'OPINIONS' });
for (const [cat, n] of entries) out.push({ kind: 'kv', label: humanLabel(cat), value: String(n) });
};
const pushTags = (out, item) => {
const tags = asList(item.tags).filter(Boolean);
if (tags.length) out.push({ kind: 'kv', label: 'Tags', value: tags.join(', ') });
};
const reportSections = (report) => {
const out = [];
out.push({ kind: 'title', text: `Report: ${txt(report.title) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'CLASSIFICATION' });
out.push({ kind: 'kv', label: 'Category', value: txt(report.category).toUpperCase() });
out.push({ kind: 'kv', label: 'Severity', value: txt(report.severity).toUpperCase() });
out.push({ kind: 'kv', label: 'Status', value: txt(report.status).toUpperCase() });
pushTags(out, report);
if (txt(report.description).trim()) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DESCRIPTION' });
out.push({ kind: 'text', text: report.description });
}
const tpl = report.template && typeof report.template === 'object' ? report.template : {};
const tplEntries = Object.entries(tpl).filter(([, v]) => txt(v).trim());
if (tplEntries.length) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DETAILS' });
for (const [k, v] of tplEntries) out.push({ kind: 'kv', label: humanLabel(k), value: v });
}
const confirmations = asList(report.confirmations);
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'CONFIRMATIONS' });
out.push({ kind: 'kv', label: 'Confirmed', value: String(confirmations.length) });
for (const c of confirmations) out.push({ kind: 'kv', label: 'Confirmed by', value: c });
pushOpinions(out, report);
pushMeta(out, report);
return out;
};
const voteSections = (vote) => {
const out = [];
out.push({ kind: 'title', text: `Votation: ${txt(vote.question) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'TERMS' });
out.push({ kind: 'kv', label: 'Status', value: txt(vote.status).toUpperCase() });
if (vote.deadline) out.push({ kind: 'kv', label: 'Deadline', value: fmtDate(vote.deadline) });
pushTags(out, vote);
const votes = vote.votes && typeof vote.votes === 'object' ? vote.votes : {};
const total = Number(vote.totalVotes) || asList(vote.voters).length;
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'RESULTS' });
out.push({ kind: 'kv', label: 'Total votes', value: String(total) });
for (const [choice, n] of Object.entries(votes)) {
const count = Number(n) || 0;
const pct = total > 0 ? Math.round((count / total) * 100) : 0;
out.push({ kind: 'kv', label: choice, value: `${count} (${pct}%)` });
}
pushOpinions(out, vote);
pushMeta(out, vote);
return out;
};
const eventSections = (event) => {
const out = [];
out.push({ kind: 'title', text: `Event: ${txt(event.title) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'SCHEDULE' });
out.push({ kind: 'kv', label: 'Date', value: fmtDate(event.date) });
out.push({ kind: 'kv', label: 'Status', value: txt(event.status).toUpperCase() });
if (event.location) out.push({ kind: 'kv', label: 'Location', value: event.location });
if (event.mapUrl) out.push({ kind: 'kv', label: 'Map', value: event.mapUrl });
if (Number(event.price) > 0) out.push({ kind: 'kv', label: 'Price', value: `${Number(event.price)} ECO` });
out.push({ kind: 'kv', label: 'Privacy', value: txt(event.isPublic).toUpperCase() });
if (event.url) out.push({ kind: 'kv', label: 'Url', value: event.url });
pushTags(out, event);
if (txt(event.description).trim()) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DESCRIPTION' });
out.push({ kind: 'text', text: event.description });
}
const attendees = asList(event.attendees);
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'ATTENDEES' });
out.push({ kind: 'kv', label: 'Total', value: String(attendees.length) });
for (const a of attendees) out.push({ kind: 'kv', label: 'Attendee', value: a });
pushOpinions(out, event);
pushMeta(out, event);
return out;
};
const taskSections = (task) => {
const out = [];
out.push({ kind: 'title', text: `Task: ${txt(task.title) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'SCHEDULE' });
out.push({ kind: 'kv', label: 'Status', value: txt(task.status).toUpperCase() });
out.push({ kind: 'kv', label: 'Priority', value: txt(task.priority).toUpperCase() });
if (task.startTime) out.push({ kind: 'kv', label: 'Starts', value: fmtDate(task.startTime) });
if (task.endTime) out.push({ kind: 'kv', label: 'Ends', value: fmtDate(task.endTime) });
if (task.location) out.push({ kind: 'kv', label: 'Location', value: task.location });
out.push({ kind: 'kv', label: 'Privacy', value: txt(task.isPublic).toUpperCase() });
pushTags(out, task);
if (txt(task.description).trim()) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DESCRIPTION' });
out.push({ kind: 'text', text: task.description });
}
const assignees = asList(task.assignees);
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'ASSIGNEES' });
out.push({ kind: 'kv', label: 'Total', value: String(assignees.length) });
for (const a of assignees) out.push({ kind: 'kv', label: 'Assignee', value: a });
pushOpinions(out, task);
pushMeta(out, task);
return out;
};
const calendarSections = (calendar, extra = {}) => {
const dates = asList(extra.dates);
const notesByDate = extra.notesByDate && typeof extra.notesByDate === 'object' ? extra.notesByDate : {};
const out = [];
out.push({ kind: 'title', text: `Calendar: ${txt(calendar.title) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'SUMMARY' });
out.push({ kind: 'kv', label: 'Status', value: calendar.isClosed ? 'CLOSED' : txt(calendar.status).toUpperCase() });
if (calendar.deadline) out.push({ kind: 'kv', label: 'Deadline', value: fmtDate(calendar.deadline) });
if (calendar.mapUrl) out.push({ kind: 'kv', label: 'Map', value: calendar.mapUrl });
out.push({ kind: 'kv', label: 'Participants', value: String(asList(calendar.participants).length) });
out.push({ kind: 'kv', label: 'Dates', value: String(dates.length) });
const noteTotal = Object.values(notesByDate).reduce((n, arr) => n + asList(arr).length, 0);
out.push({ kind: 'kv', label: 'Notes', value: String(noteTotal) });
pushTags(out, calendar);
const participants = asList(calendar.participants);
if (participants.length) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'PARTICIPANTS' });
for (const p of participants) out.push({ kind: 'kv', label: 'Participant', value: p });
}
if (dates.length) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DATES' });
for (const d of dates) {
const day = fmtDay(d && d.date) || txt(d && d.date);
out.push({ kind: 'kv', label: day, value: txt(d && d.label) });
for (const note of asList(notesByDate[d && d.key])) {
const noteText = txt(note && note.text);
if (noteText) out.push({ kind: 'text', text: ` - ${noteText}` });
}
}
}
pushMeta(out, calendar);
return out;
};
const cvSections = (cv) => {
const out = [];
out.push({ kind: 'title', text: `Curriculum: ${txt(cv.name) || txt(cv.author) || '-'}` });
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'PROFILE' });
if (cv.location) out.push({ kind: 'kv', label: 'Location', value: cv.location });
if (cv.status) out.push({ kind: 'kv', label: 'Status', value: txt(cv.status).toUpperCase() });
if (cv.preferences) out.push({ kind: 'kv', label: 'Preferences', value: txt(cv.preferences).toUpperCase() });
if (cv.languages) out.push({ kind: 'kv', label: 'Languages', value: cv.languages });
if (txt(cv.description).trim()) {
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: 'DESCRIPTION' });
out.push({ kind: 'text', text: cv.description });
}
const blocks = [
['PERSONAL', cv.personalExperiences, cv.personalSkills],
['EDUCATION', cv.educationExperiences, cv.educationalSkills],
['PROFESSIONAL', cv.professionalExperiences, cv.professionalSkills],
['OASIS', cv.oasisExperiences, cv.oasisSkills]
];
for (const [heading, experiences, skills] of blocks) {
const skillList = asList(skills).filter(Boolean);
const body = txt(experiences).trim();
if (!body && !skillList.length) continue;
out.push({ kind: 'blank' });
out.push({ kind: 'section', text: heading });
if (body) out.push({ kind: 'text', text: body });
if (skillList.length) out.push({ kind: 'kv', label: 'Skills', value: skillList.join(', ') });
}
pushMeta(out, cv);
return out;
};
const BUILDERS = {
reports: { title: 'OASIS - Report', sections: reportSections, name: item => item.title },
votes: { title: 'OASIS - Votation', sections: voteSections, name: item => item.question },
events: { title: 'OASIS - Event', sections: eventSections, name: item => item.title },
tasks: { title: 'OASIS - Task', sections: taskSections, name: item => item.title },
calendars: { title: 'OASIS - Calendar', sections: calendarSections, name: item => item.title },
cv: { title: 'OASIS - Curriculum', sections: cvSections, name: item => item.name || item.author }
};
const isSupported = kind => Object.prototype.hasOwnProperty.call(BUILDERS, kind);
const pdfFilename = (kind, item) => {
const b = BUILDERS[kind];
const raw = b ? txt(b.name(item || {})) : '';
const slug = raw.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
return `oasis-${kind}-${slug || 'document'}.pdf`;
};
const buildContentPdf = (kind, item, extra = {}, viewerId = null) => {
const b = BUILDERS[kind];
if (!b) throw new Error('Unsupported pdf kind');
return buildDocumentPdf({
title: b.title,
issuedToLabel: 'Issued to',
issuedTo: viewerId || null,
sections: b.sections(item || {}, extra)
});
};
module.exports = { buildContentPdf, pdfFilename, isSupported };

View file

@ -0,0 +1,153 @@
const fs = require("fs");
const path = require("path");
const TEMPLATE = path.join(__dirname, "../configs/content_favorites.json");
const storePath = () => {
try {
return require("../server/ssb_config").statePath("content_favorites.json") || TEMPLATE;
} catch (_) { return TEMPLATE; }
};
const DEFAULT = {
audios: [],
blogs: [],
bookmarks: [],
calendars: [],
chats: [],
documents: [],
events: [],
forum: [],
housing: [],
images: [],
jobs: [],
logs: [],
maps: [],
pads: [],
polls: [],
projects: [],
reports: [],
shops: [],
market: [],
shopProducts: [],
tasks: [],
torrents: [],
transfers: [],
videos: [],
votes: []
};
const safeArr = (v) => (Array.isArray(v) ? v : []);
let queue = Promise.resolve();
const withLock = (fn) => {
queue = queue.then(fn, fn);
return queue;
};
const normalize = (raw) => {
const out = {};
for (const k of Object.keys(DEFAULT)) {
const list = safeArr(raw?.[k]).map((x) => String(x || "").trim()).filter(Boolean);
out[k] = Array.from(new Set(list));
}
return out;
};
const ensureFile = async () => {
try {
await fs.promises.access(storePath());
} catch (e) {
const dir = path.dirname(storePath());
await fs.promises.mkdir(dir, { recursive: true });
await fs.promises.writeFile(storePath(), JSON.stringify(DEFAULT, null, 2), "utf8");
}
};
const readAll = async () => {
await ensureFile();
try {
const txt = await fs.promises.readFile(storePath(), "utf8");
return normalize(JSON.parse(txt || "{}"));
} catch (e) {
const fixed = normalize(DEFAULT);
await fs.promises.writeFile(storePath(), JSON.stringify(fixed, null, 2), "utf8");
return fixed;
}
};
const writeAll = async (data) => {
const dir = path.dirname(storePath());
const tmp = path.join(dir, `.content_favorites.${process.pid}.${Date.now()}.tmp`);
const txt = JSON.stringify(normalize(data), null, 2);
await fs.promises.writeFile(tmp, txt, "utf8");
await fs.promises.rename(tmp, storePath());
};
const assertKind = (kind) => {
const k = String(kind || "").trim();
if (!Object.prototype.hasOwnProperty.call(DEFAULT, k)) throw new Error("Invalid favorites kind");
return k;
};
const lastArg = (args, n) => args[args.length - n];
const kindFromArgs = (args) => {
const k = String(lastArg(args, 1) || "").trim();
return assertKind(k);
};
const idFromArgs = (args) => String(lastArg(args, 1) || "").trim();
exports.getFavoriteSet = async (kind) => {
const k = assertKind(kind);
const data = await readAll();
return new Set(safeArr(data[k]).map(String));
};
exports.getFavoriteIndex = async () => {
const data = await readAll();
const index = new Map();
for (const kind of Object.keys(DEFAULT)) {
for (const id of safeArr(data[kind])) index.set(String(id), kind);
}
return index;
};
exports.addFavorite = async (kind, id) =>
withLock(async () => {
const k = assertKind(kind);
const favId = String(id || "").trim();
if (!favId) return;
const data = await readAll();
const set = new Set(safeArr(data[k]).map(String));
set.add(favId);
data[k] = Array.from(set);
await writeAll(data);
});
exports.removeFavorite = async (kind, id) =>
withLock(async () => {
const k = assertKind(kind);
const favId = String(id || "").trim();
if (!favId) return;
const data = await readAll();
const set = new Set(safeArr(data[k]).map(String));
set.delete(favId);
data[k] = Array.from(set);
await writeAll(data);
});
exports.getFavoritesSet = async (...args) => exports.getFavoriteSet(kindFromArgs(args));
exports.addToFavorites = async (...args) => {
const kind = kindFromArgs(args.slice(0, -1));
const id = idFromArgs(args);
return exports.addFavorite(kind, id);
};
exports.removeFromFavorites = async (...args) => {
const kind = kindFromArgs(args.slice(0, -1));
const id = idFromArgs(args);
return exports.removeFavorite(kind, id);
};
exports.storePath = storePath;

52
src/backend/dedupe.js Normal file
View file

@ -0,0 +1,52 @@
const norm = (v) => String(v == null ? '' : v).trim().toLowerCase();
const dedupeBy = (items, keyFn) => {
const seen = new Set();
const out = [];
for (const it of (Array.isArray(items) ? items : [])) {
let k = null;
try { k = keyFn(it); } catch (_) { k = null; }
if (k == null || k === '') { out.push(it); continue; }
if (seen.has(k)) continue;
seen.add(k);
out.push(it);
}
return out;
};
const mergeDuplicatesBy = (items, keyFn, mergeFn) => {
const slots = new Map();
const out = [];
for (const it of (Array.isArray(items) ? items : [])) {
let k = null;
try { k = keyFn(it); } catch (_) { k = null; }
if (k == null || k === '') { out.push(it); continue; }
if (!slots.has(k)) {
const slot = { i: out.length, v: it };
slots.set(k, slot);
out.push(it);
} else {
const slot = slots.get(k);
slot.v = mergeFn(slot.v, it);
out[slot.i] = slot.v;
}
}
return out;
};
const dedupeByPreferring = (items, keyFn, scoreFn) => {
const best = new Map();
const order = [];
for (const it of (Array.isArray(items) ? items : [])) {
let k = null;
try { k = keyFn(it); } catch (_) { k = null; }
if (k == null || k === '') { order.push({ solo: it }); continue; }
let s = 0;
try { s = Number(scoreFn(it)) || 0; } catch (_) { s = 0; }
if (!best.has(k)) { const slot = { v: it, s }; best.set(k, slot); order.push({ slot }); }
else { const slot = best.get(k); if (s > slot.s) { slot.v = it; slot.s = s; } }
}
return order.map(o => (o.solo !== undefined ? o.solo : o.slot.v));
};
module.exports = { dedupeBy, mergeDuplicatesBy, dedupeByPreferring, norm };

View file

@ -0,0 +1,74 @@
const crypto = require('crypto');
const ALG = 'aes-256-gcm';
const IV_LEN = 12;
const TAG_LEN = 16;
const KEY_LEN = 32;
const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;
const generateFileKey = () => crypto.randomBytes(KEY_LEN);
const keyToHex = (key) => Buffer.isBuffer(key) ? key.toString('hex') : String(key);
const keyFromHex = (hex) => {
const buf = Buffer.from(String(hex), 'hex');
if (buf.length !== KEY_LEN) throw new Error('Invalid file key');
return buf;
};
const encryptChunk = (plaintext, key) => {
const iv = crypto.randomBytes(IV_LEN);
const cipher = crypto.createCipheriv(ALG, key, iv);
const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, ct]);
};
const decryptChunk = (payload, key) => {
if (!Buffer.isBuffer(payload) || payload.length < IV_LEN + TAG_LEN) throw new Error('Corrupt chunk');
const iv = payload.subarray(0, IV_LEN);
const tag = payload.subarray(IV_LEN, IV_LEN + TAG_LEN);
const ct = payload.subarray(IV_LEN + TAG_LEN);
const decipher = crypto.createDecipheriv(ALG, key, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ct), decipher.final()]);
};
const sha256Hex = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
const splitBuffer = (buffer, chunkSize = DEFAULT_CHUNK_SIZE) => {
const size = Math.max(1, Number(chunkSize) || DEFAULT_CHUNK_SIZE);
const out = [];
for (let off = 0; off < buffer.length; off += size) {
out.push(buffer.subarray(off, Math.min(off + size, buffer.length)));
}
if (!out.length) out.push(Buffer.alloc(0));
return out;
};
const buildManifest = ({ filename, mime, size, chunkSize, chunkHashes, plainSha256 }) => ({
v: 1,
alg: ALG,
filename: String(filename || 'file'),
mime: String(mime || 'application/octet-stream'),
size: Number(size) || 0,
chunkSize: Number(chunkSize) || DEFAULT_CHUNK_SIZE,
chunks: Array.isArray(chunkHashes) ? chunkHashes.slice() : [],
plainSha256: plainSha256 || null
});
const encryptManifest = (manifest, key) => encryptChunk(Buffer.from(JSON.stringify(manifest), 'utf8'), key);
const decryptManifest = (payload, key) => {
const json = decryptChunk(payload, key).toString('utf8');
const m = JSON.parse(json);
if (!m || m.v !== 1 || !Array.isArray(m.chunks)) throw new Error('Invalid manifest');
return m;
};
module.exports = {
ALG, IV_LEN, TAG_LEN, KEY_LEN, DEFAULT_CHUNK_SIZE,
generateFileKey, keyToHex, keyFromHex,
encryptChunk, decryptChunk, sha256Hex, splitBuffer,
buildManifest, encryptManifest, decryptManifest
};

208
src/backend/fork_routes.js Normal file
View file

@ -0,0 +1,208 @@
"use strict";
// Rutas propias de la rama experimental (modulo Karvan: salas efimeras en RAM,
// mensajes temporales y senalizacion WebRTC).
//
// Viven fuera de backend.js a proposito: ese fichero concentra las 577 rutas de
// upstream en una sola cadena fluida y se mueve +905/-298 lineas por release, asi
// que cualquier ruta anadida en medio entra en conflicto en cada integracion.
// Aqui se montan en un router propio que se inserta en la cadena de middleware
// antes del router de upstream; lo que no casa cae a next() y sigue su curso.
//
// Las dependencias se inyectan en lugar de reconstruirse: cooler abre la conexion
// al sbot y duplicarla abriria un segundo cliente muxrpc.
const koaRouter = require("../server/node_modules/@koa/router");
const { koaBody } = require("../server/node_modules/koa-body");
const { stripDangerousTags } = require("./sanitizeHtml");
const { buildIceServers } = require("./turnCredentials");
const karvanModel = require('../models/karvan_model')({}); // FORK_IA_UX: salas efímeras en RAM (mensajes temporales + señalización WebRTC)
const { karvanView, karvanRoomView } = require("../views/karvan_view");
module.exports = ({ cooler, pull, pmModel, checkMod, getViewerId,
getConfig, saveConfig, legacyModel, onboardingModel,
isLoopbackRequest, sendErrorPage }) => {
// FORK_IA_UX Fase 2 (cross-device): relay de MENSAJES de Karvan por privados SSB. Funciona vía un pub
// (el privado se replica al otro móvil); los SIGNAL de WebRTC NO se relayan (serían demasiados/lentos por el log).
// No toca el arranque del SSB. Ingesta por stream EN VIVO (no polling) → eficiente.
const karvanSeenRelay = new Set(); // mids ya inyectados (evita duplicados/bucles)
let karvanRelaySub = false; // ¿suscriptor del log en vivo montado?
async function karvanPublishRelay(roomId, mid, from, text) {
try {
const feeds = karvanModel.getRemoteFeeds(roomId);
if (!feeds.length) return;
const ssbClient = await cooler.open();
const recps = [...new Set([ssbClient.id, ...feeds])].slice(0, 8);
await new Promise((res, rej) => ssbClient.private.publish(
{ type: 'karvan-relay', roomId, mid: String(mid || '').slice(0, 60), from: String(from || '?').slice(0, 80), text: String(text || '').slice(0, 2000), private: true },
recps, (e, m) => e ? rej(e) : res(m)));
} catch (e) {}
}
async function karvanStartRelay() {
if (karvanRelaySub) return;
karvanRelaySub = true;
try {
const ssbClient = await cooler.open();
const me = ssbClient.id;
pull(
ssbClient.createLogStream({ old: false, live: true }),
pull.drain((m) => {
try {
if (!m || !m.value) return;
let dec; try { dec = ssbClient.private.unbox({ key: m.key, value: m.value, timestamp: m.timestamp }); } catch (_) { return; }
const c = dec && dec.value && dec.value.content;
if (!c || c.type !== 'karvan-relay' || !c.roomId || !c.mid) return;
if (dec.value.author === me) return; // no reinyectar lo propio (evita bucle A→B→A)
if (karvanSeenRelay.has(c.mid)) return;
if (!karvanModel.getRoom(c.roomId)) return; // solo si tenemos esa sala localmente
karvanSeenRelay.add(c.mid);
if (karvanSeenRelay.size > 5000) karvanSeenRelay.clear();
karvanModel.postMessage(c.roomId, { from: c.from, text: c.text, mid: c.mid });
} catch (e) {}
})
);
} catch (e) { karvanRelaySub = false; }
}
// ¿quién me invitó a esta sala? (para registrar su feed en el espejo local) — reutiliza el lector de privados
async function karvanInviteAuthor(roomId) {
try {
const msgs = await pmModel.listAllPrivate();
for (const m of (msgs || [])) {
const c = m && m.value && m.value.content;
if (c && c.subject === 'KARVAN_INVITE' && typeof c.text === 'string' && c.text.indexOf('/karvan/' + roomId) !== -1) return m.value.author;
}
} catch (e) {}
return null;
}
const forkRouter = new koaRouter();
forkRouter
// Configuracion ICE para las llamadas. Solo loopback: la credencial TURN va
// firmada con el secreto del nodo y no debe salir de la maquina.
.get('/karvan/ice', async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
if (!isLoopbackRequest(ctx)) { ctx.status = 403; ctx.body = { error: 'forbidden' }; return; }
let who = ''; try { who = getViewerId() || ''; } catch (e) {}
let rtc = null; try { rtc = (getConfig() || {}).rtc || null; } catch (e) {}
ctx.body = buildIceServers(rtc, who);
})
// ===== FORK_IA_UX: módulo KARVAN (mensajes temporales RAM + WebRTC data-channel) =====
.get('/karvan', async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.redirect('/modules'); return; }
let selfId = ''; try { selfId = getViewerId(); } catch (e) {}
ctx.body = karvanView(karvanModel.listRooms(), { selfId });
})
.post('/karvan/create', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.redirect('/modules'); return; }
const b = ctx.request.body || {};
const room = karvanModel.createRoom({
title: stripDangerousTags(String(b.title || '').trim()).slice(0, 80),
ttlMinutes: b.ttl,
});
ctx.redirect('/karvan/' + room.id);
})
.get('/karvan/:id', async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.redirect('/modules'); return; }
let room = karvanModel.getRoom(ctx.params.id);
// unirse por enlace/invitación crea un espejo local, pero SOLO en una navegación real (documento):
// un <img>/subrecurso de una web maliciosa NO debe poder crear/expulsar salas por GET (CSRF). El navegador
// controla sec-fetch-dest/accept, así que son señales fiables.
let justAdopted = false;
if (!room) {
const isNav = ctx.get('sec-fetch-dest') === 'document' || (ctx.get('accept') || '').includes('text/html');
if (isNav) { room = karvanModel.adoptRoom({ id: ctx.params.id }); justAdopted = !!room; }
}
if (!room) { ctx.redirect('/karvan'); return; }
if (justAdopted) { // al unirte por enlace, registra el feed de quien te invitó → relay cross-device
const author = await karvanInviteAuthor(ctx.params.id);
if (author) { karvanModel.addRemoteFeed(ctx.params.id, author); karvanStartRelay(); }
}
let selfId = ''; try { selfId = getViewerId(); } catch (e) {}
const msgs = karvanModel.listMessages(room.id, 0) || [];
ctx.body = karvanRoomView(room, msgs, { selfId, invite: ctx.query.invite || '' });
})
.post('/karvan/:id/invite', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
const id = ctx.params.id;
const room = karvanModel.getRoom(id);
if (!room) { ctx.redirect('/karvan'); return; }
const to = String((ctx.request.body || {}).to || '').trim();
if (!/^@[A-Za-z0-9+/=]{20,}\.ed25519$/.test(to)) { ctx.redirect('/karvan/' + id + '?invite=bad'); return; }
try {
// reutiliza el patrón de invitación por mensaje privado de Oasis (como el módulo industry):
// le llega al INBOX del contacto con un enlace a la sala. Sin código SSB nuevo.
await pmModel.sendMessage([to], 'KARVAN_INVITE',
'You have been invited to an ephemeral Karvan room' + (room.title ? ' ("' + room.title + '")' : '') + ' -> /karvan/' + id);
karvanModel.addRemoteFeed(id, to); karvanStartRelay(); // relay cross-device hacia el invitado
ctx.redirect('/karvan/' + id + '?invite=ok');
} catch (e) { ctx.redirect('/karvan/' + id + '?invite=fail'); }
})
.post('/karvan/:id/msg', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
const b = ctx.request.body || {};
let selfId = ''; try { selfId = getViewerId(); } catch (e) {}
const msg = karvanModel.postMessage(ctx.params.id, {
from: String(b.from || selfId || '?').slice(0, 80),
text: stripDangerousTags(String(b.text || '')).slice(0, 2000),
mid: b.mid,
});
if (!msg) { ctx.status = 404; ctx.body = { error: 'no room' }; return; }
karvanPublishRelay(ctx.params.id, msg.mid || (msg.from + '-' + msg.ts + '-' + msg.seq), msg.from, msg.text); // → feeds remotos (si hay)
const wantsJson = (ctx.get('accept') || '').indexOf('application/json') !== -1
|| (ctx.get('content-type') || '').indexOf('application/json') !== -1;
if (wantsJson) ctx.body = { ok: true, seq: msg.seq };
else ctx.redirect('/karvan/' + ctx.params.id);
})
.get('/karvan/:id/msgs', async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
const msgs = karvanModel.listMessages(ctx.params.id, ctx.query.since || 0);
ctx.body = { messages: msgs || [] };
})
.post('/karvan/:id/signal', koaBody(), async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
const b = ctx.request.body || {};
karvanModel.postSignal(ctx.params.id, { from: b.from, to: b.to, payload: b.payload });
ctx.body = { ok: true };
})
.get('/karvan/:id/signal', async (ctx) => {
if (!checkMod(ctx, 'karvanMod')) { ctx.status = 403; ctx.body = { error: 'off' }; return; }
const r = karvanModel.getSignals(ctx.params.id, { forId: ctx.query.for || '', since: ctx.query.since || 0 });
ctx.body = r || { signals: [], members: [] };
})
.get("/settings/bottombar", async (ctx) => {
ctx.body = require("../views/main_views").bottomBarPickerView();
})
.post("/settings/bottombar", koaBody(), async (ctx) => {
const cfg = getConfig();
const MAX = 4;
const body = ctx.request.body || {};
const action = String(body.action || '').trim();
const key = String(body.key || '').trim();
const catalog = require("../views/main_views").PINNABLE_MODULES || [];
let pins = Array.isArray(cfg.bottomBarPins) ? cfg.bottomBarPins.slice() : [];
if (action === 'add') {
if (key && catalog.some(m => m.key === key) && !pins.includes(key) && pins.length < MAX) pins.push(key);
} else if (action === 'remove') {
pins = pins.filter(k => k !== key);
} else if (action === 'clear') {
pins = [];
}
cfg.bottomBarPins = pins.slice(0, MAX);
saveConfig(cfg);
ctx.redirect('/settings/bottombar');
})
.get('/legacy/export', async (ctx) => {
if (!isLoopbackRequest(ctx)) { ctx.status = 403; ctx.body = ''; return; }
const pw = ctx.query && ctx.query.password;
if (!pw || pw.length < 32) return ctx.redirect('/legacy');
try {
const { filename, data } = await legacyModel.exportData({ password: pw });
ctx.set('Content-Type', 'application/octet-stream');
ctx.set('Content-Disposition', `attachment; filename="${filename}"`);
ctx.set('Content-Length', String(data.length));
ctx.body = data;
try { onboardingModel.markStep('backup'); } catch (_) {}
} catch (error) { sendErrorPage(ctx, error.message); }
});
return forkRouter.routes();
};

206
src/backend/logsPdf.js Normal file
View file

@ -0,0 +1,206 @@
const fs = require('fs');
const path = require('path');
const LOGO_PATH = path.join(__dirname, '..', 'client', 'assets', 'images', 'snh-oasis.jpg');
const { escapePdf } = require('./pdfDocument');
const linkPattern = /(?:https?:\/\/[^\s]+|www\.[^\s]+|@[A-Za-z0-9+/=.\-]+\.ed25519|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})/g;
const splitSegments = (line) => {
const segs = [];
let last = 0;
const re = new RegExp(linkPattern.source, 'g');
let m;
while ((m = re.exec(line)) !== null) {
if (m.index > last) segs.push({ t: line.slice(last, m.index), l: false });
segs.push({ t: m[0], l: true });
last = m.index + m[0].length;
}
if (last < line.length) segs.push({ t: line.slice(last), l: false });
return segs;
};
const wrap = (txt, max = 82) => {
const out = [];
for (const raw of String(txt || '').split('\n')) {
let line = raw;
while (line.length > max) {
let cut = line.lastIndexOf(' ', max);
if (cut <= 0) cut = max;
out.push(line.slice(0, cut));
line = line.slice(cut).replace(/^\s+/, '');
}
out.push(line);
}
return out;
};
const readJpegDims = (buf) => {
let i = 2;
while (i < buf.length) {
if (buf[i] !== 0xFF) return null;
const marker = buf[i + 1];
if (marker === 0xD8 || marker === 0xD9) { i += 2; continue; }
const len = buf.readUInt16BE(i + 2);
if (marker >= 0xC0 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC) {
const h = buf.readUInt16BE(i + 5);
const w = buf.readUInt16BE(i + 7);
const c = buf[i + 9];
return { w, h, c };
}
i += 2 + len;
}
return null;
};
function buildLogsPdf(entries, oasisId, opts = {}) {
const pageW = 612;
const pageH = 792;
const marginX = 50;
const headerH = 90;
const footerH = 40;
const bodyTop = pageH - headerH - 22;
const bodyBottom = footerH + 10;
const lineH = 12;
const maxBodyLines = Math.floor((bodyTop - bodyBottom) / lineH);
let logoBuf = null;
let logoDims = null;
try {
logoBuf = fs.readFileSync(LOGO_PATH);
logoDims = readJpegDims(logoBuf);
} catch (_) {}
const allLines = [];
for (const e of entries) {
const ts = new Date(e.ts);
const when = ts.toISOString().replace('T', ' ').slice(0, 19);
allLines.push({ kind: 'header', text: `[${when}]:` });
allLines.push({ kind: 'blank', text: '' });
for (const l of wrap(e.text, 82)) allLines.push({ kind: 'text', text: l });
allLines.push({ kind: 'blank', text: '' });
}
if (!allLines.length) allLines.push({ kind: 'text', text: '(no entries)' });
const pages = [];
for (let i = 0; i < allLines.length; i += maxBodyLines) {
pages.push(allLines.slice(i, i + maxBodyLines));
}
if (!pages.length) pages.push([{ kind: 'text', text: '(no entries)' }]);
const objects = [];
const addObj = body => { objects.push(body); return objects.length; };
const catalogId = addObj(null);
const pagesId = addObj(null);
const fontId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>');
const fontBoldId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier-Bold /Encoding /WinAnsiEncoding >>');
let logoXObjId = null;
if (logoBuf && logoDims) {
const colorSpace = logoDims.c === 1 ? '/DeviceGray' : '/DeviceRGB';
const dict = `<< /Type /XObject /Subtype /Image /Width ${logoDims.w} /Height ${logoDims.h} /ColorSpace ${colorSpace} /BitsPerComponent 8 /Filter /DCTDecode /Length ${logoBuf.length} >>`;
logoXObjId = addObj({ dict, stream: logoBuf });
}
const exportDate = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
const footerLeft = `Generated: ${exportDate}`;
const pageIds = [];
const contentIds = [];
pages.forEach((pg, pgIdx) => {
const parts = [];
if (logoXObjId) {
const logoH = 60;
const logoW = Math.round((logoDims.w / logoDims.h) * logoH);
const logoX = marginX;
const logoY = pageH - headerH + 15;
parts.push(`q\n${logoW} 0 0 ${logoH} ${logoX} ${logoY} cm\n/Logo Do\nQ`);
}
const titleX = (logoXObjId ? marginX + 80 : marginX);
const titleY = pageH - 45;
parts.push(`BT\n/F2 16 Tf\n${titleX} ${titleY} Td\n(${escapePdf('OASIS - Experience logs')}) Tj\nET`);
const inhabitantPrefix = 'Inhabitant: ';
const inhabitantPrefixW = inhabitantPrefix.length * 5.4;
parts.push(`BT\n/F1 9 Tf\n${titleX} ${titleY - 16} Td\n(${escapePdf(inhabitantPrefix)}) Tj\nET`);
parts.push(`BT\n/F2 9 Tf\n${titleX + inhabitantPrefixW} ${titleY - 16} Td\n(${escapePdf(String(oasisId || ''))}) Tj\nET`);
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${pageH - headerH} m\n${pageW - marginX} ${pageH - headerH} l\nS\nQ`);
let y = bodyTop;
const charW = 6;
for (const ln of pg) {
if (ln.kind === 'header') {
parts.push(`BT\n/F2 10 Tf\n1 0.647 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
} else if (ln.text) {
const segs = splitSegments(ln.text);
let x = marginX;
for (const s of segs) {
if (!s.t) continue;
const color = s.l ? '0 0 1 rg' : '0 0 0 rg';
parts.push(`BT\n/F1 10 Tf\n${color}\n${x} ${y} Td\n(${escapePdf(s.t)}) Tj\nET`);
x += s.t.length * charW;
}
}
y -= lineH;
}
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${footerH + 5} m\n${pageW - marginX} ${footerH + 5} l\nS\nQ`);
parts.push(`BT\n/F1 8 Tf\n${marginX} ${footerH - 10} Td\n(${escapePdf(footerLeft)}) Tj\nET`);
const pageLabel = `Page ${pgIdx + 1} of ${pages.length}`;
const pageLabelW = pageLabel.length * 4.8;
parts.push(`BT\n/F1 8 Tf\n${pageW - marginX - pageLabelW} ${footerH - 10} Td\n(${escapePdf(pageLabel)}) Tj\nET`);
const content = parts.join('\n');
const stream = `<< /Length ${Buffer.byteLength(content, 'latin1')} >>\nstream\n${content}\nendstream`;
const cid = addObj(stream);
contentIds.push(cid);
const pid = addObj(null);
pageIds.push(pid);
});
for (let i = 0; i < pageIds.length; i++) {
const resources = logoXObjId
? `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> /XObject << /Logo ${logoXObjId} 0 R >> >>`
: `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> >>`;
objects[pageIds[i] - 1] = `<< /Type /Page /Parent ${pagesId} 0 R /MediaBox [0 0 ${pageW} ${pageH}] /Contents ${contentIds[i]} 0 R /Resources ${resources} >>`;
}
objects[catalogId - 1] = `<< /Type /Catalog /Pages ${pagesId} 0 R >>`;
objects[pagesId - 1] = `<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(' ')}] /Count ${pageIds.length} >>`;
const chunks = [];
const offsets = [0];
let byteLen = 0;
const push = (buf) => { chunks.push(buf); byteLen += buf.length; };
push(Buffer.from('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n', 'binary'));
for (let i = 0; i < objects.length; i++) {
offsets.push(byteLen);
const obj = objects[i];
if (obj && typeof obj === 'object' && obj.dict && obj.stream) {
push(Buffer.from(`${i + 1} 0 obj\n${obj.dict}\nstream\n`, 'binary'));
push(obj.stream);
push(Buffer.from('\nendstream\nendobj\n', 'binary'));
} else {
push(Buffer.from(`${i + 1} 0 obj\n${obj}\nendobj\n`, 'binary'));
}
}
const xrefStart = byteLen;
let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (let i = 1; i <= objects.length; i++) {
xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
}
xref += `trailer\n<< /Size ${objects.length + 1} /Root ${catalogId} 0 R >>\nstartxref\n${xrefStart}\n%%EOF`;
push(Buffer.from(xref, 'binary'));
return Buffer.concat(chunks);
}
module.exports = { buildLogsPdf };

View file

@ -0,0 +1,126 @@
const fs = require("fs");
const path = require("path");
const FILE = path.join(__dirname, "../configs/media-favorites.json");
const DEFAULT = {
audios: [],
bookmarks: [],
calendars: [],
chats: [],
documents: [],
images: [],
maps: [],
pads: [],
shops: [],
market: [],
shopProducts: [],
torrents: [],
videos: []
};
const safeArr = (v) => (Array.isArray(v) ? v : []);
let queue = Promise.resolve();
const withLock = (fn) => {
queue = queue.then(fn, fn);
return queue;
};
const normalize = (raw) => {
const out = {};
for (const k of Object.keys(DEFAULT)) {
const list = safeArr(raw?.[k]).map((x) => String(x || "").trim()).filter(Boolean);
out[k] = Array.from(new Set(list));
}
return out;
};
const ensureFile = async () => {
try {
await fs.promises.access(FILE);
} catch (e) {
const dir = path.dirname(FILE);
await fs.promises.mkdir(dir, { recursive: true });
await fs.promises.writeFile(FILE, JSON.stringify(DEFAULT, null, 2), "utf8");
}
};
const readAll = async () => {
await ensureFile();
try {
const txt = await fs.promises.readFile(FILE, "utf8");
return normalize(JSON.parse(txt || "{}"));
} catch (e) {
const fixed = normalize(DEFAULT);
await fs.promises.writeFile(FILE, JSON.stringify(fixed, null, 2), "utf8");
return fixed;
}
};
const writeAll = async (data) => {
const dir = path.dirname(FILE);
const tmp = path.join(dir, `.media-favorites.${process.pid}.${Date.now()}.tmp`);
const txt = JSON.stringify(normalize(data), null, 2);
await fs.promises.writeFile(tmp, txt, "utf8");
await fs.promises.rename(tmp, FILE);
};
const assertKind = (kind) => {
const k = String(kind || "").trim();
if (!Object.prototype.hasOwnProperty.call(DEFAULT, k)) throw new Error("Invalid favorites kind");
return k;
};
const lastArg = (args, n) => args[args.length - n];
const kindFromArgs = (args) => {
const k = String(lastArg(args, 1) || "").trim();
return assertKind(k);
};
const idFromArgs = (args) => String(lastArg(args, 1) || "").trim();
exports.getFavoriteSet = async (kind) => {
const k = assertKind(kind);
const data = await readAll();
return new Set(safeArr(data[k]).map(String));
};
exports.addFavorite = async (kind, id) =>
withLock(async () => {
const k = assertKind(kind);
const favId = String(id || "").trim();
if (!favId) return;
const data = await readAll();
const set = new Set(safeArr(data[k]).map(String));
set.add(favId);
data[k] = Array.from(set);
await writeAll(data);
});
exports.removeFavorite = async (kind, id) =>
withLock(async () => {
const k = assertKind(kind);
const favId = String(id || "").trim();
if (!favId) return;
const data = await readAll();
const set = new Set(safeArr(data[k]).map(String));
set.delete(favId);
data[k] = Array.from(set);
await writeAll(data);
});
exports.getFavoritesSet = async (...args) => exports.getFavoriteSet(kindFromArgs(args));
exports.addToFavorites = async (...args) => {
const kind = kindFromArgs(args.slice(0, -1));
const id = idFromArgs(args);
return exports.addFavorite(kind, id);
};
exports.removeFromFavorites = async (...args) => {
const kind = kindFromArgs(args.slice(0, -1));
const id = idFromArgs(args);
return exports.removeFavorite(kind, id);
};

20
src/backend/nameCache.js Normal file
View file

@ -0,0 +1,20 @@
const cache = new Map()
const get = (feedId) => {
if (!feedId) return null
const entry = cache.get(String(feedId))
return entry ? entry.name : null
}
const set = (feedId, name, ts) => {
if (!feedId || typeof name !== 'string' || !name) return
const id = String(feedId)
const t = Number(ts) || 0
const prev = cache.get(id)
if (!prev || (prev.ts || 0) <= t) cache.set(id, { name, ts: t })
}
const has = (feedId) => !!feedId && cache.has(String(feedId))
const size = () => cache.size
module.exports = { get, set, has, size }

View file

@ -0,0 +1,50 @@
const positive = [
"interesting",
"necessary",
"useful",
"informative",
"wellResearched",
"accurate",
"insightful",
"actionable",
"creative",
"inspiring",
"love",
"funny",
"clear",
"uplifting"
];
const constructive = [
"unnecessary",
"rejected",
"needsSources",
"wrong",
"lowQuality",
"confusing",
"misleading",
"offTopic",
"duplicate",
"clickbait",
"propaganda"
];
const moderation = [
"spam",
"troll",
"adultOnly",
"nsfw",
"violent",
"toxic",
"harassment",
"hate",
"scam",
"triggering"
];
const all = [...positive, ...constructive, ...moderation];
all.positive = positive;
all.constructive = constructive;
all.moderation = moderation;
module.exports = all;

199
src/backend/pdfDocument.js Normal file
View file

@ -0,0 +1,199 @@
const fs = require('fs');
const path = require('path');
const LOGO_PATH = path.join(__dirname, '..', 'client', 'assets', 'images', 'snh-oasis.jpg');
const WIN_ANSI_HIGH = {
'\u20AC': '\x80', '\u201A': '\x82', '\u0192': '\x83', '\u201E': '\x84',
'\u2026': '\x85', '\u2020': '\x86', '\u2021': '\x87', '\u02C6': '\x88',
'\u2030': '\x89', '\u0160': '\x8A', '\u2039': '\x8B', '\u0152': '\x8C',
'\u017D': '\x8E', '\u2018': '\x91', '\u2019': '\x92', '\u201C': '\x93',
'\u201D': '\x94', '\u2022': '\x95', '\u2013': '\x96', '\u2014': '\x97',
'\u02DC': '\x98', '\u2122': '\x99', '\u0161': '\x9A', '\u203A': '\x9B',
'\u0153': '\x9C', '\u017E': '\x9E', '\u0178': '\x9F'
};
const escapePdf = s => String(s == null ? '' : s)
.replace(/[\r\n\t]+/g, ' ')
.replace(/[\u0152\u0153\u0160\u0161\u0178\u017D\u017E\u0192\u02C6\u02DC\u2013\u2014\u2018\u2019\u201A\u201C\u201D\u201E\u2020\u2021\u2022\u2026\u2030\u2039\u203A\u20AC\u2122]/g,
(c) => WIN_ANSI_HIGH[c] || '?')
.replace(/[^\x20-\xFF\x80-\x9F]/g, '?')
.replace(/\\/g, '\\\\')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)');
const wrap = (txt, max = 82) => {
const out = [];
for (const raw of String(txt == null ? '' : txt).split('\n')) {
let line = raw;
while (line.length > max) {
let cut = line.lastIndexOf(' ', max);
if (cut <= 0) cut = max;
out.push(line.slice(0, cut));
line = line.slice(cut).replace(/^\s+/, '');
}
out.push(line);
}
return out;
};
const readJpegDims = (buf) => {
let i = 2;
while (i < buf.length) {
if (buf[i] !== 0xFF) return null;
const marker = buf[i + 1];
if (marker === 0xD8 || marker === 0xD9) { i += 2; continue; }
const len = buf.readUInt16BE(i + 2);
if (marker >= 0xC0 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC) {
const h = buf.readUInt16BE(i + 5);
const w = buf.readUInt16BE(i + 7);
const c = buf[i + 9];
return { w, h, c };
}
i += 2 + len;
}
return null;
};
const flattenSections = (sections) => {
const lines = [];
for (const s of Array.isArray(sections) ? sections : []) {
if (!s) continue;
if (s.kind === 'kv') {
const txt = `${s.label}: ${s.value == null ? '' : s.value}`;
for (const w of wrap(txt, 82)) lines.push({ kind: 'kv', text: w });
} else if (s.kind === 'text') {
for (const w of wrap(s.text, 82)) lines.push({ kind: 'kv', text: w });
} else {
lines.push({ kind: s.kind, text: s.text });
}
}
return lines;
};
function buildDocumentPdf({ title, issuedToLabel, issuedTo, sections } = {}) {
const pageW = 612;
const pageH = 792;
const marginX = 50;
const headerH = 90;
const footerH = 40;
const bodyTop = pageH - headerH - 24;
const bodyBottom = footerH + 10;
const lineH = 14;
let logoBuf = null;
let logoDims = null;
try {
logoBuf = fs.readFileSync(LOGO_PATH);
logoDims = readJpegDims(logoBuf);
} catch (_) {}
const lines = flattenSections(sections);
const maxBodyLines = Math.floor((bodyTop - bodyBottom) / lineH);
const pages = [];
for (let i = 0; i < lines.length; i += maxBodyLines) pages.push(lines.slice(i, i + maxBodyLines));
if (!pages.length) pages.push([]);
const objects = [];
const addObj = body => { objects.push(body); return objects.length; };
const catalogId = addObj(null);
const pagesId = addObj(null);
const fontId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>');
const fontBoldId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier-Bold /Encoding /WinAnsiEncoding >>');
let logoXObjId = null;
if (logoBuf && logoDims) {
const cs = logoDims.c === 1 ? '/DeviceGray' : '/DeviceRGB';
const dict = `<< /Type /XObject /Subtype /Image /Width ${logoDims.w} /Height ${logoDims.h} /ColorSpace ${cs} /BitsPerComponent 8 /Filter /DCTDecode /Length ${logoBuf.length} >>`;
logoXObjId = addObj({ dict, stream: logoBuf });
}
const exportDate = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
const footerLeft = `Generated: ${exportDate}`;
const pageIds = [];
const contentIds = [];
pages.forEach((pg, pgIdx) => {
const parts = [];
if (logoXObjId) {
const logoH = 60;
const logoW = Math.round((logoDims.w / logoDims.h) * logoH);
parts.push(`q\n${logoW} 0 0 ${logoH} ${marginX} ${pageH - headerH + 15} cm\n/Logo Do\nQ`);
}
const titleX = (logoXObjId ? marginX + 80 : marginX);
const titleY = pageH - 45;
parts.push(`BT\n/F2 16 Tf\n${titleX} ${titleY} Td\n(${escapePdf(title || 'OASIS')}) Tj\nET`);
if (issuedTo) {
const prefix = `${issuedToLabel || 'Issued to'}: `;
const prefixW = prefix.length * 5.4;
parts.push(`BT\n/F1 9 Tf\n${titleX} ${titleY - 16} Td\n(${escapePdf(prefix)}) Tj\nET`);
parts.push(`BT\n/F2 9 Tf\n${titleX + prefixW} ${titleY - 16} Td\n(${escapePdf(String(issuedTo))}) Tj\nET`);
}
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${pageH - headerH} m\n${pageW - marginX} ${pageH - headerH} l\nS\nQ`);
let y = bodyTop;
for (const ln of pg) {
if (ln.kind === 'title') {
parts.push(`BT\n/F2 14 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
} else if (ln.kind === 'subtitle') {
parts.push(`BT\n/F1 11 Tf\n0.2 0.2 0.2 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
} else if (ln.kind === 'section') {
parts.push(`BT\n/F2 11 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
parts.push(`q\n0 0 0 RG\n0.5 w\n${marginX} ${y - 3} m\n${pageW - marginX} ${y - 3} l\nS\nQ`);
} else if (ln.kind === 'kv') {
parts.push(`BT\n/F1 10 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
}
y -= lineH;
}
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${footerH + 5} m\n${pageW - marginX} ${footerH + 5} l\nS\nQ`);
parts.push(`BT\n/F1 8 Tf\n${marginX} ${footerH - 10} Td\n(${escapePdf(footerLeft)}) Tj\nET`);
const pageLabel = `Page ${pgIdx + 1} of ${pages.length}`;
const pageLabelW = pageLabel.length * 4.8;
parts.push(`BT\n/F1 8 Tf\n${pageW - marginX - pageLabelW} ${footerH - 10} Td\n(${escapePdf(pageLabel)}) Tj\nET`);
const content = parts.join('\n');
const stream = `<< /Length ${Buffer.byteLength(content, 'latin1')} >>\nstream\n${content}\nendstream`;
const cid = addObj(stream);
contentIds.push(cid);
const pid = addObj(null);
pageIds.push(pid);
});
for (let i = 0; i < pageIds.length; i++) {
const resources = logoXObjId
? `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> /XObject << /Logo ${logoXObjId} 0 R >> >>`
: `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> >>`;
objects[pageIds[i] - 1] = `<< /Type /Page /Parent ${pagesId} 0 R /MediaBox [0 0 ${pageW} ${pageH}] /Contents ${contentIds[i]} 0 R /Resources ${resources} >>`;
}
objects[catalogId - 1] = `<< /Type /Catalog /Pages ${pagesId} 0 R >>`;
objects[pagesId - 1] = `<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(' ')}] /Count ${pageIds.length} >>`;
const chunks = [];
const offsets = [0];
let byteLen = 0;
const push = (buf) => { chunks.push(buf); byteLen += buf.length; };
push(Buffer.from('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n', 'binary'));
for (let i = 0; i < objects.length; i++) {
offsets.push(byteLen);
const obj = objects[i];
if (obj && typeof obj === 'object' && obj.dict && obj.stream) {
push(Buffer.from(`${i + 1} 0 obj\n${obj.dict}\nstream\n`, 'binary'));
push(obj.stream);
push(Buffer.from('\nendstream\nendobj\n', 'binary'));
} else {
push(Buffer.from(`${i + 1} 0 obj\n${obj}\nendobj\n`, 'binary'));
}
}
const xrefStart = byteLen;
let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (let i = 1; i <= objects.length; i++) xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
xref += `trailer\n<< /Size ${objects.length + 1} /Root ${catalogId} 0 R >>\nstartxref\n${xrefStart}\n%%EOF`;
push(Buffer.from(xref, 'binary'));
return Buffer.concat(chunks);
}
module.exports = { buildDocumentPdf, escapePdf, wrap };

50
src/backend/pm_policy.js Normal file
View file

@ -0,0 +1,50 @@
const fs = require('fs');
const ANNOUNCE_SEEN_FILE = 'oasis-political-seen';
const isMutual = (relationship) => !!(relationship && relationship.following && relationship.followsMe);
const isRecipientAllowed = ({ pmVisibility, viewerId, recipientId, relationship } = {}) => {
if (recipientId && viewerId && recipientId === viewerId) return true;
if (pmVisibility !== 'mutuals') return true;
return isMutual(relationship);
};
const announceSeenPath = () => {
try { return require('../server/ssb_config').statePath(ANNOUNCE_SEEN_FILE); } catch (_) { return null; }
};
const readAnnounceSeen = () => {
const file = announceSeenPath();
if (!file) return {};
try {
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (_) { return {}; }
};
const writeAnnounceSeen = (state) => {
const file = announceSeenPath();
if (!file) return false;
try { fs.writeFileSync(file, JSON.stringify(state || {})); return true; } catch (_) { return false; }
};
const everAnnounced = (announced, subject) => {
for (const entry of (announced || [])) {
if (String(entry).startsWith(`${subject}|`)) return true;
}
return false;
};
const decideAnnouncement = ({ subject, ref, announced = new Set(), seen = {} } = {}) => {
if (!subject || !ref) return { send: false, remember: false };
const key = String(ref);
if (announced.has(`${subject}|${key}`)) return { send: false, remember: false };
if (seen[subject] === key) return { send: false, remember: false };
if (!everAnnounced(announced, subject) && seen[subject] === undefined) {
return { send: false, remember: true };
}
return { send: true, remember: true };
};
module.exports = { isRecipientAllowed, isMutual, announceSeenPath, readAnnounceSeen, writeAnnounceSeen, decideAnnouncement };

View file

@ -0,0 +1,139 @@
const i18nBase = require("../client/assets/translations/i18n");
function getI18n() {
try {
const { i18n } = require("../views/main_views");
return i18n;
} catch (_) {
return i18nBase['en'] || {};
}
}
function renderTextPreview(text, maxLength = 220) {
if (!text) return ''
let preview = String(text)
preview = preview
.replace(/```[\s\S]*?```/g, '')
.replace(/^>.*$/gm, '')
.replace(/^#{1,6}\s*/gm, '')
.replace(/^- /gm, '')
.replace(/^\d+\. /gm, '')
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/\*(.*?)\*/g, '$1')
.replace(/`([^`]+)`/g, '$1')
.replace(/!\[.*?\]\(.*?\)/g, '')
.replace(/\[.*?\]\(.*?\)/g, '')
.replace(/\n+/g, ' ')
.trim()
if (preview.length > maxLength) {
preview = preview.slice(0, maxLength) + '...'
}
return preview
}
function renderTextWithStyles(text) {
if (!text) return ''
const i18n = getI18n()
let html = String(text)
html = html
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
html = html
.replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
.replace(/^> (.*)$/gim, '<blockquote>$1</blockquote>')
.replace(/^---$/gim, '<hr/>')
.replace(/^### (.*)$/gim, '<h3>$1</h3>')
.replace(/^## (.*)$/gim, '<h2>$1</h2>')
.replace(/^# (.*)$/gim, '<h1>$1</h1>')
html = html
.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
.replace(/\*(.*?)\*/gim, '<em>$1</em>')
.replace(/`([^`]+)`/gim, '<code>$1</code>')
html = html
.replace(/!\[([^\]]*)\]\(\s*(&amp;[^)\s]+\.sha256)\s*\)/g, (_, alt, blob) =>
`<img src="/blob/${encodeURIComponent(blob.replace(/&amp;/g, '&'))}" alt="${alt}" class="post-image" />`
)
.replace(/\[video:([^\]]*)\]\(\s*(&amp;[^)\s]+\.sha256)\s*\)/g, (_, _name, blob) =>
`<video controls class="post-video" src="/blob/${encodeURIComponent(blob.replace(/&amp;/g, '&'))}"></video>`
)
.replace(/\[audio:([^\]]*)\]\(\s*(&amp;[^)\s]+\.sha256)\s*\)/g, (_, _name, blob) =>
`<audio controls class="post-audio" src="/blob/${encodeURIComponent(blob.replace(/&amp;/g, '&'))}"></audio>`
)
.replace(/\[pdf:([^\]]*)\]\(\s*(&amp;[^)\s]+\.sha256)\s*\)/g, (_, name, blob) =>
`<a class="post-pdf" href="/blob/${encodeURIComponent(blob.replace(/&amp;/g, '&'))}" target="_blank">${name || i18n.pdfFallbackLabel || 'PDF'}</a>`
)
html = html
.replace(/\[@([^\]]+)\]\(@?([A-Za-z0-9+/=.\-]+\.ed25519)\)/g, (_, name, id) =>
`<a href="/author/${encodeURIComponent('@' + id)}" class="mention" target="_blank">@${name}</a>`
)
.replace(/@([A-Za-z0-9+/=.\-]+\.ed25519)/g, (_, id) =>
`<a href="/author/${encodeURIComponent('@' + id)}" class="mention" target="_blank">@${id}</a>`
)
const escAttr = (s) => String(s).replace(/"/g, '&quot;').replace(/'/g, '&#39;')
html = html
.replace(/#(\w+)/g, (_, tag) =>
`<a href="/hashtag/${encodeURIComponent(tag)}" class="styled-link" target="_blank">#${escAttr(tag)}</a>`
)
.replace(/(https?:\/\/[^\s"'<>]+)/g, url =>
`<a href="${escAttr(url)}" target="_blank" class="styled-link">${escAttr(url)}</a>`
)
.replace(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/g, email =>
`<a href="mailto:${escAttr(email)}" class="styled-link">${escAttr(email)}</a>`
)
const lines = html.split('\n')
let result = ''
let inUL = false
let inOL = false
for (let line of lines) {
if (/^- /.test(line)) {
if (!inUL) {
result += '<ul>'
inUL = true
}
result += `<li>${line.replace(/^- /, '')}</li>`
continue
}
if (/^\d+\. /.test(line)) {
if (!inOL) {
result += '<ol>'
inOL = true
}
result += `<li>${line.replace(/^\d+\. /, '')}</li>`
continue
}
if (inUL) {
result += '</ul>'
inUL = false
}
if (inOL) {
result += '</ol>'
inOL = false
}
result += line + '<br>'
}
if (inUL) result += '</ul>'
if (inOL) result += '</ol>'
return result
}
module.exports = { renderTextWithStyles, renderTextPreview }

92
src/backend/renderUrl.js Normal file
View file

@ -0,0 +1,92 @@
const { a, img, video, audio } = require("../server/node_modules/hyperaxe");
const i18nBase = require("../client/assets/translations/i18n");
function getI18n() {
try {
const { i18n } = require("../views/main_views");
return i18n;
} catch (_) {
return i18nBase['en'] || {};
}
}
function renderUrl(text) {
if (typeof text !== 'string') return [text];
const blobImageRegex = /!\[([^\]]*)\]\(\s*(&[^)\s]+\.sha256)\s*\)/g;
const blobVideoRegex = /\[video:([^\]]*)\]\(\s*(&[^)\s]+\.sha256)\s*\)/g;
const blobAudioRegex = /\[audio:([^\]]*)\]\(\s*(&[^)\s]+\.sha256)\s*\)/g;
const blobPdfRegex = /\[pdf:([^\]]*)\]\(\s*(&[^)\s]+\.sha256)\s*\)/g;
const mdMentionRegex = /\[@([^\]]+)\]\(@?([A-Za-z0-9+/=.\-]+\.ed25519)\)/g;
const rawMentionRegex = /@([A-Za-z0-9+/=.\-]+\.ed25519)/g;
const urlRegex = /\b(?:https?:\/\/|www\.)[^\s]+/g;
const emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi;
const allMatches = [];
for (const m of text.matchAll(blobImageRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'blob-image', name: m[1], blob: m[2] });
}
for (const m of text.matchAll(blobVideoRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'blob-video', name: m[1], blob: m[2] });
}
for (const m of text.matchAll(blobAudioRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'blob-audio', name: m[1], blob: m[2] });
}
for (const m of text.matchAll(blobPdfRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'blob-pdf', name: m[1], blob: m[2] });
}
for (const m of text.matchAll(mdMentionRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'md-mention', name: m[1], feedId: m[2] });
}
for (const m of text.matchAll(rawMentionRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'raw-mention', feedId: m[1] });
}
for (const m of text.matchAll(urlRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'url', text: m[0] });
}
for (const m of text.matchAll(emailRegex)) {
allMatches.push({ index: m.index, length: m[0].length, type: 'email', text: m[0] });
}
allMatches.sort((a, b) => a.index - b.index);
const filtered = [];
let lastEnd = 0;
for (const m of allMatches) {
if (m.index < lastEnd) continue;
filtered.push(m);
lastEnd = m.index + m.length;
}
const result = [];
let cursor = 0;
for (const m of filtered) {
if (cursor < m.index) {
result.push(text.slice(cursor, m.index));
}
if (m.type === 'blob-image') {
result.push(img({ src: `/blob/${encodeURIComponent(m.blob)}`, alt: m.name || '', class: 'post-image' }));
} else if (m.type === 'blob-video') {
result.push(video({ controls: true, class: 'post-video', src: `/blob/${encodeURIComponent(m.blob)}` }));
} else if (m.type === 'blob-audio') {
result.push(audio({ controls: true, class: 'post-audio', src: `/blob/${encodeURIComponent(m.blob)}` }));
} else if (m.type === 'blob-pdf') {
const i18n = getI18n();
const label = m.name || i18n.pdfFallbackLabel || 'PDF';
result.push(a({ href: `/blob/${encodeURIComponent(m.blob)}`, class: 'post-pdf', target: '_blank' }, label));
} else if (m.type === 'md-mention') {
const feedWithAt = '@' + m.feedId;
result.push(a({ href: `/author/${encodeURIComponent(feedWithAt)}`, class: 'mention' }, '@' + m.name));
} else if (m.type === 'raw-mention') {
const feedWithAt = '@' + m.feedId;
result.push(a({ href: `/author/${encodeURIComponent(feedWithAt)}`, class: 'mention' }, '@' + m.feedId.slice(0, 8) + '...'));
} else if (m.type === 'url') {
const href = m.text.startsWith('http') ? m.text : `https://${m.text}`;
result.push(a({ href, target: '_blank', rel: 'noopener noreferrer' }, m.text));
} else if (m.type === 'email') {
result.push(a({ href: `mailto:${m.text}` }, m.text));
}
cursor = m.index + m.length;
}
if (cursor < text.length) {
result.push(text.slice(cursor));
}
return result;
}
module.exports = { renderUrl };

View file

@ -0,0 +1,45 @@
"use strict";
const { JSDOM } = require('../server/node_modules/jsdom');
const DOMPurify = require('../server/node_modules/dompurify');
const window = new JSDOM('').window;
const purify = DOMPurify(window);
const stripDangerousTags = (input) => {
if (typeof input !== 'string') return '';
return purify.sanitize(input, {
USE_PROFILES: { html: true },
ALLOWED_TAGS: [
'p', 'br',
'b', 'strong', 'i', 'em', 'u',
'ul', 'ol', 'li',
'blockquote',
'code', 'pre'
],
ALLOWED_ATTR: [],
FORBID_TAGS: ['svg', 'math', 'iframe', 'object', 'embed', 'form', 'input', 'textarea', 'select', 'button', 'script'],
FORBID_ATTR: ['style']
});
};
const sanitizeHtml = (input) => {
if (typeof input !== 'string') return '';
return purify.sanitize(input, {
USE_PROFILES: { html: true },
ALLOWED_TAGS: [
'p', 'br', 'hr',
'b', 'strong', 'i', 'em', 'u', 's', 'del',
'ul', 'ol', 'li',
'blockquote', 'code', 'pre',
'a', 'span', 'div',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'img', 'video', 'audio',
'table', 'thead', 'tbody', 'tr', 'th', 'td'
],
ALLOWED_ATTR: ['href', 'class', 'target', 'rel', 'src', 'alt', 'title', 'controls'],
FORBID_TAGS: ['svg', 'math', 'iframe', 'object', 'embed', 'form', 'input', 'textarea', 'select', 'button', 'script', 'style', 'link', 'meta'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'onsubmit', 'onchange', 'style']
});
};
module.exports = { stripDangerousTags, sanitizeHtml };

View file

@ -0,0 +1,228 @@
const fs = require('fs');
const path = require('path');
const LOGO_PATH = path.join(__dirname, '..', 'client', 'assets', 'images', 'snh-oasis.jpg');
const { escapePdf } = require('./pdfDocument');
const wrap = (txt, max = 82) => {
const out = [];
for (const raw of String(txt || '').split('\n')) {
let line = raw;
while (line.length > max) {
let cut = line.lastIndexOf(' ', max);
if (cut <= 0) cut = max;
out.push(line.slice(0, cut));
line = line.slice(cut).replace(/^\s+/, '');
}
out.push(line);
}
return out;
};
const readJpegDims = (buf) => {
let i = 2;
while (i < buf.length) {
if (buf[i] !== 0xFF) return null;
const marker = buf[i + 1];
if (marker === 0xD8 || marker === 0xD9) { i += 2; continue; }
const len = buf.readUInt16BE(i + 2);
if (marker >= 0xC0 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC) {
const h = buf.readUInt16BE(i + 5);
const w = buf.readUInt16BE(i + 7);
const c = buf[i + 9];
return { w, h, c };
}
i += 2 + len;
}
return null;
};
function buildSmartContractPdf({ transfer, block, viewerId }) {
const pageW = 612;
const pageH = 792;
const marginX = 50;
const headerH = 90;
const footerH = 40;
const bodyTop = pageH - headerH - 24;
const bodyBottom = footerH + 10;
const lineH = 14;
let logoBuf = null;
let logoDims = null;
try {
logoBuf = fs.readFileSync(LOGO_PATH);
logoDims = readJpegDims(logoBuf);
} catch (_) {}
const t = transfer || {};
const b = block || {};
const fmt = v => (v === undefined || v === null) ? '' : String(v);
const fmtAmount = () => {
const cat = String(t.category || 'ECONOMIC').toUpperCase();
const unit = cat === 'TIME' ? 'h' : cat === 'TRUST' ? 'trust' : 'ECO';
return `${Number(t.amount || 0).toFixed(6)} ${unit}`;
};
const fmtDate = v => v ? new Date(v).toISOString().replace('T', ' ').slice(0, 19) + ' UTC' : '';
const confirmedBy = Array.isArray(t.confirmedBy) ? t.confirmedBy : [];
const required = t.from === t.to ? 1 : 2;
const confirmedCount = confirmedBy.length;
const tags = Array.isArray(t.tags) ? t.tags.join(', ') : '';
const sections = [];
sections.push({ kind: 'title', text: `Concept: ${t.concept || '-'}` });
sections.push({ kind: 'blank' });
sections.push({ kind: 'section', text: 'OASIS IDs' });
sections.push({ kind: 'kv', label: 'From', value: fmt(t.from) });
sections.push({ kind: 'kv', label: 'To', value: fmt(t.to) });
sections.push({ kind: 'blank' });
sections.push({ kind: 'section', text: 'TERMS' });
sections.push({ kind: 'kv', label: 'Category', value: String(t.category || 'ECONOMIC').toUpperCase() });
if (String(t.category || '').toUpperCase() !== 'TRUST') sections.push({ kind: 'kv', label: 'Amount', value: fmtAmount() });
sections.push({ kind: 'kv', label: 'Status', value: fmt(t.status) });
if (t.deadline) sections.push({ kind: 'kv', label: 'Deadline', value: fmtDate(t.deadline) });
if (tags) sections.push({ kind: 'kv', label: 'Tags', value: tags });
sections.push({ kind: 'blank' });
sections.push({ kind: 'section', text: 'CONFIRMATIONS' });
sections.push({ kind: 'kv', label: 'Required', value: String(required) });
sections.push({ kind: 'kv', label: 'Confirmed', value: String(confirmedCount) });
if (confirmedBy.length) {
for (const f of confirmedBy) sections.push({ kind: 'kv', label: 'Signed by', value: fmt(f) });
}
sections.push({ kind: 'blank' });
sections.push({ kind: 'section', text: 'BLOCK VERIFICATION' });
if (b && b.id) {
sections.push({ kind: 'kv', label: 'Block ID', value: fmt(b.id) });
if (b.ts) sections.push({ kind: 'kv', label: 'Block Timestamp', value: fmtDate(b.ts) });
if (b.type) sections.push({ kind: 'kv', label: 'Block Type', value: String(b.type).toUpperCase() });
if (b.author) sections.push({ kind: 'kv', label: 'Block Author', value: fmt(b.author) });
if (b.size) sections.push({ kind: 'kv', label: 'Block Size', value: `${b.size} bytes` });
} else {
sections.push({ kind: 'kv', label: 'Block ID', value: fmt(t.id) });
}
sections.push({ kind: 'blank' });
sections.push({ kind: 'section', text: 'METADATA' });
sections.push({ kind: 'kv', label: 'Transfer ID', value: fmt(t.id) });
if (t.createdAt) sections.push({ kind: 'kv', label: 'Created At', value: fmtDate(t.createdAt) });
if (t.updatedAt) sections.push({ kind: 'kv', label: 'Updated At', value: fmtDate(t.updatedAt) });
const lines = [];
for (const s of sections) {
if (s.kind === 'kv') {
const txt = `${s.label}: ${s.value}`;
for (const w of wrap(txt, 82)) lines.push({ kind: 'kv', text: w });
} else {
lines.push(s);
}
}
const maxBodyLines = Math.floor((bodyTop - bodyBottom) / lineH);
const pages = [];
for (let i = 0; i < lines.length; i += maxBodyLines) pages.push(lines.slice(i, i + maxBodyLines));
if (!pages.length) pages.push([]);
const objects = [];
const addObj = body => { objects.push(body); return objects.length; };
const catalogId = addObj(null);
const pagesId = addObj(null);
const fontId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>');
const fontBoldId = addObj('<< /Type /Font /Subtype /Type1 /BaseFont /Courier-Bold /Encoding /WinAnsiEncoding >>');
let logoXObjId = null;
if (logoBuf && logoDims) {
const cs = logoDims.c === 1 ? '/DeviceGray' : '/DeviceRGB';
const dict = `<< /Type /XObject /Subtype /Image /Width ${logoDims.w} /Height ${logoDims.h} /ColorSpace ${cs} /BitsPerComponent 8 /Filter /DCTDecode /Length ${logoBuf.length} >>`;
logoXObjId = addObj({ dict, stream: logoBuf });
}
const exportDate = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
const footerLeft = `Generated: ${exportDate}`;
const pageIds = [];
const contentIds = [];
pages.forEach((pg, pgIdx) => {
const parts = [];
if (logoXObjId) {
const logoH = 60;
const logoW = Math.round((logoDims.w / logoDims.h) * logoH);
parts.push(`q\n${logoW} 0 0 ${logoH} ${marginX} ${pageH - headerH + 15} cm\n/Logo Do\nQ`);
}
const titleX = (logoXObjId ? marginX + 80 : marginX);
const titleY = pageH - 45;
parts.push(`BT\n/F2 16 Tf\n${titleX} ${titleY} Td\n(${escapePdf('OASIS - Smart Contract')}) Tj\nET`);
const prefix = 'Issued to: ';
const prefixW = prefix.length * 5.4;
parts.push(`BT\n/F1 9 Tf\n${titleX} ${titleY - 16} Td\n(${escapePdf(prefix)}) Tj\nET`);
parts.push(`BT\n/F2 9 Tf\n${titleX + prefixW} ${titleY - 16} Td\n(${escapePdf(String(viewerId || ''))}) Tj\nET`);
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${pageH - headerH} m\n${pageW - marginX} ${pageH - headerH} l\nS\nQ`);
let y = bodyTop;
for (const ln of pg) {
if (ln.kind === 'title') {
parts.push(`BT\n/F2 14 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
} else if (ln.kind === 'subtitle') {
parts.push(`BT\n/F1 11 Tf\n0.2 0.2 0.2 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
} else if (ln.kind === 'section') {
parts.push(`BT\n/F2 11 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
parts.push(`q\n0 0 0 RG\n0.5 w\n${marginX} ${y - 3} m\n${pageW - marginX} ${y - 3} l\nS\nQ`);
} else if (ln.kind === 'kv') {
parts.push(`BT\n/F1 10 Tf\n0 0 0 rg\n${marginX} ${y} Td\n(${escapePdf(ln.text)}) Tj\nET`);
}
y -= lineH;
}
parts.push(`q\n0.6 0.6 0.6 RG\n0.5 w\n${marginX} ${footerH + 5} m\n${pageW - marginX} ${footerH + 5} l\nS\nQ`);
parts.push(`BT\n/F1 8 Tf\n${marginX} ${footerH - 10} Td\n(${escapePdf(footerLeft)}) Tj\nET`);
const pageLabel = `Page ${pgIdx + 1} of ${pages.length}`;
const pageLabelW = pageLabel.length * 4.8;
parts.push(`BT\n/F1 8 Tf\n${pageW - marginX - pageLabelW} ${footerH - 10} Td\n(${escapePdf(pageLabel)}) Tj\nET`);
const content = parts.join('\n');
const stream = `<< /Length ${Buffer.byteLength(content, 'latin1')} >>\nstream\n${content}\nendstream`;
const cid = addObj(stream);
contentIds.push(cid);
const pid = addObj(null);
pageIds.push(pid);
});
for (let i = 0; i < pageIds.length; i++) {
const resources = logoXObjId
? `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> /XObject << /Logo ${logoXObjId} 0 R >> >>`
: `<< /Font << /F1 ${fontId} 0 R /F2 ${fontBoldId} 0 R >> >>`;
objects[pageIds[i] - 1] = `<< /Type /Page /Parent ${pagesId} 0 R /MediaBox [0 0 ${pageW} ${pageH}] /Contents ${contentIds[i]} 0 R /Resources ${resources} >>`;
}
objects[catalogId - 1] = `<< /Type /Catalog /Pages ${pagesId} 0 R >>`;
objects[pagesId - 1] = `<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(' ')}] /Count ${pageIds.length} >>`;
const chunks = [];
const offsets = [0];
let byteLen = 0;
const push = (buf) => { chunks.push(buf); byteLen += buf.length; };
push(Buffer.from('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n', 'binary'));
for (let i = 0; i < objects.length; i++) {
offsets.push(byteLen);
const obj = objects[i];
if (obj && typeof obj === 'object' && obj.dict && obj.stream) {
push(Buffer.from(`${i + 1} 0 obj\n${obj.dict}\nstream\n`, 'binary'));
push(obj.stream);
push(Buffer.from('\nendstream\nendobj\n', 'binary'));
} else {
push(Buffer.from(`${i + 1} 0 obj\n${obj}\nendobj\n`, 'binary'));
}
}
const xrefStart = byteLen;
let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (let i = 1; i <= objects.length; i++) xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
xref += `trailer\n<< /Size ${objects.length + 1} /Root ${catalogId} 0 R >>\nstartxref\n${xrefStart}\n%%EOF`;
push(Buffer.from(xref, 'binary'));
return Buffer.concat(chunks);
}
module.exports = { buildSmartContractPdf };

View file

@ -0,0 +1,50 @@
"use strict";
// Credenciales efimeras para un TURN propio (coturn con use-auth-secret).
//
// Es el mecanismo REST de coturn: el servidor no guarda usuarios, valida que
// credential == base64(HMAC-SHA1(static-auth-secret, username))
// y que el timestamp del username no haya caducado. Asi las credenciales se
// generan sin hablar con coturn y caducan solas.
//
// Portado del turn.js de karvan-web, cambiando sessionId por el feed id: lo que
// identifica a quien llama en Oasis es su feed, no una sesion anonima.
const crypto = require("crypto");
const DEFAULT_TTL = 3600;
// username = <caduca en unix> ":" <identificador>
function mintTurnCredentials({ urls, secret, ttlSec = DEFAULT_TTL }, who, now = Date.now()) {
if (!secret || !Array.isArray(urls) || !urls.length) return null;
const expiry = Math.floor(now / 1000) + ttlSec;
const username = expiry + ":" + String(who || "anon").slice(0, 64);
const credential = crypto.createHmac("sha1", secret).update(username).digest("base64");
return { urls, username, credential, ttl: ttlSec, expiry };
}
// Lee la configuracion de rtc y devuelve lo que el navegador espera en iceServers.
// Formas admitidas en oasis-config.json:
// "rtc": { "stun": ["stun:mi.pub:3478"] }
// "rtc": { "turn": { "urls": [...], "secret": "...", "ttlSec": 3600 }, "relayOnly": true }
// "rtc": { "turn": { "urls": [...], "username": "...", "credential": "..." } } (estatico)
function buildIceServers(rtc, who, now = Date.now()) {
const out = [];
if (!rtc || typeof rtc !== "object") return { iceServers: out, relayOnly: false };
if (Array.isArray(rtc.stun)) {
for (const u of rtc.stun) if (typeof u === "string" && u) out.push({ urls: u });
}
const t = rtc.turn;
if (t && Array.isArray(t.urls) && t.urls.length) {
if (t.secret) {
const c = mintTurnCredentials(t, who, now);
if (c) out.push({ urls: c.urls, username: c.username, credential: c.credential });
} else if (t.username && t.credential) {
out.push({ urls: t.urls, username: t.username, credential: t.credential });
}
}
return { iceServers: out, relayOnly: !!rtc.relayOnly && out.some(s => s.credential) };
}
module.exports = { mintTurnCredentials, buildIceServers };

121
src/backend/updater.js Normal file
View file

@ -0,0 +1,121 @@
const fetch = require('../server/node_modules/node-fetch');
const { existsSync, readFileSync, writeFileSync, unlinkSync } = require('fs');
const { join } = require('path');
const localpackage = join(__dirname, '../server/package.json');
const remoteUrl = 'https://code.03c8.net/KrakensLab/oasis/raw/master/src/server/package.json'; // Official SNH-Oasis
const remoteUrl2 = 'https://raw.githubusercontent.com/epsylon/oasis/refs/heads/main/src/server/package.json'; // Mirror SNH-Oasis
let printed = false;
async function extractVersionFromText(text) {
try {
const versionMatch = text.match(/"version":\s*"([^"]+)"/);
if (versionMatch) {
return versionMatch[1];
} else {
throw new Error('Version not found in the response.');
}
} catch (error) {
console.error("Error extracting version:", error.message);
return null;
}
}
async function diffVersion(body, callback) {
try {
const remoteData = JSON.parse(body);
const remoteVersion = remoteData.version;
const localData = JSON.parse(readFileSync(localpackage, 'utf8'));
const localVersion = localData.version;
const updateFlagPath = join(__dirname, "../server/.update_required");
if (remoteVersion !== localVersion) {
writeFileSync(updateFlagPath, JSON.stringify({ required: true }));
callback("required");
} else {
if (existsSync(updateFlagPath)) unlinkSync(updateFlagPath);
callback(""); // no updates required
}
} catch (error) {
console.error("Error comparing versions:", error.message);
callback("error");
}
}
async function checkMirror(callback) {
try {
const response = await fetch(remoteUrl2, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Referer': 'https://raw.githubusercontent.com',
'Origin': 'https://raw.githubusercontent.com'
}
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.text();
callback(null, data);
} catch (error) {
console.error("\noasis@version: no updates requested.\n");
callback(error);
}
}
exports.getRemoteVersion = async () => {
if (existsSync('../../.git')) {
try {
const response = await fetch(remoteUrl, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Referer': 'https://code.03c8.net',
'Origin': 'https://code.03c8.net'
}
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.text();
diffVersion(data, (status) => {
if (status === "required" && !printed) {
printed = true;
console.log("\noasis@version: new code updates are available!\n\n1) Run Oasis and go to 'Settings' tab\n2) Click at 'Get updates' button to download latest code\n3) Restart Oasis when finished\n");
} else if (status === "") {
console.log("\noasis@version: no updates requested.\n");
}
});
} catch (error) {
checkMirror((err, data) => {
if (err) {
console.error("\noasis@version: no updates requested.\n");
} else {
diffVersion(data, (status) => {
if (status === "required" && !printed) {
printed = true;
console.log("\noasis@version: new code updates are available!\n\n1) Run Oasis and go to 'Settings' tab\n2) Click at 'Get updates' button to download latest code\n3) Restart Oasis when finished\n");
} else {
console.log("oasis@version: no updates requested.\n");
}
});
}
});
}
}
};

116
src/backend/vote_tally.js Normal file
View file

@ -0,0 +1,116 @@
const buildVoteTally = (messages) => {
const nodes = new Map();
const ballots = [];
for (const m of messages) {
const v = m && m.value;
const c = v && v.content;
if (!c) continue;
if (c.type === 'votesVote') { if (c.target) ballots.push({ target: c.target, author: v.author, choice: c.choice }); continue; }
if (c.type !== 'votes') continue;
nodes.set(m.key, { key: m.key, author: v.author, content: c, ts: v.timestamp || m.timestamp || 0 });
}
const prev = new Map();
for (const [k, n] of nodes) {
const t = n.content.replaces;
if (typeof t === 'string' && nodes.has(t)) prev.set(k, t);
}
const childrenOf = new Map();
for (const [k, p] of prev) {
if (!childrenOf.has(p)) childrenOf.set(p, []);
childrenOf.get(p).push(k);
}
const rootOf = (k) => { let x = k, g = 0; while (prev.has(x) && g++ < 100000) x = prev.get(x); return x; };
const groups = new Map();
for (const k of nodes.keys()) { const r = rootOf(k); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(k); }
const tallyByKey = new Map();
for (const [root, keys] of groups.entries()) {
const rootNode = nodes.get(root);
if (!rootNode) continue;
const options = Array.isArray(rootNode.content.options) ? rootNode.content.options : [];
let votesMap = Object.assign({}, rootNode.content.votes || {});
let voters = Array.isArray(rootNode.content.voters) ? rootNode.content.voters.slice() : [];
for (const o of options) if (!(o in votesMap)) votesMap[o] = 0;
let cur = root;
let g = 0;
let creatorChoice = null;
let creatorCounted = false;
while (g++ < 100000) {
const kids = (childrenOf.get(cur) || []).map(k => nodes.get(k)).filter(Boolean).sort((a, b) => a.ts - b.ts);
if (!kids.length) break;
let advanced = false;
for (const kid of kids) {
const kVotes = Object.assign({}, kid.content.votes || {});
const kVoters = Array.isArray(kid.content.voters) ? kid.content.voters.slice() : [];
for (const o of options) if (!(o in kVotes)) kVotes[o] = 0;
if (kid.author === rootNode.author) {
if (!creatorCounted && kVoters.includes(rootNode.author) && !voters.includes(rootNode.author)) {
creatorCounted = true;
let inc = null;
let incCount = 0;
for (const o of options) {
const d = (Number(kVotes[o]) || 0) - (Number(votesMap[o]) || 0);
if (d >= 1) { inc = o; incCount++; }
}
if (incCount === 1) creatorChoice = inc;
}
votesMap = kVotes;
voters = kVoters;
cur = kid.key;
advanced = true;
break;
}
if (voters.includes(kid.author)) continue;
if (kVoters.length !== voters.length + 1) continue;
const added = kVoters.filter(x => !voters.includes(x));
if (added.length !== 1 || added[0] !== kid.author) continue;
let deltas = 0;
let deltaOk = true;
for (const o of options) {
const d = (Number(kVotes[o]) || 0) - (Number(votesMap[o]) || 0);
if (d === 0) continue;
if (d === 1) { deltas++; continue; }
deltaOk = false;
break;
}
if (!deltaOk || deltas !== 1) continue;
votesMap = kVotes;
voters = kVoters;
cur = kid.key;
advanced = true;
break;
}
if (!advanced) break;
}
if (voters.includes(rootNode.author)) {
voters = voters.filter(x => x !== rootNode.author);
if (creatorChoice && (Number(votesMap[creatorChoice]) || 0) > 0) votesMap[creatorChoice] = votesMap[creatorChoice] - 1;
}
const voterSet = new Set(voters);
let totalVotes = voters.length;
const chainKeys = new Set(keys);
for (const b of ballots) {
if (!chainKeys.has(b.target)) continue;
if (b.author === rootNode.author) continue;
if (!b.author || voterSet.has(b.author)) continue;
if (!options.includes(b.choice)) continue;
voterSet.add(b.author);
voters.push(b.author);
votesMap[b.choice] = (votesMap[b.choice] || 0) + 1;
totalVotes += 1;
}
const tally = { votes: votesMap, voters, totalVotes };
for (const k of keys) tallyByKey.set(k, tally);
}
return tallyByKey;
};
module.exports = { buildVoteTally };

View file

@ -0,0 +1,17 @@
const fs = require("fs");
const path = require("path");
const STORAGE_DIR = path.join(__dirname, "..", "configs");
const ADDR_PATH = path.join(STORAGE_DIR, "wallet-addresses.json");
function ensure() {
if (!fs.existsSync(STORAGE_DIR)) fs.mkdirSync(STORAGE_DIR, { recursive: true });
if (!fs.existsSync(ADDR_PATH)) fs.writeFileSync(ADDR_PATH, "{}");
}
function readAll() { ensure(); return JSON.parse(fs.readFileSync(ADDR_PATH, "utf8")); }
function writeAll(m) { fs.writeFileSync(ADDR_PATH, JSON.stringify(m, null, 2)); }
async function getAddress(userId) { const m = readAll(); return m[userId] || null; }
async function setAddress(userId, address) { const m = readAll(); m[userId] = address; writeAll(m); return true; }
module.exports = { getAddress, setAddress };

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View file

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<title>oasis favicon</title>
<text x="0" y="14">🏝️</text>
</svg>

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

View file

@ -0,0 +1,92 @@
{
"academia": {
"name": "ACADEMIA",
"short": "aca",
"motto": "Nosce te ipsum…",
"roles": "Educators, teachers, coordinators",
"function": "Education, understanding, talent discovery, selection process",
"description": "All inhabitants start here. ACADEMIA receives newcomers, provides information on the simulation mechanics, presents each house's objectives and runs the selection process.",
"month": 1,
"image": "/assets/larp/images/academia.jpg"
},
"solaris": {
"name": "SolarIS",
"short": "sol",
"motto": "The word makes us human. Violence, beasts.",
"roles": "Rulers, lawyers, diplomats",
"function": "Governance, law, dialogue, politics, communication",
"description": "Holds the political voice. Mediates disputes, drafts norms, builds coalitions through dialogue and persuasion.",
"month": 2,
"image": "/assets/larp/images/solaris.jpg"
},
"arrakis": {
"name": "ARRakis",
"short": "arr",
"motto": "How long do you say that it must be resolved?",
"roles": "Engineers, scientists, technicians",
"function": "Technology, invention, problem-solving, building and maintaining",
"description": "The makers. They keep the machinery running, prototype, repair, automate; favour pragmatic solutions over endless debate.",
"month": 3,
"image": "/assets/larp/images/arrakis.jpg"
},
"terraverde": {
"name": "TERRA.VErDE",
"short": "ter",
"motto": "Love nature, universe and being, because we are all one.",
"roles": "Farmers, ecologists, doctors, nutritionists",
"function": "Healthcare, food, nature, resources, climate management",
"description": "Stewards of the living systems. Manage food, health and the relationship with the biosphere; long timescales, regenerative principles.",
"month": 4,
"image": "/assets/larp/images/terraverde.jpg"
},
"unsystem": {
"name": "UNSYSTem",
"short": "uns",
"motto": "We do not make statements!",
"roles": "Chaos agents, trolls, punks",
"function": "Organization of disorder, tactical chaos",
"description": "Holds the right to question, sabotage, provoke. Resists capture by any other house and keeps the system uncomfortable.",
"month": 5,
"image": "/assets/larp/images/unsystem.jpg"
},
"dogma": {
"name": "DogmA",
"short": "dog",
"motto": "The question is not when to do it, the question is how.",
"roles": "Thinkers, journalists, philosophers",
"function": "Information control, knowledge, philosophy, memory, AI",
"description": "The archive and the discourse. Curates knowledge, drafts narratives, governs how information is produced and propagated.",
"month": 6,
"image": "/assets/larp/images/dogma.jpg"
},
"helix": {
"name": "HeliX",
"short": "hlx",
"motto": "If you do not smile, it's not my revolution.",
"roles": "Clowns, influencers, musicians, priests",
"function": "Entertainment, culture, humor, celebration, human relationships",
"description": "Carries culture, ritual and joy. Holds the social fabric together through art, festival and shared emotion.",
"month": 7,
"image": "/assets/larp/images/helix.jpg"
},
"quark": {
"name": "QuarK",
"short": "quk",
"motto": "Without security, there is no freedom!",
"roles": "Athletes, soldiers, street people",
"function": "Protection, security, defense, survival, family",
"description": "The guard. Trains, defends, organises mutual aid; demands clear loyalties and clear lines.",
"month": 8,
"image": "/assets/larp/images/quark.jpg"
},
"hermandad": {
"name": "HERmanDAD",
"short": "hrm",
"motto": "Grow. Build. Expand!",
"roles": "Architects, builders, investors, industrialists",
"function": "Construction, development, sustainability, logistics, production",
"description": "The builders. Plan large works, organise production lines and supply chains; measure success in things shipped and capacity created.",
"month": 9,
"image": "/assets/larp/images/hermandad.jpg"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -0,0 +1,67 @@
.hljs-comment,
.hljs-quote {
color: var(--base03);
}
.hljs-variable,
.hljs-template-variable,
.hljs-tag,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class,
.hljs-regexp,
.hljs-deletion {
color: var(--base08);
}
.hljs-number,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params,
.hljs-meta,
.hljs-link {
color: var(--base09);
}
.hljs-attribute {
color: var(--base0A);
}
.hljs-string,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: var(--base0B);
}
.hljs-title,
.hljs-section {
color: var(--base0D);
}
.hljs-keyword,
.hljs-selector-tag {
color: var(--base0E);
}
.hljs {
display: block;
overflow-x: auto;
color: var(--base05);
padding: 0.5em;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
.hljs-string, .hljs-link {
background: #FFA500;
user-select: text;
}

View file

@ -0,0 +1,88 @@
/* Estilos del modulo Karvan (salas efimeras y llamadas).
*
* Viven aparte del tema para que el modulo se vea igual en cualquier tema y
* tambien en escritorio, donde OasisMobile.css no se carga. Mismo patron que
* highlight.css, que tampoco pertenece a ningun tema concreto.
*/
/* --- Reply a mensaje en chats (server-side ?replyTo=, sin JS) --- */
.chat-message-meta .chat-reply-btn { margin-left: auto; padding: 0 4px; color: #FFD700; text-decoration: none; font-size: 15px; opacity: .85; }
.chat-message-self .chat-message-meta .chat-reply-btn { margin-left: 8px; }
.chat-quote {
display: block; border-left: 3px solid #FFD700; padding: 3px 8px; margin: 0 0 5px;
background: rgba(255,215,0,.08); border-radius: 6px; font-size: 12px; line-height: 1.3;
}
.chat-quote-author, .chat-quote-author a { color: #FFD700; font-weight: 700; margin-right: 6px; }
.chat-quote-text { color: #FFDD44; }
.chat-replying-to {
display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
border-left: 3px solid #FFD700; background: rgba(255,215,0,.10);
padding: 6px 10px; margin-bottom: 8px; border-radius: 8px; font-size: 12px;
}
.chat-replying-label { color: #FFD700; font-weight: 700; }
.chat-reply-cancel { margin-left: auto; color: #FFD700; text-decoration: none; font-weight: 700; font-size: 14px; }
/* ==========================================================================
FORK_IA_UX · Módulo KARVAN (mensajes temporales + WebRTC) chat estilo burbujas
========================================================================== */
.karvan-intro h2 { color: #FFD700; margin: 0 0 6px; }
.karvan-sub { color: #FFDD44; font-size: 13px; }
.karvan-create input[type="text"] { width: 100%; box-sizing: border-box; padding: 10px 12px;
background: #161616; border: 1px solid #333; border-radius: 10px; color: #FFD700; }
.karvan-ttl { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin: 10px 0; }
.karvan-ttl-lbl { color: #FFDD44; font-size: 13px; }
.karvan-ttl-opt { display: inline-flex; align-items: center; gap: 4px; color: #FFD700; font-size: 13px; }
.karvan-create button, .karvan-compose button { padding: 10px 16px; border: 1px solid #FFD700;
border-radius: 10px; background: #FFD700; color: #121212; font-weight: 700; cursor: pointer; }
.karvan-rooms { list-style: none; margin: 8px 0 0; padding: 0; }
.karvan-rooms li { margin: 0 0 8px; }
.karvan-room-item { display: flex; justify-content: space-between; align-items: center; gap: 10px;
padding: 12px 14px; background: #161616; border: 1px solid #333; border-radius: 12px;
color: #FFD700; text-decoration: none; min-height: 48px; box-sizing: border-box; }
.karvan-room-item .kr-title { font-weight: 600; }
.karvan-room-item .kr-meta { color: #FFDD44; font-size: 12px; white-space: nowrap; }
.karvan-empty { color: #FFDD44; }
/* sala */
.karvan-room-head { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
.karvan-back { color: #FFD700; text-decoration: none; font-weight: 600; }
.karvan-room-title { flex: 1 1 auto; color: #FFD700; font-weight: 700; text-align: center;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.karvan-expire { color: #FFDD44; font-size: 12px; white-space: nowrap; }
.karvan-live { display: inline-flex; align-items: center; gap: 6px; color: #FFDD44; font-size: 12px; margin-bottom: 8px; }
.karvan-live .kl-dot { width: 8px; height: 8px; border-radius: 50%; background: #777; }
.karvan-live.on .kl-dot { background: #35d07f; }
.karvan-live.on .kl-txt { color: #35d07f; }
.karvan-msgs { list-style: none; margin: 0; padding: 6px 0; display: flex; flex-direction: column; gap: 6px;
max-height: 58vh; overflow-y: auto; }
.karvan-msg { max-width: 82%; align-self: flex-start; background: #1c1c1c; border: 1px solid #333;
border-radius: 14px; padding: 7px 11px; box-sizing: border-box; }
.karvan-msg-self { align-self: flex-end; background: #2a2412; border-color: #FFD700; }
.karvan-msg-live { border-left: 2px solid #35d07f; }
.karvan-msg .km-from { display: block; font-size: 10px; color: #FFDD44; margin-bottom: 2px; }
.karvan-msg .km-text { color: #FFD700; word-break: break-word; }
.karvan-compose { display: flex; gap: 8px; margin-top: 10px; }
.karvan-compose input[type="text"] { flex: 1 1 auto; min-width: 0; padding: 10px 12px;
background: #161616; border: 1px solid #333; border-radius: 10px; color: #FFD700; }
/* Fase 2: invitar a un contacto por feed id */
.karvan-invite { display: flex; gap: 8px; margin-top: 8px; }
.karvan-invite input[type="text"] { flex: 1 1 auto; min-width: 0; padding: 9px 12px;
background: #161616; border: 1px solid #333; border-radius: 10px; color: #FFD700; font-family: monospace; font-size: 12px; }
.karvan-invite button { flex: 0 0 auto; padding: 9px 14px; border: 1px solid #FFD700; background: #161616; color: #FFD700; border-radius: 10px; cursor: pointer; }
.karvan-invite-msg { font-size: 12px; margin: 6px 0 0; }
.karvan-invite-msg.ok { color: #35d07f; }
.karvan-invite-msg.err { color: #ff8a8a; }
/* --- Karvan videollamada (Fase 1): media P2P sobre el mismo WebRTC del chat --- */
.karvan-call, .karvan-videos, .karvan-call-bar, .kc-status {
background-color: transparent; box-shadow: none; border-radius: 0; padding: 0; margin: 0; /* anular div{#222}
.karvan-call { margin: 10px 0; }
.karvan-videos { display: none; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 6px; margin-bottom: 8px; }
.karvan-call.active .karvan-videos { display: grid; }
.kc-video { width: 100%; aspect-ratio: 4 / 3; background: #000; border-radius: 10px; border: 1px solid #333; object-fit: cover; display: block; }
.kc-local { transform: scaleX(-1); }
.kc-remote { display: contents; }
.karvan-call-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.kc-btn { min-height: 44px; min-width: 44px; padding: 8px 12px; border-radius: 999px;
border: 1px solid #333; background: #161616; color: #FFD700; line-height: 1; cursor: pointer; }
.kc-btn.on { background: #FFD700; color: #121212; border-color: #FFD700; }
.kc-btn-start { font-weight: 600; }
.kc-btn-stop { background: #241414; border-color: #5a2a2a; }
.kc-status { font-size: 12px; color: #FFDD44; margin-top: 6px; min-height: 14px; }

View file

@ -0,0 +1,944 @@
html {
-webkit-text-size-adjust: 100%;
box-sizing: border-box;
overflow-x: hidden !important;
}
*, *::before, *::after {
box-sizing: inherit;
}
body {
font-size: 15px;
overflow-x: hidden;
max-width: 100vw;
}
img,
video,
canvas,
iframe,
table {
max-width: 100% !important;
}
pre,
code {
white-space: pre-wrap !important;
word-break: break-word !important;
overflow-wrap: anywhere !important;
}
.header {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
padding: 4px !important;
gap: 4px !important;
overflow: visible !important;
}
.header-content {
display: flex !important;
flex-wrap: wrap !important;
width: 100% !important;
max-width: 100% !important;
padding: 2px !important;
gap: 4px !important;
overflow: visible !important;
}
.top-bar-left,
.top-bar-mid,
.top-bar-right {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
align-items: stretch !important;
gap: 6px !important;
}
.top-bar-left nav ul,
.top-bar-mid nav ul,
.top-bar-right nav ul {
display: flex !important;
flex-wrap: wrap !important;
gap: 6px !important;
padding: 0 !important;
margin: 0 !important;
overflow: visible !important;
}
.top-bar-left nav ul li,
.top-bar-mid nav ul li,
.top-bar-right nav ul li {
margin: 0 !important;
}
.top-bar-left nav ul li a,
.top-bar-mid nav ul li a,
.top-bar-right nav ul li a {
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
padding: 6px 8px !important;
font-size: 0.9rem !important;
white-space: nowrap !important;
}
.search-input,
.activity-search-input {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
height: 40px !important;
font-size: 16px !important;
}
.main-content {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
gap: 12px !important;
}
.sidebar-left,
.sidebar-right,
.main-column {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
padding: 10px !important;
border-left: none !important;
border-right: none !important;
}
.sidebar-left {
order: 1 !important;
}
.main-column {
order: 3 !important;
}
.sidebar-right {
order: 2 !important;
}
.sidebar-left nav ul,
.sidebar-right nav ul {
display: flex !important;
flex-direction: column !important;
}
.oasis-nav-header {
font-size: 0.85rem !important;
}
.oasis-nav-list li a {
font-size: 0.9rem !important;
padding: 8px 12px !important;
}
button,
input[type="submit"],
input[type="button"],
.filter-btn,
.create-button,
.edit-btn,
.delete-btn,
.join-btn,
.leave-btn,
.buy-btn {
min-height: 44px !important;
font-size: 16px !important;
white-space: normal !important;
text-align: center !important;
}
.feed-row,
.comment-body-row,
table {
display: block !important;
width: 100% !important;
overflow-x: auto !important;
}
textarea,
input:not([type="checkbox"]):not([type="radio"]),
select {
width: 100% !important;
max-width: 100% !important;
font-size: 16px !important;
}
input[type="checkbox"]:not(.oasis-nav-toggle):not(.oasis-nav-side-toggle),
input[type="radio"] {
width: auto !important;
max-width: none !important;
flex: none !important;
}
.gallery {
display: grid !important;
grid-template-columns: 1fr 1fr !important;
gap: 8px !important;
}
footer,
.footer {
display: block !important;
width: 100% !important;
max-width: 100% !important;
padding: 12px !important;
overflow-x: auto !important;
}
footer div {
display: flex !important;
flex-direction: column !important;
gap: 8px !important;
}
h1 { font-size: 1.35em !important; }
h2 { font-size: 1.2em !important; }
h3 { font-size: 1em !important; }
.small,
.time {
font-size: 0.8rem !important;
}
.created-at {
display: block !important;
width: 100% !important;
white-space: normal !important;
word-break: break-word !important;
overflow-wrap: anywhere !important;
line-height: 1.5 !important;
font-size: 0.8rem !important;
}
.header-content .created-at {
display: block !important;
flex: 1 1 100% !important;
min-width: 0 !important;
max-width: 100% !important;
}
.post-meta,
.feed-post-meta,
.feed-row .small,
.feed-row .time,
.feed-row .created-at {
display: block !important;
width: 100% !important;
white-space: normal !important;
word-break: break-word !important;
overflow-wrap: anywhere !important;
line-height: 1.4 !important;
}
.post-meta,
.feed-post-meta {
flex-direction: column !important;
gap: 4px !important;
}
.mode-buttons,
.mode-buttons-cols,
.mode-buttons-row,
.filter-group,
.activity-filter-grid,
.activity-sub-filter,
.filters .ui-toolbar,
.filter-group,
.inhabitant-action,
.mode-buttons {
display: flex !important;
flex-direction: row !important;
flex-wrap: wrap !important;
justify-content: center !important;
align-items: center !important;
width: 100% !important;
max-width: 100% !important;
gap: 6px !important;
overflow-x: hidden !important;
scroll-snap-type: none !important;
grid-template-columns: none !important;
}
.mode-buttons .column,
.mode-buttons > div,
.activity-filter-col {
display: contents !important;
}
.mode-buttons form,
.filter-group form,
.inhabitant-action form,
.activity-filter-col form {
width: auto !important;
flex: 0 1 auto !important;
scroll-snap-align: none !important;
margin: 0 !important;
}
.inhabitant-action .filter-btn {
min-height: 0 !important;
padding: 7px 12px !important;
font-size: 13px !important;
white-space: nowrap !important;
}
.profile-sensors-box {
display: flex !important;
flex-direction: column !important;
align-items: flex-start !important;
gap: 6px !important;
width: 100% !important;
max-width: 100% !important;
}
.profile-sensors-box > * {
max-width: 100% !important;
word-break: break-word !important;
overflow-wrap: anywhere !important;
}
.inhabitant-activity-group {
display: flex !important;
flex-wrap: wrap !important;
gap: 6px !important;
}
.activity-filter-grid .filter-btn,
.activity-filter-col .filter-btn,
.activity-sub-filter .filter-btn {
min-height: 0 !important;
padding: 7px 12px !important;
font-size: 13px !important;
white-space: nowrap !important;
}
.mode-buttons .filter-btn,
.mode-buttons button,
.filter-group .filter-btn,
.filter-group button,
.activity-filter-grid .filter-btn,
.activity-filter-grid button,
.activity-sub-filter .filter-btn,
.filters .filter-btn,
.filters button {
width: auto !important;
flex: 0 0 auto !important;
white-space: nowrap !important;
min-width: 0 !important;
}
.inhabitant-card {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
overflow: visible !important;
}
.inhabitant-left {
width: 100% !important;
text-align: center !important;
flex: 0 0 auto !important;
height: auto !important;
}
.inhabitant-details {
width: 100% !important;
}
.inhabitant-left > a:first-of-type,
.inhabitant-left > a:first-child {
display: inline-block !important;
width: 150px !important;
height: 150px !important;
max-width: 150px !important;
margin: 0 auto 12px !important;
}
.inhabitant-photo,
.inhabitant-photo-details {
width: 150px !important;
height: 150px !important;
max-width: 150px !important;
object-fit: cover !important;
border-radius: 50% !important;
display: block !important;
margin: 0 auto !important;
}
.inhabitants-list,
.inhabitants-grid {
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
}
.tribe-card {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
overflow: hidden !important;
}
.tribe-grid {
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
grid-template-columns: 1fr !important;
}
.tribes-list,
.tribes-grid {
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
}
.tribe-card-image {
width: 100% !important;
max-width: 100% !important;
}
.tribe-section-nav {
display: flex !important;
flex-wrap: wrap !important;
justify-content: center !important;
align-items: center !important;
gap: 6px !important;
overflow-x: visible !important;
width: 100% !important;
max-width: 100% !important;
}
.tribe-section-group {
display: contents !important;
}
.tribe-section-btn {
font-size: 12px !important;
padding: 7px 12px !important;
white-space: nowrap !important;
flex: 0 0 auto !important;
}
.tribe-details {
flex-direction: column !important;
}
.tribe-side {
width: 100% !important;
}
.tribe-main {
width: 100% !important;
}
.tribe-content-grid {
grid-template-columns: 1fr !important;
}
.tribe-inhabitants-grid {
grid-template-columns: repeat(2, 1fr) !important;
}
.tribe-media-grid {
grid-template-columns: repeat(2, 1fr) !important;
}
.tribe-overview-grid {
grid-template-columns: 1fr !important;
}
.tribe-mode-buttons {
flex-wrap: wrap !important;
}
.tribe-card-hero-image {
height: 180px !important;
}
.tribe-votation-option {
flex-direction: column !important;
align-items: flex-start !important;
}
.tribe-content-header {
flex-direction: column !important;
gap: 8px !important;
}
.tribe-content-filters {
flex-wrap: wrap !important;
}
.tribe-media-filters {
flex-wrap: wrap !important;
}
.forum-card {
flex-direction: column !important;
}
.forum-score-col,
.forum-main-col,
.root-vote-col {
width: 100% !important;
}
.forum-header-row {
flex-direction: column !important;
gap: 4px !important;
}
.forum-meta {
flex-wrap: wrap !important;
gap: 8px !important;
}
.forum-thread-header {
flex-direction: column !important;
}
.forum-comment {
margin-left: 0;
padding-left: 8px;
}
.comment-body-row {
flex-direction: column;
}
.comment-vote-col,
.comment-text-col {
width: 100%;
}
.forum-score-box,
.forum-score-form {
flex-direction: row;
justify-content: center;
}
.new-message-form textarea,
.comment-textarea {
width: 100%;
}
[style*="grid-template-columns: repeat(6"] {
grid-template-columns: 1fr !important;
}
[style*="grid-template-columns: repeat(3"] {
grid-template-columns: 1fr !important;
}
[style*="grid-template-columns:repeat(6"] {
grid-template-columns: 1fr !important;
}
[style*="grid-template-columns:repeat(3"] {
grid-template-columns: 1fr !important;
}
[style*="grid-template-columns: repeat(auto-fit"] {
grid-template-columns: 1fr !important;
}
[style*="grid-template-columns:repeat(auto-fit"] {
grid-template-columns: 1fr !important;
}
[style*="width:50%"] {
width: 100% !important;
}
.inhabitant-karma-ubi .ubi-line{display:block;font-size:0.9em}
.pad-editor-container{flex-direction:column !important}
.pad-editor-area,.pad-members-list{width:100% !important;min-width:unset !important}
.chat-main-split{flex-direction:column !important}
.chat-messages-column,.chat-participants-column{width:100% !important;min-width:unset !important;flex:unset !important}
.games-grid{grid-template-columns:1fr !important}
.game-card{width:100% !important}
.main-column [class*="-row"],
.main-column [class*="-card"],
.main-column [class*="-item"],
.main-column [class*="-entry"],
.main-column .card,
.main-column article {
flex-wrap: wrap !important;
min-width: 0 !important;
}
.main-column [class*="-row"] > *,
.main-column [class*="-card"] > * {
min-width: 0 !important;
}
button:not([class]),
input[type="submit"]:not([class]),
input[type="button"]:not([class]),
.filter-btn,
a.filter-btn,
.conn-actions button,
.peers-conn-actions button {
background-color: #FFA500 !important;
color: #1a1a1a !important;
border: 1px solid #FFA500 !important;
border-radius: 8px !important;
font-weight: 600 !important;
font-size: 14px !important;
min-height: 42px !important;
padding: 9px 14px !important;
text-align: center !important;
white-space: normal !important;
max-width: 100% !important;
overflow-wrap: anywhere !important;
}
.filter-btn.active {
background-color: #FFD700 !important;
border-color: #FFD700 !important;
}
.audios-search,
.videos-search,
.images-search {
width: 100% !important;
max-width: 100% !important;
margin: 8px 0 !important;
}
.filter-box {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 100% !important;
gap: 8px !important;
align-items: stretch !important;
}
.filter-box__input {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
height: 42px !important;
font-size: 16px !important;
box-sizing: border-box !important;
}
.filter-box__controls {
display: flex !important;
flex-direction: row !important;
flex-wrap: wrap !important;
width: 100% !important;
gap: 8px !important;
align-items: stretch !important;
}
.filter-box__controls .transfer-range {
display: flex !important;
flex-direction: row !important;
flex: 1 1 100% !important;
width: 100% !important;
gap: 8px !important;
}
.filter-box__number {
flex: 1 1 0 !important;
min-width: 0 !important;
width: auto !important;
height: 42px !important;
font-size: 15px !important;
box-sizing: border-box !important;
}
.filter-box__select {
flex: 1 1 auto !important;
min-width: 0 !important;
height: 42px !important;
font-size: 15px !important;
}
.filter-box__button {
flex: 0 0 auto !important;
width: auto !important;
min-height: 42px !important;
white-space: nowrap !important;
background-color: #FFA500 !important;
color: #1a1a1a !important;
border: 1px solid #FFA500 !important;
border-radius: 8px !important;
font-weight: 600 !important;
padding: 9px 16px !important;
}
.filters .ui-toolbar--filters {
justify-content: center !important;
align-items: center !important;
gap: 6px !important;
}
.main-column button,
.main-column input,
.main-column select,
.main-column textarea,
.main-column .btn,
.main-column .create-button,
.main-column .update-btn,
.main-column .delete-btn,
.main-column .edit-btn,
.main-column .join-btn,
.main-column .leave-btn,
.main-column .buy-btn,
.main-column .submit-button {
max-width: 100% !important;
box-sizing: border-box !important;
overflow-wrap: anywhere !important;
}
.main-column button,
.main-column .btn,
.main-column .create-button,
.main-column .update-btn,
.main-column .delete-btn,
.main-column .submit-button {
white-space: normal !important;
}
.main-column form {
max-width: 100% !important;
min-width: 0 !important;
}
.card-field {
display: flex !important;
flex-wrap: wrap !important;
min-width: 0 !important;
max-width: 100% !important;
gap: 4px !important;
}
.card-field .card-value,
.card-field .card-label {
min-width: 0 !important;
max-width: 100% !important;
white-space: normal !important;
overflow-wrap: anywhere !important;
word-break: break-word !important;
}
.card-value .user-link,
.card-value a {
white-space: normal !important;
max-width: 100% !important;
overflow-wrap: anywhere !important;
}
.market-grid,
.shop-products-grid,
.jobs-grid {
display: grid !important;
grid-template-columns: 1fr !important;
gap: 12px !important;
width: 100% !important;
max-width: 100% !important;
}
.market-card,
.market-item {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
}
.cycle-info {
display: grid !important;
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
gap: 8px !important;
}
.kpi {
min-width: 0 !important;
padding: 8px !important;
}
.kpi__label {
letter-spacing: 0 !important;
word-break: normal !important;
overflow-wrap: break-word !important;
font-size: 11px !important;
}
.kpi__value {
word-break: break-word !important;
overflow-wrap: anywhere !important;
font-size: 13px !important;
}
.table-wrap {
display: block !important;
width: 100% !important;
max-width: 100% !important;
overflow-x: hidden !important;
}
.table-wrap table,
.table-wrap .table {
display: table !important;
width: 100% !important;
max-width: 100% !important;
table-layout: fixed !important;
}
.table-wrap th,
.table-wrap td {
white-space: normal !important;
word-break: normal !important;
overflow-wrap: break-word !important;
font-size: 10px !important;
padding: 4px 3px !important;
text-align: center !important;
}
.search-filters-row {
display: block !important;
width: 100% !important;
max-width: 100% !important;
overflow-x: hidden !important;
}
.search-filters-table,
.search-filters-table tbody,
.search-filters-table tr,
.search-filters-table td {
display: block !important;
width: 100% !important;
max-width: 100% !important;
overflow-x: hidden !important;
}
.search-filters-table td {
padding: 4px 0 !important;
}
.search-filters-table input,
.search-filters-table select,
.search-oasis-id {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
box-sizing: border-box !important;
margin-left: 0 !important;
}
.oasis-id-copy {
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
font-family: monospace !important;
font-size: 12px !important;
text-align: center !important;
padding: 8px !important;
border: 1px solid #FFA500 !important;
border-radius: 8px !important;
background: rgba(255, 165, 0, 0.08) !important;
color: inherit !important;
-webkit-user-select: all !important;
user-select: all !important;
}
.peer-key,
.user-link.peer-key {
-webkit-user-select: all !important;
user-select: all !important;
word-break: break-all !important;
}
.create-button,
button.create-button,
a.create-button {
background-color: #ffcc00 !important;
border-color: #e6b800 !important;
color: #000 !important;
}
.peers-list .block-info-table,
.peers-technical-block .block-info-table,
.gov-overview {
display: block !important;
width: 100% !important;
max-width: 100% !important;
border: 0 !important;
background: transparent !important;
box-shadow: none !important;
}
.peers-list .block-info-table tbody,
.peers-technical-block .block-info-table tbody,
.gov-overview tbody {
display: block !important;
width: 100% !important;
}
.gov-overview thead { display: none !important; }
.peers-list .block-info-table tr:first-child,
.peers-technical-block .block-info-table tr:first-child {
display: none !important;
}
.peers-list .block-info-table tr,
.peers-technical-block .block-info-table tr,
.gov-overview tbody tr {
display: block !important;
width: 100% !important;
box-sizing: border-box !important;
border: 1px solid rgba(255, 165, 0, 0.35) !important;
border-radius: 8px !important;
margin: 0 0 8px 0 !important;
padding: 6px 10px !important;
background: rgba(255, 165, 0, 0.04) !important;
}
.peers-list .block-info-table td,
.peers-technical-block .block-info-table td,
.gov-overview tbody td {
display: flex !important;
justify-content: space-between !important;
align-items: baseline !important;
gap: 10px !important;
width: 100% !important;
border: 0 !important;
padding: 3px 0 !important;
font-size: 12px !important;
text-align: right !important;
word-break: break-all !important;
overflow-wrap: anywhere !important;
}
.peers-list .block-info-table td::before,
.peers-technical-block .block-info-table td::before,
.gov-overview tbody td::before {
content: attr(data-label);
flex: 0 0 auto !important;
font-weight: 700 !important;
text-transform: uppercase;
font-size: 10px !important;
letter-spacing: .03em;
opacity: .7 !important;
text-align: left !important;
white-space: nowrap !important;
word-break: normal !important;
}
.peers-technical-block .block-info-table td[data-label=""] { justify-content: center !important; }
.peers-technical-block .block-info-table td[data-label=""]::before { content: none !important; }
.peers-list .block-info-table td .peer-key,
.peers-technical-block .block-info-table td .peer-key { text-align: right !important; }
.relationship-status .relationship-actions { flex-direction: column !important; align-items: stretch !important; gap: 8px !important; }
.relationship-status .relationship-actions form,
.relationship-status .relationship-actions button { width: 100% !important; }
.profile-sensors-box { align-items: center !important; text-align: center !important; }
.profile-sensors-box > * { margin-left: auto !important; margin-right: auto !important; justify-content: center !important; }
.tribe-feed .refeed-column,
.tribe-feed-full .refeed-column { align-self: center !important; align-items: center !important; justify-content: center !important; }
.tribe-feed .card-footer,
.tribe-feed-full .card-footer { display: flex !important; flex-direction: column !important; align-items: center !important; text-align: center !important; gap: 2px !important; }
.invite-qr-card { display: flex !important; justify-content: center !important; border: none !important; background: transparent !important; padding: 0 !important; box-shadow: none !important; margin: 0 auto !important; }
.invite-qr-img { display: block; margin: 0 auto; }
.stats-kpi { display: flex !important; flex-direction: column !important; align-items: center !important; text-align: center !important; gap: 2px !important; }
.stats-kpi-label,
.stats-kpi-value { width: 100% !important; text-align: center !important; }
.main-column audio,
.main-column video { width: 100% !important; max-width: 100% !important; }
.main-column section:has(.chat-messages-list) { border: none !important; background: transparent !important; padding: 0 !important; box-shadow: none !important; }
.tribe-details:has(.chat-messages-list) { display: block !important; border: none !important; background: transparent !important; padding: 6px !important; margin: 0 !important; box-shadow: none !important; }
.chat-full-width { border: none !important; background: transparent !important; padding: 0 !important; }
.chat-messages-list { padding: 0 !important; }
.chat-message { max-width: 92% !important; }
.chat-message.chat-poll { max-width: 97% !important; }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,372 @@
body {
background-color: #F9F9F9 !important;
color: #2C2C2C !important;
font-family: 'Roboto', sans-serif !important;
}
.main-column {
background-color: #FFFFFF !important;
border: 1px solid #E0E0E0 !important;
}
button, input[type="submit"], input[type="button"] {
background-color: #FF6F00 !important;
color: #FFFFFF !important;
border: none !important;
border-radius: 6px !important;
padding: 10px 20px !important;
cursor: pointer !important;
font-weight: 600 !important;
}
button:hover, input[type="submit"]:hover, input[type="button"]:hover {
background-color: #FF8F00 !important;
}
input, textarea, select {
background-color: #FFFFFF !important;
color: #2C2C2C !important;
border: 1px solid #E0E0E0 !important;
border-radius: 4px !important;
padding: 8px !important;
font-size: 16px !important;
}
a {
color: #007BFF !important;
text-decoration: none !important;
}
a:hover {
text-decoration: underline !important;
}
p {
color: black !important;
text-decoration: none !important;
}
.created-at, .about-time, .time {
font-size: 0.9rem;
color: black;
}
table {
background-color: #FFFFFF !important;
color: #2C2C2C !important;
width: 100% !important;
border-collapse: collapse !important;
}
table th {
background-color: #F8F8F8 !important;
padding: 12px 15px !important;
text-align: left !important;
font-weight: 600 !important;
}
table tr:nth-child(even) {
background-color: #FAFAFA !important;
}
table td {
padding: 12px 15px !important;
}
.profile {
background-color: #FFFFFF !important;
padding: 20px !important;
border-radius: 8px !important;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1) !important;
}
.profile .name {
color: #FF6F00 !important;
font-size: 20px !important;
font-weight: 700 !important;
}
.avatar {
border: 3px solid #FF6F00 !important;
border-radius: 50% !important;
width: 60px !important;
height: 60px !important;
}
article, section {
background-color: #FFFFFF !important;
color: #2C2C2C !important;
padding: 20px !important;
border-radius: 8px !important;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05) !important;
}
.post-preview img {
border-radius: 8px !important;
max-width: 100% !important;
height: auto !important;
}
div {
background-color: #FFFFFF !important;
border: 1px solid #E0E0E0 !important;
}
::-webkit-scrollbar-thumb {
background-color: #B0B0B0 !important;
}
::-webkit-scrollbar-track {
background-color: #F9F9F9 !important;
}
.action-container {
background-color: #FFFFFF !important;
border-color: #E0E0E0 !important;
color: #2C2C2C !important;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05) !important;
}
footer {
background-color: #FFFFFF !important;
border-top: 1px solid #E0E0E0 !important;
padding: 15px 0 !important;
}
footer a {
background-color: #007BFF !important;
color: #FFFFFF !important;
padding: 10px 20px !important;
border-radius: 6px !important;
text-decoration: none !important;
font-weight: 600 !important;
}
footer a:hover {
background-color: #0056b3 !important;
}
.sidebar-left nav ul,
.sidebar-right nav ul {
display: flex !important;
flex-direction: column !important;
}
.sidebar-left nav ul,
.sidebar-right nav ul {
display: flex;
flex-direction: column;
margin: 0;
}
.sidebar-left nav ul li,
.sidebar-right nav ul li {
width: 100%;
display: block;
}
.sidebar-left nav ul li a,
.sidebar-right nav ul li a,
.header nav ul li a {
display: block;
width: 100%;
padding: 12px 16px;
font-size: 15px;
font-weight: 500;
border-radius: 6px;
background-color: #ffffff !important;
color: #2C2C2C !important;
border: 1px solid #D0D0D0 !important;
text-align: left;
box-sizing: border-box;
}
.sidebar-left nav ul li a:hover,
.sidebar-right nav ul li a:hover,
.header nav ul li a:hover {
background-color: #f0f0f0 !important;
}
.filter-btn,
.create-button,
.edit-btn,
.delete-btn,
.join-btn,
.leave-btn,
.buy-btn {
background-color: #FF6F00 !important;
color: #FFFFFF !important;
border: none !important;
}
.filter-btn:hover,
.create-button:hover {
background-color: #FF8F00 !important;
color: #FFFFFF !important;
}
.card {
color: #4A4A4A;
box-shadow: 0 4px 30px 0 rgba(0, 0, 0, 0.1);
background-color: #F4F4F4;
}
.card-label {
color: #2D2D2D;
}
.card-footer {
color: #6C6C6C;
background: none;
}
.card-field {
background: none;
}
.card-tags a.tag-link {
color: #181818;
background: #D94F4F;
}
.card-tags a.tag-link:hover {
background: #D94F4F;
color: #111;
cursor: pointer;
}
a.user-link {
background-color: #FFD600;
color: #FFFFFF;
border-color: #FFD600;
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
}
a.user-link:hover {
background-color: #FFD600;
border-color: #FFD600;
color: #FFFFFF;
cursor: pointer;
}
a.user-link:focus {
background-color: #9A2F2F;
border-color: #9A2F2F;
color: #FFFFFF;
}
.date-link {
background-color: #2F3C32;
color: #fff;
}
.date-link:hover {
background-color: #3E4A3D;
color: #fff;
}
.activitySpreadInhabitant2 {
background-color: #3E4A3D;
color: #fff;
}
.activityVotePost {
background-color: #3B5C42;
color: #fff;
}
.update-banner {
background-color: #FFF3E0 !important;
border-bottom-color: #FFE0B2 !important;
color: #E65100 !important;
}
.update-banner-link {
color: #FF6F00 !important;
}
.snh-invite-code {
color: #007BFF !important;
}
.carbon-bar-track {
background: #e0e0e0 !important;
}
.carbon-bar-max {
background: #cc7700 !important;
}
.stats-kpi-label { color: #2D2D2D !important; }
.stats-kpi-value { color: #007BFF !important; }
.carbon-bar-note, .carbon-bar-formula { color: #007BFF !important; }
.graphos-node-label { fill: #2C2C2C !important; }
.graphos-node-label-me { fill: #cc7700 !important; }
.data-best-label { color: #cc7700 !important; }
.data-best-card { background: #FFF3E0 !important; border: 1px solid rgba(204, 119, 0, .4) !important; }
.graphos-legend { color: #2C2C2C !important; }
.graphos-edge { stroke: #BBB !important; }
.graphos-edge-discovered { stroke: #b8860b !important; }
.graphos-edge-unknown { stroke: #999 !important; }
.graphos-node-circle-discovered { fill: #ffd700 !important; stroke: #b8860b !important; }
.graphos-legend-dot.graphos-node-circle-discovered { background: #ffd700 !important; border-color: #b8860b !important; }
/* Blockexplorer */
.blockchain-view { background-color: #F4F4F4 !important; color: #2C2C2C !important; }
.block { background: #FFFFFF !important; box-shadow: 0 2px 12px rgba(0,0,0,0.06) !important; }
.block:hover { box-shadow: 0 8px 32px rgba(0,0,0,0.10) !important; }
.blockchain-card-label, .block-info-table .card-label, .pm-info-table .card-label, .block-content-label { color: #2D2D2D !important; }
.blockchain-card-value, .block-info-table .card-value, .pm-info-table .card-value, .block-timestamp, .json-content { color: #007BFF !important; }
.block-content-preview, .block-content { background: #F8F8F8 !important; color: #2C2C2C !important; }
.block-author { color: #FF6F00 !important; background: rgba(255,111,0,0.08) !important; }
.block-author:hover { color: #FF8F00 !important; }
.block-url { color: #007BFF !important; }
.block-row--details .block-url { background: #F0F0F0 !important; }
.block-row--details .block-url:hover { background: #E0E0E0 !important; color: #FF6F00 !important; }
.btn-singleview { background: #F0F0F0 !important; color: #FF6F00 !important; }
.btn-singleview:hover { background: #E0E0E0 !important; color: #FF8F00 !important; }
.btn-spread-on, .content-actions .btn-pin-on { background: #FF6F00 !important; color: #FFFFFF !important; }
.btn-spread-on:hover, .content-actions .btn-pin-on:hover { background: #FF8F00 !important; color: #FFFFFF !important; }
.btn-back { background: #FF6F00 !important; color: #FFFFFF !important; }
.btn-back:hover { background: #FF8F00 !important; color: #FFFFFF !important; }
.block-info-table td, .pm-info-table td { border-color: #E0E0E0 !important; }
.block-diagram { border-color: #E0E0E0 !important; background: #FFFFFF !important; }
.block-diagram-ruler { color: #2D2D2D !important; background: #F8F8F8 !important; border-bottom-color: #E0E0E0 !important; }
.block-diagram-ruler span { color: #2D2D2D !important; }
.block-diagram-cell { border-color: #E0E0E0 !important; background: #FFFFFF !important; }
.bd-label { color: #2D2D2D !important; }
.bd-value { color: #007BFF !important; }
.deleted-label { color: #D32F2F !important; }
/* Tribes */
.tribe-card { background: #FFFFFF !important; border-color: #E0E0E0 !important; }
.tribe-card:hover { border-color: #007BFF !important; }
.tribe-card-title { color: #2D2D2D !important; }
.tribe-card-description { color: #555 !important; }
.tribe-info-table td { border-color: #E0E0E0 !important; }
.tribe-info-label { color: #2D2D2D !important; background: #FFFFFF !important; }
.tribe-info-value { color: #007BFF !important; background: #FFFFFF !important; }
.tribe-info-empty { color: #999 !important; }
.tribe-card-members { border-color: #E0E0E0 !important; background: #F8F8F8 !important; }
.tribe-members-count { color: #FF6F00 !important; }
.tribe-card-actions { border-color: #E0E0E0 !important; background: #F8F8F8 !important; }
.tribe-action-btn { border-color: #FF6F00 !important; color: #FF6F00 !important; }
.tribe-action-btn:hover { background: #FF6F00 !important; color: #fff !important; }
.tribe-subtribe-link { background: #F0F0F0 !important; border-color: #E0E0E0 !important; color: #FF6F00 !important; }
.tribe-thumb-link { border-color: #E0E0E0 !important; }
.tribe-thumb-link:hover { border-color: #FF6F00 !important; }
.tribe-subtribe-link:hover { background: #E0E0E0 !important; }
.tribe-parent-image { border-color: #E0E0E0 !important; }
.tribe-parent-box { background: #FFFFFF !important; }
.chat-message { background: #FFFFFF !important; border: 1px solid #E0E0E0 !important; }
.chat-bubble-row-self .chat-message { background: #FFF3E0 !important; border-color: rgba(204, 119, 0, .35) !important; }
.chat-message-author { background: #FDF6EC !important; }
.chat-bubble-sender { color: #1565C0 !important; }
.chat-bubble-sender-owner { color: #cc7700 !important; }
.chat-bubble-time { color: #999 !important; }
.chat-day-chip { background: #F0F0F0 !important; color: #666 !important; border-color: #DDD !important; }
.chat-topics { background: #FAFAFA !important; border-color: #E0E0E0 !important; }
.chat-topic:hover { background: #F0F0F0 !important; }
.chat-topic-active { background: #FFF3E0 !important; }
.chat-topic-title { color: #2D2D2D !important; }
.chat-workspace-empty { border-color: #DDD !important; }

View file

@ -0,0 +1,364 @@
body {
background-color: #121212;
color: #FFD700;
}
header, footer {
background-color: #1F1F1F;
}
.sidebar-left, .sidebar-right {
background-color: #1A1A1A;
border: 1px solid #333;
}
.main-column {
background-color: #1C1C1C;
}
button, input[type="submit"], input[type="button"] {
background-color: #444;
color: #FFD700;
border: 1px solid #444;
}
button:hover, input[type="submit"]:hover, input[type="button"]:hover {
background-color: #333;
border-color: #666;
}
input, textarea, select {
background-color: #333;
color: #FFD700;
border: 1px solid #555;
}
a {
color: #FFD700;
}
a:hover {
color: #FFDD44;
}
table {
background-color: #222;
color: #FFD700;
}
table th {
background-color: #333;
}
table tr:nth-child(even) {
background-color: #2A2A2A;
}
nav ul li a:hover {
color: #FFDD44;
text-decoration: underline;
}
.profile {
background-color: #222;
padding: 15px;
border-radius: 8px;
}
.profile .name {
color: #FFD700;
}
.avatar {
border: 3px solid #FFD700;
}
article, section {
background-color: #1C1C1C;
color: #FFD700;
}
.article img {
border: 3px solid #FFD700;
}
.post-preview img {
border: 3px solid #FFD700;
}
.post-preview .image-container {
max-width: 100%;
overflow: hidden;
display: block;
margin: 0 auto;
}
div {
background-color: #1A1A1A;
border: 1px solid #333;
}
div .header-content {
width: 100%;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background-color: #444;
border-radius: 10px;
}
::-webkit-scrollbar-track {
background-color: #222;
}
.action-container {
background-color: #1A1A1A;
border: 1px solid #333;
padding: 10px;
border-radius: 8px;
color: #FFD700;
}
footer {
background-color: #1F1F1F;
padding: 10px 0;
}
footer a {
background-color: #444;
color: #FFD700;
text-align: center;
padding: 8px 16px;
border-radius: 5px;
text-decoration: none;
}
footer a:hover {
background-color: #333;
color: #FFDD44;
}
.card {
border-radius: 16px;
padding: 0px 24px 10px 24px;
margin-bottom: 16px;
color: #FFD600;
font-family: inherit;
box-shadow: 0 2px 20px 0 #FFD60024;
}
.card-section {
border:none;
padding: 10px 0 0 16px;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 0px;
margin-top: 8px;
padding-top: 0px;
border: none;
}
.card-label {
color: #ffa300;
font-weight: bold;
letter-spacing: 1.5px;
line-height: 1.2;
margin-bottom: 0;
}
.card-footer {
margin-top: 6px;
font-weight: 500;
color: #ff9900;
font-size: 1.07em;
display: flex;
align-items: center;
gap: 8px;
background: none;
border: none;
padding-top: 0;
margin-bottom: 6;
}
.card-body {
margin-top: 0;
margin-bottom: 4;
padding: 0;
}
.card-field {
display: flex;
align-items: baseline;
padding: 0;
margin-bottom: 0;
border: none;
background: none;
}
.card-tags {
margin: 5px 0 3px 0;
display: flex;
flex-wrap: wrap;
gap: 9px;
}
.card-tags a.tag-link {
text-decoration: none;
color: #181818;
background: #FFD600;
padding: 5px 13px 4px 13px;
border-radius: 7px;
font-size: .98em;
border: none;
font-weight: bold;
}
.card-tags a.tag-link:hover {
background: #ffe86a;
color: #111;
cursor: pointer;
}
a.user-link {
background-color: #FFA500;
color: #000;
padding: 8px 16px;
border-radius: 5px;
text-align: center;
font-weight: bold;
text-decoration: none;
display: inline-block;
border: 2px solid transparent;
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
font-size: 0.8em;
}
a.user-link:hover {
background-color: #FFD700;
border-color: #FFD700;
color: #000;
cursor: pointer;
}
a.user-link:focus {
background-color: #007B9F;
border-color: #007B9F;
color: #fff;
}
.date-link {
background-color: #444;
color: #FFD600;
padding: 8px 16px;
border-radius: 5px;
margin-left: 8px;
}
.date-link:hover {
background-color: #555;
color: #FFD700;
}
.activitySpreadInhabitant2 {
background-color: #007B9F;
color: #fff;
padding: 8px 16px;
border-radius: 5px;
font-weight: bold;
text-decoration: none;
display: inline-block;
border: 2px solid transparent;
}
.activityVotePost {
background-color: #557d3b;
color: #fff;
padding: 8px 16px;
border-radius: 5px;
font-weight: bold;
text-decoration: none;
display: inline-block;
border: 2px solid transparent;
}
.update-banner {
background-color: #1a1400;
border-bottom-color: #3a2e00;
color: #FFD700;
}
.update-banner-link {
color: #FFD700;
}
.oasis-footer-center a {
color: #FFA500;
}
.oasis-footer-center a:hover {
color: #FFD700;
}
.snh-invite-code {
color: #FFA500 !important;
}
/* Blockexplorer */
.stats-kpi-label { color: #ffa300 !important; }
.stats-kpi-value { color: #FFD700 !important; }
.carbon-bar-note, .carbon-bar-formula { color: #FFD700 !important; }
.graphos-node-label { fill: #ddd !important; }
.graphos-node-label-me { fill: #ffa500 !important; }
.graphos-legend { color: #ddd !important; }
.blockchain-view { background-color: #191b20 !important; color: #FFD700 !important; }
.block { background: #23242a !important; }
.block:hover { box-shadow: 0 8px 32px rgba(35,40,50,0.18) !important; }
.blockchain-card-label, .block-info-table .card-label, .pm-info-table .card-label, .block-content-label { color: #ffa300 !important; }
.blockchain-card-value, .block-info-table .card-value, .pm-info-table .card-value, .block-timestamp, .json-content { color: #FFD700 !important; }
.block-content-preview, .block-content { background: #222326 !important; color: #FFD700 !important; }
.block-author { color: #FFD700 !important; background: rgba(255,163,0,0.08) !important; }
.block-author:hover { color: #FFDD44 !important; }
.block-url { color: #FFD700 !important; }
.block-row--details .block-url { background: #1f2023 !important; }
.block-row--details .block-url:hover { background: #292b36 !important; color: #ffa300 !important; }
.btn-singleview { background: #1e1f23 !important; color: #ffa300 !important; }
.btn-singleview:hover { background: #2d2e34 !important; color: #FFD700 !important; }
.btn-spread-on, .content-actions .btn-pin-on { background: #ffa300 !important; color: #000000 !important; }
.btn-spread-on:hover, .content-actions .btn-pin-on:hover { background: #ffb733 !important; color: #000000 !important; }
.btn-back { background: #21232b !important; color: #ffa300 !important; }
.btn-back:hover { background: #292b36 !important; color: #FFD700 !important; }
.block-info-table td, .pm-info-table td { border-color: #444 !important; }
.block-diagram { border-color: #555 !important; background: #191b20 !important; }
.block-diagram-ruler { color: #ffa300 !important; background: #111 !important; border-bottom-color: #555 !important; }
.block-diagram-ruler span { color: #ffa300 !important; }
.block-diagram-cell { border-color: #555 !important; background: #1e1f23 !important; }
.bd-label { color: #ffa300 !important; }
.bd-value { color: #FFD700 !important; }
/* Tribes */
.tribe-card { background: #23242a !important; border-color: #444 !important; }
.tribe-card:hover { border-color: #ffa300 !important; }
.tribe-card-description { color: #cfd3e1 !important; }
.tribe-info-table td { border-color: #444 !important; }
.tribe-info-label { color: #ffa300 !important; background: #1e1f23 !important; }
.tribe-info-value { color: #FFD700 !important; background: #1e1f23 !important; }
.tribe-info-empty { color: #9aa3b2 !important; }
.tribe-card-members { border-color: #444 !important; background: #1e1f23 !important; }
.tribe-members-count { color: #ffa300 !important; }
.tribe-card-actions { border-color: #444 !important; background: #1e1f23 !important; }
.tribe-action-btn { border-color: #ffa300 !important; color: #ffa300 !important; }
.tribe-action-btn:hover { background: #ffa300 !important; color: #000 !important; }
.tribe-subtribe-link { background: #191b20 !important; border-color: #444 !important; color: #ffa300 !important; }
.tribe-thumb-link { border-color: #444 !important; }
.tribe-thumb-link:hover { border-color: #ffa300 !important; }
.tribe-subtribe-link:hover { background: #333 !important; }
.tribe-parent-image { border-color: #ffa300 !important; }
.tribe-parent-box { background: #1e1f23 !important; }

View file

@ -0,0 +1,382 @@
body {
background-color: #000000 !important;
color: #00FF00 !important;
font-family: 'Courier New', monospace;
}
header, footer {
background-color: #000000;
color: #00FF00;
padding: 20px;
text-align: center;
font-size: 18px;
}
footer {
border-top: 2px solid #00FF00;
}
.sidebar-left, .sidebar-right {
background-color: #000000;
color: #00FF00;
border-right: 2px solid #00FF00;
padding: 15px;
margin-bottom: 10px;
}
.main-column {
background-color: #000000;
color: #00FF00;
padding: 20px;
border-left: 2px solid #00FF00;
margin-bottom: 20px;
}
button, input[type="submit"], input[type="button"] {
background-color: #000000;
color: #00FF00;
border: 2px solid #00FF00;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
font-family: 'Courier New', monospace;
text-transform: none;
font-size: 16px;
}
button:hover, input[type="submit"]:hover, input[type="button"]:hover {
background-color: #00FF00;
color: #000000;
border-color: #00FF00;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.8);
}
input, textarea, select {
background-color: #1A1A1A;
color: #00FF00;
border: 1px solid #00FF00;
border-radius: 5px;
padding: 10px;
font-family: 'Courier New', monospace;
font-size: 16px;
}
a {
color: #00FF00;
text-decoration: none;
font-weight: normal;
font-size: 16px;
}
table {
background-color: #000000;
color: #00FF00;
width: 100%;
border: 1px solid #00FF00;
font-size: 16px;
}
table th {
background-color: #00FF00;
color: #000000;
}
table tr:nth-child(even) {
background-color: #1A1A1A;
}
nav ul {
background-color: #000000;
padding: 0;
margin: 0;
}
nav ul li {
display: inline-block;
margin-right: 10px;
}
nav ul li a {
color: #00FF00;
padding: 10px;
display: inline-block;
font-family: 'Courier New', monospace;
text-transform: none;
font-size: 16px;
}
.profile {
background-color: #1A1A1A;
color: #00FF00;
padding: 20px;
border-radius: 8px;
border: 1px solid #00FF00;
box-shadow: 0 2px 5px rgba(0,255,0,0.5);
}
.profile .name {
color: #00FF00;
font-size: 18px;
font-weight: bold;
}
.avatar {
border: 4px solid #00FF00;
border-radius: 50%;
width: 80px;
height: 80px;
margin-bottom: 10px;
}
article, section {
background-color: #1A1A1A;
color: #00FF00;
padding: 20px;
border-radius: 10px;
border: 1px solid #00FF00;
box-shadow: 0 4px 10px rgba(0, 255, 0, 0.5);
}
.post-preview {
background-color: #00FF00;
padding: 15px;
border-radius: 8px;
color: #000000;
}
.post-preview img {
border-radius: 8px;
max-width: 100%;
}
::-webkit-scrollbar-thumb {
background-color: #00FF00;
}
::-webkit-scrollbar-track {
background-color: #000000;
}
.action-container {
background-color: #1A1A1A;
border-color: #00FF00;
color: #00FF00;
}
footer a {
background-color: #00FF00;
color: #000000;
padding: 8px 20px;
border-radius: 5px;
text-decoration: none;
}
.top-bar-left,
.top-bar-mid,
.top-bar-right {
background-color: #000000 !important;
border: 2px solid #00FF00 !important;
padding: 12px 16px;
box-shadow: 0 0 12px #00FF00;
border-radius: 8px;
display: flex;
gap: 12px;
}
.sidebar-left,
.sidebar-right {
background-color: #000000 !important;
border: 2px solid #00FF00 !important;
box-shadow: 0 0 15px #00FF00;
padding: 16px;
}
.sidebar-left nav ul,
.sidebar-right nav ul {
display: flex;
flex-direction: column;
gap: 10px;
margin: 0;
padding: 0;
}
.sidebar-left nav ul li,
.sidebar-right nav ul li {
width: 100%;
}
.sidebar-left nav ul li a,
.sidebar-right nav ul li a,
.header nav ul li a {
background-color: #000000 !important;
color: #00FF00 !important;
border: 1px solid #00FF00 !important;
font-weight: bold;
border-radius: 6px;
padding: 10px 14px;
display: flex;
justify-content: flex-start;
box-shadow: 0 0 6px #00FF00;
transition: background-color 0.3s ease, color 0.3s ease;
}
.sidebar-left nav ul li a:hover,
.sidebar-right nav ul li a:hover,
.header nav ul li a:hover {
background-color: #00FF00 !important;
color: #000000 !important;
}
.card {
color: #00FF00;
font-family: 'Courier New', monospace;
background-color: #1A1A1A;
}
.card-label {
color: #00FF00;
}
.card-footer {
color: #00FF00;
}
.card-tags a.tag-link {
color: #00FF00;
background: #000000;
}
.card-tags a.tag-link:hover {
background: #00FF00;
color: #000000;
cursor: pointer;
}
a.user-link {
background-color: #00FF00;
color: #000000;
border-color: #00FF00;
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
}
a.user-link:hover {
background-color: #000000;
border-color: #00FF00;
color: #00FF00;
cursor: pointer;
}
a.user-link:focus {
background-color: #00FF00;
border-color: #00FF00;
color: #000000;
}
.date-link {
background-color: #00FF00;
color: #000000;
}
.date-link:hover {
background-color: #000000;
color: #00FF00;
}
.activitySpreadInhabitant2 {
background-color: #1A1A1A;
color: #00FF00;
}
.activityVotePost {
background-color: #00FF00;
color: #000000;
}
.update-banner {
background-color: #001a00;
border-bottom-color: #003300;
color: #00FF00;
}
.update-banner-link {
color: #00FF00;
}
.snh-invite-code {
color: #00FF00 !important;
}
.stats-kpi-label { color: #00FF00 !important; }
.stats-kpi-value { color: #00FF00 !important; }
.carbon-bar-note, .carbon-bar-formula { color: #00FF00 !important; }
.graphos-node-label { fill: #00FF00 !important; }
.graphos-node-label-me { fill: #ffa500 !important; font-weight: bold !important; }
.graphos-legend { color: #00FF00 !important; }
.graphos-edge { stroke: #003300 !important; }
/* Blockexplorer */
.blockchain-view { background-color: #000000 !important; color: #00FF00 !important; }
.block { background: #1A1A1A !important; border: 1px solid #00FF00 !important; }
.block:hover { box-shadow: 0 0 15px rgba(0,255,0,0.3) !important; }
.blockchain-card-label, .block-info-table .card-label, .pm-info-table .card-label, .block-content-label { color: #00FF00 !important; }
.blockchain-card-value, .block-info-table .card-value, .pm-info-table .card-value, .block-timestamp, .json-content { color: #00FF00 !important; }
.block-content-preview, .block-content { background: #1A1A1A !important; color: #00FF00 !important; }
.block-author { color: #00FF00 !important; background: rgba(0,255,0,0.08) !important; }
.block-author:hover { color: #00FF00 !important; }
.block-url { color: #00FF00 !important; }
.block-row--details .block-url { background: #1A1A1A !important; }
.block-row--details .block-url:hover { background: #00FF00 !important; color: #000000 !important; }
.btn-singleview { background: #000000 !important; color: #00FF00 !important; border: 1px solid #00FF00 !important; }
.btn-singleview:hover { background: #00FF00 !important; color: #000000 !important; }
.btn-spread-on, .content-actions .btn-pin-on { background: #00FF00 !important; color: #000000 !important; }
.btn-spread-on:hover, .content-actions .btn-pin-on:hover { background: #66FF66 !important; color: #000000 !important; }
.btn-back { background: #000000 !important; color: #00FF00 !important; border: 1px solid #00FF00 !important; }
.btn-back:hover { background: #00FF00 !important; color: #000000 !important; }
.block-info-table td, .pm-info-table td { border-color: #00FF00 !important; }
.block-diagram { border-color: #00FF00 !important; background: #000000 !important; }
.block-diagram-ruler { color: #00FF00 !important; background: #000000 !important; border-bottom-color: #00FF00 !important; }
.block-diagram-ruler span { color: #00FF00 !important; }
.block-diagram-cell { border-color: #00FF00 !important; background: #1A1A1A !important; }
.bd-label { color: #00FF00 !important; }
.bd-value { color: #00FF00 !important; }
.deleted-label { color: #ff3333 !important; }
/* Tribes */
.tribe-card { background: #1A1A1A !important; border-color: #00FF00 !important; }
.tribe-card:hover { box-shadow: 0 0 15px rgba(0,255,0,0.3) !important; }
.tribe-card-title { color: #00FF00 !important; }
.tribe-card-description { color: #00FF00 !important; }
.tribe-info-table td { border-color: #00FF00 !important; }
.tribe-info-label { color: #00FF00 !important; background: #1A1A1A !important; }
.tribe-info-value { color: #00FF00 !important; background: #1A1A1A !important; }
.tribe-info-empty { color: #006600 !important; }
.tribe-card-members { border-color: #00FF00 !important; background: #1A1A1A !important; }
.tribe-members-count { color: #00FF00 !important; }
.tribe-card-actions { border-color: #00FF00 !important; background: #1A1A1A !important; }
.tribe-action-btn { border-color: #00FF00 !important; color: #00FF00 !important; }
.tribe-action-btn:hover { background: #00FF00 !important; color: #000 !important; }
.tribe-subtribe-link { background: #000000 !important; border-color: #00FF00 !important; color: #00FF00 !important; }
.tribe-thumb-link { border-color: #00FF00 !important; }
.tribe-thumb-link:hover { box-shadow: 0 0 10px rgba(0,255,0,0.3) !important; }
.tribe-subtribe-link:hover { background: #00FF00 !important; color: #000 !important; }
.tribe-parent-image { border-color: #00FF00 !important; }
.tribe-parent-box { background: #1A1A1A !important; }
.oasis-nav-header { color: #00FF00 !important; border-color: #00FF00 !important; background: #000000 !important; }
.oasis-nav-header:hover { color: #000000 !important; background: #00FF00 !important; }
.oasis-nav-header .emoji, .oasis-nav-header .nav-text, .oasis-nav-arrow { color: inherit !important; }
.oasis-nav-list li a { color: #00FF00 !important; }
.oasis-nav-list li a:hover { color: #00FF00 !important; opacity: 1 !important; }
.oasis-nav-list .emoji, .oasis-nav-list .nav-text { color: inherit !important; }
nav, .sidebar-left nav, .sidebar-right nav, .sidebar-left ul, .sidebar-right ul { color: #00FF00 !important; }
.sidebar-left a, .sidebar-right a { color: #00FF00 !important; }
.ai-ask-form .ai-ask-input, .ai-ask-form .ai-ask-btn { color: #00FF00 !important; border-color: #00FF00 !important; background: #000000 !important; }
.ai-ask-form .ai-ask-input::placeholder { color: rgba(0,255,0,0.55) !important; }
.ai-ask-form .ai-ask-input:focus { border-color: #00FF00 !important; background: #1A1A1A !important; box-shadow: 0 0 6px rgba(0,255,0,0.4) !important; }
.ai-ask-form .ai-ask-btn:hover { background: #00FF00 !important; color: #000000 !important; border-color: #00FF00 !important; }
.ai-nav-results, .ai-nav-result-card { color: #00FF00 !important; border-color: #00FF00 !important; background: #000000 !important; }
.ai-nav-result-card .card-label { color: #00FF00 !important; }
.ai-nav-result-card a { color: #00FF00 !important; }
.ai-nav-result-card a:hover { background: #00FF00 !important; color: #000000 !important; }
.ai-nav-query { color: #00FF00 !important; }
.trending-card.own-content { box-shadow: inset 3px 0 0 #00FF00; }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,398 @@
body {
background-color: #4B0A6D;
color: #E5E5E5;
font-family: 'Arial', sans-serif;
}
footer {
border-top: 2px solid #9B1C96;
}
.sidebar-left, .sidebar-right {
background-color: #39006D;
border: 1px solid #9B1C96;
color: #E5E5E5;
padding: 15px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
.main-column {
background-color: #1A1A1A;
border: 1px solid #9B1C96;
padding: 20px;
color: #E5E5E5;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
button, input[type="submit"], input[type="button"] {
background-color: #9B1C96;
color: #E5E5E5;
border: 2px solid #6A0066;
border-radius: 10px;
padding: 12px 24px;
cursor: pointer;
}
button:hover, input[type="submit"]:hover, input[type="button"]:hover {
background-color: #6A0066;
border-color: #9B1C96;
box-shadow: 0 0 15px rgba(155, 28, 150, 0.8);
}
input, textarea, select {
background-color: #333333;
color: #E5E5E5;
border: 1px solid #9B1C96;
border-radius: 5px;
padding: 12px;
}
input:focus, textarea:focus, select:focus {
background-color: #39006D;
outline: none;
}
a {
color: #9B1C96;
text-decoration: none;
}
a:hover {
color: #E5E5E5;
}
table {
background-color: #1A1A1A;
color: #E5E5E5;
width: 100%;
border-collapse: collapse;
}
table th {
background-color: #6A0066;
}
table tr:nth-child(even) {
background-color: #333333;
}
nav ul {
background-color: #39006D;
padding: 0;
margin: 0;
list-style: none;
}
nav ul li {
display: inline-block;
margin-right: 10px;
}
nav ul li a {
color: #E5E5E5;
padding: 15px;
display: inline-block;
text-transform: none;
font-weight: bold;
letter-spacing: 0;
}
.profile {
background-color: #333333;
color: #E5E5E5;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.profile .name {
color: #9B1C96;
font-size: 20px;
font-weight: bold;
}
.avatar {
border: 4px solid #9B1C96;
border-radius: 50%;
width: 80px;
height: 80px;
margin-bottom: 10px;
}
article, section {
background-color: #333333;
color: #E5E5E5;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.post-preview {
background-color: #39006D;
padding: 15px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
.post-preview img {
border-radius: 8px;
max-width: 100%;
}
::-webkit-scrollbar-thumb {
background-color: #9B1C96;
}
::-webkit-scrollbar-track {
background-color: #1A1A1A;
}
.action-container {
background-color: #333333;
border-color: #9B1C96;
color: #E5E5E5;
}
footer a {
background-color: #9B1C96;
color: #FFFFFF;
padding: 8px 20px;
border-radius: 5px;
text-decoration: none;
}
footer a:hover {
background-color: #6A0066;
}
.sidebar-left nav ul li a,
.sidebar-right nav ul li a,
.header nav ul li a {
background-color: #682B94 !important;
color: #FFE082 !important;
border: 1px solid #B86ADE !important;
font-weight: 600;
border-radius: 6px;
padding: 12px 16px;
display: flex;
justify-content: flex-start;
box-sizing: border-box;
transition: background-color 0.2s ease, border-color 0.2s ease;
}
.sidebar-left nav ul li a:hover,
.sidebar-right nav ul li a:hover,
.header nav ul li a:hover {
background-color: #682B94 !important;
border-color: #FFD54F !important;
color: #FFFFFF !important;
}
body {
background-color: #2D0B47 !important;
}
.main-column,
article,
section,
.action-container,
.profile,
.post-preview {
background-color: #3C1360 !important;
border-color: #B86ADE !important;
color: #FFEEDB !important;
}
input,
textarea,
select {
background-color: #4B1A72 !important;
color: #FFFFFF !important;
border-color: #BB5EFF !important;
}
button,
input[type="submit"],
input[type="button"] {
background-color: #A34AD8 !important;
color: #FFFFFF !important;
border-color: #751E9F !important;
}
header {
background-color: #5A1A85 !important;
border-bottom: 1px solid #B86ADE !important;
box-shadow: none !important;
}
.header {
background-color: #5A1A85 !important;
}
.top-bar-left,
.top-bar-mid,
.top-bar-right {
background-color: #39006D !important;
border: 1px solid #9B1C96 !important;
padding: 15px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
display: flex;
gap: 12px;
border-radius: 10px;
}
.sidebar-left,
.sidebar-right {
padding: 16px;
box-sizing: border-box;
}
.sidebar-left nav ul,
.sidebar-right nav ul {
display: flex;
flex-direction: column;
gap: 10px;
margin: 0;
padding: 0;
}
.sidebar-left nav ul li,
.sidebar-right nav ul li {
width: 100%;
}
.card {
color: #E5E5E5;
box-shadow: 0 4px 30px 0 rgba(0, 0, 0, 0.2);
background-color: #3C1360;
border-color: #B86ADE;
}
.card-label {
color: #9B1C96;
}
.card-footer {
color: #B86ADE;
}
.card-tags a.tag-link {
color: #FFFFFF;
background: #D94F4F;
}
.card-tags a.tag-link:hover {
background: #B86ADE;
color: #E5E5E5;
cursor: pointer;
}
a.user-link {
background-color: #FFD600;
color: #3C1360;
border-color: #FFD600;
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
}
a.user-link:hover {
background-color: #FFB600;
border-color: #FFB600;
color: #3C1360;
cursor: pointer;
}
a.user-link:focus {
background-color: #9A2F2F;
border-color: #9A2F2F;
color: #E5E5E5;
}
.date-link {
background-color: #2F3C32;
color: #fff;
}
.date-link:hover {
background-color: #3E4A3D;
color: #fff;
}
.activitySpreadInhabitant2 {
background-color: #3E4A3D;
color: #fff;
}
.activityVotePost {
background-color: #3B5C42;
color: #fff;
}
.update-banner {
background-color: #1a0025;
border-bottom-color: #3d004d;
color: #E5E5E5;
}
.update-banner-link {
color: #c44bc1;
}
.snh-invite-code {
color: #9B1C96 !important;
}
.stats-kpi-label { color: #B86ADE !important; }
.stats-kpi-value { color: #FFEEDB !important; }
.carbon-bar-note, .carbon-bar-formula { color: #FFEEDB !important; }
.graphos-node-label { fill: #FFEEDB !important; }
.graphos-node-label-me { fill: #ffa500 !important; }
.graphos-legend { color: #FFEEDB !important; }
/* Blockexplorer */
.blockchain-view { background-color: #2D0B47 !important; color: #FFEEDB !important; }
.block { background: #3C1360 !important; border: 1px solid #B86ADE !important; }
.block:hover { box-shadow: 0 0 15px rgba(184,106,222,0.3) !important; }
.blockchain-card-label, .block-info-table .card-label, .pm-info-table .card-label, .block-content-label { color: #B86ADE !important; }
.blockchain-card-value, .block-info-table .card-value, .pm-info-table .card-value, .block-timestamp, .json-content { color: #FFEEDB !important; }
.block-content-preview, .block-content { background: #4B1A72 !important; color: #FFEEDB !important; }
.block-author { color: #FFD600 !important; background: rgba(255,214,0,0.08) !important; }
.block-author:hover { color: #FFB600 !important; }
.block-url { color: #B86ADE !important; }
.block-row--details .block-url { background: #4B1A72 !important; }
.block-row--details .block-url:hover { background: #5A1A85 !important; color: #FFD600 !important; }
.btn-singleview { background: #4B1A72 !important; color: #B86ADE !important; }
.btn-singleview:hover { background: #5A1A85 !important; color: #FFD600 !important; }
.btn-spread-on, .content-actions .btn-pin-on { background: #B86ADE !important; color: #2A0E42 !important; }
.btn-spread-on:hover, .content-actions .btn-pin-on:hover { background: #CE8CE9 !important; color: #2A0E42 !important; }
.btn-back { background: #A34AD8 !important; color: #FFFFFF !important; }
.btn-back:hover { background: #751E9F !important; color: #FFFFFF !important; }
.block-info-table td, .pm-info-table td { border-color: #B86ADE !important; }
.block-diagram { border-color: #B86ADE !important; background: #2D0B47 !important; }
.block-diagram-ruler { color: #B86ADE !important; background: #1A0030 !important; border-bottom-color: #B86ADE !important; }
.block-diagram-ruler span { color: #B86ADE !important; }
.block-diagram-cell { border-color: #B86ADE !important; background: #3C1360 !important; }
.bd-label { color: #B86ADE !important; }
.bd-value { color: #FFEEDB !important; }
.deleted-label { color: #ff5555 !important; }
/* Tribes */
.tribe-card { background: #3C1360 !important; border-color: #B86ADE !important; }
.tribe-card:hover { box-shadow: 0 0 15px rgba(184,106,222,0.3) !important; }
.tribe-card-title { color: #FFEEDB !important; }
.tribe-card-description { color: #FFEEDB !important; }
.tribe-info-table td { border-color: #B86ADE !important; }
.tribe-info-label { color: #B86ADE !important; background: #3C1360 !important; }
.tribe-info-value { color: #FFEEDB !important; background: #3C1360 !important; }
.tribe-info-empty { color: #8844aa !important; }
.tribe-card-members { border-color: #B86ADE !important; background: #2D0B47 !important; }
.tribe-members-count { color: #FFD600 !important; }
.tribe-card-actions { border-color: #B86ADE !important; background: #2D0B47 !important; }
.tribe-action-btn { border-color: #B86ADE !important; color: #B86ADE !important; }
.tribe-action-btn:hover { background: #B86ADE !important; color: #000 !important; }
.tribe-subtribe-link { background: #4B1A72 !important; border-color: #B86ADE !important; color: #FFD600 !important; }
.tribe-thumb-link { border-color: #B86ADE !important; }
.tribe-thumb-link:hover { border-color: #FFD600 !important; }
.tribe-subtribe-link:hover { background: #5A1A85 !important; }
.tribe-parent-image { border-color: #B86ADE !important; }
.tribe-parent-box { background: #3C1360 !important; }
.trending-card.own-content { box-shadow: inset 3px 0 0 #B86ADE; }

View file

@ -0,0 +1,524 @@
// Claves de traduccion propias de la rama experimental.
// Se fusionan sobre las de upstream desde i18n.js, para no editar los 11
// ficheros oasis_*.js (upstream los reescribe entero en cada release).
//
// Contiene tres grupos:
// 1. Claves que anade la rama: barra inferior (bb*), menu Personal/Community
// y el modulo Karvan.
// 2. Claves que upstream tenia en 0.9.1 y elimino en 0.9.5, pero que el
// codigo de la rama sigue usando (menuBlogs, spreadHint, chatShareUrl...).
// 3. Textos de upstream que la rama corrige (el grupo spread en castellano).
module.exports = {
en: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Category",
bookmarkCategoryPlaceholder: "Optional",
chatShareUrl: "Share URL",
filter: "Filter",
forumFilterHot: "Hot",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blogs",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Device",
publishBlog: "Publish Blog",
spreadHint: "Spread this to your supporters (replicates via your feed).",
spreadMore: "more"
},
es: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Salas efimeras: los mensajes viven solo en memoria y se autodestruyen.",
chatReply: "Responder",
bbAdd: "Añadir",
bbDone: "Hecho",
bbFull: "Máximo alcanzado",
bbManage: "Editar",
bbPickDesc: "Elige hasta 4 accesos para la barra inferior.",
bbPickNone: "Ninguno",
bbPickTitle: "Personaliza la barra",
bbQuickActions: "Accesos rápidos",
bbRemove: "Quitar",
bbYourBar: "Tu barra",
bookmarkCategoryLabel: "Categoría",
bookmarkCategoryPlaceholder: "Opcional",
chatShareUrl: "Compartir URL",
filter: "Filtrar",
forumFilterHot: "Populares",
karvanActive: "Salas activas",
karvanBlurb: "Salas que solo viven en memoria y se autodestruyen.",
karvanCall: "Llamar",
karvanCreate: "Crear sala efímera",
karvanEphemeral: "Salas efímeras",
karvanInvite: "Invitar",
karvanInviteBad: "✗ No es un @feed-id válido.",
karvanInviteFail: "✗ No se pudo enviar la invitación.",
karvanInvitePlaceholder: "Invita a un contacto por @feed-id…",
karvanInviteSent: "✓ Invitación enviada a su buzón.",
karvanNone: "No hay salas activas. Crea una: desaparece sola.",
karvanRelay: "relay del servidor",
karvanRoomName: "Nombre de la sala (opcional)",
karvanRooms: "Salas",
karvanSay: "Mensaje temporal…",
karvanSend: "Enviar",
karvanTitle: "Karvan",
karvanTtl: "Se autodestruye en:",
menuAll: "Todo",
menuBlogs: "Blogs",
menuCommunity: "Comunidad",
peerLastChange: "Último cambio",
profileVisibilityDevice: "Dispositivo",
publishBlog: "Publicar Blog",
spreadChron: "Difusión",
spreadHint: "Difunde esto a quienes te apoyan (se replica vía tu feed).",
spreadLabel: "Difundir",
spreadMore: "más",
spreaded: "Difundido",
spreadedDescription: "Lista de posts replicados por habitante.",
totalspreads: "Replicas totales"
},
fr: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Catégorie",
bookmarkCategoryPlaceholder: "Optionnel",
chatShareUrl: "Partager URL",
filter: "Filter",
forumFilterHot: "Populaires",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blogs",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Appareil",
publishBlog: "Publier un blog",
spreadHint: "Diffusez ceci à ceux qui vous soutiennent (réplique via votre feed).",
spreadMore: "plus"
},
eu: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Kategoria",
bookmarkCategoryPlaceholder: "Aukerakoa",
chatShareUrl: "URLa Partekatu",
filter: "Filter",
forumFilterHot: "Beroa",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blogak",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Gailua",
publishBlog: "Bloga argitaratu",
spreadHint: "Hedatu zure babesleei (zure feed bidez errepikatzen da).",
spreadMore: "gehiago"
},
de: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Kategorie",
bookmarkCategoryPlaceholder: "Optional",
chatShareUrl: "URL Teilen",
filter: "Filter",
forumFilterHot: "Beliebt",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blogs",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Gerät",
publishBlog: "Blog veröffentlichen",
spreadHint: "Verbreite dies an deine Unterstützer (über deinen Feed).",
spreadMore: "mehr"
},
it: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Categoria",
bookmarkCategoryPlaceholder: "Opzionale",
chatShareUrl: "Condividi URL",
filter: "Filter",
forumFilterHot: "Caldi",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blog",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Dispositivo",
publishBlog: "Pubblica post",
spreadHint: "Diffondi questo a chi ti supporta (replica via il tuo feed).",
spreadMore: "altro"
},
pt: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Categoria",
bookmarkCategoryPlaceholder: "Opcional",
chatShareUrl: "Partilhar URL",
filter: "Filter",
forumFilterHot: "Populares",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Blogues",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Dispositivo",
publishBlog: "Publicar blog",
spreadHint: "Difunde isto aos teus apoiantes (replica pelo teu feed).",
spreadMore: "mais"
},
zh: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "类别",
bookmarkCategoryPlaceholder: "可选",
chatShareUrl: "分享链接",
filter: "Filter",
forumFilterHot: "热门",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "博客",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "设备",
publishBlog: "发布博客",
spreadHint: "转发给你的支持者(通过你的 feed 复制)。",
spreadMore: "更多"
},
ar: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "الفئة",
bookmarkCategoryPlaceholder: "اختياري",
chatShareUrl: "مشاركة الرابط",
filter: "Filter",
forumFilterHot: "رائج",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "مدونات",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "الجهاز",
publishBlog: "نشر مدونة",
spreadHint: "نشر هذا لداعميك (يتم النسخ عبر تغذيتك).",
spreadMore: "المزيد"
},
hi: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "श्रेणी",
bookmarkCategoryPlaceholder: "वैकल्पिक",
chatShareUrl: "URL शेयर करें",
filter: "Filter",
forumFilterHot: "लोकप्रिय",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "ब्लॉग",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "डिवाइस",
publishBlog: "ब्लॉग प्रकाशित करें",
spreadHint: "अपने समर्थकों को फैलाएँ (फ़ीड से प्रतिकृति)।",
spreadMore: "और"
},
ru: {
modulesKarvanLabel: "Karvan",
modulesKarvanDescription: "Ephemeral rooms: messages live only in memory and self-destruct.",
chatReply: "Reply",
bbAdd: "Add",
bbDone: "Done",
bbFull: "Maximum reached",
bbManage: "Edit",
bbPickDesc: "Choose up to 4 shortcuts for the bottom bar.",
bbPickNone: "None",
bbPickTitle: "Customize the bar",
bbQuickActions: "Quick actions",
bbRemove: "Remove",
bbYourBar: "Your bar",
bookmarkCategoryLabel: "Категория",
bookmarkCategoryPlaceholder: "Необязательно",
chatShareUrl: "Поделиться URL",
filter: "Filter",
forumFilterHot: "Популярные",
karvanActive: "Active rooms",
karvanBlurb: "Rooms that live only in memory and destroy themselves.",
karvanCall: "Call",
karvanCreate: "Create ephemeral room",
karvanEphemeral: "Ephemeral rooms",
karvanInvite: "Invite",
karvanInviteBad: "✗ That is not a valid @feed-id.",
karvanInviteFail: "✗ Could not send the invitation.",
karvanInvitePlaceholder: "Invite a contact by @feed-id…",
karvanInviteSent: "✓ Invitation sent to their inbox.",
karvanNone: "No active rooms. Create one — it disappears on its own.",
karvanRelay: "server relay",
karvanRoomName: "Room name (optional)",
karvanRooms: "Rooms",
karvanSay: "Temporary message…",
karvanSend: "Send",
karvanTitle: "Karvan",
karvanTtl: "Self-destruct in:",
menuAll: "All",
menuBlogs: "Блоги",
menuCommunity: "Community",
peerLastChange: "Last change",
profileVisibilityDevice: "Устройство",
publishBlog: "Опубликовать блог",
spreadHint: "Распространить вашим сторонникам (через ваш feed).",
spreadMore: "ещё"
}
};

View file

@ -0,0 +1,20 @@
const path = require('path');
let i18n = {};
const languages = ['en', 'es', 'fr', 'eu', 'de', 'it', 'pt', 'zh', 'ar', 'hi', 'ru'];
languages.forEach(language => {
try {
const languagePath = path.join(__dirname, `oasis_${language}.js`);
const languageData = require(languagePath);
i18n[language] = languageData[language];
} catch (error) {
console.error(`Failed to load language file for ${language}:`, error);
}
});
try {
const overlay = require('./fork/i18n_fork.js');
languages.forEach(l => Object.assign(i18n[l] = i18n[l] || {}, overlay[l] || overlay.en || {}));
} catch (e) {}
module.exports = i18n;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,10 @@
module.exports = {
feed: 'createFeedStream',
history: 'createHistoryStream',
hist: 'createHistoryStream',
public: 'getPublicKey',
pub: 'getPublicKey',
log: 'createLogStream',
logt: 'messagesByType',
conf: 'config',
};

124
src/client/gui.js Normal file
View file

@ -0,0 +1,124 @@
const path = require('path');
const fs = require('fs');
const os = require('os');
const debug = require('../server/node_modules/debug')('oasis');
const lodash = require('../server/node_modules/lodash');
const ssbClient = require('../server/node_modules/ssb-client');
const ssbConfig = require('../server/node_modules/ssb-config');
const ssbKeys = require('../server/node_modules/ssb-keys');
const { printMetadata } = require('../server/ssb_metadata');
const updateFlagPath = path.join(__dirname, "../server/.update_required");
let internalSSB = null;
try {
const { server } = require('../server/SSB_server');
internalSSB = server;
} catch {}
if (process.env.OASIS_TEST) {
ssbConfig.path = fs.mkdtempSync(path.join(os.tmpdir(), "oasis-"));
ssbConfig.keys = ssbKeys.generate();
}
const socketPath = path.join(ssbConfig.path, "socket");
const publicInteger = ssbConfig.keys.public.replace(".ed25519", "");
const remote = `unix:${socketPath}~noauth:${publicInteger}`;
const connect = (options) =>
new Promise((resolve, reject) => {
ssbClient(process.env.OASIS_TEST ? ssbConfig.keys : null, options)
.then(resolve)
.catch(reject);
});
let closing = false;
let clientHandle;
const attemptConnectionWithBackoff = (attempt = 1) => {
const maxAttempts = 5;
const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
return new Promise((resolve, reject) => {
connect({ remote })
.then(resolve)
.catch((error) => {
if (attempt >= maxAttempts) {
return reject(new Error("Failed to connect after multiple attempts"));
}
setTimeout(() => {
attemptConnectionWithBackoff(attempt + 1).then(resolve).catch(reject);
}, delay);
});
});
};
let pendingConnection = null;
const ensureConnection = (customConfig) => {
if (pendingConnection === null) {
pendingConnection = new Promise((resolve) => {
setTimeout(() => {
attemptConnectionWithBackoff()
.then(resolve)
.catch(() => {
resolve(null);
});
});
});
const cancel = () => (pendingConnection = null);
pendingConnection.then(cancel, cancel);
}
return pendingConnection;
};
module.exports = ({ offline, port = 3000, host = 'localhost', isPublic = false }) => {
const customConfig = JSON.parse(JSON.stringify(ssbConfig));
if (offline === true) {
lodash.set(customConfig, "conn.autostart", false);
}
lodash.set(
customConfig,
"conn.hops",
lodash.get(ssbConfig, "conn.hops", lodash.get(ssbConfig.friends, "hops", 0))
);
const cooler = {
open() {
return new Promise((resolve, reject) => {
if (internalSSB) {
const { printMetadata, colors } = require('../server/ssb_metadata');
printMetadata('OASIS GUI', colors.yellow, port, host, offline, isPublic);
return resolve(internalSSB);
}
if (clientHandle && clientHandle.closed === false) {
return resolve(clientHandle);
}
ensureConnection(customConfig).then((ssb) => {
if (!ssb) return reject(new Error("No SSB server available"));
clientHandle = ssb;
if (closing) {
cooler.close();
reject(new Error("Closing Oasis"));
} else {
const { printMetadata, colors } = require('../server/ssb_metadata');
printMetadata('OASIS GUI', colors.yellow, port, host, offline, isPublic);
resolve(ssb);
}
}).catch(reject);
});
},
close() {
closing = true;
if (clientHandle && clientHandle.closed === false) {
clientHandle.close();
}
},
};
return cooler;
};

212
src/client/middleware.js Normal file
View file

@ -0,0 +1,212 @@
const path = require("path");
const os = require("os");
const Koa = require(path.join(__dirname, "../server/node_modules/koa"));
const koaStatic = require(path.join(__dirname, "../server/node_modules/koa-static"));
const { join } = require("path");
const mount = require(path.join(__dirname, "../server/node_modules/koa-mount"));
function obfuscateClearnetHtml(html) {
if (typeof html !== 'string' || html.length === 0) return html;
const preserve = [];
const stash = (re) => {
html = html.replace(re, (m) => {
preserve.push(m);
return `${preserve.length - 1}`;
});
};
stash(/<pre[\s\S]*?<\/pre>/gi);
stash(/<textarea[\s\S]*?<\/textarea>/gi);
stash(/<style[\s\S]*?<\/style>/gi);
html = html.replace(/<!--[\s\S]*?-->/g, '');
html = html.replace(/>[\s\n\r\t]+</g, '><');
html = html.replace(/[ \t]{2,}/g, ' ');
html = html.replace(/[\r\n]+/g, '');
html = html.replace(/(\d+)/g, (_, i) => preserve[Number(i)] || '');
return html;
}
const collectLocalIPs = () => {
const out = [];
try {
const ifaces = os.networkInterfaces();
for (const name of Object.keys(ifaces)) {
for (const info of (ifaces[name] || [])) {
if (info && !info.internal && (info.family === 'IPv4' || info.family === 4)) {
out.push(info.address);
}
}
}
} catch (_) {}
return out;
};
module.exports = ({ host, port, middleware, allowHost }) => {
const assets = new Koa()
assets.use(koaStatic(join(__dirname, "..", "client", "assets"), { maxage: 60 * 60 * 1000 }));
const app = new Koa();
const validHosts = [];
const isClearnetPath = (request) => {
const url = String(request.url || '');
return url === '/c' || url.startsWith('/c/') || url.startsWith('/c?');
};
const isValidRequest = (request) => {
if (isClearnetPath(request)) return request.method === 'GET';
if (validHosts.includes(request.hostname) !== true) {
return false;
}
if (request.method !== "GET") {
if (request.header.referer == null) {
return false;
}
try {
const refererUrl = new URL(request.header.referer);
if (validHosts.includes(refererUrl.hostname) !== true) {
return false;
}
if (refererUrl.pathname.startsWith("/blob/")) {
return false;
}
} catch (e) {
return false;
}
}
return true;
};
const httpDebug = process.argv.includes('--debug') || process.env.OASIS_DEBUG === '1' || process.env.OASIS_DEBUG === 'true';
app.on("error", (err, ctx) => {
if (err && (err.code === 'ECONNRESET' || err.code === 'EPIPE')) {
return;
}
if (err && (err.name === 'BadRequestError' || err.status === 400)) {
if (httpDebug) console.error(`[400] ${err.message}`);
return null;
}
console.error(err);
if (ctx && isValidRequest(ctx.request)) {
err.message = err.message || 'Internal server error';
err.expose = true;
}
return null;
});
app.use(mount("/assets", assets));
const maptiles = new Koa();
maptiles.use(koaStatic(join(__dirname, "..", "maps", "tiles")));
app.use(mount("/maptiles", maptiles));
const mapcache = new Koa();
mapcache.use(koaStatic(join(__dirname, "..", "maps", "cache")));
app.use(mount("/mapcache", mapcache));
const gamesStatic = new Koa();
gamesStatic.use(koaStatic(join(__dirname, "..", "games")));
app.use(mount("/game-assets", gamesStatic));
app.use(mount("/js", koaStatic(path.join(__dirname, 'public/js'))));
app.use(koaStatic(path.join(__dirname, 'public')));
app.use(async (ctx, next) => {
if (httpDebug) console.log(`[http] ${ctx.method} ${ctx.path}`);
const isClearnet = isClearnetPath(ctx.request);
const csp = isClearnet
? [
"default-src 'self'",
"script-src 'none'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"media-src 'self' blob:",
"connect-src 'self'",
"form-action 'self'",
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'"
].join("; ")
: [
"default-src 'self'",
"script-src 'self' http://localhost:3000/js",
"style-src 'self'",
"img-src 'self'",
"media-src 'self' blob:",
"worker-src 'self' blob:",
"frame-src 'self'",
"form-action 'self'",
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'"
].join("; ");
ctx.set("Content-Security-Policy", csp);
ctx.set("X-Frame-Options", "SAMEORIGIN");
ctx.set("X-Content-Type-Options", "nosniff");
ctx.set("Referrer-Policy", "same-origin");
ctx.set("Permissions-Policy", "speaker=(self)");
const validHostsString = validHosts.join(" or ");
ctx.assert(
isValidRequest(ctx.request),
400,
`Request must be addressed to ${validHostsString} and non-GET requests must contain non-blob referer.`
);
await next();
if (isClearnet && typeof ctx.body === 'string') {
const type = String(ctx.response.type || ctx.response.get('Content-Type') || '').toLowerCase();
if (type.includes('html')) {
ctx.body = obfuscateClearnetHtml(ctx.body);
}
}
});
// pdf viewer
const pdfjsPath = path.join(__dirname, '../server/node_modules/pdfjs-dist/build/pdf.min.js');
app.use(koaStatic(pdfjsPath));
middleware.forEach((m) => app.use(m));
const server = app.listen({ host, port });
server.on("listening", () => {
const address = server.address();
if (typeof address === "string") {
throw new Error("HTTP server should never bind to Unix socket");
}
if (allowHost !== null) {
validHosts.push(allowHost);
}
validHosts.push(address.address);
if (validHosts.includes(host) === false) {
validHosts.push(host);
}
for (const ip of collectLocalIPs()) {
if (validHosts.includes(ip) === false) validHosts.push(ip);
}
for (const loopback of ['localhost', '127.0.0.1']) {
if (validHosts.includes(loopback) === false) validHosts.push(loopback);
}
});
return server;
};

Some files were not shown because too many files have changed in this diff Show more