Compare commits

...
Sign in to create a new pull request.

21 commits
v0 ... main

Author SHA1 Message Date
Nixyan
d13cc3bcf4 chore: update README for version bump and integration test improvements
- Updated version badge from 0.1.1 to 0.2.0.
- Renamed "Manual integration tests" section to "Docker-based integration tests" and clarified the testing process with Docker.
- Enhanced descriptions of integration scripts to reflect their functionality with a Docker cluster.
- Updated the coverage section to align with the new testing approach, emphasizing the discover round-trips.
2026-05-18 12:03:38 -03:00
Nixyan
660c17b319 feat: add client-side identity system, rate limiting, proxy hardening, and full test suite
### Major changes

- **Client-side identity** — New session key store (`sessionKey.ts`) backed by
  `sessionStorage` with a module-level caching, a `crypto.subtle` cache, a `useIdentityLock`
  hook for decrypt-once signing, `followSignature.ts` for signed follows, and
  two new UI modals (`IdentityBackup.tsx`, `UnlockIdentityModal.tsx`).
  `CreateIdentity.tsx` is rewritten to generate BIP-39 mnemonics and encrypt the
  Ed25519 keypair with AES-256-GCM via PBKDF2 (600k iterations) before storing
  in IndexedDB.

- **Rate limiting** — New `rate-limit-config.ts` and `rate-limit.ts` provide a
  per-IP sliding-window rate limiter backed by Redis. All external-facing routes
  (`/discover`, `/discover/rotate/*`, `/proxy`, social API endpoints) now have
  conservative defaults wired into the custom HTTP server before requests reach
  Next.js handlers.

- **Proxy route hardening** — The `/proxy` route now enforces a 256 KB payload
  limit (HTTP 413), validates JSON before parsing, applies a per-origin rate
  limit (100 req/min), and imports the `blocks` table to reject requests from
  blocked servers.

- **Docker integration-test cluster** — New `Dockerfile`, `.dockerignore`, and
  `tests/docker-compose.yml` orchestrate three SiPher instances (A, B, C) plus
  shared PostgreSQL and Redis. Key generation (`generate-keys.ts`) and discovery
  setup (`setup-discovery.ts`) scripts automate cluster bootstrap. Three example
  env files document required per-instance configuration.

- **Full test suite overhaul** — Replaces the old attack/auth/discover/key/proxy
  tests with a structured suite:
  * `tests/federation/` — Keytools unit tests + key-rotation e2e test
  * `tests/proxy/` — Proxy relay e2e tests (single-server validation)
  * `tests/integration/` — Multi-instance integration tests for discover,
    proxy-chain relay, and federated post delivery via BullMQ
  * `tests/helpers/` — Reusable DB, identity, and auth-user utilities
  * Playwright config updated to match new file conventions
  * Unused helpers (`tests/helpers/queue.ts`) removed

- **Social plugin endpoints** — Rewritten `follows.ts`, `blocks.ts`, `mutes.ts`,
  and `posts.ts` with proper federation integration. `social.ts` gains helpers
  for looking up posts by federation URL.

### Minor changes

- **README** — Expanded from a 42-line stub to a full architecture guide with
  tables for every layer (auth, DB, queues, storage, real-time), API route
  documentation, setup instructions, environment variables, test coverage, and
  the updated roadmap.

- **Federation helpers** — `keytools.ts` refactors imports and cleans up the public surface.
  `fetch.ts`, `registry.ts`, and `proxy-helpers/federated-post.ts` pick up small
  improvements. `PostFederationSchema` simplifies its encryption type assertion.

- **Plugin infrastructure** — Oven plugin schema and server index gain minor
  refactors. Social client adds a `muteUser` method.

- **UI components** — `switch.tsx` and `tooltip.tsx` rewritten for Radix v2 /
  Tailwind 4; `accordion.tsx`, `dropdown-menu.tsx`, `form`, `button`, `card` get
  minor consistency fixes. `dialog.tsx` removes unused `DialogHeader`.

- **Server bootstrap** — `server.ts` imports DB schema before `instrumentation`
  for correct Drizzle initialization, rate-limiting routes are wired, and CORS
  allows federation origins. `auth.ts` regenerates Oven and social plugin schemas.

- **Dependencies** — Added `@noble/ciphers` and `@noble/hashes` (crypto
  primitives). Removed `@signalapp/libsignal-client`, `base58-js`, `nanostores`,
  `tweetnacl-util`, `dexie-react-hooks`, `socket.io-client`. Updated all Better
  Auth packages to 1.6.11, BullMQ to 5.76.10, and various dev deps across the
  board.

- **.gitignore** — Added `/audits` and `tests/docker/*.env` to prevent secret
  leakage.

- **DB schema** — `blocks` table imported in `src/lib/db/schema/index.ts`.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 09:48:42 -03:00
Nixyan
e943fe227f feat: add Redis worker connection and improve health check job scheduling
- Introduced a new Redis worker connection function to manage worker-specific connections, enhancing reliability.
- Updated the health check job scheduling to use a SHA-256 hash for generating safe job IDs, improving uniqueness and security.
- Added a comprehensive README to document the federation background job queue, including job interfaces, exported functions, and usage examples.
- Refactored existing code for better organization and clarity, including updates to job processing and error handling.

This update aims to strengthen the federation's job processing capabilities and improve overall system documentation.
This update also finishes #4
2026-05-06 11:17:40 -03:00
Nixyan
66ebebd105 refactor: modularize plugins with federation and encryption infrastructure
Major changes:
- Restructure plugin architecture: moved federation logic into a dedicated `federation` plugin with Better Auth integration, defining schemas for server registry, key rotation, and blacklist management
- Extract encryption layer: new `oven` plugin handles end-to-end encryption (E2EE) with OLM client/server implementations
- Reorganize social features: consolidated social endpoints (posts, follows, blocks, mutes) and removed legacy plugin patterns in favor of unified plugin structure
- Decentralized key management: refactored `keytools` and `keygen` to support federation key rotation with challenge tokens and health checks

Infrastructure updates:
- Upgrade dependencies: bump Better Auth to 1.6.9, React to 19.2.5, Next.js to 16.2.3, Tailwind to 4.2.4
- Add cryptographic libraries: @scure/bip39, @signalapp/libsignal-client, @matrix-org/matrix-sdk-crypto-wasm for enhanced federation security
- Add utilities: base58-js, uuid for federation identifier handling
- Update database schema with new federation tables (serverRegistry, rotateChallengeTokens, blacklistedServers)

Minor updates: test suite alignment, storage client cleanup, PostFederationSchema refinements

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-05 11:40:14 -03:00
Nixyan
7049a40870 feat: enhance federation functionality by reworking the workers.
- Introduced single Redis connection for managing federation delivery jobs, improving reliability and performance.
- Updated environment configuration to include Redis connection details and allowed hostnames for CORS.
- Refactored existing code to streamline federation processes and improve error handling.
- Enhanced database schema to track acknowledgment status for follow requests.

This update aims to strengthen the federation's communication capabilities and ensure better handling of server interactions.

#3 #4
2026-04-08 10:35:59 -03:00
Nixyan
cb95c9cdba chore: update dependencies and enhance configuration
#3
2026-03-28 10:39:46 -03:00
Nixyan
1d619b9d2a feat: enhance federation functionality and improve documentation
- Added a new proxy route to relay encrypted federation traffic between servers, allowing for better communication in restricted environments.
- Implemented health check mechanisms for server registration, including tracking health status and scheduling health checks.
- Updated the database schema to include health check attempts and unhealthy reasons for servers.
- Enhanced the federation fetch logic to handle errors more gracefully and support proxying requests.
- Improved README documentation with a new section explaining public/private data handling and added links to mirrors.
- Refactored existing code for better organization and clarity, including updates to various federation-related modules.

#3

This should all be tested throughly, the workers are messy and poluted, a rework is needed and should be prioritized.
They work, but the code is poorly documented and there is no proper testing of the workers, some of them run twice and there are major issues on them.
2026-03-26 11:09:31 -03:00
Nixyan
9a6883a726 chore: update dependencies and configuration
- Updated package dependencies to their latest versions.
- Modified `next.config.ts` to dynamically set allowed development origins from environment variables.
- Enhanced `package.json` scripts for development and testing, adding new test commands for proxy tests.
- Adjusted Playwright configuration to use the updated server command for testing.

#3
2026-03-26 11:06:44 -03:00
Nixyan
1206e57638
Merge pull request #1 from tockawaffle/dependabot/npm_and_yarn/npm_and_yarn-229c191f58
chore(deps): bump next from 16.1.6 to 16.1.7 in the npm_and_yarn group across 1 directory
2026-03-18 08:52:53 -03:00
dependabot[bot]
328b1d35bb
chore(deps): bump next in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [next](https://github.com/vercel/next.js).


Updates `next` from 16.1.6 to 16.1.7
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.1.6...v16.1.7)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.1.7
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-17 19:35:23 +00:00
Nixyan
1c4d6e0acc docs: add mirrors section to README for repository links 2026-03-16 17:10:50 -03:00
Nixyan
d5d7f66f08 feat: enhance social follow functionality and federation integration
- Added support for following users with optional federation URLs, allowing for cross-server interactions.
- Implemented new endpoints for following and unfollowing users, including payload validation and error handling.
- Introduced federation delivery jobs to handle follow requests across different servers.
- Updated database schema to include references for follower and following server URLs.
- Enhanced URL validation to allow localhost during development while maintaining security checks.
- Refactored existing social endpoints to accommodate new follow logic and improve code organization.
2026-03-16 17:04:50 -03:00
Nixyan
c587737f38 feat: enhance federation key rotation and server discovery functionality
- Added new environment variables for MinIO configuration in .env.local.example.
- Updated package.json and bun.lock to include new dependencies for key management and encryption.
- Refactored server and route handling to support Ed25519 and X25519 key pairs for improved security during key rotation.
- Implemented validation for public keys and enhanced error handling in the discovery routes.
- Introduced new challenges for key rotation, ensuring secure communication between federations.
- Updated README with additional instructions for the new key rotation process.
2026-03-12 18:42:52 -03:00
Nixyan
75f3a0ed04 feat: enhance security and testing for federation routes. Added routes for uploading files to posts and initial logic of handling it client-side.
- Added a new test suite for attack vectors targeting the /discover federation routes, ensuring (known) vulnerabilities are addressed.
- Implemented a proxy function to check for blacklisted servers, enhancing security measures.
- Introduced URL validation to prevent SSRF attacks by blocking internal addresses.
- Updated package.json with a new test command for the attack tests.
- Refactored server and route handling to improve type safety and error handling.
- Added new middleware for blacklist checks and URL validation to prevent unauthorized access.
2026-03-11 11:48:38 -03:00
Nixyan
b1d3dda308 fix: fixed the comment that was out of # 2026-03-10 18:28:30 -03:00
Nixyan
28ad8483c0 fix: fix federation key generation and update dependencies
- Reintroduced the command for generating federation keys in the package.json.
- Updated the route for server discovery to use the new BETTER_AUTH_URL environment variable.
- Added checks to ensure federation keys are set before authentication.
- Updated package dependencies, including the addition of the 'minio' package and updates to '@types/node' and 'shadcn'.
2026-03-10 18:26:31 -03:00
Nixyan
462bf95275 docs: add security section to README 2026-03-10 14:17:54 -03:00
Nixyan
8309770be5 feat: add server discovery tests and enhance public key validation
- Introduced a new test suite for server discovery functionality, ensuring proper registration and response handling.
- Enhanced public key validation logic to include detailed error messages for invalid keys.
- Updated package.json with a new test command for the discovery tests.
- Removed outdated Playwright CI workflow configuration.
2026-03-10 14:05:04 -03:00
Nixyan
ea172050a6 feat: implement server discovery and key rotation functionality
- Added new routes for server discovery and key rotation, including challenge issuance and confirmation processes.
- Introduced database schema for managing server registrations and rotation challenges.
- Implemented encryption and decryption utilities for secure communication between servers.
- Updated package dependencies and added new client and server plugins for social features.
- Enhanced user management with additional fields and relations in the database schema.
2026-03-09 21:37:59 -03:00
Nixyan
b1b80dd75b feat: added auth page and the whole functionallity surrounding it.
feat: added tests (not working currently, will fix later)

chore: removed turnstile dep. will check later other options.
2026-03-06 16:21:42 -03:00
Nixyan
87196d312e Restarting the project once again.
This commit has the skeleton of what is going to be the app.
2026-03-05 18:52:46 -03:00
227 changed files with 29895 additions and 17756 deletions

11
.cursor/mcp.json Normal file
View file

@ -0,0 +1,11 @@
{
"mcpServers": {
"next-devtools": {
"command": "npx",
"args": [
"-y",
"next-devtools-mcp@latest"
]
}
}
}

23
.dockerignore Normal file
View file

@ -0,0 +1,23 @@
# Deps and build output — reinstalled inside the image
node_modules
.next
out
build
# Local environment — secrets must come from Docker Compose, not the image
.env.local
.env
# Tests and tooling output — not needed at runtime
test-results
playwright-report
blob-report
coverage
# Version control
.git
.gitignore
# Editor artefacts
.DS_Store
*.pem

29
.env.local.example Normal file
View file

@ -0,0 +1,29 @@
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=
# Should follow the format: redis://<host>:<port>
# Could use password and username if needed
REDIS_URL=
# Comma separated list of allowed hostnames for CORS
# Example: DEV_ALLOWED_HOSTNAMES=localhost,127.0.0.1,::1
DEV_ALLOWED_HOSTNAMES=
DATABASE_URL=postgresql://<username>:<password>@<host>:<port>/<database>
EMAIL_HOST=
EMAIL_PORT=
EMAIL_SECURE=
EMAIL_USER=
EMAIL_PASSWORD=
DEBUG=app:*,test:*
MINIO_BUCKET=
MINIO_ENDPOINT=
MINIO_PORT=
MINIO_USE_SSL=
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
NEXT_PUBLIC_GIT_URL=

20
.gitignore vendored
View file

@ -23,6 +23,7 @@
# misc
.DS_Store
*.pem
/audits
# debug
npm-debug.log*
@ -31,7 +32,14 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env.local
.env
# Docker instance env files (contain federation keys + secrets)
# Regenerate with: bun run docker:generate-keys
tests/docker/sipher-a.env
tests/docker/sipher-b.env
tests/docker/sipher-c.env
# vercel
.vercel
@ -40,6 +48,10 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
# OLM (copied from node_modules by scripts/copy-olm.js)
/public/olm.js
/public/olm.wasm
# Playwright
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/

View file

@ -10,7 +10,6 @@
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": true,
"typescript.preferences.quoteStyle": "double",
"editor.formatOnSaveMode": "file",
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"

27
Dockerfile Normal file
View file

@ -0,0 +1,27 @@
FROM node:22
WORKDIR /app
# ---- Bun ----
RUN curl -fsSL https://bun.sh/install | bash
ENV PATH="/root/.bun/bin:$PATH"
# ---- dependencies ----
# Copy lockfile first so this layer is only rebuilt when deps change.
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
# Some packages ship pre-built native binaries via a post-install download script.
# Run it here so the layer is cached and not re-downloaded on every code change.
RUN bun run build:matrix || true
# ---- source ----
COPY . .
# Never bake secrets into the image; env vars come from Docker Compose or the host.
RUN rm -f .env.local
EXPOSE 3000
# Bun runs TypeScript natively — no separate tsx invocation needed.
CMD ["bun", "run", "src/server.ts"]

661
LICENSE
View file

@ -1,7 +1,660 @@
Copyright 2026 Marcello Brito
# GNU AFFERO GENERAL PUBLIC LICENSE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Version 3, 19 November 2007
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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.
SiPher
Copyright (C) 2026 Marcello Brito
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/>.

432
README.md
View file

@ -1,4 +1,430 @@
please don't use this
I made this to test things
# SiPher
I am not to be trusted under any circunstances
> *Silent Whisper — A federated social network built for the modern age.*
[![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
![Version](https://img.shields.io/badge/version-0.2.0-purple.svg)
![Status](https://img.shields.io/badge/status-early%20development-orange.svg)
SiPher is a federated social network. Each server is independent, no central authority, no single point of failure.
Your identity is `you@<base58_id>`. Your data, your rules.
Every user controls their own Ed25519 keypair generated from a BIP-39 mnemonic. The secret key never leaves the browser. Posts, follows, and every social action are signed client-side and verified server-side.
---
## Architecture
SiPher runs as a single Node.js process that serves both the web app and the federation API.
| Layer | Technology |
| -------------- | ------------------------------------------------------------------------------------- |
| Framework | Next.js 16 (App Router, React 19, standalone output) |
| Authentication | [Better Auth](https://better-auth.com) — email/password, username, 2FA, bearer tokens |
| Database | PostgreSQL via [Drizzle ORM](https://orm.drizzle.team) |
| Cache / Queues | Redis — session storage, rate limiting, BullMQ background jobs |
| Object Storage | MinIO (S3-compatible) — media uploads with presigned URLs |
| Client Storage | IndexedDB (Dexie) — encrypted identity keypairs |
| Real-time | Socket.IO — firehose channel for live updates |
| UI | Tailwind CSS v4, shadcn/ui, Radix primitives, Framer Motion |
### Custom Better Auth Plugins
SiPher extends Better Auth with three custom plugins, each registering its own database schema and API endpoints:
- **sipher-federation** — Server registry, key rotation challenges, blacklist management.
- **sipher-social** — Posts, follows, blocks, mutes as Better Auth API endpoints.
- **sipher-oven** — E2EE identity registration (Ed25519 keys, OLM device key bundles).
### API Routes
| Route | Purpose |
| -------------------------------- | -------------------------------------------------- |
| `GET /discover` | Return this server's public keys and healthy peers |
| `POST /discover` | Discover or register a remote server |
| `POST /discover/rotate/init` | Initiate key rotation (4 challenges) |
| `POST /discover/rotate/confirm` | Submit key rotation proofs |
| `POST /proxy` | Relay federation traffic through a proxy peer |
| `POST /api/auth/social/posts` | Create or receive a federated post |
| `GET /api/auth/social/posts/:id` | Get a post |
| `POST /api/auth/social/follows` | Follow, respond, or federate a follow |
| `POST /api/auth/social/blocks` | Block a user (auto-cleanses follows both ways) |
| `POST /api/auth/social/mutes` | Mute a user |
| `POST /oven/identity/register` | Register a user's public identity key |
| `POST /oven/keys/upload` | Upload OLM device key bundle |
| `GET /oven/identity/check` | Check identity registration status |
---
## Identity & E2EE
### User Identity (the "Oven")
Every SiPher user has a cryptographic identity generated entirely in the browser:
1. A **BIP-39 mnemonic** (12 words, 128-bit entropy) is generated.
2. An **Ed25519 keypair** is derived from the mnemonic seed via HKDF-SHA256.
3. The keypair is **encrypted with AES-256-GCM** and stored in IndexedDB via Dexie. The encryption key is derived from the user's master password (PBKDF2, 600k iterations).
4. The public key (base58) and a fingerprint are uploaded to the server.
5. **OLM device keys** are generated and all public keys are uploaded to the server for Matrix-protocol-based E2EE messaging.
### Session Key Store
Once unlocked, the Ed25519 keypair is held in module-level memory and `sessionStorage`. The sessionStorage layer means the key survives hard page reloads within the same tab but is cleared when the tab closes. It is intentionally NOT stored in `localStorage`.
The session key store exposes a simple `sign(message)` function that uses the cached secret key. For one-shot operations where you don't want to cache the key across the session, the Oven plugin provides `useSigningKey` — a callback API that decrypts the key, hands the caller a sign closure, and zeroes the in-memory secret immediately after the callback resolves. The secret never escapes that scope.
### Unlock Flow
1. On page load, `UnlockIdentityModal` tries `restoreSessionKey()` from sessionStorage.
2. If that fails, the user is prompted for their master password.
3. On correct password, `unlockSessionKey()` decrypts the Dexie blob, caches the keypair, and notifies listeners via a pub/sub pattern.
4. On logout, `clearSessionKey()` zeroes the in-memory secret and clears sessionStorage.
---
## Federation
### Discovery & Registration
Every server exposes its public keys via `GET /discover`. A server can register a peer by sending a `REGISTER` request to the peer's `/discover` endpoint. The registration flow:
1. Validates the URL is safe (SSRF guard — see Security section).
2. Fetches the remote `/discover` to confirm the claimed keys match.
3. Upserts into the `serverRegistry` table.
4. Returns an echo of the registering server's own keys.
The `DISCOVER` method lets a server look up another server by signing public key and confirm that the stored keys still match the live peer.
### Proxy Relay
When two servers cannot reach each other directly (censorship, NAT, firewall), traffic can be routed through a mutual peer:
- **PROXY method** — Server A sends an encrypted payload + target URL + its public keys to proxy peer B. B verifies both A and C are registered, forwards to C as a `TARGETED` request, and returns the encrypted response.
- **TARGETED method** — Server C decrypts the inner payload, validates signatures, processes the action (follow, post), and returns an encrypted acknowledgment.
The proxy **never sees plaintext content**. It only knows "Server A is talking to Server B."
A threat model (`threat-model.ts`) classifies network errors and determines whether proxy fallback is eligible:
| Error | Proxy-Eligible | Direct Health-Checkable |
| ---------------- | -------------- | ----------------------- |
| DNS_BLOCKED | Yes | No |
| TLS_ERROR | No | Yes |
| TIMEOUT | No | Yes |
| CONN_REFUSED | No | Yes |
| INVALID_RESPONSE | Yes | No |
### Background Jobs (BullMQ)
Two Redis-backed queues handle asynchronous federation operations:
- **Federation delivery queue** — Encrypts and delivers activity (follows, posts, unfollows) to remote servers. 10 concurrent workers, up to 5 retries with exponential backoff (5s base). On success, the delivery job record is cleaned up automatically.
- **Health-check queue** — Probes unhealthy servers via `GET /discover` with exponential backoff (5min, 15min, 25min...), up to 5 attempts. If a server responds, it is re-marked healthy.
Workers are started automatically at application bootstrap via Next.js `instrumentation.ts`.
### Key Rotation
Federation identity is tied to two keypairs (Ed25519 for signing, X25519 for encryption). The `rotateKeys.ts` script walks through every known federation, proves ownership of both the old and new keys via a challenge-response protocol, and updates `.env.local` when all federations confirm.
Each rotation requires proving possession of **four** things to each peer:
1. Old signing key (sign a challenge nonce)
2. New signing key (sign a challenge nonce)
3. Old encryption key (decrypt a challenge nonce)
4. New encryption key (decrypt a challenge nonce)
Failed confirmations do **not** auto-blacklist the server — preventing griefing attacks where anyone could spam init for a victim URL to get them banned.
---
## Setup
### Prerequisites
- [Node.js](https://nodejs.org/) 20+
- [Bun](https://bun.sh/) (for tooling scripts and key generation)
- [PostgreSQL](https://www.postgresql.org/) 15+
- [Redis](https://redis.io/) 7+
- (Optional) [MinIO](https://min.io/) or any S3-compatible object store for media
### Environment Variables
Copy `.env.local.example` to `.env.local` and populate:
```env
# SiPher server URL (your canonical public address)
BETTER_AUTH_URL=https://your-server.com
# Better Auth secret (generate with: openssl rand -hex 32)
BETTER_AUTH_SECRET=<random-hex>
# PostgreSQL connection
DATABASE_URL=postgresql://user:password@host:5432/sipher
# Redis connection
REDIS_URL=redis://host:6379
# Federation signing keypair (Ed25519, base64)
# Generate with: npm run keygen
FEDERATION_PUBLIC_KEY=<base64>
FEDERATION_PRIVATE_KEY=<base64>
# Federation encryption keypair (X25519, base64)
FEDERATION_ENCRYPTION_PUBLIC_KEY=<base64>
FEDERATION_ENCRYPTION_PRIVATE_KEY=<base64>
# MinIO / S3 storage (optional, only if using media uploads)
MINIO_BUCKET=sipher
MINIO_ENDPOINT=minio.your-server.com
MINIO_PORT=443
MINIO_USE_SSL=true
MINIO_ACCESS_KEY=<access-key>
MINIO_SECRET_KEY=<secret-key>
# SMTP email (optional, used for verification emails)
EMAIL_HOST=smtp.your-server.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=noreply@your-server.com
EMAIL_PASSWORD=<password>
# Development only: override SSRF guard to allow private IPs
# DEV_ALLOWED_HOSTNAMES=localhost,127.0.0.1,::1
# Debug logging namespaces
DEBUG=app:*,test:*
```
### Database
The schema is managed via Drizzle Kit. Everything is auto-generated from Better Auth's schema generator plus the custom plugin schemas.
```sh
# Push schema directly (development)
npm run db:push
# Or generate a migration and apply it
npm run db:generate
npm run db:migrate
```
### Federation Keys
```sh
npm run keygen
```
This runs `src/lib/federation/keygen.ts`, which generates both Ed25519 (signing) and X25519 (encryption) keypairs and writes them to `.env.local`.
---
## Scripts
| Command | Purpose |
| ----------------------------------- | ------------------------------------------------------------- |
| `npm run dev` | Start development server (enables private URLs for local dev) |
| `npm run build` | `next build` |
| `npm run start` | Production start (`node src/server.ts`) |
| `npm run keygen` | Generate federation signing + encryption keys |
| `npm run build:matrix` | Download native Matrix crypto WASM binary |
| `npm run email:dev` | React Email dev server (port 3001) |
| `npm run db:push` | Push Drizzle schema to database |
| `npm run db:migrate` | Push + migrate (two-step) |
| `npm run db:generate` | Regenerate Better Auth schema + Drizzle files |
| `npm run db:update` | Generate + push |
| `npm run test` | Run Playwright e2e tests (`**/*.e2e.ts`) |
| `npm run test:federation` | Key rotation e2e tests |
| `npm run test:key` | Key rotation e2e tests only |
| `npm run test:proxy` | Proxy `/proxy` route e2e tests (single-server validation) |
| `npm run docker:test:discover` | `/discover` integration tests against the 3-instance cluster |
| `npm run docker:test:proxy-chain` | Proxy relay + failover integration tests |
| `npm run docker:test:post-delivery` | Federated post delivery integration test |
---
## Rotating Federation Keys
**Rotating Federation Keys**
Federation identity is tied to two keypairs (Ed25519 for signing, X25519 for encryption). The `rotateKeys.ts` script walks through every known federation, proves ownership of both the old and new keys via a challenge-response protocol, and updates `.env.local` when all federations confirm.
You **need** the old keys in order to run this script. If you lost them, there is currently no recovery mechanism.
### Prerequisites
- A running database with the server registry populated (at least one peer federation).
- `.env.local` with valid `FEDERATION_`* keys and `BETTER_AUTH_URL`.
### Basic rotation
```sh
bun run rotateKeys.ts
```
The script will:
1. List all federations in the registry.
2. Ask for confirmation before proceeding.
3. For each federation: request a challenge, solve it, and confirm.
4. On full success: back up `.env.local` and write the new keys.
5. On any failure: print a retry command and exit without writing keys.
### Retrying after partial failure
If some federations failed while others succeeded, the script prints a ready-to-copy command targeting only the failures:
```sh
bun run rotateKeys.ts --resume '<keys-json>' --only '<failed-urls>'
```
- `--resume <json>` — Reuse the new keys from the previous run instead of generating fresh ones (required because successful federations already registered them).
- `--only <urls>` — Comma-separated list of federation URLs to retry. Federations not in this list are skipped.
You can also retry all federations with just `--resume`:
```sh
bun run rotateKeys.ts --resume '<keys-json>'
```
---
## Tests
SiPher uses [Playwright](https://playwright.dev) for integration/e2e tests (matched by `**/*.e2e.ts`) and [Bun's test runner](https://bun.sh/docs/cli/test) for unit tests (matched by `**/*.test.ts`).
### Running tests
```sh
npm test # All Playwright e2e tests
npm run test:federation # Discover + key rotation tests
npm run test:proxy # Proxy relay tests
bun test # Bun unit tests (keytools, etc.)
```
Playwright starts the server automatically via `tsx src/server.ts` with `NODE_ENV=test`. The Playwright suites that remain (`tests/proxy/proxy.e2e.ts`, `tests/federation/key-rotation.e2e.ts`) drive their own local DB state and don't need the federation cluster. Anything that exercises real peer-to-peer federation — `/discover` REGISTER/DISCOVER, proxy relay, federated post delivery — lives under `tests/integration/` and runs against the dockerized 3-instance cluster.
### Docker-based integration tests
Three integration scripts exercise the federation protocol against a real 3-instance Docker cluster (A, B, C) with mutual discovery. All three auto-create their own Better Auth users + identity keys via HTTP — no `--bearer` token needed.
```sh
# Run inside the Docker test cluster (A, B, C must be healthy):
docker compose -f tests/docker-compose.yml run --rm test-runner \
tests/integration/discover.ts --peer http://sipher-c:3002
docker compose -f tests/docker-compose.yml run --rm test-runner \
tests/integration/federation-post-delivery.ts \
--proxy http://sipher-b:3001 --target http://sipher-c:3002
docker compose -f tests/docker-compose.yml run --rm test-runner \
tests/integration/proxy-chain.ts \
--proxy http://sipher-b:3001 --target http://sipher-c:3002
```
These test the `/discover` REGISTER and DISCOVER handshake with real encrypted envelopes, the Post → BullMQ delivery → proxy fallback pipeline, and the full PROXY/TARGETED relay chain respectively.
### Test coverage
- **Discover e2e** — SSRF guards, key mismatch rejection, REGISTER and DISCOVER happy paths, encrypted envelope validation.
- **Key rotation e2e** — Full init → solve → confirm flow, rate limiting, expired challenges, exhausted attempts without blacklist-griefing.
- **Proxy e2e** — PROXY and TARGETED validation, unknown sender rejection, blacklist enforcement, signature verification, duplicate follow rejection, rate limiting, payload size limits.
- **Keytools unit** — Encryption round-trip, tamper detection, signature verification, deterministic fingerprinting.
- **Integration (docker)** — Post delivery via proxy fallback, full proxy chain relay, discover round-trips.
---
## Roadmap
- **[X] Federation key rotation** — Challenge-response protocol for rotating Ed25519 + X25519 keypairs across all peers.
- **[X] Proxy relay** — Traffic routed through mutual peers when direct connections fail. Proxy is blind to content.
- **[X] Background delivery** — BullMQ queues for async federation delivery with retries and health monitoring.
- **[X] Serialization format** — The JSON-based federation schema (EncryptedEnvelope, FollowSchema, PostFederationSchema).
- **[X] SSRF protection** — URL guard blocking private/internal IPs, blocked hostnames, non-HTTP protocols.
- **[X] Client-side identity** — BIP-39 mnemonics, Ed25519 keypairs, encrypted IndexedDB storage, session key cache.
- **[X] Rate limiting** — Per-route and per-origin sliding-window rate limits enforced server-side.
- **[X] Threat model** — Error-code classification dictating proxy eligibility and health-check strategy.
- **[ ] Discovery propagation** — When a new server is registered, propagate its existence to all known peers.
- **[ ] Server trust scoring** — A public vouch ledger so servers can signal trustworthiness about peers.
- **[ ] End-to-end encryption** — OLM device keys are already uploaded. The encrypted message transport ("Oven") needs to be wired into the messaging layer.
- **[ ] Web UI** — The frontend is minimal (dev test form and auth pages). A proper feed, profile pages, notifications, and settings UI need to be built.
- **[ ] Federation status dashboard** — View connected peers, health status, pending deliveries, and rotation logs.
---
## What is public/private?
### Public (visible to receiving federations)
Post content is encrypted in transit between servers (X25519 key agreement + HKDF + AES-256-GCM), but the receiving federation decrypts and stores the plaintext:
- **Posts**: Content (text, images, video, audio, links), authorId, publication date, and the federation of origin.
- **Profiles**: Username, display name, public key fingerprint.
- **Follow graph**: Who follows whom (used for federation routing to deliver posts to the right servers).
### Private (server-side, not federated)
- **Mutes/blocks**: Stored server-side, never sent to other federations.
- **Passwords**: Hashed by Better Auth, never stored in plaintext.
### Private (client-side, never sent to server)
- **Ed25519 secret key**: Derived from a BIP-39 mnemonic. Encrypted in IndexedDB (AES-256-GCM with PBKDF2, 600k iterations), decrypted on login and held in module memory + sessionStorage for tab-scoped persistence. Cleared on logout or tab close. Never transmitted to any server.
- **BIP-39 mnemonic**: Shown to the user once during identity creation, then discarded. The only recovery mechanism.
### Client-side signing
All social actions are signed by the user's Ed25519 identity key before submission:
- **Posts** — The `authorSignature` field contains a detached Ed25519 signature covering the canonical post payload (`postId`, `authorId`, `publishedAt`, `content`, `federationUrl`). Verified server-side before storage.
- **Follows** — Follow requests and responses carry detached Ed25519 signatures (`requesterSignature`, `responderSignature`) covering a canonical payload that includes `federationUrl` to prevent cross-server replay.
---
## Security
SiPher implements custom federation and cryptographic protocols. I am not a professional cryptographer or security researcher — this system has not been audited and almost certainly contains multiple vulnerabilities I am not aware of.
### What SiPher does for safety
- **SSRF protection**: A URL guard (`url-guard.ts`) blocks requests to private/internal IPv4 ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, link-local), IPv6 ULA and link-local addresses, blocked hostnames (localhost, metadata endpoints), and non-HTTP(S) protocols. Only overridable via `DEV_ALLOWED_HOSTNAMES` env var.
- **Federation encryption**: All cross-server payloads are encrypted with X25519 + AES-256-GCM (hybrid ECIES). Ephemeral keys per message.
- **Canonical signatures**: Posts and follows are signed with a versioned byte format (`v: 2`) that includes the federation URL to prevent cross-server replay attacks.
- **Key rotation requires 4 proofs**: Possession of both old and new keypairs must be proven before keys are updated. Failed confirmations don't auto-blacklist (prevents griefing).
- **No secret key on server**: User Ed25519 secret keys never leave the browser. The server only stores public keys and OLM device key bundles.
- **Session-scoped key caching**: The signing key lives in module memory + sessionStorage (not localStorage). It is zeroed on logout and cleared when the tab closes.
- **Rate limiting**: Per-route sliding-window limits prevent abuse of registration, key rotation, and proxy endpoints.
If you find a vulnerability, please open an issue or contact me directly at [tocka@tockanest.com](mailto:tocka@tockanest.com). Responsible disclosure is appreciated.
Contributions from people with security or cryptography experience are especially welcome, even if just pure criticism.
**Do not use SiPher in any context where your physical safety depends on it — not yet.**
---
## Author
**Marcello Brito** (Tocka) — [tockanest.com](https://tockanest.com)
## Mirrors
[Forgejo](https://git.tockanest.com/Cete/sipher)
[GitHub](https://github.com/tockawaffle/sipher)
## License
[AGPL-3.0](./LICENSE)

1769
bun.lock

File diff suppressed because it is too large Load diff

View file

@ -6,11 +6,12 @@
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"baseColor": "stone",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",

File diff suppressed because it is too large Load diff

View file

@ -1,23 +0,0 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import { anyApi, componentsGeneric } from "convex/server";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api = anyApi;
export const internal = anyApi;
export const components = componentsGeneric();

View file

@ -1,58 +0,0 @@
/* eslint-disable */
/**
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import { AnyDataModel } from "convex/server";
import type { GenericId } from "convex/values";
/**
* No `schema.ts` file found!
*
* This generated code has permissive types like `Doc = any` because
* Convex doesn't know your schema. If you'd like more type safety, see
* https://docs.convex.dev/using/schemas for instructions on how to add a
* schema file.
*
* After you change a schema, rerun codegen with `npx convex dev`.
*/
/**
* The names of all of your Convex tables.
*/
export type TableNames = string;
/**
* The type of a document stored in Convex.
*/
export type Doc = any;
/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*/
export type Id<TableName extends TableNames = TableNames> =
GenericId<TableName>;
/**
* A type describing your Convex data model.
*
* This type includes information about what tables you have, the type of
* documents stored in those tables, and the indexes defined on them.
*
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = AnyDataModel;

View file

@ -1,143 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const query: QueryBuilder<DataModel, "public">;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const internalQuery: QueryBuilder<DataModel, "internal">;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const mutation: MutationBuilder<DataModel, "public">;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const internalMutation: MutationBuilder<DataModel, "internal">;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export declare const action: ActionBuilder<DataModel, "public">;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export declare const internalAction: ActionBuilder<DataModel, "internal">;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export declare const httpAction: HttpActionBuilder;
/**
* A set of services for use within Convex query functions.
*
* The query context is passed as the first argument to any Convex query
* function run on the server.
*
* This differs from the {@link MutationCtx} because all of the services are
* read-only.
*/
export type QueryCtx = GenericQueryCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*/
export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex action functions.
*
* The action context is passed as the first argument to any Convex action
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<DataModel>;
/**
* An interface to read from the database within Convex query functions.
*
* The two entry points are {@link DatabaseReader.get}, which fetches a single
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
* building a query.
*/
export type DatabaseReader = GenericDatabaseReader<DataModel>;
/**
* An interface to read from and write to the database within Convex mutation
* functions.
*
* Convex guarantees that all writes within a single mutation are
* executed atomically, so you never have to worry about partial writes leaving
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
* for the guarantees Convex provides your functions.
*/
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;

View file

@ -1,93 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/server";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query = queryGeneric;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const internalQuery = internalQueryGeneric;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const mutation = mutationGeneric;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const internalMutation = internalMutationGeneric;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export const action = actionGeneric;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const internalAction = internalActionGeneric;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export const httpAction = httpActionGeneric;

View file

@ -1,8 +0,0 @@
import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config";
import type { AuthConfig } from "convex/server";
export default {
providers: [
getAuthConfigProvider(),
],
} satisfies AuthConfig;

View file

@ -1,256 +0,0 @@
import { createClient, type GenericCtx } from "@convex-dev/better-auth";
import { convex } from "@convex-dev/better-auth/plugins";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { captcha, oneTimeToken, openAPI, username } from "better-auth/plugins";
import { v } from "convex/values";
import { components } from "./_generated/api";
import { DataModel } from "./_generated/dataModel";
import { mutation, query } from "./_generated/server";
import authConfig from "./auth.config";
import authSchema from "./betterAuth/schema";
const siteUrl = process.env.SITE_URL!;
// The component client has methods needed for integrating Convex with Better Auth,
// as well as helper methods for general use.
export const authComponent = createClient<DataModel, typeof authSchema>(
components.betterAuth,
{
local: {
schema: authSchema
}
}
);
export const createAuthOptions = (ctx: GenericCtx<DataModel>) => {
return {
baseURL: siteUrl,
database: authComponent.adapter(ctx),
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
autoSignIn: true
},
trustedOrigins: [
siteUrl,
"http://localhost:8081",
"https://sipher.tockanest.com"
],
user: {
additionalFields: {
metadata: {
type: "json",
required: false,
},
friends: {
type: "string[]",
required: false,
index: true
}
},
},
plugins: [
convex({
authConfig,
jwksRotateOnTokenGenerationError: true,
}),
captcha({
provider: "cloudflare-turnstile",
secretKey: process.env.CAPTCHA_SECRET_KEY!,
}),
username({
displayUsernameValidator: (displayUsername) => {
// Allow only alphanumeric characters, underscores, and hyphens
return /^[a-zA-Z0-9_-]+$/.test(displayUsername)
}
}),
oneTimeToken(),
openAPI(),
],
} satisfies BetterAuthOptions;
}
export const createAuth = (
ctx: GenericCtx<DataModel>
) => {
return betterAuth(createAuthOptions(ctx));
};
// Example function for getting the current user
// Feel free to edit, omit, etc.
export const getCurrentUser = query({
args: {},
handler: async (ctx) => {
return authComponent.getAuthUser(ctx);
},
});
export const sendKeysToServer = mutation({
args: {
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
forceInsert: v.boolean(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.olm.index.sendKeysToServer, {
userId: args.userId,
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys,
forceInsert: args.forceInsert,
});
},
});
export const retrieveServerOlmAccount = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.olm.index.retrieveServerOlmAccount, {
userId: args.userId,
});
},
});
export const updateUserStatus = mutation({
args: {
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
isUserSet: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.updateUserStatus, {
status: args.status,
isUserSet: args.isUserSet,
});
},
});
export const getNonOfflineUserIds = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getNonOfflineUserIds, {});
},
});
export const forceUserOffline = mutation({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.forceUserOffline, {
userId: args.userId,
});
},
});
export const updateUserMetadata = mutation({
args: {
metadata: v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
}),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.updateUserMetadata, {
metadata: args.metadata,
});
},
});
export const sendFriendRequest = mutation({
args: {
username: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.sendFriendRequest, {
username: args.username,
});
},
});
export const answerFriendRequest = mutation({
args: {
requestId: v.string(),
answer: v.union(v.literal("accept"), v.literal("decline"), v.literal("ignore")),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.answerFriendRequest, {
requestId: args.requestId,
answer: args.answer,
});
},
});
export const getFriendRequests = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getFriendRequests)
},
});
export const getFriends = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getFriends)
},
});
export const getUserStatus = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getUserStatus)
},
});
export const getParticipantDetails = query({
args: {
participantIds: v.array(v.string()),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.user.index.getParticipantDetails, {
participantIds: args.participantIds,
});
},
});
export const consumeOTK = mutation({
args: {
userId: v.string(),
keyId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.olm.index.consumeOTK, {
userId: args.userId,
keyId: args.keyId,
});
},
});
export const getKeyVersion = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.olm.index.getKeyVersion, {
userId: args.userId,
});
},
});
export const migrateOlmAccounts = mutation({
handler: async (ctx) => {
return ctx.runMutation(components.betterAuth.olm.index.migrateOlmAccounts, {});
},
});
export const getUserNests = query({
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.nests.locals.getUserNests);
},
});

View file

@ -1,62 +0,0 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type * as adapter from "../adapter.js";
import type * as auth from "../auth.js";
import type * as nests_locals from "../nests/locals.js";
import type * as olm_index from "../olm/index.js";
import type * as schemas_nests from "../schemas/nests.js";
import type * as schemas_user from "../schemas/user.js";
import type * as user_index from "../user/index.js";
import type {
ApiFromModules,
FilterApi,
FunctionReference,
} from "convex/server";
import { anyApi, componentsGeneric } from "convex/server";
const fullApi: ApiFromModules<{
adapter: typeof adapter;
auth: typeof auth;
"nests/locals": typeof nests_locals;
"olm/index": typeof olm_index;
"schemas/nests": typeof schemas_nests;
"schemas/user": typeof schemas_user;
"user/index": typeof user_index;
}> = anyApi as any;
/**
* A utility for referencing Convex functions in your app's public API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
> = anyApi as any;
/**
* A utility for referencing Convex functions in your app's internal API.
*
* Usage:
* ```js
* const myFunctionReference = internal.myModule.myFunction;
* ```
*/
export const internal: FilterApi<
typeof fullApi,
FunctionReference<any, "internal">
> = anyApi as any;
export const components = componentsGeneric() as unknown as {};

File diff suppressed because it is too large Load diff

View file

@ -1,60 +0,0 @@
/* eslint-disable */
/**
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
DataModelFromSchemaDefinition,
DocumentByName,
TableNamesInDataModel,
SystemTableNames,
} from "convex/server";
import type { GenericId } from "convex/values";
import schema from "../schema.js";
/**
* The names of all of your Convex tables.
*/
export type TableNames = TableNamesInDataModel<DataModel>;
/**
* The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames | SystemTableNames> =
GenericId<TableName>;
/**
* A type describing your Convex data model.
*
* This type includes information about what tables you have, the type of
* documents stored in those tables, and the indexes defined on them.
*
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;

View file

@ -1,156 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const internalQuery: QueryBuilder<DataModel, "internal"> =
internalQueryGeneric;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const internalMutation: MutationBuilder<DataModel, "internal"> =
internalMutationGeneric;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const internalAction: ActionBuilder<DataModel, "internal"> =
internalActionGeneric;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export const httpAction: HttpActionBuilder = httpActionGeneric;
/**
* A set of services for use within Convex query functions.
*
* The query context is passed as the first argument to any Convex query
* function run on the server.
*
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
*/
export type QueryCtx = GenericQueryCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
*/
export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex action functions.
*
* The action context is passed as the first argument to any Convex action
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<DataModel>;
/**
* An interface to read from the database within Convex query functions.
*
* The two entry points are {@link DatabaseReader.get}, which fetches a single
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
* building a query.
*/
export type DatabaseReader = GenericDatabaseReader<DataModel>;
/**
* An interface to read from and write to the database within Convex mutation
* functions.
*
* Convex guarantees that all writes within a single mutation are
* executed atomically, so you never have to worry about partial writes leaving
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
* for the guarantees Convex provides your functions.
*/
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;

View file

@ -1,13 +0,0 @@
import { createApi } from "@convex-dev/better-auth";
import { createAuthOptions } from "../auth";
import schema from "./schema";
export const {
create,
findOne,
findMany,
updateOne,
updateMany,
deleteOne,
deleteMany,
} = createApi(schema, createAuthOptions);

View file

@ -1,4 +0,0 @@
import { createAuth } from '../auth';
// Export a static instance for Better Auth schema generation
export const auth = createAuth({} as any)

View file

@ -1,5 +0,0 @@
import { defineComponent } from "convex/server";
const component = defineComponent("betterAuth");
export default component;

View file

@ -1,60 +0,0 @@
import { UserIdentity } from "convex/server";
import { Doc, Id } from "../_generated/dataModel";
import { MutationCtx, query, QueryCtx } from "../_generated/server";
// Overload signatures
async function userValidation(ctx: MutationCtx | QueryCtx, options: { required: false }): Promise<{ userId: Id<"user">; user: any } | null>;
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: true }): Promise<{ userId: Id<"user">; user: UserIdentity }>;
// Implementation
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: boolean }) {
const required = options?.required ?? true;
const user = await ctx.auth.getUserIdentity();
if (!user) {
if (required) throw new Error("User not found");
return null;
}
const userId = ctx.db.normalizeId("user", user.subject as string) as Id<"user">;
if (!userId) {
if (required) throw new Error("User not found");
return null;
}
return { userId, user };
}
export const getUserNests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx, { required: true });
if (!userId) throw new Error("User not found");
const getUser = await ctx.db.get<"user">(userId);
if (!getUser) throw new Error("User not found");
else if (!getUser.nests || getUser.nests.length === 0) return [];
// Get the nests the user is a member of
const nests: Doc<"nests">[] = [];
for (const nestId of getUser.nests) {
const nest = await ctx.db.get<"nests">(nestId);
if (!nest) continue;
nests.push(nest);
}
return nests;
}
});
export const getRecommendedNests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx, { required: true });
if (!userId) throw new Error("User not found");
const getUser = await ctx.db.get<"user">(userId);
if (!getUser) throw new Error("User not found");
const nests = await ctx.db.query<"nests">("nests").withIndex("onDiscover", q => q.eq("onDiscover", true)).collect();
return nests;
}
});

View file

@ -1,143 +0,0 @@
import { v } from "convex/values";
import { mutation, query } from "../_generated/server";
export const sendKeysToServer = mutation({
args: {
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
forceInsert: v.boolean(), // if true, insert even if user already has an olm account
},
handler: async (ctx, args) => {
const now = Date.now();
// check if user already has an olm account
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (olmAccount && !args.forceInsert) {
throw new Error("User already has an olm account");
} else if (olmAccount && args.forceInsert) {
// Keys are being rotated - increment version and update timestamp
await ctx.db.patch(olmAccount._id, {
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys,
updatedAt: now,
keyVersion: (olmAccount.keyVersion || 0) + 1,
});
// Notify all users who have sessions with this user that their sessions are now invalid
// This will be handled client-side by checking key versions
console.log(`[OLM] Keys rotated for user ${args.userId}, new version: ${(olmAccount.keyVersion || 0) + 1}`);
return { ...olmAccount, keyVersion: (olmAccount.keyVersion || 0) + 1 };
}
// Create new account with initial key version
const newOlmAccount = await ctx.db.insert<"olmAccount">("olmAccount", {
userId: args.userId,
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys || [],
createdAt: now,
updatedAt: now,
keyVersion: 1,
});
return newOlmAccount;
},
});
export const retrieveServerOlmAccount = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) return null;
// Ensure backward compatibility with old records that don't have keyVersion
return {
...olmAccount,
keyVersion: olmAccount.keyVersion ?? 1,
createdAt: olmAccount.createdAt ?? olmAccount._creationTime,
updatedAt: olmAccount.updatedAt ?? olmAccount._creationTime,
};
},
});
export const consumeOTK = mutation({
args: {
userId: v.string(),
keyId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) throw new Error("User has no OLM account");
const oneTimeKeys = olmAccount.oneTimeKeys;
const keyIndex = oneTimeKeys.findIndex((key) => key.keyId === args.keyId);
if (keyIndex === -1) throw new Error("The key to be consumed was not found");
oneTimeKeys.splice(keyIndex, 1);
await ctx.db.patch(olmAccount._id, {
oneTimeKeys,
});
return {
consumed: true,
keysLeft: oneTimeKeys.length
}
},
});
export const getKeyVersion = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) return null;
return {
keyVersion: olmAccount.keyVersion ?? 1,
updatedAt: olmAccount.updatedAt ?? olmAccount._creationTime,
identityKey: olmAccount.identityKey,
};
},
});
/**
* Migration mutation to add keyVersion, createdAt, updatedAt to existing olmAccount records
* Run this once to migrate old records
*/
export const migrateOlmAccounts = mutation({
handler: async (ctx) => {
const accounts = await ctx.db.query("olmAccount").collect();
let updated = 0;
for (const account of accounts) {
// Only update if keyVersion is missing
if (account.keyVersion === undefined) {
await ctx.db.patch(account._id, {
keyVersion: 1, // Initial version for existing accounts
createdAt: account.createdAt ?? account._creationTime,
updatedAt: account.updatedAt ?? account._creationTime,
});
updated++;
}
}
return {
message: `Migrated ${updated} olmAccount records`,
total: accounts.length,
updated
};
},
});

View file

@ -1,116 +0,0 @@
// This file is auto-generated. Do not edit this file manually.
// To regenerate the schema, run:
// `npx @better-auth/cli generate --output undefined -y`
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
import { nests } from "./schemas/nests";
import { user } from "./schemas/user";
const Attachment = v.object({
contentType: v.string(), // MIME type
description: v.union(v.null(), v.string()), // Description
ephemeral: v.boolean(), // Whether the attachment is ephemeral
height: v.optional(v.number()), // Height in pixels
width: v.optional(v.number()), // Width in pixels
id: v.id("storage"), // Storage ID
size: v.number(), // Size in bytes
spoiler: v.boolean(), // Whether the attachment is a spoiler
url: v.string(), // Public URL
});
const Message = v.object({
inGuild: v.optional(v.boolean()),
attachments: v.optional(v.array(v.id("attachments"))),
authorId: v.id("user"),
channelId: v.id("channel"),
content: v.string(),
createdAt: v.string(),
createdTimestamp: v.number(),
editedAt: v.optional(v.string()),
guildId: v.optional(v.id("guild")),
id: v.string(),
nonce: v.optional(v.string()),
position: v.optional(v.number()),
referencedMessage: v.optional(
v.union(v.null(), v.id("messages"), v.id("channel"), v.id("guild")),
),
url: v.optional(v.string()),
})
export const tables = {
...user,
...nests,
messages: defineTable(Message)
.index("channelId", ["channelId"])
.index("channelId_createdTimestamp", ["channelId", "createdTimestamp"])
.index("authorId", ["authorId"])
.index("guildId", ["guildId"]),
attachments: defineTable(Attachment),
session: defineTable({
expiresAt: v.number(),
token: v.string(),
createdAt: v.number(),
updatedAt: v.number(),
ipAddress: v.optional(v.union(v.null(), v.string())),
userAgent: v.optional(v.union(v.null(), v.string())),
userId: v.string(),
})
.index("expiresAt", ["expiresAt"])
.index("expiresAt_userId", ["expiresAt", "userId"])
.index("token", ["token"])
.index("userId", ["userId"]),
account: defineTable({
accountId: v.string(),
providerId: v.string(),
userId: v.string(),
accessToken: v.optional(v.union(v.null(), v.string())),
refreshToken: v.optional(v.union(v.null(), v.string())),
idToken: v.optional(v.union(v.null(), v.string())),
accessTokenExpiresAt: v.optional(v.union(v.null(), v.number())),
refreshTokenExpiresAt: v.optional(v.union(v.null(), v.number())),
scope: v.optional(v.union(v.null(), v.string())),
password: v.optional(v.union(v.null(), v.string())),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("accountId", ["accountId"])
.index("accountId_providerId", ["accountId", "providerId"])
.index("providerId_userId", ["providerId", "userId"])
.index("userId", ["userId"]),
verification: defineTable({
identifier: v.string(),
value: v.string(),
expiresAt: v.number(),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("expiresAt", ["expiresAt"])
.index("identifier", ["identifier"]),
jwks: defineTable({
publicKey: v.string(),
privateKey: v.string(),
createdAt: v.number(),
}),
olmAccount: defineTable({
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
createdAt: v.optional(v.number()),
updatedAt: v.optional(v.number()),
keyVersion: v.optional(v.number()), // Increments when keys are rotated
})
.index("userId", ["userId"])
.index("userId_keys", ["userId", "oneTimeKeys"])
.index("userId_identityKey", ["userId", "identityKey"]),
};
const schema = defineSchema(tables);
export default schema;

View file

@ -1,75 +0,0 @@
import { defineTable } from "convex/server";
import { v } from "convex/values";
export const nests = {
nests: defineTable({
type: v.union(v.literal("global"), v.literal("regional"), v.literal("private")),
name: v.string(),
description: v.optional(v.string()),
images: v.optional(
v.object({
banner: v.id("storage"),
icon: v.id("storage"),
})
),
colors: v.optional(
v.object({
primary: v.string(),
accent: v.string(),
})
),
createdAt: v.number(),
updatedAt: v.number(),
managerId: v.id("user"),
members: v.array(v.id("user")),
channels: v.array(v.id("channel")),
roles: v.array(v.id("role")),
region: v.optional(v.string()),
emojis: v.array(v.object({
id: v.id("storage"),
name: v.string(),
createdAt: v.number(),
})),
onDiscover: v.optional(v.boolean()),
})
.index("managerId", ["managerId"])
.index("type", ["type"])
.index("type_region", ["type", "region"])
.index("createdAt", ["createdAt"])
.index("onDiscover", ["onDiscover"]),
roles: defineTable({
nestId: v.id("nests"),
name: v.string(),
color: v.optional(v.string()),
hoist: v.optional(v.boolean()),
mentionable: v.optional(v.boolean()),
icon: v.optional(v.id("storage")),
position: v.optional(v.number()),
permissions: v.array(v.int64()), // Permissions as bitfield
flags: v.array(v.int64()), // Flags as bitfield
createdAt: v.number(),
updatedAt: v.number(),
members: v.array(v.id("user")),
})
.index("nestId", ["nestId"])
.index("nestId_position", ["nestId", "position"])
.index("nestId_members", ["nestId", "members"])
.index("members", ["members"]),
channels: defineTable({
type: v.union(v.literal("text"), v.literal("category"), v.literal("announcement")),
name: v.string(),
nestId: v.id("nests"),
position: v.number(),
permissions: v.array(v.int64()), // Permissions as bitfield
overwrites: v.array(v.object({
id: v.union(v.id("user"), v.id("role")),
allow: v.union(v.array(v.int64()), v.null()), // Permissions as bitfield
deny: v.union(v.array(v.int64()), v.null()), // Permissions as bitfield
})),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("nestId", ["nestId"])
.index("nestId_position", ["nestId", "position"])
.index("nestId_type", ["nestId", "type"])
}

View file

@ -1,64 +0,0 @@
import { defineTable } from "convex/server";
import { v } from "convex/values";
export const user = {
user: defineTable({
name: v.string(),
email: v.string(),
emailVerified: v.boolean(),
image: v.optional(v.union(v.null(), v.string())),
createdAt: v.number(),
updatedAt: v.number(),
userId: v.optional(v.union(v.null(), v.string())),
username: v.optional(v.union(v.null(), v.string())),
displayUsername: v.optional(v.union(v.null(), v.string())),
metadata: v.optional(v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
})),
nests: v.optional(v.array(v.id("nests"))),
})
.index("email_name", ["email", "name"])
.index("nests", ["nests"])
.index("byName", ["name"])
.index("userId", ["userId"])
.index("username", ["username"]),
userStatus: defineTable({
userId: v.id("user"),
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
userSetStatus: v.optional(
v.object({
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
updatedAt: v.number(),
isSet: v.boolean(),
})
),
updatedAt: v.number(),
})
.index("userId", ["userId"])
.index("status", ["status"]),
friendRequests: defineTable({
userId: v.id("user"),
requestTo: v.id("user"),
method: v.union(v.literal("receive"), v.literal("send")),
requestId: v.string(),
createdAt: v.number(),
expiresAt: v.optional(v.number()),
acceptedAt: v.optional(v.number()),
declinedAt: v.optional(v.number()),
ignoredAt: v.optional(v.number()),
})
.index("userId_method", ["userId", "method"])
.index("userId", ["userId"])
.index("requestId", ["requestId"])
.index("userId_requestTo", ["userId", "requestTo"])
.index("requestTo", ["requestTo"])
.index("expiresAt", ["expiresAt"]),
friends: defineTable({
userId: v.id("user"),
friendId: v.id("user"),
createdAt: v.number(),
})
.index("userId", ["userId"])
.index("friendId", ["friendId"])
.index("userId_friendId", ["userId", "friendId"]),
}

View file

@ -1,446 +0,0 @@
import { v } from "convex/values";
import { Id } from "../_generated/dataModel";
import { mutation, MutationCtx, query, QueryCtx } from "../_generated/server";
// Overload signatures
async function userValidation(ctx: MutationCtx | QueryCtx, options: { required: false }): Promise<{ userId: Id<"user">; user: any } | null>;
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: true }): Promise<{ userId: Id<"user">; user: any }>;
// Implementation
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: boolean }) {
const required = options?.required ?? true;
const user = await ctx.auth.getUserIdentity();
if (!user) {
if (required) throw new Error("User not found");
return null;
}
const userId = ctx.db.normalizeId("user", user.subject as string) as Id<"user">;
if (!userId) {
if (required) throw new Error("User not found");
return null;
}
return { userId, user };
}
export const updateUserStatus = mutation({
args: {
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
isUserSet: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
try {
const { userId } = await userValidation(ctx);
const isUserSet = args.isUserSet ?? false;
const userStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", userId)).first();
if (userStatus) {
let resolvedStatus = args.status;
// Restore user-set status when reconnecting
if (args.status === "online" && !isUserSet && userStatus.userSetStatus?.isSet) {
resolvedStatus = userStatus.userSetStatus.status;
}
await ctx.db.patch(userStatus._id, {
status: resolvedStatus,
userSetStatus: isUserSet
? { status: args.status, updatedAt: Date.now(), isSet: true }
: userStatus.userSetStatus,
updatedAt: Date.now(),
});
} else {
await ctx.db.insert("userStatus", {
userId: userId,
status: args.status,
userSetStatus: {
status: args.status,
updatedAt: Date.now(),
isSet: isUserSet,
},
updatedAt: Date.now(),
});
}
return { success: true, message: "User status updated successfully" };
} catch (error) {
console.error("Error updating user status:", error);
throw new Error("Failed to update user status");
}
},
});
export const getUserStatus = query({
handler: async (ctx) => {
const validation = await userValidation(ctx, { required: false });
if (!validation) {
return null; // User not authenticated
}
const { userId } = validation;
const userStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", userId)).first();
return userStatus;
}
});
export const getNonOfflineUserIds = query({
args: {},
handler: async (ctx) => {
const results: { userId: string; status: string; isUserSet: boolean }[] = [];
for (const status of ["online", "busy", "away"] as const) {
const records = await ctx.db
.query("userStatus")
.withIndex("status", (q) => q.eq("status", status))
.collect();
for (const record of records) {
results.push({
userId: record.userId,
status: record.status,
isUserSet: record.userSetStatus?.isSet ?? false,
});
}
}
return results;
},
});
export const forceUserOffline = mutation({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const normalizedId = ctx.db.normalizeId("user", args.userId);
if (!normalizedId) return;
const userStatus = await ctx.db
.query("userStatus")
.withIndex("userId", (q) => q.eq("userId", normalizedId))
.first();
if (!userStatus || userStatus.status === "offline") return;
await ctx.db.patch(userStatus._id, {
status: "offline",
userSetStatus: userStatus.userSetStatus ? {
status: userStatus.userSetStatus.status,
updatedAt: Date.now(),
isSet: userStatus.userSetStatus.isSet,
} : undefined,
updatedAt: Date.now(),
});
console.log(`[forceUserOffline] Set user ${args.userId} offline (was: ${userStatus.status})`);
},
});
export const updateUserMetadata = mutation({
args: {
metadata: v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
}),
},
handler: async (ctx, args) => {
const { userId } = await userValidation(ctx);
return ctx.db.patch("user", userId, {
metadata: args.metadata,
});
},
});
export const sendFriendRequest = mutation({
args: {
username: v.string(),
},
handler: async (ctx, args) => {
const { userId, user: currentUser } = await userValidation(ctx);
// Find the target user
const targetUser = await ctx.db.query("user").withIndex("byName", (q) => q.eq("name", args.username)).first();
if (!targetUser) {
throw new Error("User not found");
}
// Check if trying to send request to yourself
if (targetUser._id === userId) {
throw new Error("You cannot send a friend request to yourself");
}
// Check if already friends
const existingFriendship = await ctx.db
.query("friends")
.withIndex("userId_friendId", (q) => q.eq("userId", userId).eq("friendId", targetUser._id))
.first();
if (existingFriendship) {
throw new Error("You are already friends with this user");
}
// Check for existing requests in both directions
const existingRequests = await ctx.db
.query("friendRequests")
.filter((q) =>
q.or(
q.and(
q.eq(q.field("userId"), userId),
q.eq(q.field("requestTo"), targetUser._id)
),
q.and(
q.eq(q.field("userId"), targetUser._id),
q.eq(q.field("requestTo"), userId)
)
)
)
.filter((q) => q.eq(q.field("acceptedAt"), undefined))
.filter((q) => q.eq(q.field("declinedAt"), undefined))
.collect();
const existingSentRequest = existingRequests.find(r => r.userId === userId);
const incomingRequest = existingRequests.find(r => r.userId === targetUser._id);
if (existingSentRequest) {
throw new Error("You have already sent a friend request to this user");
}
if (incomingRequest) {
const timestamp = Date.now();
// Auto-accept the incoming request
await ctx.db.patch(incomingRequest._id, {
acceptedAt: timestamp,
});
// Create bidirectional friendship entries
await Promise.all([
ctx.db.insert("friends", {
userId: userId,
friendId: targetUser._id,
createdAt: timestamp,
}),
ctx.db.insert("friends", {
userId: targetUser._id,
friendId: userId,
createdAt: timestamp,
}),
]);
return {
success: true,
message: "Friend request accepted automatically (they had already sent you a request)",
};
}
// Create the friend request (single row)
const requestId = crypto.randomUUID();
await ctx.db.insert("friendRequests", {
userId: userId,
requestTo: targetUser._id,
method: "send",
requestId,
createdAt: Date.now(),
});
return {
success: true,
message: "Friend request sent successfully",
};
}
})
export const answerFriendRequest = mutation({
args: {
requestId: v.string(),
answer: v.union(v.literal("accept"), v.literal("decline"), v.literal("ignore")),
},
handler: async (ctx, args) => {
const { userId } = await userValidation(ctx);
// Get the friend request
const request = await ctx.db
.query("friendRequests")
.withIndex("requestId", (q) => q.eq("requestId", args.requestId))
.first();
if (!request) {
throw new Error("Request not found");
}
// Verify current user is the recipient
if (request.requestTo !== userId) {
throw new Error("You are not the recipient of this request");
}
// Check if already answered
if (request.acceptedAt || request.declinedAt || request.ignoredAt) {
throw new Error("Request already answered");
}
const timestamp = Date.now();
// Update the request based on the answer
switch (args.answer) {
case "accept":
// Update request status
await ctx.db.patch(request._id, { acceptedAt: timestamp });
// Create bidirectional friendship entries
await Promise.all([
ctx.db.insert("friends", {
userId: userId,
friendId: request.userId,
createdAt: timestamp,
}),
ctx.db.insert("friends", {
userId: request.userId,
friendId: userId,
createdAt: timestamp,
}),
]);
break;
case "decline":
await ctx.db.patch(request._id, { declinedAt: timestamp });
break;
case "ignore":
await ctx.db.patch(request._id, { ignoredAt: timestamp });
break;
}
return {
success: true,
message: `Friend request ${args.answer}ed successfully`,
};
}
})
export const getFriendRequests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx);
// Get all unanswered requests involving this user (sent by them OR sent to them)
const allRequests = await ctx.db
.query("friendRequests")
.filter((q) =>
q.or(
q.eq(q.field("userId"), userId), // Requests sent by me
q.eq(q.field("requestTo"), userId) // Requests sent to me
)
)
.filter((q) => q.eq(q.field("acceptedAt"), undefined))
.filter((q) => q.eq(q.field("declinedAt"), undefined))
.filter((q) => q.eq(q.field("ignoredAt"), undefined))
.collect();
// Transform to include method field based on perspective
const requestsWithMethod = await Promise.all(
allRequests.map(async (request) => {
const isSentByMe = request.userId === userId;
const otherUserId = isSentByMe ? request.requestTo : request.userId;
const otherUser = await ctx.db.get(otherUserId);
return {
id: request.requestId,
_id: request._id,
userId: otherUserId,
username: otherUser?.username || otherUser?.displayUsername || otherUser?.name || "Unknown",
avatar: otherUser?.image || "",
createdAt: request.createdAt,
method: isSentByMe ? "send" : "receive",
};
})
);
return requestsWithMethod;
}
})
export const getFriends = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx);
// Get all friendships for this user
const friendships = await ctx.db
.query("friends")
.withIndex("userId", (q) => q.eq("userId", userId))
.collect();
// Populate friend data with relevant fields
const friends = await Promise.all(
friendships.map(async (friendship) => {
const friend = await ctx.db.get(friendship.friendId);
const friendStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", friendship.friendId)).first();
if (!friend) return null;
return {
_id: friend._id,
id: friend._id,
name: friend.name,
username: friend.username,
displayUsername: friend.displayUsername,
image: friend.image,
friendshipCreatedAt: friendship.createdAt,
status: friendStatus ? {
status: friendStatus.status,
isUserSet: friendStatus.userSetStatus?.isSet ?? false,
} : {
status: "offline" as const,
isUserSet: false,
},
};
})
);
return friends.filter(Boolean);
}
})
export const getParticipantDetails = query({
args: {
participantIds: v.array(v.string()),
},
handler: async (ctx, args) => {
const { participantIds } = args;
const { userId } = await userValidation(ctx);
if (!userId) throw new Error("User not found");
if (participantIds.length === 0) return [];
const normalizedParticipantIds = participantIds.map((id) => ctx.db.normalizeId("user", id));
if (normalizedParticipantIds.length === 0) return [];
// Filter out all null values
const filteredParticipantIds = normalizedParticipantIds.filter((id) => id !== null);
if (filteredParticipantIds.length === 0) return [];
const participantDetails = await Promise.all(filteredParticipantIds.map(async (id) => {
const participant = await ctx.db.get("user", id)
const participantStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", id)).first();
const participantOlmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", id)).first();
if (!participant) return null;
// Ensure backward compatibility with old olmAccount records
const olmAccountWithDefaults = participantOlmAccount ? {
...participantOlmAccount,
keyVersion: participantOlmAccount.keyVersion ?? 1,
createdAt: participantOlmAccount.createdAt ?? participantOlmAccount._creationTime,
updatedAt: participantOlmAccount.updatedAt ?? participantOlmAccount._creationTime,
} : null;
return {
id: participant._id,
name: participant.name,
username: participant.username,
displayUsername: participant.displayUsername,
image: participant.image,
status: participantStatus?.status || "offline",
olmAccount: olmAccountWithDefaults,
}
}));
return participantDetails
}
})

View file

@ -1,7 +0,0 @@
import { defineApp } from "convex/server";
import betterAuth from "./betterAuth/convex.config";
const app = defineApp();
app.use(betterAuth);
export default app;

View file

@ -1,8 +0,0 @@
import { httpRouter } from "convex/server";
import { authComponent, createAuth } from "./auth";
const http = httpRouter();
authComponent.registerRoutes(http, createAuth);
export default http;

12
drizzle.config.ts Normal file
View file

@ -0,0 +1,12 @@
import dotenv from 'dotenv';
dotenv.config({ path: '.env.local' });
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/lib/db/schema/index.ts',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});

View file

@ -0,0 +1,53 @@
CREATE TABLE "account" (
"id" text PRIMARY KEY NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" text NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp,
"refresh_token_expires_at" timestamp,
"scope" text,
"password" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
"token" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" text NOT NULL,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"image" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier");

View file

@ -0,0 +1,374 @@
{
"id": "5e0d4aeb-3b1b-4137-b4a9-8a09a93c788f",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"account_userId_idx": {
"name": "account_userId_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_userId_idx": {
"name": "session_userId_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}

View file

@ -0,0 +1,20 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1772741645429,
"tag": "0000_lazy_slyde",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1746392520000,
"tag": "0001_otk_schema_fix",
"breakpoints": true
}
]
}

View file

@ -1,44 +0,0 @@
const fs = require('fs');
const path = require('path');
// Load .env.local if it exists
function loadEnvFile(filename) {
const envPath = path.resolve(__dirname, filename);
if (!fs.existsSync(envPath)) return {};
const content = fs.readFileSync(envPath, 'utf-8');
const env = {};
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const [key, ...rest] = trimmed.split('=');
if (key) env[key.trim()] = rest.join('=').trim().replace(/^["']|["']$/g, '');
}
return env;
}
const envLocal = loadEnvFile('.env.local');
module.exports = {
apps: [
{
name: 'sipher',
script: 'src/server.ts',
interpreter: 'node_modules/.bin/tsx',
instances: 1,
exec_mode: 'fork',
watch: false,
max_memory_restart: '4G',
env: {
...envLocal,
NODE_ENV: 'development',
PORT: 3000,
},
env_production: {
...envLocal,
NODE_ENV: 'production',
PORT: 8081,
},
},
],
};

View file

@ -1,8 +1,15 @@
import type { NextConfig } from "next";
const allowedDevOrigins = process.env.DEV_ALLOWED_HOSTNAMES!.split(",").map((hostname) => hostname.trim())
const nextConfig: NextConfig = {
/* config options here */
reactCompiler: true,
allowedDevOrigins,
output: "standalone",
experimental: {
webpackMemoryOptimizations: true
}
};
export default nextConfig;

12810
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,70 +1,121 @@
{
"name": "sipher",
"version": "0.1.0",
"name": "silent-whisper",
"description": "A federated social media platform for the modern age.",
"author": [
{
"name": "Marcello Brito",
"alias": "Tocka",
"email": "tocka@tockanest.com",
"url": "https://tockanest.com"
}
],
"license": "AGPL-3.0",
"version": "0.2.0",
"private": true,
"scripts": {
"postinstall": "bun src/lib/scripts/copy-olm.ts",
"dev": "cross-env NODE_ENV=development PORT=3000 tsx src/server.ts",
"build": "bun src/lib/scripts/copy-olm.ts && convex deploy --cmd \"next build\"",
"build:local": "bun src/lib/scripts/copy-olm.ts && next build",
"start": "cross-env NODE_ENV=production PORT=8081 tsx src/server.ts",
"start:dev": "cross-env NODE_ENV=development PORT=3000 tsx src/server.ts"
"dev": "cross-env NODE_ENV=development FEDERATION_ALLOW_PRIVATE_URLS=true tsx src/server.ts",
"email:dev": "cross-env NODE_ENV=development email dev --dir src/lib/mail/templates --port 3001",
"test": "cross-env NODE_ENV=test playwright test",
"test:integration:post": "cross-env NODE_ENV=test bun run tests/integration/federation-post-delivery.ts",
"test:integration:proxy-chain": "cross-env NODE_ENV=test bun run tests/integration/proxy-chain.ts",
"keygen": "bun run src/lib/federation/keygen.ts",
"docker:generate-keys": "bun run tests/docker/generate-keys.ts",
"docker:setup-discovery": "docker compose -f tests/docker-compose.yml run --rm setup-discovery",
"docker:build": "docker compose -f tests/docker-compose.yml --profile init --profile setup --profile test build",
"docker:up": "docker compose -f tests/docker-compose.yml up -d",
"docker:down": "docker compose -f tests/docker-compose.yml down",
"docker:init": "docker compose -f tests/docker-compose.yml --profile init up",
"docker:test:proxy-chain": "docker compose -f tests/docker-compose.yml run --rm test-runner tests/integration/proxy-chain.ts --proxy http://sipher-b:3001 --target http://sipher-c:3002",
"docker:test:post-delivery": "docker compose -f tests/docker-compose.yml run --rm test-runner tests/integration/federation-post-delivery.ts --proxy http://sipher-b:3001 --target http://sipher-c:3002",
"docker:test:discover": "docker compose -f tests/docker-compose.yml run --rm test-runner tests/integration/discover.ts --peer http://sipher-c:3002",
"test:key": "cross-env NODE_ENV=test playwright test tests/federation/key-rotation.e2e.ts",
"test:federation": "cross-env NODE_ENV=test playwright test tests/federation",
"test:proxy": "cross-env NODE_ENV=test playwright test tests/proxy",
"build": "next build",
"build:matrix": "cd node_modules/@matrix-org/matrix-sdk-crypto-nodejs && node download-lib.js",
"start": "cross-env NODE_ENV=production node src/server.ts",
"db:push": "drizzle-kit push",
"db:migrate": "bun run db:push && bun run drizzle-kit migrate",
"db:generate": "auth generate --output src/lib/db/schema/index.ts --yes",
"db:update": "bun run db:generate && bun run db:push"
},
"dependencies": {
"@convex-dev/better-auth": "^0.10.10",
"@marsidev/react-turnstile": "^1.4.2",
"@matrix-org/olm": "^3.2.15",
"@nanostores/react": "^1.0.0",
"@phosphor-icons/react": "^2.1.10",
"@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-menubar": "^1.1.16",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tooltip": "^1.2.8",
"@types/bun": "^1.3.9",
"@types/libsodium-wrappers": "^0.7.14",
"better-auth": "1.4.12",
"@better-auth/drizzle-adapter": "^1.6.11",
"@hookform/resolvers": "^5.2.2",
"@matrix-org/matrix-sdk-crypto-wasm": "^18.3.0",
"@noble/ciphers": "^2.2.0",
"@noble/hashes": "^2.2.0",
"@react-email/components": "1.0.12",
"@react-email/render": "^2.0.8",
"@react-email/tailwind": "^2.0.7",
"@scure/bip39": "^2.2.0",
"better-auth": "^1.6.11",
"bullmq": "^5.76.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"convex": "^1.31.7",
"cross-env": "^10.1.0",
"date-fns": "^4.1.0",
"dexie": "^4.3.0",
"dexie-react-hooks": "^4.2.0",
"dotenv": "^17.3.1",
"framer-motion": "^12.34.0",
"lucide-react": "^0.562.0",
"moment": "^2.30.1",
"nanostores": "^1.1.0",
"next": "16.1.1",
"debug": "^4.4.3",
"dexie": "^4.4.2",
"dotenv": "^17.4.2",
"drizzle-orm": "^0.45.2",
"framer-motion": "^12.38.0",
"ioredis": "^5.10.1",
"lucide-react": "^1.16.0",
"minio": "^8.0.7",
"next": "16.2.3",
"next-themes": "^0.4.6",
"react": "19.2.3",
"react-day-picker": "^9.13.1",
"react-dom": "19.2.3",
"nodemailer": "^8.0.7",
"pg": "^8.21.0",
"radix-ui": "^1.4.3",
"react": "19.2.5",
"react-dom": "19.2.5",
"react-hook-form": "^7.76.0",
"socket.io": "^4.8.3",
"socket.io-client": "^4.8.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.6"
"tailwind-merge": "^3.6.0",
"tweetnacl": "^1.0.3",
"uuid": "^14.0.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.18",
"@types/node": "^25.2.2",
"@types/react": "^19.2.13",
"@playwright/test": "^1.60.0",
"@react-email/preview-server": "^5.2.10",
"@tailwindcss/postcss": "^4.3.0",
"@types/bun": "^1.3.14",
"@types/debug": "^4.1.13",
"@types/node": "^25.8.0",
"@types/nodemailer": "^8.0.0",
"@types/pg": "^8.20.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"auth": "^1.6.11",
"babel-plugin-react-compiler": "1.0.0",
"tailwindcss": "^4.1.18",
"tsx": "^4.21.0",
"cross-env": "^10.1.0",
"drizzle-kit": "^0.31.10",
"react-email": "5.2.10",
"shadcn": "^4.7.0",
"tailwindcss": "^4.3.0",
"tsx": "^4.22.1",
"tw-animate-css": "^1.4.0",
"typescript": "^5.9.3"
}
"typescript": "^6.0.3"
},
"ignoreScripts": [
"sharp",
"unrs-resolver"
],
"trustedDependencies": [
"sharp",
"unrs-resolver"
],
"repository": {
"type": "git",
"url": "https://github.com/tockawaffle/sipher.git"
},
"bugs": {
"url": "https://github.com/tockawaffle/sipher/issues"
},
"keywords": [
"social",
"media",
"federated"
]
}

32
playwright.config.ts Normal file
View file

@ -0,0 +1,32 @@
import { defineConfig, devices } from '@playwright/test';
import dotenv from 'dotenv';
import path from 'path';
dotenv.config({ path: path.resolve(__dirname, '.env.local') });
export default defineConfig({
testDir: './tests',
/** Bun discovers `*.test.ts` / `*.spec.ts` as Bun tests; keep HTTP suites under `*.e2e.ts`. */
testMatch: '**/*.e2e.ts',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: 1,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
},
webServer: {
command: 'cross-env NODE_ENV=test tsx src/server.ts',
url: process.env.BETTER_AUTH_URL,
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.8 KiB

View file

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Camada_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1024 1024">
<!-- Generator: Adobe Illustrator 29.8.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 2) -->
<defs>
<style>
.st0 {
fill: #d3d0cb;
}
.st1 {
fill: #fff;
}
.st2 {
display: none;
}
</style>
</defs>
<g>
<path class="st0" d="M775.3,448.2c-7.1-39.8-22.1-69-51.4-97.7-4.2-3.8-8.8-8-.3-5.7,5.7,1.6,12.7,4.5,17.9,7.5,3.4,1.8,6,3.6,7.5,3.3,1.2-.5.5-3.1-1-6.8-2.2-4.9-5.6-11.2-8.9-16.4-12.3-20.3-27.7-36-45.5-51.7-6.7-6.1-16.9-14.1-23.7-17.2-3.6-1.8-7.2-3.6-10.9-5-2.8-1.1-6.3-2-3.4-2.7,5.8-.7,21.2.8,28.9,2.5,2.8.2,12.6,3.5,12.5,1.5-5.1-5.8-15.9-10.6-23.4-14.3-10.6-4.8-19.8-8.6-30.7-11-7.1-2-16.8-1.5-23.5-3-2.1-.7,6.7-3.1,11.1-3.6,5.2-.8,10.8-1.3,15.8-1.1,4.5,0,9.3.6,10.4,0,.4-.2.4-.4.2-.8-6.9-5.5-19.6-9-28.5-11.2-13.2-2.8-26-3.6-39.2-3.2-8.1,0-18.5,2.8-26.1,3.9-5,.1,6.7-5.4,8.2-6.1,2.7-1.8,18.1-5.3,9.4-6.2-16.9-1.3-36.3.8-52.6,6.6-6.4,1.9-13.5,7-19,9.9-.1,0-.2,0-.1,0,0-.5,3.9-4.3,7.3-7.2,2.1-1.8,4.3-3.5,6.4-4.9,8.2-5.4,9.3-6.8.4-4.7-9.1,2.5-18,5.6-26.1,10-5.7,2.8-11.1,7.6-16.3,10.6-3.5.9,1.7-5.9,2.4-7.1,4.3-6.2-13.7,3.8-14.9,5.1-12,8.3-23.4,16.8-34.3,26.3-14.2,12.5-11.7,14.9-32.2,14.9-20.7,0-40.2,2.7-60.8,6.9-34.8,7.7-68.1,22.4-92.1,51.5-7.2,9.7-15.4,25.9-19.8,37.7-.6,1.6-1.3,3.2-1.7,4.5-.2.5,0,.7.6.6l2.4-.4c2.2-.3,4.1-.5,6.4-.8,5.7-.7,9.8-1.1,16.1-1.7,27.4-2.3,52.8-5,81.8-2.5,22.6,1.9,46.5,3.4,67.1,13.2,33.7,14.5,48.2,49.8,40.6,82.2-6.6,29.3-24.7,45.9-40.5,67.8-4.4,5.8-28.3,44.8-14.5,40.9,3.9.1,26.7-20.1,21-8.6-5.8,10.1-8.8,20.9-10.1,33-4.1,23.9-3.1,52.6,7.1,74.8,1.9,3.3,3.1,3.3,3.9-.1,1.1-4.5,1.8-9.5,3.5-14.3,1.7-4.6,6.1-17.7,10.5-19.5.8,0,1.3,1.3,1.5,3.4.3,2.6,0,6.2,0,9.1,0,6.4,2.8,38.3,20.3,69.5,5.9,10.5,15.7,25.4,31.4,40.1,9.3,8.2,14.6,12.8,15,11,0-.4-.5-4-.6-5.2-.3-3-.6-5.2-.2-9.6,1-10.4,4.6-20.4,8.6-30,4.2-9.7,10.5-19.6,15.6-28.2,10.2-17.9,24-34.9,38.2-50.2,16.4-17.4,61.4-63.2,68.4-57.8.2,8.4-14.2,27.5-20.3,34.5-1.9,2.2-4.1,4.5-6.2,6.6-9.5,9.1-11.4,12.1.7,8.5,8.9-3,19.2-7.9,27.6-12.4,13-7,25.3-13.8,36.6-24.3,8.2-7.5,14.7-16.1,20.1-26,9.3-14.3,14.3-43.1,19-38,5,7,5,28.2,5.9,39.1.6,3.9-.7,17.3,4,13.7,10.1-11.1,14.2-30.5,17.1-44.9.6-1.9,1-10.7,4.2-6.4,6,12.3,7.1,26.3,8,40,1.5,13.7-3.6,43.1,4.4,26.7,6.7-14.5,14.5-29.8,17.3-44.5,2.1-9.9,2.5-19.2,2.5-28.7,0-14.3,0-25.4-3.5-44.1-3.1-15.3-7.7-28-14.4-41.8-4.4-9.2-8.3-15.4-10.9-21.8-1.5-5.2,5.8.3,7.3,1.5,5.8,4.8,10.2,9.3,15.1,15.3,2.3,2.9,4.6,6,6.8,9.1,8.8,12.9,14.6,26.3,12.4,6.2ZM520.8,289.4c6.4,0,11.5,5.2,11.5,11.5s-5.2,11.5-11.5,11.5-11.5-5.2-11.5-11.5,5.2-11.5,11.5-11.5ZM407.3,328.3c-13.6-1.5-27.7-2-41.6-2.2-20.2-.3-40.8-.6-60.7,2-12.8,2-25.6,3.4-37.7,7.8-2,.6-6,3.1-4.5.3h0c4.7-7.1,11.1-12.1,17.8-16.9,8.5-6.3,17-11.6,26.4-15.6,12.4-5.7,25.8-10.4,39.2-12.8,14.7-2.3,32-4.3,47.2-4.1,8.2.2,18.2-.3,26.1.7,1.4.5-2.7,1.5-5.2,2.2-4.4,1.2-7.8,2.1-12.4,3.4-5.9,1.7-11.9,3.5-16.5,5.3-1.9.7-4.8,1.9-6.6,2.9-1,.5-1.5.9-1.5,1.2.6.7,2.5.4,4.7.5,4.8,0,10.3.4,15,1,8.3,1,16.8,2.5,25.1,4.3,7.6,1.6,12.4,2.4,17.6,4.1,14.7,4.9,28.6,13.1,40,23.5,2.8,2.5,5.9,5.8,8.3,8.5,1,1.2,1.7,2,1.5,2.2-.4.4-3.6-1.1-4.6-1.5-9-4-19.8-6.3-29.4-8.7-15.6-3.6-32.2-6.1-48.5-8.2ZM478.3,533.9c-2.9,3.7-3.7,4.7-5,6-2.2,2.3-3.3,3.4-4.9,4-.8.3-3.3,1.2-5.9,0-1.9-.9-2.8-2.5-3.1-3-2-3.5-.3-7.3,0-7.8.4-.8.8-1.5,5.1-5,2.9-2.3,4.7-3.8,8-6.1,1.5-1.1,3-2.1,6-4,6.1-4,7.5-4.8,11-7.2,2.4-1.6,4.3-3,5.7-4-.7,1.8-1.9,4.7-3.8,7.9-1,1.8-1.2,1.8-3.9,6.2-3.2,5.1-3.4,5.7-5,7.9-.3.3-1.5,1.9-4,5ZM533.7,546.6c-2,4.8-4.2,9.4-5.9,14.3-5.5,14.9-9.6,30.1-15,45.1-1.8,5.3-3.5,11.1-7.7,14.9-8.5,8.8-21,2.8-21.1-8.9,0-2.4.5-4.8,1.4-7,5.5-11.5,11.6-21.1,19.7-31.5,6-7.2,12.6-14.5,19.2-20.9h.1c1.2-1.1,10.9-10.3,9.3-6ZM577.9,528.4c-3.2,3.6-8.1,5.2-12.6,2.9-4.4-2.1-6.1-7.7-5.4-12.2,1.1-5.5,5.9-11.9,9.5-17.3,5.5-8.2,8.8-16.1,12.4-26.4.2-.7.6-2,1-2.3h0c.5-.2.8,1.4.9,1.9,4.1,17.3,9.4,38.4-5.8,53.3ZM645.2,492.5c-.7,4-4.1,8-8.5,8.1-3,.2-6.3-1.4-8.8-3.1-7.1-6.6-5.1-16.8-6.7-25.2-1.9-10-4.6-20.3-10.9-28.1,0,0,0-.1,0,0,16,10.1,35.6,27.5,34.8,48.4ZM685.2,438.4c0,1.4,0,1.4-.2,2.1-.2,1.1-.9,2.8-1.6,3.7l-.5.6c-.9,1.2-2.1,2.2-3.4,2.8l-.8.4c-.8.4-1.6.6-2.4.8l-1.2.2c-1.1.2-2.1.2-3.2,0-1.3-.2-2.5-.6-3.6-1.2l-.5-.3c-.4-.3-.9-.5-1.3-.9-5.1-4.5-7-12.8-8.9-19-2-6.4-6.2-14.8-9.5-20.6-8.9-13.5-20.7-26-33.6-35.7,0,0,0,0,0,0,23.9,7.6,46.9,23.1,61.9,43.4,3.8,6.6,8.9,14.3,8.9,22.7s0,0,0,1Z"/>
<g class="st2">
<path class="st1" d="M489.8,346.7c.1-.3-.5-1.1-1.5-2.2-2.4-2.7-5.5-6-8.3-8.5-11.5-10.4-25.3-18.6-40-23.5-5.2-1.7-10-2.6-17.6-4.1-8.3-1.9-16.8-3.3-25.1-4.3-4.7-.6-10.2-1-15-1-2.2-.1-4.1.2-4.7-.5,0-.3.5-.7,1.5-1.2,1.8-1,4.7-2.1,6.6-2.9,4.6-1.8,10.7-3.6,16.5-5.3,4.6-1.3,8-2.2,12.4-3.4,2.5-.7,6.6-1.7,5.2-2.2-7.9-1-17.9-.4-26.1-.7-15.2-.2-32.6,1.8-47.2,4.1-13.4,2.5-26.8,7.1-39.2,12.8-9.5,4-18,9.3-26.4,15.6-6.7,4.8-13.2,9.8-17.8,16.7h0c-1.6,2.9,2.5.5,4.5-.1,12.1-4.4,24.9-5.8,37.7-7.8,20-2.6,40.5-2.3,60.7-2,13.9.3,28,.7,41.6,2.2,16.3,2.1,32.9,4.5,48.5,8.2,9.6,2.4,20.4,4.7,29.4,8.7,1.1.4,4.2,1.9,4.6,1.5Z"/>
<circle class="st1" cx="520.8" cy="300.9" r="11.5" transform="translate(-41.5 87.3) rotate(-9.2)"/>
<path class="st1" d="M614.5,371.3s0,0,0,0c12.9,9.7,24.7,22.2,33.6,35.7,3.3,5.8,7.5,14.2,9.5,20.6,1.9,6.2,3.7,14.5,8.9,19,.4.3.8.6,1.3.9l.5.3c1.1.6,2.3,1.1,3.6,1.2,1.1.1,2.1.1,3.2,0l1.2-.2c.8-.2,1.6-.4,2.4-.8l.8-.4c1.4-.7,2.5-1.6,3.4-2.8l.5-.6c.7-.9,1.4-2.6,1.6-3.7.1-.7.2-.7.2-2.1,0-1.1,0-.7,0-1,0-8.4-5-16.2-8.9-22.7-15-20.3-37.9-35.8-61.9-43.4Z"/>
<path class="st1" d="M610.5,444.2c0,0-.1,0,0,0,6.3,7.7,9,18.1,10.9,28.1,1.6,8.4-.4,18.5,6.7,25.2,2.4,1.7,5.7,3.3,8.8,3.1,4.3-.1,7.7-4.1,8.5-8.1.9-20.9-18.8-38.3-34.8-48.4Z"/>
<path class="st1" d="M582.8,473.1h0c-.4.3-.8,1.6-1,2.3-3.6,10.3-6.9,18.1-12.4,26.4-3.5,5.4-8.3,11.9-9.5,17.3-.7,4.5,1,10.1,5.4,12.2,4.5,2.3,9.4.7,12.6-2.9,15.3-15,10-36,5.8-53.3-.2-.5-.4-2.1-.9-2Z"/>
<path class="st1" d="M491.2,514.8c1.9-3.3,3.1-6.1,3.8-7.9-1.4,1-3.3,2.4-5.7,4-3.5,2.4-5,3.2-11,7.2-2.9,1.9-4.4,2.9-6,4-3.3,2.3-5.1,3.8-8,6.1-4.2,3.5-4.7,4.2-5.1,5-.3.6-2,4.3,0,7.8.3.5,1.2,2.1,3.1,3,2.6,1.2,5.2.3,5.9,0,1.6-.6,2.8-1.8,4.9-4,1.3-1.3,2.1-2.3,5-6,2.5-3.1,3.7-4.7,4-5,1.6-2.3,1.8-2.8,5-7.9,2.8-4.4,2.9-4.4,3.9-6.2Z"/>
<path class="st1" d="M524.5,552.5h-.1c-6.6,6.5-13.2,13.8-19.2,21-8,10.4-14.2,20.1-19.7,31.5-.9,2.2-1.4,4.6-1.4,7,0,11.7,12.5,17.6,21.1,8.9,4.2-3.8,5.9-9.6,7.7-14.9,5.3-15,9.4-30.2,15-45.1,1.7-4.9,3.9-9.5,5.9-14.3,1.6-4.4-8,4.9-9.3,5.8Z"/>
</g>
</g>
<g>
<circle class="st0" cx="695.1" cy="187.8" r="7.7"/>
<circle class="st0" cx="685.8" cy="222" r="4.5"/>
<ellipse class="st0" cx="731" cy="209.2" rx="4.2" ry="3.5"/>
<circle class="st0" cx="731" cy="243.6" r="7.2"/>
<circle class="st0" cx="745.2" cy="273.8" r="4.1"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 6.6 KiB

11
public/logo/sipher.svg Normal file
View file

@ -0,0 +1,11 @@
<svg class="icon-192" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="512" height="512" fill="#080808" />
<rect x="32" y="32" width="448" height="448" stroke="#C8F000" stroke-width="6" fill="none" />
<polygon points="80,32 32,32 32,80" fill="#C8F000" opacity="0.15" />
<polygon points="432,32 480,32 480,80" fill="#C8F000" opacity="0.15" />
<polygon points="32,432 32,480 80,480" fill="#C8F000" opacity="0.15" />
<polygon points="480,432 480,480 432,480" fill="#C8F000" opacity="0.15" />
<path d="M 180 160 L 330 160 L 330 240 L 180 240 L 180 352 L 330 352" stroke="#C8F000" stroke-width="28"
stroke-linecap="square" fill="none" />
<rect x="32" y="248" width="448" height="6" fill="#FF3C3C" opacity="0.25" />
</svg>

After

Width:  |  Height:  |  Size: 760 B

379
rotateKeys.ts Normal file
View file

@ -0,0 +1,379 @@
/**
* This script is used to rotate the keys of the federation.
* It will go through all known federations and request the key rotation challenge one by one.
* It will then solve the challenges and send the proofs to the federation that we are who we say we are.
*
* This script is meant to be run manually and should not under any circumstances be run automatically under an endpoint.
*
* Usage:
* bun run rotateKeys.ts generate fresh keys and rotate all federations
* bun run rotateKeys.ts --resume <json> retry all federations with previously generated keys
* bun run rotateKeys.ts --resume <json> --only <urls> retry only specific federations (comma-separated URLs)
*/
import db from "@/lib/db";
import { serverRegistry } from "@/lib/db/schema";
import { decryptPayload, EncryptedEnvelope, encryptPayload, signMessage } from "@/lib/federation/keytools";
import { config } from "dotenv";
import nacl from "tweetnacl";
config({ path: ".env.local" });
const FETCH_TIMEOUT_MS = 30_000;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
interface FedKeys {
signingPublicKey: string;
signingSecretKey: string;
encryptionPublicKey: string;
encryptionSecretKey: string;
}
function generateEnvKeyPair(): FedKeys {
const signing = nacl.sign.keyPair();
const encryption = nacl.box.keyPair();
return {
signingPublicKey: Buffer.from(signing.publicKey).toString("base64"),
signingSecretKey: Buffer.from(signing.secretKey).toString("base64"),
encryptionPublicKey: Buffer.from(encryption.publicKey).toString("base64"),
encryptionSecretKey: Buffer.from(encryption.secretKey).toString("base64"),
};
}
function printKeys(label: string, keys: FedKeys) {
console.log(label);
console.log(` FEDERATION_PUBLIC_KEY=${keys.signingPublicKey}`);
console.log(` FEDERATION_PRIVATE_KEY=${keys.signingSecretKey}`);
console.log(` FEDERATION_ENCRYPTION_PUBLIC_KEY=${keys.encryptionPublicKey}`);
console.log(` FEDERATION_ENCRYPTION_PRIVATE_KEY=${keys.encryptionSecretKey}`);
}
async function readErrorBody(response: Response): Promise<string> {
try {
const body = await response.json();
return body?.error ?? body?.message ?? JSON.stringify(body);
} catch {
try {
return await response.text();
} catch {
return response.statusText;
}
}
}
async function confirm(prompt: string): Promise<boolean> {
process.stdout.write(`${prompt} [y/N] `);
for await (const line of console) {
return line.trim().toLowerCase() === "y";
}
return false;
}
// ---------------------------------------------------------------------------
// Validate environment
// ---------------------------------------------------------------------------
const REQUIRED_ENV = [
"FEDERATION_PUBLIC_KEY",
"FEDERATION_PRIVATE_KEY",
"FEDERATION_ENCRYPTION_PUBLIC_KEY",
"FEDERATION_ENCRYPTION_PRIVATE_KEY",
"BETTER_AUTH_URL",
] as const;
const missing = REQUIRED_ENV.filter((k) => !process.env[k]);
if (missing.length > 0) {
console.error("Missing required environment variables:");
missing.forEach((k) => console.error(` - ${k}`));
console.error("Ensure .env.local is present and populated.");
process.exit(1);
}
const oldFedKeys: FedKeys = {
signingPublicKey: process.env.FEDERATION_PUBLIC_KEY!,
signingSecretKey: process.env.FEDERATION_PRIVATE_KEY!,
encryptionPublicKey: process.env.FEDERATION_ENCRYPTION_PUBLIC_KEY!,
encryptionSecretKey: process.env.FEDERATION_ENCRYPTION_PRIVATE_KEY!,
};
const ORIGIN = process.env.BETTER_AUTH_URL!;
// ---------------------------------------------------------------------------
// Parse --resume flag
// ---------------------------------------------------------------------------
let newFedKeys: FedKeys;
const resumeIdx = process.argv.indexOf("--resume");
if (resumeIdx !== -1) {
const raw = process.argv[resumeIdx + 1];
if (!raw) {
console.error("--resume requires a JSON string argument containing the new keys.");
process.exit(1);
}
try {
const parsed = JSON.parse(raw);
if (
!parsed.signingPublicKey ||
!parsed.signingSecretKey ||
!parsed.encryptionPublicKey ||
!parsed.encryptionSecretKey
) {
throw new Error("Missing key fields");
}
newFedKeys = parsed as FedKeys;
console.log("Resuming rotation with previously generated keys.");
} catch (err) {
console.error("Failed to parse --resume keys:", (err as Error).message);
process.exit(1);
}
} else {
newFedKeys = generateEnvKeyPair();
}
// ---------------------------------------------------------------------------
// Parse --only filter
// ---------------------------------------------------------------------------
const onlyIdx = process.argv.indexOf("--only");
let onlyUrls: Set<string> | null = null;
if (onlyIdx !== -1) {
const raw = process.argv[onlyIdx + 1];
if (!raw) {
console.error("--only requires a comma-separated list of federation URLs.");
process.exit(1);
}
onlyUrls = new Set(raw.split(",").map((u) => u.trim()).filter(Boolean));
if (onlyUrls.size === 0) {
console.error("--only list is empty.");
process.exit(1);
}
}
// ---------------------------------------------------------------------------
// Fetch federations
// ---------------------------------------------------------------------------
const allFederations = await db.select().from(serverRegistry);
if (allFederations.length === 0) {
console.log("No federations found in the registry. Nothing to rotate.");
process.exit(0);
}
const federations = onlyUrls
? allFederations.filter((f) => onlyUrls!.has(f.url))
: allFederations;
if (federations.length === 0) {
console.error("None of the --only URLs matched federations in the registry:");
onlyUrls!.forEach((u) => console.error(` - ${u}`));
process.exit(1);
}
if (onlyUrls) {
const unmatched = [...onlyUrls].filter((u) => !federations.some((f) => f.url === u));
if (unmatched.length > 0) {
console.warn("Warning: these --only URLs were not found in the registry and will be skipped:");
unmatched.forEach((u) => console.warn(` - ${u}`));
}
}
console.log(`Targeting ${federations.length} federation(s) for key rotation:`);
federations.forEach((f) => console.log(` - ${f.url}`));
if (!await confirm("\nProceed with key rotation?")) {
console.log("Aborted.");
process.exit(0);
}
// ---------------------------------------------------------------------------
// Solve init challenges
// ---------------------------------------------------------------------------
interface InitChallenges {
signingOldChallenge: string;
signingNewChallenge: string;
encryptionOldChallenge: EncryptedEnvelope;
encryptionNewChallenge: EncryptedEnvelope;
}
function solveInitChallenges(challenges: InitChallenges, oldKeys: FedKeys, newKeys: FedKeys) {
const oldSigningSecret = new Uint8Array(Buffer.from(oldKeys.signingSecretKey, "base64"));
const newSigningSecret = new Uint8Array(Buffer.from(newKeys.signingSecretKey, "base64"));
const oldEncSecret = new Uint8Array(Buffer.from(oldKeys.encryptionSecretKey, "base64"));
const newEncSecret = new Uint8Array(Buffer.from(newKeys.encryptionSecretKey, "base64"));
return {
signingOldSignature: signMessage(challenges.signingOldChallenge, oldSigningSecret),
signingNewSignature: signMessage(challenges.signingNewChallenge, newSigningSecret),
encryptionOldPlaintext: decryptPayload(challenges.encryptionOldChallenge, oldEncSecret),
encryptionNewPlaintext: decryptPayload(challenges.encryptionNewChallenge, newEncSecret),
};
}
// ---------------------------------------------------------------------------
// Rotate each federation
// ---------------------------------------------------------------------------
const transactions: Array<{
url: string;
success: boolean;
message: string;
}> = [];
for (const federation of federations) {
const tag = federation.url;
console.log(`\n[${tag}] Requesting rotation challenge...`);
try {
// Step 1 — Init challenge
const initResponse = await fetch(`${federation.url}/discover/rotate/init`, {
method: "POST",
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
headers: {
"Content-Type": "application/json",
"Origin": ORIGIN,
"x-federation-origin": ORIGIN,
},
body: JSON.stringify({
url: ORIGIN,
newSigningPublicKey: newFedKeys.signingPublicKey,
newEncryptionPublicKey: newFedKeys.encryptionPublicKey,
}),
});
if (!initResponse.ok) {
const detail = await readErrorBody(initResponse);
console.error(`[${tag}] Init failed (${initResponse.status}): ${detail}`);
transactions.push({ url: tag, success: false, message: detail });
continue;
}
const challenges: InitChallenges = await initResponse.json();
// Step 2 — Fetch the federation's public encryption key
const discoverResponse = await fetch(`${federation.url}/discover`, {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
headers: {
"Content-Type": "application/json",
"Origin": ORIGIN,
"x-federation-origin": ORIGIN,
},
});
if (!discoverResponse.ok) {
const detail = await readErrorBody(discoverResponse);
console.error(`[${tag}] Discover failed (${discoverResponse.status}): ${detail}`);
transactions.push({ url: tag, success: false, message: detail });
continue;
}
const discoverData: {
url: string;
publicKey: string;
encryptionPublicKey: string;
} = await discoverResponse.json();
// Step 3 — Solve challenges
const proofs = solveInitChallenges(challenges, oldFedKeys, newFedKeys);
// Step 4 — Encrypt proofs with the federation's encryption public key
const encPubKey = new Uint8Array(Buffer.from(discoverData.encryptionPublicKey, "base64"));
const encryptedProofs = encryptPayload(JSON.stringify(proofs), encPubKey);
// Step 5 — Confirm
const confirmResponse = await fetch(`${federation.url}/discover/rotate/confirm`, {
method: "POST",
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
headers: {
"Content-Type": "application/json",
"Origin": ORIGIN,
"x-federation-origin": ORIGIN,
},
body: JSON.stringify({
serverUrl: ORIGIN,
envelope: encryptedProofs,
}),
});
if (!confirmResponse.ok) {
const detail = await readErrorBody(confirmResponse);
console.error(`[${tag}] Confirm failed (${confirmResponse.status}): ${detail}`);
transactions.push({ url: tag, success: false, message: detail });
continue;
}
const confirmData = await confirmResponse.json();
console.log(`[${tag}] ${confirmData.message}`);
transactions.push({ url: tag, success: true, message: confirmData.message });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(`[${tag}] Unexpected error: ${message}`);
transactions.push({ url: tag, success: false, message });
}
}
// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------
const successes = transactions.filter((t) => t.success);
const failures = transactions.filter((t) => !t.success);
console.log("\n================================");
console.log(`Results: ${successes.length} succeeded, ${failures.length} failed out of ${transactions.length}`);
if (failures.length > 0) {
console.error("\nFailed federations:");
failures.forEach((f) => console.error(` - ${f.url}: ${f.message}`));
const resumePayload = JSON.stringify(newFedKeys);
const failedUrls = failures.map((f) => f.url).join(",");
if (successes.length > 0) {
console.error("\nKeys NOT written to .env.local (some federations succeeded, some failed).");
console.error("Retry ONLY the failed federations with:\n");
console.log(` bun run rotateKeys.ts --resume '${resumePayload}' --only '${failedUrls}'\n`);
} else {
console.error("\nKeys NOT written to .env.local. Retry with:\n");
console.log(` bun run rotateKeys.ts --resume '${resumePayload}'\n`);
}
process.exit(1);
}
// ---------------------------------------------------------------------------
// Write new keys to .env.local (with backup)
// ---------------------------------------------------------------------------
const envPath = ".env.local";
const envContent = await Bun.file(envPath).text();
const backupPath = `.env.local.bak.${Date.now()}`;
await Bun.write(backupPath, envContent);
console.log(`\nBacked up .env.local → ${backupPath}`);
const envReplacements: [RegExp, string][] = [
[/FEDERATION_PUBLIC_KEY=.*/, `FEDERATION_PUBLIC_KEY="${newFedKeys.signingPublicKey}"`],
[/FEDERATION_PRIVATE_KEY=.*/, `FEDERATION_PRIVATE_KEY="${newFedKeys.signingSecretKey}"`],
[/FEDERATION_ENCRYPTION_PUBLIC_KEY=.*/, `FEDERATION_ENCRYPTION_PUBLIC_KEY="${newFedKeys.encryptionPublicKey}"`],
[/FEDERATION_ENCRYPTION_PRIVATE_KEY=.*/, `FEDERATION_ENCRYPTION_PRIVATE_KEY="${newFedKeys.encryptionSecretKey}"`],
];
let updatedEnv = envContent;
for (const [pattern, replacement] of envReplacements) {
if (!pattern.test(updatedEnv)) {
console.error(`Warning: ${pattern.source.split("=")[0]} not found in .env.local — appending.`);
updatedEnv += `\n${replacement}`;
} else {
updatedEnv = updatedEnv.replace(pattern, replacement);
}
}
await Bun.write(envPath, updatedEnv);
console.log("New keys written to .env.local successfully.");
printKeys("\nOld keys (displayed once, not stored anywhere):", oldFedKeys);

View file

@ -1,4 +0,0 @@
export default function DmPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function FriendsPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function GlobalNestsPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function DiscoverPage() {
return null;
}

View file

@ -1,5 +0,0 @@
import AppContainer from "@/components/app-container";
export default function AppLayout() {
return <AppContainer />;
}

View file

@ -1,4 +0,0 @@
export default function HomePage() {
return null;
}

125
src/app/PostTestForm.tsx Normal file
View file

@ -0,0 +1,125 @@
"use client";
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
import { useState } from "react";
export function PostTestForm() {
const { data: session } = authClient.useSession();
const [text, setText] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [status, setStatus] = useState<string | null>(null);
const handleSubmit = async () => {
if (!session?.user.id) {
setStatus("Not signed in.");
return;
}
setStatus("Signing & submitting...");
try {
const content: { type: "text" | "image"; value: string | File }[] = [];
if (text.trim()) {
content.push({ type: "text", value: text.trim() });
}
for (const file of files) {
content.push({ type: "image", value: file });
}
if (content.length === 0) {
setStatus("Add some text or images first.");
return;
}
const result = await authClient.createPost(content, session.user.id);
setStatus(`Done: ${JSON.stringify(result)}`);
} catch (err) {
setStatus(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
};
const registerDiscoverPayload = {
method: "REGISTER" as const,
url: process.env.BETTER_AUTH_URL!,
publicKey: process.env.FEDERATION_PUBLIC_KEY!,
encryptionPublicKey: process.env.FEDERATION_ENCRYPTION_PUBLIC_KEY!,
};
async function forceDiscover(peerBaseUrl: string) {
setStatus("Relaying discover…");
try {
const response = await fetch("/api/dev/relay-discover", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
target: peerBaseUrl,
payload: registerDiscoverPayload,
}),
});
const data = await response.json();
setStatus(`${response.status} ${response.statusText}\n${JSON.stringify(data, null, 2)}`);
} catch (err) {
setStatus(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
}
return (
<div style={{ padding: 32, maxWidth: 480, margin: "0 auto", fontFamily: "sans-serif" }}>
<h2>Test Post</h2>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Write something..."
rows={4}
style={{ width: "100%", marginBottom: 12, padding: 8, fontSize: 14 }}
/>
<div style={{ marginBottom: 12 }}>
<label style={{ display: "block", marginBottom: 4, fontWeight: 600 }}>
Images
</label>
<input
type="file"
accept="image/*"
multiple
onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
/>
{files.length > 0 && (
<div style={{ marginTop: 8, fontSize: 13, color: "#666" }}>
{files.map((f, i) => (
<div key={i}>{f.name} ({(f.size / 1024).toFixed(1)} KB)</div>
))}
</div>
)}
</div>
<button
onClick={handleSubmit}
style={{
padding: "10px 24px",
fontSize: 14,
fontWeight: 600,
cursor: "pointer",
background: "#111",
color: "#fff",
border: "none",
borderRadius: 6,
}}
>
Create Post
</button>
{status && (
<pre style={{ marginTop: 16, padding: 12, background: "#f4f4f4", borderRadius: 6, fontSize: 13, whiteSpace: "pre-wrap" }}>
{status}
</pre>
)}
<Button onClick={() => forceDiscover("http://172.21.157.201:3000")}>Force Discover</Button>
<Button onClick={() => forceDiscover("http://172.21.157.201:3001")}>Force Discover</Button>
</div>
);
}

View file

@ -1,3 +1,4 @@
import { handler } from "@/lib/auth/auth-server";
import { auth } from "@/lib/auth"; // path to your auth file
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = handler;
export const { POST, GET } = toNextJsHandler(auth);

View file

@ -0,0 +1,56 @@
import { discoverAndRegister, DiscoveryError } from "@/lib/federation/registry";
import { assertSafeUrl, UrlGuardError } from "@/lib/federation/url-guard";
import createDebug from "debug";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const debug = createDebug("app:api:dev:relay-discover");
const bodySchema = z.object({
target: z.url(),
});
/**
* Dev-only: browser calls same origin; server runs the full mutual-registration
* flow (GET keys register locally POST REGISTER process echo) so that
* both sides end up knowing each other, mirroring the production path.
*/
export async function POST(request: NextRequest) {
if (process.env.NODE_ENV === "production") {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
let json: unknown;
try {
json = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = bodySchema.safeParse(json);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.message }, { status: 400 });
}
const { target } = parsed.data;
try {
assertSafeUrl(target);
} catch (err) {
if (err instanceof UrlGuardError) {
return NextResponse.json({ error: err.message }, { status: 400 });
}
throw err;
}
try {
await discoverAndRegister(target);
debug("relay-discover: mutual registration with %s complete", target);
return NextResponse.json({ message: "Server registered successfully" });
} catch (err) {
debug("relay-discover failed: %o", err);
if (err instanceof DiscoveryError) {
return NextResponse.json({ error: err.message }, { status: 502 });
}
throw err;
}
}

View file

@ -0,0 +1,103 @@
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
const forgotPasswordSchema = z.object({
email: z.email("Please enter a valid email"),
});
export function ForgotPasswordForm({
setView,
}: {
setView: (view: "signIn" | "signUp" | "forgotPassword") => void;
}) {
const form = useForm<z.infer<typeof forgotPasswordSchema>>({
resolver: zodResolver(forgotPasswordSchema),
defaultValues: {
email: "",
},
});
async function onSubmit(values: z.infer<typeof forgotPasswordSchema>) {
console.debug(`[ForgotPasswordForm] submitting reset request for ${values.email}`);
const { email } = values;
return new Promise<void>((resolve) => {
authClient.requestPasswordReset({
email,
redirectTo: `${window.location.origin}/auth?view=resetPassword`,
}, {
onSuccess: () => {
console.debug(`[ForgotPasswordForm] reset request successful for ${email}`);
toast.success("Reset link sent to your email");
// Clean up the form
form.reset();
resolve();
},
onError: (error) => {
console.debug(`[ForgotPasswordForm] reset request failed for ${email}: ${JSON.stringify(error)}`);
form.setError("root", { message: error.error.message });
toast.error(error.error.message);
// Clean up the form
form.reset();
resolve();
}
})
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter your email"
type="email"
className="h-11 text-base bg-background border-border/50"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
className="w-full h-11 text-base font-semibold bg-primary text-primary-foreground hover:bg-primary/90"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Send reset link
</Button>
<div className="text-center text-sm text-muted-foreground">
<button
type="button"
onClick={() => setView("signIn")}
className="text-primary hover:underline underline-offset-4 font-semibold"
disabled={form.formState.isSubmitting}
>
Back to Sign In
</button>
</div>
</form>
</Form>
);
}

View file

@ -0,0 +1,348 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff, Loader2, Sparkles } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
const verifyEmailSchema = z.object({
token: z.string().min(1, "Token is required"),
});
export function VerifyEmailModal({
isOpen,
setIsOpen,
email,
}: {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
email: string;
}) {
const form = useForm<z.infer<typeof verifyEmailSchema>>({
resolver: zodResolver(verifyEmailSchema),
defaultValues: {
token: "",
},
});
async function onSubmit(values: z.infer<typeof verifyEmailSchema>) {
console.debug(`[VerifyEmailModal] submitting verification for ${email}`);
const { token } = values;
return new Promise<void>((resolve) => {
authClient.verifyEmail(
{ query: { token } },
{
onSuccess: () => {
toast.success("Email verified successfully! You will now be redirected to the dashboard.");
setIsOpen(false);
form.reset();
resolve();
},
onError: (error) => {
console.debug(`[VerifyEmailModal] verification failed for ${email}: ${JSON.stringify(error)}`);
form.setError("token", { message: error.error.message });
toast.error(error.error.message);
resolve();
},
}
);
});
}
const handleResendVerification = () => {
authClient.sendVerificationEmail(
{ email },
{
onSuccess: () => {
toast.success("A new verification email has been sent.");
},
onError: (error) => {
toast.error(error.error.message);
},
}
);
};
if (!isOpen) {
return null;
}
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Verify Your Email</DialogTitle>
<DialogDescription>
A verification code has been sent to{" "}
<span className="font-semibold">{email}</span>. Please enter it
below.
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="token"
render={({ field }) => (
<FormItem>
<FormLabel>Verification Code</FormLabel>
<FormControl>
<Input placeholder="Enter your code" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter className="flex-col-reverse sm:flex-row sm:justify-between items-center pt-2">
<div className="text-sm text-muted-foreground pt-2 sm:pt-0">
<span>No code? </span>
<button
type="button"
onClick={handleResendVerification}
className="text-primary hover:underline underline-offset-4 font-semibold"
disabled={form.formState.isSubmitting}
>
Resend
</button>
</div>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Verify
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
export function ResetPasswordModal({
isOpen,
setIsOpen,
}: {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}) {
const searchParams = useSearchParams();
const router = useRouter();
const token = searchParams.get("token");
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const formSchema = z.object({
password: z.string().min(8, "Password must be at least 8 characters"),
confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
password: "",
confirmPassword: "",
},
});
const generatePassword = () => {
// Between 8 and 12 characters
const length = Math.floor(Math.random() * 5) + 8;
const lower = "abcdefghijklmnopqrstuvwxyz";
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
const allChars = lower + upper + numbers + symbols;
const getRandom = (max: number) => {
const randomValues = new Uint32Array(1);
window.crypto.getRandomValues(randomValues);
return randomValues[0] % max;
}
let password = "";
// Ensure at least one of each character type
password += lower[getRandom(lower.length)];
password += upper[getRandom(upper.length)];
password += numbers[getRandom(numbers.length)];
password += symbols[getRandom(symbols.length)];
for (let i = 4; i < length; i++) {
password += allChars[getRandom(allChars.length)];
}
// Fisher-Yates (aka Knuth) Shuffle
let passwordArray = password.split('');
for (let i = passwordArray.length - 1; i > 0; i--) {
const j = getRandom(i + 1);
[passwordArray[i], passwordArray[j]] = [passwordArray[j], passwordArray[i]];
}
const shuffledPassword = passwordArray.join('');
form.setValue("password", shuffledPassword, { shouldValidate: true });
form.setValue("confirmPassword", shuffledPassword, { shouldValidate: true });
toast.info("Generated a secure password. Make sure to save it somewhere safe!", {
action: {
label: "Copy",
onClick: () => {
navigator.clipboard.writeText(shuffledPassword);
toast.success("Password copied to clipboard", {
closeButton: true,
});
},
},
closeButton: true,
duration: 10000,
});
};
async function onSubmit(values: z.infer<typeof formSchema>) {
if (!token) {
toast.error("Invalid password reset token.");
return;
}
return new Promise<void>((resolve) => {
authClient.resetPassword({
token,
newPassword: values.password,
}, {
onSuccess: () => {
toast.success("Password has been reset successfully!");
setIsOpen(false);
router.replace("/auth", {
scroll: false,
});
resolve();
},
onError: (error) => {
toast.error(error.error.message);
resolve();
}
});
})
}
return (
<Dialog open={isOpen} onOpenChange={(open) => {
setIsOpen(open);
if (!open) {
router.replace('/auth', {
scroll: false,
});
}
}}>
<DialogContent className="sm:max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>Reset Password</DialogTitle>
<DialogDescription>
Enter your new password below. Make sure it's secure.
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Password</FormLabel>
<FormControl>
<div className="relative">
<Input
placeholder={showPassword ? "Enter your password" : "********"}
type={showPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/50 pr-10"
{...field}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground"
>
{showPassword ? (
<EyeOff className="w-5 h-5" />
) : (
<Eye className="w-5 h-5" />
)}
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Confirm Password</FormLabel>
<FormControl>
<div className="relative">
<Input
placeholder={showConfirmPassword ? "Confirm your password" : "********"}
type={showConfirmPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/50 pr-10"
{...field}
/>
<button
type="button"
onClick={() =>
setShowConfirmPassword(!showConfirmPassword)
}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground"
>
{showConfirmPassword ? (
<EyeOff className="w-5 h-5" />
) : (
<Eye className="w-5 h-5" />
)}
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<button
type="button"
onClick={generatePassword}
className="text-xs text-muted-foreground hover:text-primary underline-offset-4 hover:underline flex items-center gap-1"
disabled={form.formState.isSubmitting}
>
<Sparkles className="w-3 h-3" />
<span>Generate Password</span>
</button>
</div>
<DialogFooter>
<Button type="submit" disabled={form.formState.isSubmitting} className="w-full">
{form.formState.isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Reset Password
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}

View file

@ -0,0 +1,153 @@
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff, Loader2 } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
export function SignInForm({
setView,
}: {
setView: (view: "signIn" | "signUp" | "forgotPassword") => void;
onEmailNotVerified: (email: string) => void;
}) {
const [showPassword, setShowPassword] = useState(false);
const formSchema = z.object({
email: z.email("Please enter a valid email"),
password: z.string().min(8, "Password must be at least 8 characters"),
})
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
},
})
async function onSubmit(values: z.infer<typeof formSchema>) {
console.debug(`[SignInForm] submitting login for ${values.email}`);
const { email, password } = values;
const { error } = await authClient.signIn.email({
email,
password,
callbackURL: "/",
})
if (error) {
form.setError("root", { message: error.message });
toast.error(error.message);
return;
}
toast.success("Login successful");
form.reset();
return;
}
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Email</FormLabel>
<FormControl>
<Input
placeholder="Enter your email"
type="email"
className="h-11 text-base bg-background border-border/50"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Password</FormLabel>
<FormControl>
<div className="relative">
<Input
placeholder="Enter your password"
type={showPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/50 pr-10"
{...field}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground"
>
{showPassword ? (
<EyeOff className="w-5 h-5" />
) : (
<Eye className="w-5 h-5" />
)}
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<button
type="button"
onClick={() => setView("forgotPassword")}
className="text-xs text-muted-foreground hover:text-primary underline-offset-4 hover:underline"
disabled={form.formState.isSubmitting}
>
Forgot password?
</button>
</div>
<Button
type="submit"
className="w-full h-11 text-base font-semibold bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Continue
</Button>
<div className="text-center text-sm text-muted-foreground text font-mono">
Don't have an account?{" "}
<button
type="button"
onClick={() => setView("signUp")}
className="text-primary hover:underline underline-offset-4 font-semibold text-nowrap"
disabled={form.formState.isSubmitting}
>
Sign up
</button>
</div>
</form>
</Form>
</>
)
}

View file

@ -0,0 +1,274 @@
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff, Loader2, Sparkles } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
const signUpFormSchema = z.object({
email: z.email("Please enter a valid email"),
password: z.string().min(8, "Password must be at least 8 characters"),
confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
});
export function SignUpForm({
setView,
onSuccess,
}: {
setView: (view: "signIn" | "signUp" | "forgotPassword") => void;
onSuccess: (email: string) => void;
}) {
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const form = useForm<z.infer<typeof signUpFormSchema>>({
resolver: zodResolver(signUpFormSchema),
defaultValues: {
email: "",
password: "",
confirmPassword: "",
},
});
async function onSubmit(values: z.infer<typeof signUpFormSchema>) {
console.debug(`[SignUpForm] submitting registration for ${values.email}`);
const { email, password, confirmPassword } = values;
if (password !== confirmPassword) {
form.setError("confirmPassword", { message: "Passwords don't match" });
return;
}
const username = email.split("@")[0];
// Check if username is already taken
const check = await authClient.isUsernameAvailable({ username });
if (!check) {
form.setError("root", { message: "Username is already taken" });
toast.error("Username is already taken");
return;
}
await authClient.signUp.email({
email,
password,
name: username,
username,
}, {
onSuccess: (res) => {
console.debug(JSON.stringify(res, null, 2));
console.debug(`[SignUpForm] registration successful for ${email}`);
toast.success("Registration successful, please check your email for the verification link!");
onSuccess(email);
return;
},
onError: (error: any) => {
console.debug(`[SignUpForm] registration failed for ${email}: ${JSON.stringify(error)}`);
if (error.error.code === "PASSWORD_COMPROMISED") {
toast.error("Password is compromised, please use a different password", {
action: {
label: "More details",
onClick: () => {
window.open("https://haveibeenpwned.com/Passwords", "_blank");
},
},
duration: 10000,
});
} else {
form.setError("root", { message: error.error.message });
toast.error(error.error.message);
}
// Clean up the form
form.reset();
return;
}
})
}
const generatePassword = () => {
// Between 8 and 12 characters
const length = Math.floor(Math.random() * 5) + 8;
const lower = "abcdefghijklmnopqrstuvwxyz";
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
const allChars = lower + upper + numbers + symbols;
const getRandom = (max: number) => {
const randomValues = new Uint32Array(1);
window.crypto.getRandomValues(randomValues);
return randomValues[0] % max;
}
let password = "";
// Ensure at least one of each character type
password += lower[getRandom(lower.length)];
password += upper[getRandom(upper.length)];
password += numbers[getRandom(numbers.length)];
password += symbols[getRandom(symbols.length)];
for (let i = 4; i < length; i++) {
password += allChars[getRandom(allChars.length)];
}
// Fisher-Yates (aka Knuth) Shuffle
let passwordArray = password.split('');
for (let i = passwordArray.length - 1; i > 0; i--) {
const j = getRandom(i + 1);
[passwordArray[i], passwordArray[j]] = [passwordArray[j], passwordArray[i]];
}
const shuffledPassword = passwordArray.join('');
form.setValue("password", shuffledPassword, { shouldValidate: true });
form.setValue("confirmPassword", shuffledPassword, { shouldValidate: true });
toast.info("Generated a secure password. Make sure to save it somewhere safe!", {
action: {
label: "Copy",
onClick: () => {
navigator.clipboard.writeText(shuffledPassword);
toast.success("Password copied to clipboard", {
closeButton: true,
});
},
},
closeButton: true,
duration: 10000,
});
};
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Email</FormLabel>
<FormControl>
<Input
placeholder="Enter your email"
type="email"
className="h-11 text-base bg-background border-border/50"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Password</FormLabel>
<FormControl>
<div className="relative">
<Input
placeholder={showPassword ? "Enter your password" : "********"}
type={showPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/50 pr-10"
{...field}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground"
>
{showPassword ? (
<EyeOff className="w-5 h-5" />
) : (
<Eye className="w-5 h-5" />
)}
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel className="text-xs font-semibold text-muted-foreground uppercase">Confirm Password</FormLabel>
<FormControl>
<div className="relative">
<Input
placeholder={showConfirmPassword ? "Confirm your password" : "********"}
type={showConfirmPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/50 pr-10"
{...field}
/>
<button
type="button"
onClick={() =>
setShowConfirmPassword(!showConfirmPassword)
}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground"
>
{showConfirmPassword ? (
<EyeOff className="w-5 h-5" />
) : (
<Eye className="w-5 h-5" />
)}
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<button
type="button"
onClick={generatePassword}
className="text-xs text-muted-foreground hover:text-primary underline-offset-4 hover:underline flex items-center gap-1"
disabled={form.formState.isSubmitting}
>
<Sparkles className="w-3 h-3" />
<span>Generate Password</span>
</button>
</div>
<Button
type="submit"
className="w-full h-11 text-base font-semibold bg-primary text-primary-foreground hover:bg-primary/90"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Create Account
</Button>
<div className="text-center text-sm text-muted-foreground">
Already have an account?{" "}
<button
type="button"
onClick={() => setView("signIn")}
className="text-primary hover:underline underline-offset-4 font-semibold"
disabled={form.formState.isSubmitting}
>
Sign in
</button>
</div>
</form>
</Form>
</>
);
}

View file

@ -0,0 +1,6 @@
export * from "./ForgotPasswordForm";
export * from "./Modals";
export * from "./settings-dropdown";
export * from "./SignInForm";
export * from "./SignUpForm";

View file

@ -0,0 +1,55 @@
"use client";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import { Monitor, Moon, Settings, Sun } from "lucide-react";
import { useTheme } from "next-themes";
export function SettingsDropdown() {
const { setTheme, theme } = useTheme();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-auto p-2 text-muted-foreground hover:text-foreground focus:ring-0 focus:ring-offset-0">
<Settings className="size-5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Appearance</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger>
{theme === 'light' ? <Sun className="mr-2 size-4" /> : theme === 'dark' ? <Moon className="mr-2 size-4" /> : <Monitor className="mr-2 size-4" />}
<span>Theme</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun className="mr-2 size-4" />
<span>Light</span>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon className="mr-2 size-4" />
<span>Dark</span>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
<Monitor className="mr-2 size-4" />
<span>System</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
);
}

View file

@ -1,89 +0,0 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth/client";
import { ErrorContext } from "better-auth/react";
import { Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
export function SignInForm(
{ captchaToken }: { captchaToken: string | null }
) {
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const handleSignIn = async (e: React.FormEvent) => {
e.preventDefault();
await authClient.signIn.username(
{
username,
password,
fetchOptions: {
headers: {
"x-captcha-response": captchaToken ?? "",
},
},
},
{
onRequest: () => {
setLoading(true);
},
onSuccess: (d: any) => {
console.log(d)
setLoading(false);
toast.success("Signed in successfully");
router.push("/");
},
onError: (ctx: ErrorContext) => {
setLoading(false);
toast.error(ctx.error.message);
},
}
);
};
return (
<form onSubmit={handleSignIn} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="john_doe"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="bg-background/50 focus:bg-background transition-colors"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="********"
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="bg-background/50 focus:bg-background transition-colors"
/>
</div>
<Button
type="submit"
className="w-full font-semibold mt-2"
disabled={loading}
>
{loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : "Sign In"}
</Button>
</form>
);
}

View file

@ -1,217 +0,0 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth/client";
import { ErrorContext } from "better-auth/react";
import { Check, Eye, EyeOff, Loader2, RefreshCw, X } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
export function SignUpForm(
{ captchaToken, setShowSignIn }: { captchaToken: string | null, setShowSignIn: (show: boolean) => void }
) {
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isUsernameAvailable, setIsUsernameAvailable] = useState<boolean | null>(null);
const [loading, setLoading] = useState(false);
const [isValidatingUsername, setIsValidatingUsername] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error("Passwords do not match");
return;
}
if (password.length > 30) {
toast.error("Password must be less than 30 characters");
return;
}
await authClient.signUp.email(
{
email: `${username}.user@sipher.space`,
name: username,
username,
password,
fetchOptions: {
headers: {
"x-captcha-response": captchaToken ?? "",
},
},
},
{
onRequest: () => {
setLoading(true);
},
onSuccess: async () => {
setLoading(false);
toast.success("Account created successfully, now log in to continue!");
setShowSignIn(true);
router.push("/");
},
onError: (ctx: ErrorContext) => {
setLoading(false);
toast.error(ctx.error.message);
},
}
);
};
const generatePassword = () => {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
let newPassword = "";
for (let i = 0; i < 16; i++) {
newPassword += chars.charAt(Math.floor(Math.random() * chars.length));
}
setPassword(newPassword);
setConfirmPassword(newPassword);
navigator.clipboard.writeText(newPassword);
toast.success("Password generated and copied to clipboard");
};
return (
<form onSubmit={handleSignUp} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<div className="relative">
<Input
id="username"
type="text"
placeholder="john_doe"
required
value={username}
onChange={async (e) => {
const val = e.target.value;
setUsername(val);
if (val) {
setIsValidatingUsername(true);
// @ts-ignore
const isValid = await authClient.isUsernameAvailable({ username: val });
setIsUsernameAvailable(!!isValid);
setIsValidatingUsername(false);
} else {
setIsUsernameAvailable(null);
}
}}
className={`bg-background/50 focus:bg-background transition-colors pr-10 ${isUsernameAvailable === false ? "border-red-500 focus-visible:ring-red-500" :
isUsernameAvailable === true ? "border-green-500 focus-visible:ring-green-500" : ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
{isValidatingUsername ? (
<Loader2 className="size-4 animate-spin" />
) : isUsernameAvailable === true ? (
<Check className="size-4 text-green-500" />
) : isUsernameAvailable === false ? (
<X className="size-4 text-red-500" />
) : null}
</div>
</div>
{isUsernameAvailable === false && (
<p className="text-xs text-red-500">Username is already taken</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="********"
autoComplete="new-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className={`bg-background/50 focus:bg-background transition-colors pr-24 ${password.length >= 8 && password.length <= 30
? "border-green-500 focus-visible:ring-green-500"
: password.length > 30
? "border-red-500 focus-visible:ring-red-500"
: ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
{password.length > 30 ? (
<X className="size-4 text-red-500" />
) : password.length >= 8 && (
<Check className="size-4 text-green-500" />
)}
<Button
type="button"
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-primary"
onClick={() => setShowPassword(!showPassword)}
title={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? <EyeOff className="size-3" /> : <Eye className="size-3" />}
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-primary"
onClick={generatePassword}
title="Generate secure password"
>
<RefreshCw className="size-3" />
</Button>
</div>
</div>
{password.length > 30 && (
<p className="text-xs text-red-500">Password must be less than 30 characters</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<div className="relative">
<Input
id="confirmPassword"
type={showPassword ? "text" : "password"}
placeholder="********"
autoComplete="new-password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className={`bg-background/50 focus:bg-background transition-colors pr-10 ${confirmPassword && password === confirmPassword && password.length <= 30
? "border-green-500 focus-visible:ring-green-500"
: (confirmPassword && password !== confirmPassword) || (confirmPassword && password.length > 30)
? "border-red-500 focus-visible:ring-red-500"
: ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
{confirmPassword && password === confirmPassword && password.length <= 30 ? (
<Check className="size-4 text-green-500" />
) : confirmPassword && (password !== confirmPassword || password.length > 30) ? (
<X className="size-4 text-red-500" />
) : null}
</div>
</div>
{confirmPassword && password !== confirmPassword && (
<p className="text-xs text-red-500">Passwords do not match</p>
)}
</div>
<Button
type="submit"
className="w-full font-semibold mt-2"
disabled={
loading ||
isUsernameAvailable === false ||
password !== confirmPassword ||
password.length < 8 ||
password.length > 30
}
>
{loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : "Sign Up"}
</Button>
</form>
);
}

View file

@ -1,162 +1,133 @@
"use client";
import { ModeToggle } from "@/components/mode-toggle";
import { Button } from "@/components/ui/button";
import Captcha, { CaptchaRef } from "@/components/ui/captcha";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Spinner } from "@/components/ui/spinner";
import { authClient } from "@/lib/auth/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { authClient } from "@/lib/auth-client";
import { AnimatePresence, motion } from "framer-motion";
import { RefreshCw } from "lucide-react";
import { ArrowLeft, Loader2 } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { SignInForm } from "./components/sign-in-form";
import { SignUpForm } from "./components/sign-up-form";
export default function AuthPage() {
const { data, error, isPending } = authClient.useSession();
const [captchaToken, setCaptchaToken] = useState<string | null>(null);
const [method, setMethod] = useState<"signIn" | "signUp">("signIn");
const captchaRef = useRef<CaptchaRef>(null);
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { ForgotPasswordForm, ResetPasswordModal, SettingsDropdown, SignInForm, SignUpForm, VerifyEmailModal } from "./components";
function AuthPageContent() {
const searchParams = useSearchParams();
const method = searchParams.get("method") as "signUp" | "signIn";
const type = searchParams.get("type");
const { data: session, error: sessionError, isPending } = authClient.useSession();
const router = useRouter();
const [view, setView] = useState<"signIn" | "signUp" | "forgotPassword">(
type === "orgInvite" ? (method === "signUp" ? "signUp" : "signIn") : "signIn"
);
const [isResetPasswordModalOpen, setResetPasswordModalOpen] = useState(false);
const [isVerifyEmailModalOpen, setVerifyEmailModalOpen] = useState(false);
const [emailToVerify, setEmailToVerify] = useState("");
useEffect(() => {
if (error && error.status !== 404) {
console.error("[AuthPage] > Error:", error);
toast.error(error.message);
} else if (data) {
console.log(`[AuthPage] > User ${data.user.username} logged in, redirecting to home...`);
redirect("/");
const viewParam = searchParams.get("view");
if (viewParam?.startsWith("resetPassword")) {
setResetPasswordModalOpen(true);
}
}, [error, data])
}, [searchParams]);
if (isPending) {
if (session === undefined) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin text-primary" />
<div className="flex h-screen w-screen items-center justify-center bg-background">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
);
)
} else if (session !== null && "user" in session) {
router.replace("/");
}
const toggleMethod = () => {
setMethod(method === "signIn" ? "signUp" : "signIn");
};
return (
<div className="min-h-screen w-full flex items-center justify-center bg-background relative overflow-hidden p-4">
{/* Animated Background Blobs */}
<motion.div
animate={{
scale: [1, 1.2, 1],
rotate: [0, 90, 0],
}}
transition={{
duration: 20,
repeat: Infinity,
ease: "linear",
}}
className="absolute top-0 left-0 w-[500px] h-[500px] bg-primary/20 rounded-full mix-blend-multiply filter blur-[100px] opacity-50 pointer-events-none"
<>
<ResetPasswordModal
isOpen={isResetPasswordModalOpen}
setIsOpen={setResetPasswordModalOpen}
/>
<motion.div
animate={{
scale: [1, 1.1, 1],
rotate: [0, -60, 0],
}}
transition={{
duration: 15,
repeat: Infinity,
ease: "linear",
}}
className="absolute bottom-0 right-0 w-[500px] h-[500px] bg-accent/20 rounded-full mix-blend-multiply filter blur-[100px] opacity-50 pointer-events-none"
<VerifyEmailModal
isOpen={isVerifyEmailModalOpen}
setIsOpen={setVerifyEmailModalOpen}
email={emailToVerify}
/>
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5, type: "spring" }}
className="w-full max-w-md z-10"
>
<Card className="backdrop-blur-md bg-card/90 border-muted/50 shadow-2xl relative">
<div className="absolute top-4 right-4">
<ModeToggle />
<div className="flex flex-col min-h-screen w-screen items-center justify-center bg-background gap-8 p-4 sm:p-0 ">
<div className="flex flex-col items-center gap-1">
<span className="font-display text-4xl sm:text-5xl tracking-[0.08em] text-primary">SiPher</span>
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase w-full">Silent Whisper</span>
</div>
<Card className="relative w-full max-w-md bg-card text-card-foreground p-6 sm:p-8 rounded-lg shadow-2xl border-border">
<div className="absolute top-4 left-4">
<Button disabled={type === "orgInvite"} variant="ghost" size="icon" className="text-muted-foreground hover:text-foreground" onClick={() => router.back()}>
<ArrowLeft className="w-5 h-5" />
</Button>
</div>
<CardHeader className="space-y-1 text-center">
<AnimatePresence mode="wait">
<div className="absolute top-4 right-4">
<SettingsDropdown />
</div>
<CardHeader className="flex flex-col items-center space-y-6 pt-8 text-center">
<CardTitle className="text-2xl font-semibold font-mono">
{view === "signIn" && "Sign In"}
{view === "signUp" && "Create an account"}
{view === "forgotPassword" && "Reset Password"}
</CardTitle>
</CardHeader>
<CardContent className="p-0 overflow-hidden">
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={method}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
key={view}
initial={{ opacity: 0, x: 50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -50 }}
transition={{ duration: 0.3 }}
>
<CardTitle className="text-2xl font-bold">
{method === "signIn" ? "Welcome Back" : "Create Account"}
</CardTitle>
<CardDescription>
{method === "signIn"
? "Enter your credentials to access your account"
: "Enter your details to get started with us"}
</CardDescription>
{view === "signIn" ? (
<SignInForm
setView={setView}
onEmailNotVerified={(email) => {
setEmailToVerify(email);
setVerifyEmailModalOpen(true);
}}
/>
) : view === "signUp" ? (
<SignUpForm
setView={setView}
onSuccess={(email) => {
setEmailToVerify(email);
setVerifyEmailModalOpen(true);
}}
/>
) : (
<ForgotPasswordForm setView={setView} />
)}
</motion.div>
</AnimatePresence>
</CardHeader>
<CardContent>
{method === "signIn" ? <SignInForm captchaToken={captchaToken} /> : <SignUpForm captchaToken={captchaToken} setShowSignIn={() => setMethod("signIn")} />}
</CardContent>
<CardFooter className="flex flex-col gap-4 pt-2">
<div className="text-center text-sm text-muted-foreground">
{method === "signIn" ? "Don't have an account? " : "Already have an account? "}
<button
type="button"
onClick={toggleMethod}
className="font-semibold text-primary hover:underline focus:outline-none"
>
{method === "signIn" ? "Sign up" : "Sign in"}
</button>
</div>
{/* Turnstile */}
<div className="flex flex-col justify-center items-center gap-2">
<Captcha ref={captchaRef} onSuccess={setCaptchaToken} />
{/* Reload the captcha */}
<Button
variant="outline"
size="sm"
onClick={() => {
setCaptchaToken(null);
captchaRef.current?.reset();
}}
>
<RefreshCw className="size-4" />
<div className="border-px border-l border-border h-full ml-2" />
<span className="text-xs">Reload Captcha</span>
</Button>
</div>
<div className="flex justify-center w-full border-t pt-4">
<p className="text-center text-xs text-muted-foreground">
built with{" "}
<Link
href="https://better-auth.com"
className="underline hover:text-primary transition-colors"
target="_blank"
>
better-auth
</Link>
</p>
</div>
</CardFooter>
</Card>
</motion.div>
</div>
<div className="flex flex-col items-center gap-1">
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase w-full">© 2026 Sipher. All rights reserved.</span>
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase w-full">
Refuse to be dominated. Be free. <Link href={process.env.PUBLIC_GIT_URL ?? ""} target="_blank" className="text-primary underline">Create your own network.</Link>
</span>
</div>
</div>
</>
);
}
export default function AuthPage() {
return (
<Suspense
fallback={
<div className="flex h-screen w-screen items-center justify-center bg-background">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
}
>
<AuthPageContent />
</Suspense>
);
}

View file

@ -1,125 +0,0 @@
import { db } from "@/lib/db";
// Track OLM initialization state
let olmInitPromise: Promise<any> | null = null;
// Load OLM via script tag to bypass bundler entirely
export async function loadOlm() {
if (typeof window === "undefined") throw new Error("OLM requires browser");
// If already initialized, return cached Olm
if ((window as any).__olmInitialized && (window as any).Olm) {
console.debug("[makeKeysOnSignUp]: OLM already initialized");
return (window as any).Olm;
}
// If initialization is in progress, wait for it
if (olmInitPromise) {
console.debug("[makeKeysOnSignUp]: OLM initialization in progress, waiting for it");
return olmInitPromise;
}
// Start initialization
olmInitPromise = new Promise((resolve, reject) => {
// Check if script already loaded but not initialized
if ((window as any).Olm) {
const Olm = (window as any).Olm;
Olm.init({ locateFile: () => "/olm.wasm" })
.then(() => {
(window as any).__olmInitialized = true;
resolve(Olm);
})
.catch(reject);
return;
}
const script = document.createElement("script");
script.src = "/olm.js";
script.onload = async () => {
try {
const Olm = (window as any).Olm;
await Olm.init({ locateFile: () => "/olm.wasm" });
(window as any).__olmInitialized = true;
resolve(Olm);
} catch (err) {
reject(err);
}
};
script.onerror = (err) => {
console.error("[makeKeysOnSignUp]: Failed to load OLM: ", err);
reject(new Error(`Failed to load OLM: ${err}`));
};
document.head.appendChild(script);
});
return olmInitPromise;
}
type SendKeysToServerFn = (args: {
userId: string;
identityKey: { curve25519: string; ed25519: string };
oneTimeKeys: { keyId: string; publicKey: string }[];
forceInsert: boolean;
}) => Promise<unknown>;
export default async function makeKeysOnSignUp(
odId: string,
localPassword: string,
sendKeysToServer: SendKeysToServerFn,
forceInsert: boolean = false,
) {
const Olm = await loadOlm() as typeof import("@matrix-org/olm");
const account = new Olm.Account();
account.create();
const identityKey: { curve25519: string; ed25519: string } = JSON.parse(account.identity_keys());
console.debug("[makeKeysOnSignUp] Identity key: ", identityKey);
account.generate_one_time_keys(50);
const oneTimeKeys = JSON.parse(account.one_time_keys());
console.debug("[makeKeysOnSignUp] One time keys: ", oneTimeKeys);
account.mark_keys_as_published();
try {
await sendKeysToServer({
userId: odId,
identityKey: {
curve25519: identityKey.curve25519,
ed25519: identityKey.ed25519,
},
oneTimeKeys: Object.entries(oneTimeKeys.curve25519).map(([key, value]) => ({
keyId: key,
publicKey: value as string,
})),
forceInsert,
});
} catch (error) {
console.error("Failed to make keys", error);
return false;
}
const pickledAccount = account.pickle(localPassword);
// Note: Password storage is handled by the OlmContext with encryption
// Do NOT store plain text password here
// Cache the account in window
if (!(window as any).olmAccountCache) {
(window as any).olmAccountCache = {};
}
(window as any).olmAccountCache[odId] = account;
// Set the OLM session into the window object
(window as any).olmSession = new Olm.Session();
// Store the olm account on DB
await db.olmAccounts.put({
odId,
pickledAccount,
createdAt: Date.now(),
updatedAt: Date.now(),
});
return true;
}

View file

@ -0,0 +1,180 @@
import db from "@/lib/db";
import { blacklistedServers, rotateChallengeTokens, serverRegistry } from "@/lib/db/schema";
import { decryptPayload, verifySignature } from "@/lib/federation/keytools";
import { isJsonObjectBody } from "@/lib/http/json-object-body";
import createDebug from "debug";
import { eq, sql } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const debug = createDebug("app:discover:rotate:confirm");
/**
* Confirms a key rotation challenge issued by /discover/rotate/init.
*
* Terminology: SA = this server (Server A), SB = the server rotating its keys (Server B).
*
* Full rotation flow:
* 1. SB generates new Ed25519 + X25519 keypairs.
* 2. SB sends { url, newSigningPublicKey, newEncryptionPublicKey } to SA's /discover/rotate/init.
* 3. SA issues 4 challenges:
* - signingOldChallenge: plaintext nonce (SB signs with old Ed25519 key)
* - signingNewChallenge: plaintext nonce (SB signs with new Ed25519 key)
* - encryptionOldChallenge: nonce encrypted with SB's current X25519 key
* - encryptionNewChallenge: nonce encrypted with SB's new X25519 key
* 4. SB solves all 4 challenges:
* - Signs the signing challenges with respective Ed25519 keys
* - Decrypts the encryption challenges with respective X25519 keys
* 5. SB fetches SA's /discover to get SA's X25519 public key, then encrypts
* all 4 proof values into a single EncryptedEnvelope using SA's X25519 key.
* 6. SA decrypts the envelope and verifies all 4 proofs.
*
* What each check proves:
* - signingOldSignature: SB holds the old Ed25519 private key (identity proof)
* - signingNewSignature: SB holds the new Ed25519 private key (ownership proof)
* - encryptionOldPlaintext: SB holds the old X25519 private key (encryption identity proof)
* - encryptionNewPlaintext: SB holds the new X25519 private key (encryption ownership proof)
* - Envelope encrypted with SA's X25519 key: SB fetched SA's /discover (identity binding)
*/
export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_JSON" }, { status: 400 });
}
if (!isJsonObjectBody(body)) {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_JSON" }, { status: 400 });
}
debug("POST /discover/rotate/confirm confirmation request for %s", (body as { serverUrl?: string }).serverUrl);
const validated = z.object({
serverUrl: z.url(),
envelope: z.object({
ephemeralPublicKey: z.string(),
iv: z.string(),
ciphertext: z.string(),
authTag: z.string(),
}),
}).safeParse(body);
if (!validated.success) {
debug("POST /discover/rotate/confirm validation failed: %o", validated.error.message);
return NextResponse.json({ error: validated.error.message }, { status: 400 });
}
const [blacklisted] = await db.select().from(blacklistedServers)
.where(eq(blacklistedServers.serverUrl, validated.data.serverUrl));
if (blacklisted) {
debug("POST /discover/rotate/confirm server %s is blacklisted", validated.data.serverUrl);
return NextResponse.json({ error: "Your server has been blacklisted. Please contact support to unblacklist your server." }, { status: 403 });
}
debug("POST /discover/rotate/confirm fetching pending challenge for %s", validated.data.serverUrl);
return await db.transaction(async (tx) => {
const [challenge] = await tx.select().from(rotateChallengeTokens)
.where(eq(rotateChallengeTokens.serverUrl, validated.data.serverUrl))
.for("update");
if (!challenge) {
debug("POST /discover/rotate/confirm no pending challenge found");
return NextResponse.json({ error: "No pending rotation challenge found for this server." }, { status: 404 });
}
if (challenge.expiresAt < new Date()) {
debug("POST /discover/rotate/confirm challenge expired at %s", challenge.expiresAt.toISOString());
await tx.delete(rotateChallengeTokens).where(eq(rotateChallengeTokens.id, challenge.id));
return NextResponse.json({ error: "Challenge token has expired." }, { status: 400 });
}
if (challenge.attemptsLeft <= 0) {
// Cancel the challenge without blacklisting the server. Blacklisting
// here would be unsafe because anyone can open an init challenge for
// an arbitrary server URL — auto-blacklisting on failed confirms
// lets an attacker permanently ban a legitimate peer with no effort.
debug("POST /discover/rotate/confirm no attempts left, cancelling challenge for %s", challenge.serverUrl);
await tx.delete(rotateChallengeTokens).where(eq(rotateChallengeTokens.id, challenge.id));
return NextResponse.json({
error: "Too many failed attempts. The rotation challenge has been cancelled. Please initiate a new rotation.",
}, { status: 403 });
}
debug("POST /discover/rotate/confirm %d attempt(s) left, decrypting envelope", challenge.attemptsLeft);
const ownEncryptionSecretKey = new Uint8Array(
Buffer.from(process.env.FEDERATION_ENCRYPTION_PRIVATE_KEY!, "base64"),
);
let proofs: {
signingOldSignature: string;
signingNewSignature: string;
encryptionOldPlaintext: string;
encryptionNewPlaintext: string;
};
try {
const decrypted = decryptPayload(validated.data.envelope, ownEncryptionSecretKey);
proofs = JSON.parse(decrypted);
} catch {
debug("POST /discover/rotate/confirm envelope decryption failed, decrementing attempts");
await tx.update(rotateChallengeTokens).set({
attemptsLeft: sql`${rotateChallengeTokens.attemptsLeft} - 1`,
}).where(eq(rotateChallengeTokens.id, challenge.id));
return NextResponse.json({
error: `Failed to decrypt envelope. You have ${challenge.attemptsLeft - 1} attempt(s) left.`,
}, { status: 400 });
}
const [server] = await tx.select().from(serverRegistry)
.where(eq(serverRegistry.url, challenge.serverUrl));
if (!server) {
debug("POST /discover/rotate/confirm server not found in registry");
return NextResponse.json({ error: "Server not found in registry." }, { status: 404 });
}
const currentSigningPub = new Uint8Array(Buffer.from(server.publicKey, "base64"));
const newSigningPub = new Uint8Array(Buffer.from(challenge.newSigningPublicKey, "base64"));
const signingOldValid = verifySignature(
challenge.signingOldToken,
proofs.signingOldSignature,
currentSigningPub,
);
const signingNewValid = verifySignature(
challenge.signingNewToken,
proofs.signingNewSignature,
newSigningPub,
);
const encOldValid = proofs.encryptionOldPlaintext === challenge.encryptionOldToken;
const encNewValid = proofs.encryptionNewPlaintext === challenge.encryptionNewToken;
if (!signingOldValid || !signingNewValid || !encOldValid || !encNewValid) {
debug(
"POST /discover/rotate/confirm proof mismatch (sigOld=%s, sigNew=%s, encOld=%s, encNew=%s), decrementing",
signingOldValid ? "ok" : "FAIL",
signingNewValid ? "ok" : "FAIL",
encOldValid ? "ok" : "FAIL",
encNewValid ? "ok" : "FAIL",
);
await tx.update(rotateChallengeTokens).set({
attemptsLeft: sql`${rotateChallengeTokens.attemptsLeft} - 1`,
}).where(eq(rotateChallengeTokens.id, challenge.id));
return NextResponse.json({
error: `Challenge verification failed. You have ${challenge.attemptsLeft - 1} attempt(s) left.`,
}, { status: 400 });
}
debug("POST /discover/rotate/confirm all 4 proofs passed, rotating keys for %s", challenge.serverUrl);
await tx.update(serverRegistry).set({
publicKey: challenge.newSigningPublicKey,
encryptionPublicKey: challenge.newEncryptionPublicKey,
updatedAt: new Date(),
}).where(eq(serverRegistry.url, challenge.serverUrl));
await tx.delete(rotateChallengeTokens).where(eq(rotateChallengeTokens.id, challenge.id));
debug("POST /discover/rotate/confirm key rotation complete for %s", challenge.serverUrl);
return NextResponse.json({ message: "Key rotation confirmed successfully." });
});
}

View file

@ -0,0 +1,150 @@
import db from "@/lib/db";
import { blacklistedServers, rotateChallengeTokens, serverRegistry } from "@/lib/db/schema";
import { encryptPayload } from "@/lib/federation/keytools";
import { isJsonObjectBody } from "@/lib/http/json-object-body";
import { checkRateLimit } from "@/lib/rate-limit/rate-limit";
import createDebug from "debug";
import { eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const debug = createDebug("app:discover:rotate:init");
const ED25519_PUBLIC_KEY_BYTES = 32;
const X25519_PUBLIC_KEY_BYTES = 32;
function isValidBase64Key(key: string, expectedBytes: number): boolean {
try {
const decoded = Buffer.from(key, "base64");
return decoded.length === expectedBytes;
} catch {
return false;
}
}
const schema = z.object({
url: z.url(),
newSigningPublicKey: z.string().refine(
(key) => isValidBase64Key(key, ED25519_PUBLIC_KEY_BYTES),
{ message: "Invalid Ed25519 signing public key" },
),
newEncryptionPublicKey: z.string().refine(
(key) => isValidBase64Key(key, X25519_PUBLIC_KEY_BYTES),
{ message: "Invalid X25519 encryption public key" },
),
});
/**
* Initializes a key rotation challenge for a server.
*
* Issues 4 independent challenges:
* - signingOldChallenge: plaintext nonce (SB signs with old Ed25519 key)
* - signingNewChallenge: plaintext nonce (SB signs with new Ed25519 key)
* - encryptionOldChallenge: nonce encrypted with SB's current X25519 key (SB decrypts)
* - encryptionNewChallenge: nonce encrypted with SB's new X25519 key (SB decrypts)
*
* Challenges expire in 5 minutes. SB confirms via /discover/rotate/confirm.
*/
export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_JSON" }, { status: 400 });
}
if (!isJsonObjectBody(body)) {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_JSON" }, { status: 400 });
}
debug("POST /discover/rotate/init rotation request for %s", (body as { url?: string }).url);
const validated = schema.safeParse(body);
if (!validated.success) {
debug("POST /discover/rotate/init validation failed: %o", validated.error.message);
return NextResponse.json({ error: validated.error.message }, { status: 400 });
}
// Per-serverUrl rate limit to prevent bulk rotation init attempts
const rlResult = await checkRateLimit(`rotate-init:${validated.data.url.toString()}`, {
limit: 2,
windowSeconds: 60,
});
if (!rlResult.allowed) {
debug("POST /discover/rotate/init rate limited for %s", validated.data.url);
return NextResponse.json({
error: "Too many rotation init attempts for this server. Please try again later.",
}, { status: 429 });
}
const [blacklisted] = await db.select().from(blacklistedServers)
.where(eq(blacklistedServers.serverUrl, validated.data.url.toString()));
if (blacklisted) {
debug("POST /discover/rotate/init server %s is blacklisted", validated.data.url);
return NextResponse.json({ error: "Your server has been blacklisted." }, { status: 403 });
}
debug("POST /discover/rotate/init looking up server %s", validated.data.url);
const server = await db.select().from(serverRegistry).where(eq(serverRegistry.url, validated.data.url.toString()));
if (server.length === 0) {
debug("POST /discover/rotate/init server not found");
return NextResponse.json({ error: "Server not found, please register your server first." }, { status: 404 });
}
if (
server[0].publicKey === validated.data.newSigningPublicKey &&
server[0].encryptionPublicKey === validated.data.newEncryptionPublicKey
) {
debug("POST /discover/rotate/init keys are identical to current keys, rejecting");
return NextResponse.json({ error: "Your server is already registered with these keys." }, { status: 400 });
}
const [existing] = await db.select().from(rotateChallengeTokens)
.where(eq(rotateChallengeTokens.serverUrl, validated.data.url.toString()));
if (existing) {
if (existing.expiresAt > new Date()) {
debug("POST /discover/rotate/init active challenge already exists, rejecting");
return NextResponse.json(
{ error: "A rotation challenge is already pending for this server." },
{ status: 409 },
);
}
debug("POST /discover/rotate/init deleting expired challenge");
await db.delete(rotateChallengeTokens).where(eq(rotateChallengeTokens.id, existing.id));
}
const signingOldPlaintext = crypto.randomUUID();
const signingNewPlaintext = crypto.randomUUID();
const encryptionOldPlaintext = crypto.randomUUID();
const encryptionNewPlaintext = crypto.randomUUID();
debug("POST /discover/rotate/init issuing 4 challenges for server %s", validated.data.url);
const currentEncPubKey = new Uint8Array(Buffer.from(server[0].encryptionPublicKey, "base64"));
const newEncPubKey = new Uint8Array(Buffer.from(validated.data.newEncryptionPublicKey, "base64"));
const encryptionOldChallenge = encryptPayload(encryptionOldPlaintext, currentEncPubKey);
const encryptionNewChallenge = encryptPayload(encryptionNewPlaintext, newEncPubKey);
await db.insert(rotateChallengeTokens).values({
id: crypto.randomUUID(),
signingOldToken: signingOldPlaintext,
signingNewToken: signingNewPlaintext,
encryptionOldToken: encryptionOldPlaintext,
encryptionNewToken: encryptionNewPlaintext,
newSigningPublicKey: validated.data.newSigningPublicKey,
newEncryptionPublicKey: validated.data.newEncryptionPublicKey,
serverUrl: validated.data.url.toString(),
createdAt: new Date(),
expiresAt: new Date(Date.now() + 1000 * 60 * 5),
});
debug("POST /discover/rotate/init challenges issued, expires in 5 minutes");
const response = {
signingOldChallenge: signingOldPlaintext,
signingNewChallenge: signingNewPlaintext,
encryptionOldChallenge,
encryptionNewChallenge,
}
debug("POST /discover/rotate/init response: %o", response);
return NextResponse.json(response);
}

216
src/app/discover/route.ts Normal file
View file

@ -0,0 +1,216 @@
import db from "@/lib/db";
import { serverRegistry } from "@/lib/db/schema";
import { FederationError, federationFetch } from "@/lib/federation/fetch";
import { decryptPayload, fingerprintKey } from "@/lib/federation/keytools";
import { upsertServer } from "@/lib/federation/registry";
import { assertSafeUrl, UrlGuardError } from "@/lib/federation/url-guard";
import createDebug from "debug";
import { desc, eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const debug = createDebug("app:discover");
const ED25519_PUBLIC_KEY_BYTES = 32;
const X25519_PUBLIC_KEY_BYTES = 32;
function isValidBase64Key(key: string, expectedBytes: number): boolean {
try {
const decoded = Buffer.from(key, "base64");
return decoded.length === expectedBytes;
} catch {
return false;
}
}
const signingKeySchema = z.string().refine(
(key) => isValidBase64Key(key, ED25519_PUBLIC_KEY_BYTES),
{ message: `Signing public key must be a base64-encoded Ed25519 key (${ED25519_PUBLIC_KEY_BYTES} bytes)` },
);
const encryptionKeySchema = z.string().refine(
(key) => isValidBase64Key(key, X25519_PUBLIC_KEY_BYTES),
{ message: `Encryption public key must be a base64-encoded X25519 key (${X25519_PUBLIC_KEY_BYTES} bytes)` },
);
function getOwnEncryptionSecretKey(): Uint8Array {
return new Uint8Array(Buffer.from(process.env.FEDERATION_ENCRYPTION_PRIVATE_KEY!, "base64"));
}
const discoverSchema = z.object({
method: z.literal("DISCOVER"),
publicKey: signingKeySchema,
encryptionPublicKey: encryptionKeySchema,
envelope: z.object({
ephemeralPublicKey: z.string(),
iv: z.string(),
ciphertext: z.string(),
authTag: z.string(),
}),
}).superRefine((data, ctx) => {
try {
const decrypted = decryptPayload(data.envelope, getOwnEncryptionSecretKey());
const parsed = JSON.parse(decrypted);
if (parsed.publicKeyFingerprint !== fingerprintKey(data.publicKey)) {
ctx.addIssue({ code: "custom", message: "Envelope does not match the provided signing public key" });
}
if (parsed.encryptionPublicKeyFingerprint !== fingerprintKey(data.encryptionPublicKey)) {
ctx.addIssue({ code: "custom", message: "Envelope does not match the provided encryption public key" });
}
if (!parsed.url) {
ctx.addIssue({ code: "custom", message: "Envelope is missing the url field" });
}
} catch {
ctx.addIssue({ code: "custom", message: "Invalid envelope" });
}
});
const registerSchema = z.object({
method: z.literal("REGISTER"),
url: z.url(),
publicKey: signingKeySchema,
encryptionPublicKey: encryptionKeySchema,
});
export async function GET() {
debug("GET /discover fetching healthy peers");
const peers = await db.select({
url: serverRegistry.url,
isHealthy: serverRegistry.isHealthy,
}).from(serverRegistry).where(eq(serverRegistry.isHealthy, true)).orderBy(desc(serverRegistry.lastSeen));
debug("GET /discover found %d peer(s)", peers.length);
return NextResponse.json({
url: process.env.BETTER_AUTH_URL!,
publicKey: process.env.FEDERATION_PUBLIC_KEY,
encryptionPublicKey: process.env.FEDERATION_ENCRYPTION_PUBLIC_KEY,
peers,
});
}
async function discoverServer(validated: z.infer<typeof discoverSchema>) {
debug("DISCOVER looking up server by public key");
const server = await db.select().from(serverRegistry).where(eq(serverRegistry.publicKey, validated.publicKey));
if (server.length === 0) {
debug("DISCOVER server not found");
return NextResponse.json({ error: "Server not found" }, { status: 404 });
}
try {
assertSafeUrl(server[0].url);
} catch (err) {
debug("DISCOVER stored URL failed SSRF check: %s", server[0].url);
if (err instanceof UrlGuardError) {
return NextResponse.json({ error: "Stored server URL is blocked" }, { status: 400 });
}
throw err;
}
const confirmations = {
sameKeyOnServer: false,
sameKeyOnFetch: false,
}
if (server[0].publicKey === validated.publicKey) confirmations.sameKeyOnServer = true;
debug("DISCOVER fetching public key from federation server %s", server[0].url);
try {
const { response } = await federationFetch(server[0].url + "/discover", {
serverUrl: server[0].url,
});
const federationResponse = await response.json();
if (federationResponse.publicKey === validated.publicKey) confirmations.sameKeyOnFetch = true;
} catch (err) {
debug("DISCOVER fetch to %s failed: %o", server[0].url, err);
if (err instanceof FederationError) {
return NextResponse.json({ error: "Failed to reach the federation server", code: err.code }, { status: 502 });
}
return NextResponse.json({ error: "Failed to reach the federation server" }, { status: 502 });
}
debug("DISCOVER confirmations: %o", confirmations);
return NextResponse.json(confirmations);
}
async function registerServer(validated: z.infer<typeof registerSchema>) {
try {
await assertSafeUrl(validated.url);
} catch (err) {
debug("REGISTER URL failed SSRF check: %s", validated.url);
if (err instanceof UrlGuardError) {
return NextResponse.json({ error: err.message }, { status: 400 });
}
throw err;
}
debug("REGISTER fetching /discover from %s to validate server", validated.url);
let remoteKeys: { publicKey?: string; encryptionPublicKey?: string };
try {
const { response } = await federationFetch(validated.url + "/discover", {
serverUrl: validated.url,
});
remoteKeys = await response.json();
} catch (err) {
debug("REGISTER fetch to %s failed: %o", validated.url, err);
if (err instanceof FederationError) {
return NextResponse.json({ error: "Failed to reach the server", code: err.code }, { status: 502 });
}
return NextResponse.json({ error: "Failed to reach the server" }, { status: 502 });
}
if (!remoteKeys.publicKey || !remoteKeys.encryptionPublicKey) {
debug("REGISTER remote server returned incomplete keys");
return NextResponse.json({ error: "Invalid server" }, { status: 400 });
} else if (remoteKeys.publicKey !== validated.publicKey || remoteKeys.encryptionPublicKey !== validated.encryptionPublicKey) {
debug("REGISTER key mismatch: provided vs fetched");
return NextResponse.json({ error: "Public keys do not match the ones reported by the server" }, { status: 400 });
}
debug("REGISTER checking for existing registration at %s", validated.url);
const server = await db.select().from(serverRegistry).where(eq(serverRegistry.url, validated.url.toString()));
if (server.length > 0 && server[0].publicKey !== validated.publicKey) {
debug("REGISTER key mismatch against existing registration");
return NextResponse.json({ error: "Your public key does not match the one registered on the server, to update your public key, please use the key rotation flow instead." }, { status: 400 });
}
debug("REGISTER upserting server %s", validated.url);
await upsertServer(validated.url.toString(), validated.publicKey, validated.encryptionPublicKey);
debug("REGISTER server registered successfully");
return NextResponse.json({
message: "Server registered successfully", echo: {
url: process.env.BETTER_AUTH_URL!,
publicKey: process.env.FEDERATION_PUBLIC_KEY,
encryptionPublicKey: process.env.FEDERATION_ENCRYPTION_PUBLIC_KEY,
}
});
}
export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_JSON" }, { status: 400 });
}
debug("POST /discover method: %s", (body as { method?: string })?.method);
if (typeof body === "object" && body !== null && (body as { method?: string }).method === "DISCOVER") {
const validated = discoverSchema.safeParse(body);
if (!validated.success) {
debug("POST /discover DISCOVER validation failed: %o", validated.error.message);
return NextResponse.json({ error: validated.error.message }, { status: 400 });
}
return await discoverServer(validated.data);
}
if (typeof body === "object" && body !== null && (body as { method?: string }).method === "REGISTER") {
const validated = registerSchema.safeParse(body);
if (!validated.success) {
debug("POST /discover REGISTER validation failed: %o", validated.error.message);
return NextResponse.json({ error: validated.error.message }, { status: 400 });
}
return await registerServer(validated.data);
}
return NextResponse.json({ error: "Invalid method" }, { status: 400 });
}

View file

@ -1,165 +1,221 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
/* SiPher brand palette — Silent Whisper */
:root {
--background: oklch(0.1467 0.0041 49.3141);
--foreground: oklch(0.8848 0.0037 56.3763);
--card: oklch(0.1588 0.0050 48.3894);
--card-foreground: oklch(0.8848 0.0037 56.3763);
--popover: oklch(0.1588 0.0050 48.3894);
--popover-foreground: oklch(0.8848 0.0037 56.3763);
--primary: oklch(0.7065 0.1860 48.1293);
--primary-foreground: oklch(0.9620 0.0012 56.4186);
--secondary: oklch(0.2698 0.0089 52.1501);
--secondary-foreground: oklch(0.8848 0.0037 56.3763);
--muted: oklch(0.2698 0.0089 52.1501);
--muted-foreground: oklch(0.7250 0.0092 56.2587);
--accent: oklch(0.2698 0.0089 52.1501);
--accent-foreground: oklch(0.8848 0.0037 56.3763);
--destructive: oklch(0.5714 0.2121 27.2502);
--destructive-foreground: oklch(0.9620 0.0012 56.4186);
--border: oklch(0.2371 0.0107 48.2489);
--input: oklch(0.2371 0.0107 48.2489);
--ring: oklch(0.7065 0.1860 48.1293);
--chart-1: oklch(0.7065 0.1860 48.1293);
--chart-2: oklch(0.6356 0.1398 156.1492);
--chart-3: oklch(0.6296 0.1443 251.2286);
--chart-4: oklch(0.6665 0.1797 327.3573);
--chart-5: oklch(0.9204 0.1621 109.2030);
--sidebar: oklch(0.1154 0.0031 50.5978);
--sidebar-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-primary: oklch(0.7065 0.1860 48.1293);
--sidebar-primary-foreground: oklch(0.9620 0.0012 56.4186);
--sidebar-accent: oklch(0.1931 0.0052 52.2293);
--sidebar-accent-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-border: oklch(0.2151 0.0091 48.2763);
--sidebar-ring: oklch(0.7065 0.1860 48.1293);
--font-sans: "Inter", sans-serif;
--font-serif: "Lora", serif;
--font-mono: "Fira Mono", monospace;
--radius: 0.5rem;
--shadow-x: 0px;
--shadow-y: 4px;
--shadow-blur: 10px;
--shadow-spread: -2px;
--shadow-opacity: 0.3;
--shadow-color: hsl(20, 14.3%, 2%);
--shadow-2xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-sm: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-md: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 2px 4px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-lg: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 4px 6px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 8px 10px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-2xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.75);
--tracking-normal: 0em;
--spacing: 0.25rem;
/* Brand tokens */
--black: #080808;
--surface: #0f0f0f;
--card: #141414;
--border: #1f1f1f;
--muted: #2a2a2a;
--dim: #555;
--text: #e8e8e8;
--subtle: #888;
--acid: #c8f000;
--static: #ff3c3c;
--ghost: #9b9b9b;
--void: #080808;
--signal: #00e5ff;
/* Light mode — minimal variant for system preference */
--background: #f5f5f5;
--foreground: #0a0a0a;
--card: #ffffff;
--card-foreground: #0a0a0a;
--popover: #ffffff;
--popover-foreground: #0a0a0a;
--primary: #8a9a00;
--primary-foreground: #080808;
--secondary: #e8e8e8;
--secondary-foreground: #0a0a0a;
--muted: #e5e5e5;
--muted-foreground: #555;
--accent: #c8f000;
--accent-foreground: #080808;
--destructive: #ff3c3c;
--destructive-foreground: #ffffff;
--border: #e5e5e5;
--input: #e5e5e5;
--ring: #8a9a00;
--chart-1: #8a9a00;
--chart-2: #c8f000;
--chart-3: #00e5ff;
--chart-4: #9b9b9b;
--chart-5: #555;
--sidebar: #fafafa;
--sidebar-foreground: #0a0a0a;
--sidebar-primary: #8a9a00;
--sidebar-primary-foreground: #080808;
--sidebar-accent: #e5e5e5;
--sidebar-accent-foreground: #0a0a0a;
--sidebar-border: #e5e5e5;
--sidebar-ring: #8a9a00;
--font-sans: "DM Sans", sans-serif;
--font-mono: "Space Mono", monospace;
--font-display: "Bebas Neue", sans-serif;
--radius: 0.2rem;
--tracking-normal: -0.01em;
--spacing: 0.25rem;
--shadow-2xs: 0px 2px 4px 0px rgb(0 0 0 / 0.04);
--shadow-xs: 0px 2px 4px 0px rgb(0 0 0 / 0.04);
--shadow-sm:
0px 2px 8px 0px rgb(0 0 0 / 0.06), 0px 1px 2px -1px rgb(0 0 0 / 0.06);
--shadow:
0px 2px 8px 0px rgb(0 0 0 / 0.08), 0px 1px 2px -1px rgb(0 0 0 / 0.08);
--shadow-md:
0px 2px 8px 0px rgb(0 0 0 / 0.08), 0px 2px 4px -1px rgb(0 0 0 / 0.08);
--shadow-lg:
0px 2px 8px 0px rgb(0 0 0 / 0.08), 0px 4px 6px -1px rgb(0 0 0 / 0.08);
--shadow-xl:
0px 2px 8px 0px rgb(0 0 0 / 0.08), 0px 8px 10px -1px rgb(0 0 0 / 0.08);
--shadow-2xl: 0px 2px 8px 0px rgb(0 0 0 / 0.15);
}
.dark {
--background: oklch(0.1467 0.0041 49.3141);
--foreground: oklch(0.8848 0.0037 56.3763);
--card: oklch(0.1588 0.0050 48.3894);
--card-foreground: oklch(0.8848 0.0037 56.3763);
--popover: oklch(0.1588 0.0050 48.3894);
--popover-foreground: oklch(0.8848 0.0037 56.3763);
--primary: oklch(0.7065 0.1860 48.1293);
--primary-foreground: oklch(0.9620 0.0012 56.4186);
--secondary: oklch(0.2698 0.0089 52.1501);
--secondary-foreground: oklch(0.8848 0.0037 56.3763);
--muted: oklch(0.2698 0.0089 52.1501);
--muted-foreground: oklch(0.7250 0.0092 56.2587);
--accent: oklch(0.2698 0.0089 52.1501);
--accent-foreground: oklch(0.8848 0.0037 56.3763);
--destructive: oklch(0.5714 0.2121 27.2502);
--destructive-foreground: oklch(0.9620 0.0012 56.4186);
--border: oklch(0.2371 0.0107 48.2489);
--input: oklch(0.2371 0.0107 48.2489);
--ring: oklch(0.7065 0.1860 48.1293);
--chart-1: oklch(0.7065 0.1860 48.1293);
--chart-2: oklch(0.6356 0.1398 156.1492);
--chart-3: oklch(0.6296 0.1443 251.2286);
--chart-4: oklch(0.6665 0.1797 327.3573);
--chart-5: oklch(0.9204 0.1621 109.2030);
--sidebar: oklch(0.1154 0.0031 50.5978);
--sidebar-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-primary: oklch(0.7065 0.1860 48.1293);
--sidebar-primary-foreground: oklch(0.9620 0.0012 56.4186);
--sidebar-accent: oklch(0.1931 0.0052 52.2293);
--sidebar-accent-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-border: oklch(0.2151 0.0091 48.2763);
--sidebar-ring: oklch(0.7065 0.1860 48.1293);
--font-sans: "Inter", sans-serif;
--font-serif: "Lora", serif;
--font-mono: "Fira Mono", monospace;
--radius: 0.5rem;
--shadow-x: 0px;
--shadow-y: 4px;
--shadow-blur: 10px;
--shadow-spread: -2px;
--shadow-opacity: 0.3;
--shadow-color: hsl(20, 14.3%, 2%);
--shadow-2xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-sm: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-md: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 2px 4px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-lg: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 4px 6px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 8px 10px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-2xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.75);
/* SiPher dark theme — primary brand identity */
--background: var(--black);
--foreground: var(--text);
--card: #141414;
--card-foreground: var(--text);
--popover: var(--surface);
--popover-foreground: var(--text);
--primary: var(--acid);
--primary-foreground: var(--void);
--secondary: var(--muted);
--secondary-foreground: var(--text);
--muted: var(--muted);
--muted-foreground: var(--subtle);
--accent: var(--acid);
--accent-foreground: var(--void);
--destructive: var(--static);
--destructive-foreground: #ffffff;
--border: var(--border);
--input: var(--border);
--ring: var(--acid);
--chart-1: var(--acid);
--chart-2: var(--signal);
--chart-3: var(--static);
--chart-4: var(--ghost);
--chart-5: var(--subtle);
--sidebar: var(--surface);
--sidebar-foreground: var(--text);
--sidebar-primary: var(--acid);
--sidebar-primary-foreground: var(--void);
--sidebar-accent: var(--muted);
--sidebar-accent-foreground: var(--acid);
--sidebar-border: var(--border);
--sidebar-ring: var(--acid);
--shadow-2xs: 0px 4px 12px 0px rgb(0 0 0 / 0.25);
--shadow-xs: 0px 4px 12px 0px rgb(0 0 0 / 0.25);
--shadow-sm:
0px 4px 12px 0px rgb(0 0 0 / 0.35), 0px 1px 2px -1px rgb(0 0 0 / 0.35);
--shadow:
0px 4px 12px 0px rgb(0 0 0 / 0.4), 0px 1px 2px -1px rgb(0 0 0 / 0.4);
--shadow-md:
0px 4px 12px 0px rgb(0 0 0 / 0.4), 0px 2px 4px -1px rgb(0 0 0 / 0.4);
--shadow-lg:
0px 4px 12px 0px rgb(0 0 0 / 0.4), 0px 4px 6px -1px rgb(0 0 0 / 0.4);
--shadow-xl:
0px 4px 12px 0px rgb(0 0 0 / 0.4), 0px 8px 10px -1px rgb(0 0 0 / 0.4);
--shadow-2xl: 0px 4px 12px 0px rgb(0 0 0 / 0.6);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--font-sans: var(--font-sans);
--font-mono: var(--font-mono);
--font-serif: var(--font-serif);
/* Brand palette — use as bg-acid, text-signal, etc. */
--color-acid: var(--acid);
--color-static: var(--static);
--color-ghost: var(--ghost);
--color-void: var(--void);
--color-signal: var(--signal);
--color-surface: var(--surface);
--color-dim: var(--dim);
--color-subtle: var(--subtle);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--font-sans: var(--font-sans);
--font-mono: var(--font-mono);
--font-display: var(--font-display);
--shadow-2xs: var(--shadow-2xs);
--shadow-xs: var(--shadow-xs);
--shadow-sm: var(--shadow-sm);
--shadow: var(--shadow);
--shadow-md: var(--shadow-md);
--shadow-lg: var(--shadow-lg);
--shadow-xl: var(--shadow-xl);
--shadow-2xl: var(--shadow-2xl);
}
--radius-sm: calc(var(--radius) - 2px);
--radius-md: var(--radius);
--radius-lg: calc(var(--radius) + 2px);
--radius-xl: calc(var(--radius) + 4px);
--shadow-2xs: var(--shadow-2xs);
--shadow-xs: var(--shadow-xs);
--shadow-sm: var(--shadow-sm);
--shadow: var(--shadow);
--shadow-md: var(--shadow-md);
--shadow-lg: var(--shadow-lg);
--shadow-xl: var(--shadow-xl);
--shadow-2xl: var(--shadow-2xl);
--tracking-tighter: calc(var(--tracking-normal) - 0.05em);
--tracking-tight: calc(var(--tracking-normal) - 0.025em);
--tracking-normal: var(--tracking-normal);
--tracking-wide: calc(var(--tracking-normal) + 0.025em);
--tracking-wider: calc(var(--tracking-normal) + 0.05em);
--tracking-widest: calc(var(--tracking-normal) + 0.1em);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground font-sans antialiased;
letter-spacing: var(--tracking-normal);
}
/* Section labels — Space Mono, uppercase, letter-spacing */
.section-label {
@apply font-mono text-[10px] text-muted-foreground uppercase tracking-[0.2em];
}
/* Display typography — Bebas Neue for headings */
.font-display {
font-family: var(--font-display), sans-serif;
letter-spacing: 0.04em;
}
}

View file

@ -1,60 +1,60 @@
import { AutoRequestNotifications } from "@/components/notifications/NotificationSettings";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
import { getToken } from "@/lib/auth/auth-server";
import { ConvexClientProvider } from "@/lib/providers/Convex";
import UnlockIdentityModal from "@/components/main/UnlockIdentityModal";
import { TooltipProvider } from "@/components/ui/tooltip";
import type { Metadata } from "next";
import { ThemeProvider } from "next-themes";
import { Bebas_Neue, DM_Sans, Space_Mono } from "next/font/google";
import { Toaster } from "sonner";
import "./globals.css";
const fontSans = DM_Sans({
subsets: ["latin"],
weight: ["300", "400", "500"],
variable: "--font-sans",
});
const fontMono = Space_Mono({
subsets: ["latin"],
weight: ["400", "700"],
style: ["normal", "italic"],
variable: "--font-mono",
});
const fontDisplay = Bebas_Neue({
subsets: ["latin"],
weight: "400",
variable: "--font-display",
});
export const metadata: Metadata = {
title: "SiPher - Don't trust us. We don't trust you.",
description: "SiPher is a platform made for communication. Secure? Maybe. Reliable? I don't think so. We don't trust you. We don't trust us. We don't trust anyone.",
title: "Sipher",
description: "A federated social media platform for the modern age.",
icons: {
icon: [
{
url: "/assets/logo/logo-white.svg",
href: "/assets/logo/logo-white.svg",
media: "(prefers-color-scheme: dark)",
type: "image/svg+xml",
sizes: "32x32",
rel: "icon"
},
{
url: "/assets/logo/logo-dark.svg",
href: "/assets/logo/logo-dark.svg",
media: "(prefers-color-scheme: light)",
type: "image/svg+xml",
sizes: "32x32",
rel: "icon"
}
]
}
icon: "/logo/sipher.svg",
},
manifest: "/manifest.json"
};
export default async function RootLayout({
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const token = await getToken();
return (
<html lang="en" suppressHydrationWarning>
<body
className="antialiased min-h-screen bg-background"
>
<ConvexClientProvider initialToken={token ?? null}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<html suppressHydrationWarning>
<body className={`${fontSans.variable} ${fontMono.variable} ${fontDisplay.variable} antialiased`}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
<TooltipProvider>
<Toaster />
<UnlockIdentityModal />
{children}
<AutoRequestNotifications />
</ThemeProvider>
<Toaster richColors />
</ConvexClientProvider>
</TooltipProvider>
</ThemeProvider>
</body>
</html>
);
}
}

25
src/app/manifest.ts Normal file
View file

@ -0,0 +1,25 @@
import type { MetadataRoute } from 'next'
export default function manifest(): MetadataRoute.Manifest {
return {
name: 'Silent Whisper',
short_name: 'SiPher',
description: 'A federated social media platform for the modern age.',
start_url: '/',
display: 'standalone',
background_color: '#080808',
theme_color: '#080808',
icons: [
{
src: '/logo/sipher.svg',
sizes: '192x192',
type: 'image/svg+xml',
},
{
src: '/logo/sipher.svg',
sizes: '512x512',
type: 'image/svg+xml',
},
],
}
}

31
src/app/page.tsx Normal file
View file

@ -0,0 +1,31 @@
"use server";
import CreateIdentity from "@/components/main/CreateIdentity";
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { PostTestForm } from "./PostTestForm";
export default async function Home() {
const reqHeaders = await headers();
const session = await auth.api.getSession({ headers: reqHeaders });
if (!session) redirect(`/auth`);
// Server components can't talk to the browser-side `authClient`, so we hit
// the plugin endpoint via `auth.api`. This only tells us whether the
// identity is registered remotely; the local Dexie half is verified inside
// `CreateIdentity` (client component) when needed.
const result = await auth.api.checkIdentity({ headers: reqHeaders });
const hasIdentity = "exists" in result && result.exists;
if (!hasIdentity) {
console.debug(`[Home] user ${session.user.id} has no identity, showing create identity modal`);
return <CreateIdentity />;
}
return (
<>
<PostTestForm />
</>
);
}

495
src/app/proxy/route.ts Normal file
View file

@ -0,0 +1,495 @@
import db from "@/lib/db";
import { blacklistedServers, blocks, follows, serverRegistry, user } from "@/lib/db/schema";
import { FederationError, federationFetch } from "@/lib/federation/fetch";
import { decryptPayload, encryptPayload, getOwnEncryptionSecretKey, getOwnSigningSecretKey, signMessage, verifySignature } from "@/lib/federation/keytools";
import { peerRegistryUrlOrNull } from "@/lib/federation/peer-registry-url";
import { applyFederatedPostInTransaction } from "@/lib/federation/proxy-helpers/federated-post";
import { discoverAndRegister } from "@/lib/federation/registry";
import { checkRateLimit } from "@/lib/rate-limit/rate-limit";
import { EncryptedEnvelopeBaseSchema } from "@/lib/zod/EncryptedEnvelope";
import { FollowEnvelopeSchema } from "@/lib/zod/methods/FollowSchema";
import { PostEnvelopeSchema } from "@/lib/zod/methods/PostFederationSchema";
import createDebug from "debug";
import { and, eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const debug = createDebug("app:api:federation:proxy");
// Proxy route: relays encrypted federation traffic when two servers can't reach each other directly
// (e.g. network restrictions, ISP blocking).
//
// Any federation node can act as a proxy as long as both the requesting and target federations
// have discovered and registered it (same mutual-trust model as the follow endpoint).
//
// What the proxy knows:
// - The target federation's base URL (passed in plaintext so the proxy can forward).
// - That Federation A is trying to communicate with Federation B.
//
// What the proxy does NOT know:
// - The contents of the request (method, path, payload, etc.) — all of that lives inside an
// encrypted envelope that only Federation B can decrypt.
//
// Flow:
// 1. Federation A encrypts the full request (method, path, payload) into an envelope using
// Federation B's encryption public key, and signs it with its own signing key.
// 2. Federation A sends the encrypted envelope + target URL to the proxy.
// 3. The proxy forwards the envelope to Federation B's proxy endpoint.
// 4. Federation B decrypts, validates the signature, and processes the request.
// 5. Federation B encrypts its response using Federation A's encryption public key.
// 6. The encrypted response travels back: Federation B -> Proxy -> Federation A.
//
// If the request is of PROXY type and the target fails, the proxy will return a 502 error in which the first server
// should then either retry the request later or proxy it to a different server.
// If the target does not know the sender, it'll error with a 403 error and a "UNKNOWN_FEDERATION_SERVER_INTERACTION" code.
const ProxiedDataSchema = z.discriminatedUnion("method", [
z.object({
method: z.literal("PROXY"),
targetUrl: z.url().refine((url) => {
// Check if the URL has the proxy path
const parsedUrl = new URL(url);
return parsedUrl.pathname.startsWith("/proxy");
}, { message: "The target URL must have the proxy path" }), // Federation B's base URL,
publicSigningKey: z.string().optional().nullable(), // Federation A's signing public key
publicEncryptionKey: z.string().optional().nullable(), // Federation A's encryption public key
payload: EncryptedEnvelopeBaseSchema // Opaque — proxy cannot decrypt
}),
z.object({
method: z.literal("TARGETED"),
payload: EncryptedEnvelopeBaseSchema // TODO: swap for createEncryptedEnvelopeSchema(TargetedPayloadSchema) once the inner schema is defined
})
])
type ERROR_CODE = "MISSING_FED_ORIGIN_HEADER" | "UNKNOWN_FEDERATION_SERVER_INTERACTION" | "INCORRECT_KEYS" | "INVALID_PROXY_DATA";
// TARGETED: This federation is the target of a proxy request
// PROXY: This federation is the proxy for another federation
type PROXY_METHOD = "TARGETED" | "PROXY" | "PROXY_RESPONSE";
type PostsActions = "GET_USER_POSTS" | "FEDERATE_POST" | "GET_POST_BY_ID" | "GET_POST_COMMENTS" | "FEDERATE_POST_COMMENT"
type UserActions = "FEDERATE_FOLLOW" | "FEDERATE_UNFOLLOW" | "GET_USER_PROFILE" | "BLOCK_USER" | "UNBLOCK_USER" | "GET_USER_FOLLOWERS" | "GET_USER_FOLLOWING"
type Actions = PostsActions | UserActions;
const PROXY_MAX_BODY_BYTES = 256 * 1024; // 256 KB
export async function POST(request: NextRequest) {
const contentLength = request.headers.get("content-length");
if (contentLength && parseInt(contentLength, 10) > PROXY_MAX_BODY_BYTES) {
debug("POST /proxy request body too large (%s bytes)", contentLength);
return NextResponse.json({ error: "Request body too large", code: "PAYLOAD_TOO_LARGE" }, { status: 413 });
}
const getFedUrl = request.headers.get("x-federation-origin");
if (!getFedUrl) {
debug("Missing x-federation-origin header from %s", request.url);
return NextResponse.json({ error: "Missing x-federation-origin header", code: "MISSING_FED_ORIGIN_HEADER" }, { status: 400 });
}
const proxyRateLimit = await checkRateLimit(`proxy:${getFedUrl}`, { limit: 100, windowSeconds: 60 });
if (!proxyRateLimit.allowed) {
debug("POST /proxy rate limited origin %s", getFedUrl);
return NextResponse.json(
{ error: "Too many proxy requests. Please try again later.", code: "RATE_LIMITED" },
{ status: 429, headers: { "Retry-After": String(proxyRateLimit.retryAfter) } },
);
}
const rawBody = await request.text();
if (rawBody.length > PROXY_MAX_BODY_BYTES) {
debug("POST /proxy request body too large (%d bytes)", rawBody.length);
return NextResponse.json({ error: "Request body too large", code: "PAYLOAD_TOO_LARGE" }, { status: 413 });
}
let data: unknown;
try {
data = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: "Invalid JSON", code: "INVALID_PROXY_DATA" }, { status: 400 });
}
const parsed = ProxiedDataSchema.safeParse(data);
if (!parsed.success) {
debug("POST /proxy error parsing proxied data from %s: %s", request.url, parsed.error.message);
return NextResponse.json({ error: "Invalid proxied data", code: "INVALID_PROXY_DATA" }, { status: 400 });
}
switch (parsed.data.method) {
case "PROXY": {
if (!parsed.data.publicSigningKey || !parsed.data.publicEncryptionKey) {
debug("POST /proxy error parsing proxied data from %s: %s", request.url, "Missing public signing or encryption key");
return NextResponse.json({ error: "Invalid proxied data", code: "INVALID_PROXY_DATA" }, { status: 400 });
}
const proxiedData = parsed.data;
// Verify Federation A (sender) is known and keys match
const [sender] = await db.select().from(serverRegistry).where(eq(serverRegistry.url, getFedUrl));
if (!sender) {
debug("POST /proxy sender not found in registry: %s", getFedUrl);
return NextResponse.json({
error: "Unknown federation server. Please redo the discovery process and try again.",
code: "UNKNOWN_FEDERATION_SERVER_INTERACTION",
}, { status: 403 });
} else if (sender.publicKey !== proxiedData.publicSigningKey) {
debug("POST /proxy sender signing key mismatch: %s", getFedUrl);
return NextResponse.json({
error: "The provided keys are a mismatch. If you rotated your keys, we are not aware of it.",
code: "INCORRECT_KEYS",
}, { status: 403 });
} else if (sender.encryptionPublicKey !== proxiedData.publicEncryptionKey) {
debug("POST /proxy sender encryption key mismatch: %s", getFedUrl);
return NextResponse.json({
error: "The provided keys are a mismatch. If you rotated your keys, we are not aware of it.",
code: "INCORRECT_KEYS",
}, { status: 403 });
}
// Verify Federation B (target) is known to us (prevents open-relay abuse)
const targetBaseUrl = new URL(proxiedData.targetUrl.toString()).origin;
const [target] = await db.select().from(serverRegistry).where(eq(serverRegistry.url, targetBaseUrl));
if (!target) {
debug("POST /proxy target not found in registry: %s", targetBaseUrl);
debug("POST /proxy - Starting discovery process")
await discoverAndRegister(targetBaseUrl);
}
// Proxy the request to Federation B as a TARGETED request (no proxy fallback — we ARE the proxy)
let forwardResponse: Response;
try {
const result = await federationFetch(proxiedData.targetUrl.toString(), {
method: "POST",
body: JSON.stringify({
method: "TARGETED" as PROXY_METHOD,
payload: proxiedData.payload,
}),
headers: {
"Content-Type": "application/json",
"X-Federation-Origin": process.env.BETTER_AUTH_URL!,
"Origin": process.env.BETTER_AUTH_URL!,
"X-Federation-Sender": getFedUrl,
},
serverUrl: targetBaseUrl,
proxyFallback: false,
skipHealthUpdate: true,
});
forwardResponse = result.response;
} catch (err) {
if (err instanceof FederationError) {
debug("POST /proxy federation error proxying to %s: %s", proxiedData.targetUrl.toString(), err.code);
return NextResponse.json({ error: "Failed to proxy request", code: "FAILED_TO_PROXY_REQUEST", federationError: err.code, method: "PROXY_RESPONSE" as PROXY_METHOD }, { status: 502 });
}
throw err;
}
if (!forwardResponse.ok) {
debug("POST /proxy error proxying request to %s: %s", proxiedData.targetUrl.toString(), forwardResponse.statusText);
let details: unknown;
try {
details = await forwardResponse.json();
} catch {
try {
details = await forwardResponse.text();
} catch {
details = undefined;
}
}
return NextResponse.json({ error: "Failed to proxy request", code: "FAILED_TO_PROXY_REQUEST", details, method: "PROXY_RESPONSE" as PROXY_METHOD }, { status: 502 });
}
let responseBody: unknown;
try {
responseBody = await forwardResponse.json();
} catch (err) {
debug("POST /proxy invalid JSON from target %s: %o", proxiedData.targetUrl.toString(), err);
return NextResponse.json({ error: "Failed to proxy request", code: "FAILED_TO_PROXY_REQUEST", details: "Target returned non-JSON body", method: "PROXY_RESPONSE" as PROXY_METHOD }, { status: 502 });
}
// Return the response from Federation B as a PROXY_RESPONSE
return NextResponse.json({
method: "PROXY_RESPONSE" as PROXY_METHOD,
payload: responseBody,
});
}
case "TARGETED": {
if (!parsed.data.payload) {
debug("POST /proxy error parsing targeted data from %s: %s", request.url, "Missing payload");
return NextResponse.json({ error: "Invalid targeted data", code: "INVALID_TARGETED_DATA" }, { status: 400 });
}
let decryptedPayload: string;
try {
decryptedPayload = decryptPayload(parsed.data.payload, getOwnEncryptionSecretKey());
} catch (decryptErr) {
debug("POST /proxy targeted envelope decrypt failed from %s: %o", request.url, decryptErr);
return NextResponse.json({
error: "Cannot decrypt targeted payload for this server.",
code: "DECRYPT_FAILED",
}, { status: 400 });
}
let parsedPayload: unknown;
try {
parsedPayload = JSON.parse(decryptedPayload);
} catch {
return NextResponse.json({ error: "Invalid targeted data", code: "INVALID_TARGETED_DATA" }, { status: 400 });
}
debug("POST /proxy parsed targeted data from %s: %o", request.url, parsedPayload);
// PING: lightweight connectivity / crypto-routing check.
// Still enforces the sender trust model — the sender must be registered.
if (
typeof parsedPayload === "object" &&
parsedPayload !== null &&
(parsedPayload as { method?: string }).method === "PING"
) {
const [pingSender] = await db.select({ url: serverRegistry.url })
.from(serverRegistry)
.where(eq(serverRegistry.url, getFedUrl))
.limit(1);
if (!pingSender) {
debug("POST /proxy PING from unregistered sender: %s", getFedUrl);
return NextResponse.json({
error: "Unknown federation server. Please redo the discovery process and try again.",
code: "UNKNOWN_FEDERATION_SERVER_INTERACTION",
}, { status: 403 });
}
const nonce = (parsedPayload as { nonce?: string }).nonce;
return NextResponse.json({ method: "PROXY_RESPONSE" as PROXY_METHOD, status: "pong", nonce }, { status: 200 });
}
const payloadSchema = z.object({
targetUrl: z.url(),
method: z.string(),
headers: z.record(z.string(), z.string()),
body: z.string().transform((body) => {
const parsedBody = JSON.parse(body);
return {
method: parsedBody.method,
payload: parsedBody.payload,
signature: parsedBody.signature,
};
})
}).superRefine((data, ctx) => {
try {
const originPayloadHeaders = data.headers;
debug("POST /proxy origin payload headers: %o", originPayloadHeaders);
if (!originPayloadHeaders["X-Federation-Target"] || !originPayloadHeaders["X-Federation-Origin"] || !originPayloadHeaders["Origin"]) {
ctx.addIssue({ code: "custom", message: "Missing headers" });
return z.NEVER;
}
// Should be the base URL of the target URL
const targetUrl = new URL(data.targetUrl).origin;
const federationTargetOriginHeader = new URL(originPayloadHeaders["X-Federation-Target"]).origin;
debug("POST /proxy target URL: %s", targetUrl);
debug("POST /proxy x-federation-target header: %s", federationTargetOriginHeader);
if (federationTargetOriginHeader !== targetUrl) {
ctx.addIssue({ code: "custom", message: "x-federation-target header mismatch" });
return z.NEVER;
}
} catch (error) {
ctx.addIssue({ code: "custom", message: "Decryption failed" });
return z.NEVER;
}
});
const validated = payloadSchema.safeParse(parsedPayload);
if (!validated.success) {
debug("POST /proxy error validating targeted data from %s: %s", request.url, validated.error.message);
return NextResponse.json({ error: "Invalid targeted data", code: "INVALID_TARGETED_DATA" }, { status: 400 });
}
const { targetUrl, method, headers, body } = validated.data;
// Check if the sender is known, keys match and is not blackisted
const result = await db.transaction(async (tx) => {
const senderUrl = headers["X-Federation-Origin"];
// Check if the sender is blacklisted
const [blacklisted] = await tx.select().from(blacklistedServers).where(eq(blacklistedServers.serverUrl, senderUrl));
if (blacklisted) {
debug("POST /proxy sender is blacklisted: %s", senderUrl);
return { error: "The federation server was blacklisted from interacting with this federation server. Please contact support to unblacklist your server.", code: "BLACKLISTED_FEDERATION_SERVER", action: undefined, status: 403 };
}
// Check if the sender is known
const [sender] = await tx.select().from(serverRegistry).where(eq(serverRegistry.url, senderUrl));
if (!sender) {
debug("POST /proxy sender not found in registry: %s", senderUrl);
return { error: "Unknown federation server. Please redo the discovery process and try again.", code: "UNKNOWN_FEDERATION_SERVER_INTERACTION", action: undefined, status: 403 };
}
let consolidatedFollowPayload: z.infer<typeof FollowEnvelopeSchema> | null = null;
let consolidatedPostPayload: z.infer<typeof PostEnvelopeSchema> | null = null;
let action: Actions;
switch (true) {
case targetUrl.includes("/api/auth/social/follows") && body.method === "FEDERATE": {
debug("POST /proxy parsing follow payload: %s", body.payload);
const payload = FollowEnvelopeSchema.safeParse(body.payload);
if (!payload.success) {
debug("POST /proxy error parsing follow payload: %s", body.payload);
return { error: "Invalid follow payload", code: "INVALID_FOLLOW_PAYLOAD", action: undefined, status: 400 };
}
consolidatedFollowPayload = payload.data;
action = "FEDERATE_FOLLOW";
break;
}
case targetUrl.includes("/api/auth/social/posts") && body.method === "FEDERATE_POST": {
debug("POST /proxy parsing federated post payload");
const payload = PostEnvelopeSchema.safeParse(body.payload);
if (!payload.success) {
debug("POST /proxy error parsing federated post payload: %s", payload.error.message);
return { error: "Invalid federated post payload", code: "INVALID_FEDERATED_POST_PAYLOAD", action: undefined, status: 400 };
}
consolidatedPostPayload = payload.data;
action = "FEDERATE_POST";
break;
}
default: {
debug("POST /proxy no endpoint specific parsing, rejecting request");
return { error: "Invalid payload", code: "INVALID_PAYLOAD", action: undefined, status: 400 };
}
}
const signedEnvelope = consolidatedFollowPayload ?? consolidatedPostPayload;
if (!signedEnvelope) {
return { error: "Invalid payload", code: "INVALID_PAYLOAD", action: undefined, status: 400 };
}
// Check if the signature is valid
const senderPublicKey = new Uint8Array(Buffer.from(sender.publicKey, "base64"));
const senderEncryptionPublicKey = new Uint8Array(Buffer.from(sender.encryptionPublicKey, "base64"));
if (!verifySignature(signedEnvelope._raw, body.signature, senderPublicKey)) {
debug("POST /proxy sender signature is invalid: %s", targetUrl);
return { error: "The provided signature is invalid. Please redo the discovery process and try again.", code: "INVALID_SIGNATURE", action: undefined, status: 403 };
}
debug("POST /proxy sender is known, keys match and is not blackisted: %s", targetUrl);
// Now we can assume that:
// - The sender is known to us
// - The sender is not blacklisted
// - The signature is valid with what we have in the payload
// - The payload is a valid action and has a valid payload
// - There is a known endpoint for the action
// Now the only thing left is to handle the action. This cannot be done in a worker since we need to return a response to the proxy server. This could eventually overload this endpoint and cause issues, but it's not something I can fix right now.
switch (action) {
case "FEDERATE_FOLLOW": {
const followEnv = consolidatedFollowPayload!;
debug("POST /proxy federating follow: %s", followEnv);
// We can do the follow procedure
// First check if the user exists
const [targetUser] = await tx.select().from(user).where(eq(user.id, followEnv.following.followingId));
if (!targetUser) {
debug("POST /proxy target user not found: %s", followEnv.following.followingId);
return { error: "The user you are trying to follow does not exist.", code: "USER_NOT_FOUND", status: 404 };
}
// Second check if the follow already exists
const [existingFollow] = await tx.select().from(follows).where(and(
eq(follows.followerId, followEnv.following.followerId),
eq(follows.followingId, followEnv.following.followingId),
));
if (existingFollow) {
debug("POST /proxy follow already exists: %s", existingFollow.id);
return { error: "You are already following this user.", code: "FOLLOW_ALREADY_EXISTS", status: 409 };
}
// Reject if the target user has blocked the remote follower.
const [followBlock] = await tx.select({ id: blocks.id }).from(blocks).where(and(
eq(blocks.blockerId, followEnv.following.followingId),
eq(blocks.blockedUserId, followEnv.following.followerId),
)).limit(1);
if (followBlock) {
debug("POST /proxy target user has blocked the follower");
return { error: "Unable to follow this user.", code: "USER_BLOCKED", status: 403 };
}
// Third check if the user is private
const isPrivate = !targetUser.isPrivate;
const following = await tx.insert(follows).values({
id: crypto.randomUUID(),
followerId: followEnv.following.followerId,
followingId: followEnv.following.followingId,
accepted: isPrivate,
createdAt: new Date(),
followerServerUrl: peerRegistryUrlOrNull(senderUrl),
followingServerUrl: peerRegistryUrlOrNull(targetUrl),
acknowledged: true,
}).returning();
const row = following[0];
// Same plaintext shape as the delivery job payload / FollowInnerPayloadSchema (see federation worker).
const innerPayload = JSON.stringify({
following: {
id: row.id,
createdAt: row.createdAt,
followerId: row.followerId,
followingId: row.followingId,
accepted: row.accepted,
followerServerUrl: row.followerServerUrl,
acknowledged: row.acknowledged
},
federationUrl: senderUrl,
method: "FEDERATE" as const,
});
const signature = signMessage(innerPayload, getOwnSigningSecretKey());
return { innerPayload, signature, senderEncryptionPublicKey };
}
case "FEDERATE_POST": {
const postEnv = consolidatedPostPayload!;
const postResult = await applyFederatedPostInTransaction(tx, postEnv, body.signature, {
publicKey: sender.publicKey,
encryptionPublicKey: sender.encryptionPublicKey,
url: sender.url,
});
if (!postResult.ok) {
return {
error: postResult.error,
code: postResult.code,
action: undefined,
status: postResult.status,
};
}
const encKey = new Uint8Array(Buffer.from(postResult.senderEncryptionPublicKeyB64, "base64"));
return {
innerPayload: postResult.innerPayload,
signature: postResult.signature,
senderEncryptionPublicKey: encKey,
};
}
default: {
debug("POST /proxy no action specific handling, rejecting request");
return { error: "Invalid action", code: "INVALID_ACTION", action: undefined, status: 400 };
}
}
});
if (result.error) {
return NextResponse.json({ error: result.error, code: result.code, action: result.action, status: result.status }, { status: result.status });
}
return NextResponse.json({
method: "PROXY_RESPONSE" as PROXY_METHOD,
status: "acknowledged",
data: encryptPayload(result.innerPayload!, result.senderEncryptionPublicKey!),
signature: result.signature,
}, { status: 200 });
}
}
}

View file

@ -1,190 +0,0 @@
"use client"
import AppSidebar from "@/components/home";
import OlmSetupDialog from "@/components/olm/olm-setup-dialog";
import { MainContentLayout } from "@/components/ui/layout";
import { Spinner } from "@/components/ui/spinner";
import UserFloatingCard from "@/components/ui/user/floating-card";
import { OlmProvider, useOlmContext } from "@/contexts/olm-context";
import { SocketProvider, useSocketContext } from "@/contexts/socket-context";
import { authClient } from "@/lib/auth/client";
import { getRandomPhrase, type PhrasePreference } from "@/lib/constants/phrases";
import { useMutation, useQuery } from "convex/react";
import { redirect, useParams, usePathname } from "next/navigation";
import { useCallback, useEffect, useMemo } from "react";
import { api } from "../../convex/_generated/api";
import OlmPasswordDialog from "./olm/olm-password-dialog";
type RouteParams = Record<string, string | string[] | undefined>;
type RouteMatcher = {
path?: string;
pattern?: RegExp;
type: SiPher.PageTypes;
extract?: (match: RegExpMatchArray, params: RouteParams) => Partial<SiPher.RouteInfo>;
};
const routes: RouteMatcher[] = [
{ path: '/channels/me/friends', type: 'friends' },
{ path: '/discover', type: 'discover' },
{ path: '/support', type: 'support' },
{ path: '/channels/nests/global', type: 'global-nests' },
{
pattern: /^\/channels\/me\/(.+)$/,
type: 'dm',
extract: (_, params) => ({
dmChannelId: params.id ? decodeURIComponent(params.id as string) : undefined
})
},
{
pattern: /^\/channels\/servers\/(.+)$/,
type: 'server',
extract: (_, params) => ({
serverId: params.serverId ? decodeURIComponent(params.serverId as string) : undefined,
serverChannelId: params.channelId ? decodeURIComponent(params.channelId as string) : undefined
})
},
];
function AppContainerContent() {
const pathname = usePathname();
const params = useParams();
const routeInfo: SiPher.RouteInfo = useMemo(() => {
for (const route of routes) {
if (route.path && pathname === route.path) {
return { type: route.type };
}
if (route.pattern) {
const match = pathname.match(route.pattern);
if (match) {
return {
type: route.type,
...route.extract?.(match, params)
};
}
}
}
return { type: 'friends' };
}, [pathname, params]);
const { data } = authClient.useSession();
// Use socket context instead of hook
const { socketStatus, socketInfo, disconnect, connect } = useSocketContext();
// Use OLM context
const { olmStatus, showOlmModal, setShowOlmModal, handleCreateAccount } = useOlmContext();
const updateUserMetadata = useMutation(api.auth.updateUserMetadata);
const userNests = useQuery(api.auth.getUserNests);
useEffect(() => {
if (!data) return;
const metadata = data.user.metadata
if (!metadata) {
console.debug("[AppContainer] > User metadata set", data.user.metadata)
updateUserMetadata({ metadata: { phrasePreference: "comforting" } });
}
}, [data, updateUserMetadata]);
const getPhrase = useCallback(() => {
const preference = data?.user?.metadata?.phrasePreference as PhrasePreference | undefined;
return getRandomPhrase(preference);
}, [data?.user?.metadata?.phrasePreference]);
if (["connecting", "error", "disconnected"].includes(socketStatus)) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin" />
</div>
);
}
if (!data?.user) {
return null;
}
return (
<>
<UserFloatingCard user={data.user} />
<AppSidebar
socketStatus={socketStatus}
socketInfo={socketInfo}
disconnectSocket={disconnect}
connectSocket={connect}
routeInfo={routeInfo}
>
<MainContentLayout
socketStatus={socketStatus}
emptyChannelMessage={getPhrase()}
emptyFriendsMessage={getPhrase()}
userId={data.user.id}
routeInfo={routeInfo}
userNests={userNests}
/>
</AppSidebar>
<OlmPasswordDialog userId={data.user.id} />
<OlmSetupDialog
open={showOlmModal}
onOpenChange={setShowOlmModal}
olmStatus={olmStatus}
onCreateAccount={handleCreateAccount}
/>
</>
);
}
export default function AppContainer() {
const { data, error, isPending, refetch } = authClient.useSession();
const userStatus = useQuery(api.auth.getUserStatus);
const hasServerOlm = useQuery(
api.auth.retrieveServerOlmAccount,
data?.user?.id ? { userId: data.user.id } : "skip"
);
const sendKeysToServer = useMutation(api.auth.sendKeysToServer);
const consumeOTK = useMutation(api.auth.consumeOTK);
if (isPending) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin" />
</div>
);
}
if (error || !data) {
return redirect(`/auth${error ? `?error=${error.cause}` : "?error=no-data"}`);
}
return (
<OlmProvider
userId={data?.user?.id}
hasServerOlm={hasServerOlm}
sendKeysToServer={sendKeysToServer}
consumeOTK={consumeOTK}
>
<SocketProvider
user={{
id: data?.user?.id,
status: userStatus ? {
status: userStatus.status,
isUserSet: userStatus.isUserSet,
} : {
status: "offline" as const,
isUserSet: false,
},
}}
refetchUser={refetch}
>
<AppContainerContent />
</SocketProvider>
</OlmProvider>
);
}

View file

@ -1,211 +0,0 @@
"use client";
import { cn } from "@/lib/utils";
import { BroadcastIcon as Broadcast } from "@phosphor-icons/react";
import { Activity, Clock, Globe, LogInIcon, LogOutIcon, Radio, Zap } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
function formatUptime(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
}
/**
* Connection status indicator with popover details
*/
export default function ConnectionStatusIndicator({ socketStatus, socketInfo, disconnectSocket, connectSocket }: { socketStatus: SiPher.SocketStatus; socketInfo: SiPher.SocketInfo; disconnectSocket: () => void; connectSocket: () => void }) {
const [uptime, setUptime] = useState<string>("0s");
const [isOpen, setIsOpen] = useState(false);
// Update uptime every second when connected
useEffect(() => {
if (socketStatus !== "connected" || !socketInfo.connectedAt) return;
const interval = setInterval(() => {
setUptime(formatUptime(Date.now() - socketInfo.connectedAt!));
}, 1000);
// Initial update
setUptime(formatUptime(Date.now() - socketInfo.connectedAt));
return () => clearInterval(interval);
}, [socketStatus, socketInfo.connectedAt]);
const statusConfig = {
connected: {
label: "Connected",
color: "text-primary",
glow: "drop-shadow-[0_0_6px_var(--primary)]",
dotColor: "bg-primary"
},
connecting: {
label: "Connecting",
color: "text-chart-2",
glow: "",
dotColor: "bg-chart-2 animate-pulse"
},
disconnected: {
label: "Disconnected",
color: "text-muted-foreground",
glow: "",
dotColor: "bg-muted-foreground"
},
error: {
label: "Connection Error",
color: "text-destructive",
glow: "",
dotColor: "bg-destructive"
}
};
const config = statusConfig[socketStatus as keyof typeof statusConfig] || statusConfig.error;
const getPingQuality = (ping: number | null) => {
if (!ping) return { label: "Unknown", color: "text-muted-foreground" };
if (ping < 50) return { label: "Excellent", color: "text-primary" };
if (ping < 100) return { label: "Good", color: "text-chart-1" };
if (ping < 200) return { label: "Fair", color: "text-chart-2" };
return { label: "Poor", color: "text-destructive" };
};
const pingQuality = getPingQuality(socketInfo.ping);
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<button
className={cn(
"relative flex items-center justify-center p-1.5 rounded-lg transition-all duration-200",
"hover:bg-accent/50 active:scale-95",
config.color, config.glow
)}
aria-label="Connection status"
>
<Broadcast
className="size-5"
weight={socketStatus === "connected" ? "fill" : "regular"}
/>
{/* Animated ring for connecting state */}
{socketStatus === "connecting" && (
<span className="absolute inset-0 rounded-lg border-2 border-chart-2/50 animate-ping" />
)}
</button>
</PopoverTrigger>
<PopoverContent
className={cn(
"w-72 p-0 overflow-hidden",
"bg-popover backdrop-blur-xl",
"border border-border shadow-xl"
)}
align="end"
sideOffset={8}
>
{/* Header */}
<div className="px-4 py-3 border-b border-border">
<div className="flex items-center gap-3">
<div className={cn("size-3 rounded-full", config.dotColor)} />
<div>
<p className={cn("font-semibold text-sm", config.color)}>{config.label}</p>
{socketInfo.error && (
<p className="text-xs text-destructive mt-0.5">{socketInfo.error}</p>
)}
</div>
</div>
</div>
{/* Stats Grid */}
<div className="p-3 space-y-1.5">
{/* Ping */}
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Activity className="size-4" />
<span className="text-xs font-medium">Latency</span>
</div>
<div className="text-right">
<span className={cn("text-sm font-mono font-semibold", pingQuality.color)}>
{socketInfo.ping ? `${socketInfo.ping}ms` : "—"}
</span>
<p className={cn("text-[10px]", pingQuality.color)}>{pingQuality.label}</p>
</div>
</div>
{/* Transport */}
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Zap className="size-4" />
<span className="text-xs font-medium">Transport</span>
</div>
<span className="text-sm font-medium capitalize text-foreground">
{socketInfo.transport || "—"}
</span>
</div>
{/* Uptime */}
{socketStatus === "connected" && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Clock className="size-4" />
<span className="text-xs font-medium">Uptime</span>
</div>
<span className="text-sm font-mono font-medium text-primary">
{uptime}
</span>
</div>
)}
{/* Server */}
{socketInfo.serverUrl && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Globe className="size-4" />
<span className="text-xs font-medium">Server</span>
</div>
<span className="text-xs font-mono text-foreground truncate max-w-[120px]">
{new URL(socketInfo.serverUrl).host}
</span>
</div>
)}
{/* Socket ID */}
{socketInfo.socketId && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Radio className="size-4" />
<span className="text-xs font-medium">Session</span>
</div>
<span className="text-[10px] font-mono text-muted-foreground">
{socketInfo.socketId.slice(0, 12)}...
</span>
</div>
)}
</div>
{/* Footer hint */}
<div className="flex flex-row items-center justify-between gap-2 px-4 py-2 border-t border-border bg-muted/30">
<p className="text-[10px] text-muted-foreground text-center">
Real-time connection via Socket.IO
</p>
<Button variant="ghost" size="icon-sm" className="hover:cursor-pointer hover:bg-transparent!" onClick={() => {
socketStatus === "connected" ? disconnectSocket() : connectSocket();
}}>
{
socketStatus === "connected" ? (
<LogOutIcon className="size-4" />
) : (
<LogInIcon className="size-4" />
)
}
</Button>
</div>
</PopoverContent>
</Popover>
);
}

View file

@ -1,143 +0,0 @@
"use client";
import LogoIcon from "@/components/ui/logo-icon";
import {
Sidebar,
SidebarContent,
SidebarHeader,
SidebarInset,
SidebarMenu,
SidebarMenuItem,
SidebarProvider
} from "@/components/ui/sidebar";
import { CompassIcon, GlobeIcon, HouseIcon } from "@phosphor-icons/react";
import { Plus } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Separator } from "../ui/separator";
import ConnectionStatusIndicator from "./csi";
import SidebarIcon from "./sicons";
const SidebarItems: SiPher.SidebarItem[] = [
{
id: "global-nests",
icon: <GlobeIcon className="size-5" weight="fill" />,
label: "Global Nest",
href: "/channels/nests/global"
},
{
id: "discover",
icon: <CompassIcon className="size-5" weight="fill" />,
label: "Discover",
href: "/discover"
}
];
/**
* The main component for the homepage. This component is used to wrap all the components of any page.
* It also is the controller for everything on the app, including going to other pages, showing conversations and other.
* @param children - The children to be rendered in the sidebar inset
*/
export default function AppSidebar({ children, socketStatus, socketInfo, currentChannel, disconnectSocket, connectSocket, routeInfo }: SiPher.AppSidebarProps) {
const [activeItem, setActiveItem] = useState<string>("home");
const router = useRouter();
return (
<SidebarProvider
style={{
"--sidebar-width": "5rem",
"--sidebar-width-mobile": "5rem",
} as React.CSSProperties}
defaultOpen={true}
>
<Sidebar variant="inset" collapsible="offcanvas" className="border-r-0">
<SidebarHeader className="py-3 px-0">
<SidebarIcon
isActive={activeItem === "home"}
isHome
label="Home"
onClick={() => setActiveItem("home")}
>
<LogoIcon className="size-7" />
</SidebarIcon>
</SidebarHeader>
<div className="px-5 py-0.5">
<Separator className="bg-sidebar-border" />
</div>
<SidebarContent className="pt-2 px-0 overflow-hidden">
<SidebarMenu className="gap-2">
{SidebarItems.map((item) => (
<SidebarMenuItem key={item.id} onClick={() => {
if (item.href) {
router.push(item.href);
}
}}>
<SidebarIcon
isActive={activeItem === item.id && routeInfo.type === item.id}
label={item.label}
onClick={() => setActiveItem(item.id)}
>
{item.icon}
</SidebarIcon>
</SidebarMenuItem>
))}
{/* Add Server/Channel button */}
<SidebarMenuItem>
<SidebarIcon label="Add a Server">
<Plus className="size-5 text-green-500 hover:text-white transition-colors" />
</SidebarIcon>
</SidebarMenuItem>
</SidebarMenu>
</SidebarContent>
</Sidebar>
<div className="flex flex-col flex-1 h-svh min-h-0 overflow-hidden">
<header className="flex items-center justify-between md:justify-center gap-2 px-4 py-0.5 md:border-none border-b border-border backdrop-blur sticky top-0 z-10">
<div className="flex items-center gap-2 justify-end w-full select-none">
<div className="flex items-center justify-center gap-2 text-sm font-semibold w-full text-center">
{
currentChannel ? (
<>
{
currentChannel.metadata?.icon ? (
<Avatar className="size-5">
<AvatarImage src={currentChannel.metadata!.icon!} alt={currentChannel.name} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{currentChannel.name?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
) : (
<span className="size-5 rounded-full bg-primary/20 text-primary-foreground font-semibold">
{currentChannel.name?.charAt(0).toUpperCase()}
</span>
)
}
<span className="truncate">{currentChannel.name}</span>
</>
) : (
<>
<HouseIcon className="size-5" weight="fill" />
<span className="font-semibold">
Home
</span>
</>
)
}
</div>
{/* Socket connection status */}
<ConnectionStatusIndicator socketStatus={socketStatus} socketInfo={socketInfo} disconnectSocket={disconnectSocket} connectSocket={connectSocket} />
</div>
</header>
<SidebarInset className="mr-0 mb-0 border-none flex-1 min-h-0 overflow-hidden rounded-l-lg">
<div className="w-full h-full bg-background border-border border rounded-l-lg rounded-bl-none overflow-hidden min-h-0">
{children}
</div>
</SidebarInset>
</div>
</SidebarProvider>
)
}

View file

@ -1,305 +0,0 @@
"use client"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useMutation, useQuery } from "convex/react";
import { CheckIcon, UserPlusIcon, XIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api } from "../../../../convex/_generated/api";
interface FriendRequestModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export default function FriendRequestModal({
open,
onOpenChange,
}: FriendRequestModalProps) {
const getFriendRequests = useQuery(api.auth.getFriendRequests);
const sendFriendRequest = useMutation(api.auth.sendFriendRequest);
const answerFriendRequest = useMutation(api.auth.answerFriendRequest);
const [username, setUsername] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<"send" | "pending" | "sent">("send");
const [pendingRequests, setPendingRequests] = useState<any[]>([]);
const [sentRequests, setSentRequests] = useState<any[]>([]);
useEffect(() => {
if (getFriendRequests) {
if (!getFriendRequests || getFriendRequests.length === 0) {
console.debug("[FriendRequestModal] > Such a sad day, no friend requests found")
setPendingRequests([]);
setSentRequests([]);
return;
}
console.debug("[FriendRequestModal] > This guy is important, look at him with his big friend request list (¬.¬) :", getFriendRequests);
setPendingRequests(getFriendRequests.filter((request: any) => request.method === "receive"));
setSentRequests(getFriendRequests.filter((request: any) => request.method === "send"));
}
}, [getFriendRequests]);
const handleSendRequest = async () => {
if (!username.trim()) return;
setIsLoading(true);
setError(null);
try {
await sendFriendRequest({
username: username,
});
toast.success("Friend request sent successfully");
setUsername("");
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to send friend request");
} finally {
setIsLoading(false);
}
};
const handleAccept = async (requestId: string) => {
setIsLoading(true);
try {
await answerFriendRequest({
requestId: requestId,
answer: "accept",
});
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to accept request");
} finally {
setIsLoading(false);
}
};
const handleDecline = async (requestId: string) => {
setIsLoading(true);
try {
await answerFriendRequest({
requestId: requestId,
answer: "decline",
});
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to decline request");
} finally {
setIsLoading(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !isLoading) {
handleSendRequest();
}
};
const formatTimeAgo = (timestamp: number) => {
const seconds = Math.floor((Date.now() - timestamp) / 1000);
if (seconds < 60) return "just now";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<UserPlusIcon className="size-5" />
Friend Requests
</DialogTitle>
<DialogDescription>
Send, accept, or manage your friend requests.
</DialogDescription>
</DialogHeader>
{/* Tabs */}
<div className="flex items-center gap-2 border-b border-border">
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "send" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("send")}
>
Send Request
</Button>
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "pending" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("pending")}
>
Pending ({pendingRequests.length})
</Button>
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "sent" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("sent")}
>
Sent ({sentRequests.length})
</Button>
</div>
{/* Content */}
<div className="min-h-[200px] max-h-[400px] overflow-y-auto">
{activeTab === "send" && (
<div className="flex flex-col gap-4 py-2">
<div className="flex flex-col gap-2">
<Input
placeholder="Enter username..."
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isLoading}
/>
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</div>
<Button
onClick={handleSendRequest}
disabled={!username.trim() || isLoading}
className="w-full"
>
{isLoading ? (
<>
<Spinner className="size-4 animate-spin mr-2" />
Sending...
</>
) : (
<>
<UserPlusIcon className="size-4 mr-2" />
Send Friend Request
</>
)}
</Button>
</div>
)}
{activeTab === "pending" && (
<div className="flex flex-col gap-2 py-2">
{pendingRequests.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<p className="text-sm text-muted-foreground">
No pending friend requests
</p>
</div>
) : (
pendingRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border hover:bg-accent/50 transition-colors"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<Avatar className="size-10 shrink-0">
<AvatarImage src={request.avatar} alt={request.username} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{request.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-sm font-medium truncate">
{request.username}
</span>
<span className="text-xs text-muted-foreground">
{formatTimeAgo(request.createdAt)}
</span>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button
size="icon-sm"
variant="ghost"
className="size-8 text-green-500 hover:text-green-600 hover:bg-green-500/10"
onClick={() => handleAccept(request.id)}
disabled={isLoading}
>
<CheckIcon className="size-4" />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="size-8 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => handleDecline(request.id)}
disabled={isLoading}
>
<XIcon className="size-4" />
</Button>
</div>
</div>
))
)}
</div>
)}
{activeTab === "sent" && (
<div className="flex flex-col gap-2 py-2">
{sentRequests.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<p className="text-sm text-muted-foreground">
No sent friend requests
</p>
</div>
) : (
sentRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<Avatar className="size-10 shrink-0">
<AvatarImage src={request.avatar} alt={request.username} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{request.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-sm font-medium truncate">
{request.username}
</span>
<span className="text-xs text-muted-foreground">
Sent {formatTimeAgo(request.createdAt)}
</span>
</div>
</div>
<span className="text-xs text-muted-foreground shrink-0">
Pending...
</span>
</div>
))
)}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -1,67 +0,0 @@
import { cn } from "@/lib/utils";
import { useState } from "react";
import { Button } from "../ui/button";
/**
* Discord-style sidebar icon with pill indicator
*/
export default function SidebarIcon({
children,
isActive,
isHome,
label,
onClick
}: {
children: React.ReactNode;
isActive?: boolean;
isHome?: boolean;
label?: string;
onClick?: () => void;
}) {
const [isHovered, setIsHovered] = useState(false);
return (
<div className="relative flex items-center justify-center w-full group">
{/* Left pill indicator */}
<div
className={cn(
"absolute left-0 w-1 bg-sidebar-foreground rounded-r-full transition-all duration-200",
isActive ? "h-10" : isHovered ? "h-5" : "h-0"
)}
/>
{/* Icon button */}
<Button
type="button"
variant="ghost"
size="icon-xl"
onClick={onClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className={cn(
"relative flex items-center justify-center size-12 transition-all duration-200 overflow-hidden",
"focus-visible:ring-0 focus-visible:border-none",
isHome
? "bg-primary text-primary-foreground hover:bg-primary/80"
: "bg-sidebar hover:bg-sidebar-accent text-sidebar-foreground hover:text-sidebar-foreground",
isActive
? "rounded-2xl bg-primary text-primary-foreground"
: "rounded-[24px] hover:rounded-2xl"
)}
>
{children}
</Button>
{/* Tooltip */}
{label && (
<div className={cn(
"absolute left-full ml-3 px-3 py-2 bg-popover text-popover-foreground text-sm font-medium rounded-md shadow-lg whitespace-nowrap z-50 pointer-events-none transition-all duration-150",
isHovered ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-1"
)}>
{label}
<div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-popover" />
</div>
)}
</div>
);
}

View file

@ -0,0 +1,217 @@
"use client";
import { authClient } from "@/lib/auth-client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff, KeyRound, Loader2, TriangleAlert } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "../ui/accordion";
import { Button } from "../ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
import { Input } from "../ui/input";
import IdentityBackup from "./IdentityBackup";
const createIdentityFormSchema = z.object({
password: z
.string()
.min(8, "Password must be at least 8 characters")
.max(64, "Password cannot exceed 64 characters")
.refine((val) => /[A-Z]/.test(val), {
message: "Must contain at least one uppercase letter",
})
.refine((val) => /[a-z]/.test(val), {
message: "Must contain at least one lowercase letter",
})
.refine((val) => /[0-9]/.test(val), {
message: "Must contain at least one number",
})
.refine((val) => /[^a-zA-Z0-9]/.test(val), {
message: "Must contain at least one special character",
})
});
const requirements = [
{ label: "864 characters", test: (v: string) => v.length >= 8 && v.length <= 64 },
{ label: "Uppercase letter", test: (v: string) => /[A-Z]/.test(v) },
{ label: "Lowercase letter", test: (v: string) => /[a-z]/.test(v) },
{ label: "Number", test: (v: string) => /[0-9]/.test(v) },
{ label: "Special character", test: (v: string) => /[^a-zA-Z0-9]/.test(v) },
];
export default function CreateIdentity() {
const [isOpen, setIsOpen] = useState(true);
const [showPassword, setShowPassword] = useState(false);
const [mnemonic, setMnemonic] = useState<string | null>(null);
const { data: session } = authClient.useSession();
const router = useRouter();
const form = useForm<z.infer<typeof createIdentityFormSchema>>({
resolver: zodResolver(createIdentityFormSchema),
defaultValues: {
password: "",
},
});
const password = form.watch("password");
const passwordRequirementsMet = requirements.every((req) => req.test(password));
async function onSubmit(values: z.infer<typeof createIdentityFormSchema>) {
const userId = session?.user.id;
if (!userId) return;
try {
const result = await authClient.createOvenIdentity(userId, values.password);
setMnemonic(result.mnemonic);
} catch (err) {
console.error("[CreateIdentity]", err);
toast.error("Failed to create identity. Please try again.");
}
}
function handleBackupConfirmed() {
setIsOpen(false);
router.refresh();
}
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent onInteractOutside={(e) => e.preventDefault()} className="sm:max-w-md border-border bg-card p-0 overflow-hidden [&>button]:hidden">
{mnemonic ? (
<IdentityBackup mnemonic={mnemonic} onConfirmed={handleBackupConfirmed} />
) : (
<>
<div className="px-6 pt-6 pb-2 border-b border-border/60">
<div className="flex items-center gap-3 mb-3">
<div className="flex items-center justify-center w-8 h-8 rounded bg-primary/10 border border-primary/20">
<KeyRound className="w-4 h-4 text-primary" />
</div>
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase">
Identity Setup
</span>
</div>
<DialogHeader className="text-left space-y-1">
<DialogTitle className="font-display text-3xl tracking-[0.06em] text-foreground">
Create your Sipher identity
</DialogTitle>
<p className="text-sm text-muted-foreground leading-relaxed">
This password encrypts your local identity key. It never leaves your device. <span className="font-bold">DO NOT FORGET THIS PASSWORD.</span>
</p>
<p className="text-sm text-muted-foreground leading-relaxed">
You may use the same password for your Sipher account and your identity, although it is not recommended.
</p>
</DialogHeader>
</div>
<div className="px-6 py-5">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem className="space-y-1.5">
<FormLabel className="font-mono text-[11px] tracking-[0.15em] uppercase text-muted-foreground">
Master Password
</FormLabel>
<FormControl>
<div className="relative">
<Input
{...field}
type={showPassword ? "text" : "password"}
className="h-11 text-base bg-background border-border/60 pr-10 focus-visible:ring-primary/50 focus-visible:border-primary/50"
placeholder="••••••••••••"
/>
<button
type="button"
onClick={() => setShowPassword((v) => !v)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
tabIndex={-1}
>
{showPassword
? <EyeOff className="w-4 h-4" />
: <Eye className="w-4 h-4" />
}
</button>
</div>
</FormControl>
<FormMessage className="font-mono text-[10px] tracking-wide" />
</FormItem>
)}
/>
{password.length > 0 && (
<div className="space-y-1.5">
<span className="font-mono text-[10px] tracking-[0.15em] uppercase text-muted-foreground">
Requirements
</span>
<ul className="grid grid-cols-2 gap-x-4 gap-y-1">
{requirements.map((req) => {
const met = req.test(password);
return (
<li
key={req.label}
className={`font-mono text-[10px] tracking-wide flex items-center gap-1.5 transition-colors ${met ? "text-primary" : "text-muted-foreground/60"}`}
>
<span className={`inline-block w-1 h-1 rounded-full shrink-0 ${met ? "bg-primary" : "bg-border"}`} />
{req.label}
</li>
);
})}
</ul>
</div>
)}
<Accordion type="single" collapsible className="border border-destructive/30 rounded bg-destructive/5">
<AccordionItem value="lost-password" className="border-none">
<AccordionTrigger className="px-3 py-2.5 hover:no-underline hover:bg-destructive/10 rounded transition-colors">
<span className="flex items-center gap-2 font-mono text-[10px] tracking-[0.15em] uppercase text-destructive/80">
<TriangleAlert className="w-3.5 h-3.5 shrink-0" />
What if I lose my password?
</span>
</AccordionTrigger>
<AccordionContent className="px-3 pb-3 pt-0">
<ul className="space-y-1.5 font-mono text-[10px] tracking-wide text-muted-foreground leading-relaxed">
<li className="flex gap-2">
<span className="text-destructive/60 shrink-0"></span>
Your identity key is encrypted locally with this password. There is no recovery mechanism.
</li>
<li className="flex gap-2">
<span className="text-destructive/60 shrink-0"></span>
Losing it means permanent loss of access to your encrypted messages and posts.
</li>
<li className="flex gap-2">
<span className="text-destructive/60 shrink-0"></span>
Store it somewhere safe a password manager or written offline.
</li>
<li className="flex gap-2">
<span className="text-destructive/60 shrink-0"></span>
Losing your identity means that all your messages are permanently lost and your old posts won't hold a valid signature.
</li>
</ul>
</AccordionContent>
</AccordionItem>
</Accordion>
<Button
type="submit"
className="w-full h-11 font-mono text-[11px] tracking-[0.2em] uppercase"
disabled={form.formState.isSubmitting || !passwordRequirementsMet}
>
{form.formState.isSubmitting
? <Loader2 className="w-4 h-4 animate-spin" />
: "Generate Identity"
}
</Button>
</form>
</Form>
</div>
</>
)}
</DialogContent>
</Dialog>
)
}

View file

@ -0,0 +1,85 @@
"use client";
import { Button } from "@/components/ui/button";
import { Copy, ShieldCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
interface IdentityBackupProps {
mnemonic: string;
onConfirmed: () => void;
}
export default function IdentityBackup({ mnemonic, onConfirmed }: IdentityBackupProps) {
const [confirmed, setConfirmed] = useState(false);
function copyMnemonic() {
navigator.clipboard.writeText(mnemonic).then(() => {
toast.success("Mnemonic copied to clipboard.");
});
}
const words = mnemonic.split(" ");
return (
<div className="px-6 py-6 space-y-5">
<div className="flex items-center gap-3">
<div className="flex items-center justify-center w-8 h-8 rounded bg-primary/10 border border-primary/20">
<ShieldCheck className="w-4 h-4 text-primary" />
</div>
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase">
Backup your recovery phrase
</span>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground leading-relaxed">
This is the <span className="font-semibold text-foreground">only time</span> your recovery phrase will be shown. Write it down offline and keep it safe. It is the only way to recover your identity if you lose your master password.
</p>
</div>
<div className="relative rounded border border-border bg-muted/40 p-4">
<div className="grid grid-cols-3 gap-x-4 gap-y-1.5">
{words.map((word, i) => (
<div key={i} className="flex items-center gap-1.5">
<span className="font-mono text-[10px] text-muted-foreground/60 w-4 text-right shrink-0">
{i + 1}.
</span>
<span className="font-mono text-[13px] text-foreground select-all">
{word}
</span>
</div>
))}
</div>
<button
type="button"
onClick={copyMnemonic}
className="absolute top-2 right-2 p-1.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
title="Copy recovery phrase"
>
<Copy className="w-3.5 h-3.5" />
</button>
</div>
<label className="flex items-start gap-3 cursor-pointer select-none">
<input
type="checkbox"
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
className="mt-0.5 h-4 w-4 shrink-0 rounded border-border accent-primary"
/>
<span className="font-mono text-[11px] text-muted-foreground leading-relaxed">
I have written down my recovery phrase and stored it somewhere safe. I understand this phrase will never be shown again.
</span>
</label>
<Button
onClick={onConfirmed}
disabled={!confirmed}
className="w-full h-11 font-mono text-[11px] tracking-[0.2em] uppercase"
>
Continue
</Button>
</div>
);
}

View file

@ -0,0 +1,145 @@
"use client";
import { authClient } from "@/lib/auth-client";
import { getDb } from "@/lib/dexie";
import { restoreSessionKey, unlockSessionKey } from "@/lib/identity/sessionKey";
import { useIdentityLock } from "@/lib/identity/useIdentityLock";
import { Eye, EyeOff, KeyRound, Loader2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "../ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../ui/dialog";
import { Input } from "../ui/input";
/**
* Global unlock gate shown whenever the user is authenticated, has a local
* identity, but the in-memory session key store is cold (fresh page load,
* navigation from another tab, etc.).
*
* Stays hidden for unauthenticated users and for users who have not yet
* created an identity (those see <CreateIdentity> instead).
*/
export default function UnlockIdentityModal() {
const { data: session, isPending: sessionLoading } = authClient.useSession();
const isUnlocked = useIdentityLock();
const [hasLocalIdentity, setHasLocalIdentity] = useState<boolean | null>(null);
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// On session available: first try a silent restore from sessionStorage so
// that a page reload doesn't force a password re-entry. Only if that fails
// do we confirm a local Dexie record exists and show the prompt.
useEffect(() => {
if (!session?.user.id) {
setHasLocalIdentity(null);
return;
}
// Attempt silent restore; if it works, `useIdentityLock` flips to true
// and `shouldShow` stays false — no prompt needed.
if (restoreSessionKey(session.user.id)) return;
getDb().identity.get(session.user.id).then((record) => {
setHasLocalIdentity(record !== undefined);
});
}, [session?.user.id]);
// Focus the password input when the modal becomes visible.
useEffect(() => {
if (!isUnlocked && hasLocalIdentity) {
setTimeout(() => inputRef.current?.focus(), 50);
}
}, [isUnlocked, hasLocalIdentity]);
const shouldShow =
!sessionLoading &&
!!session &&
hasLocalIdentity === true &&
!isUnlocked;
async function handleUnlock(e: React.FormEvent) {
e.preventDefault();
if (!session?.user.id || !password) return;
setLoading(true);
setError(null);
try {
await unlockSessionKey(session.user.id, password);
setPassword("");
toast.success("Identity unlocked.");
} catch {
setError("Wrong password. Please try again.");
} finally {
setLoading(false);
}
}
return (
<Dialog open={shouldShow}>
<DialogContent
onInteractOutside={(e) => e.preventDefault()}
className="sm:max-w-sm border-border bg-card p-0 overflow-hidden [&>button]:hidden"
>
<div className="px-6 pt-6 pb-2 border-b border-border/60">
<div className="flex items-center gap-3 mb-3">
<div className="flex items-center justify-center w-8 h-8 rounded bg-primary/10 border border-primary/20">
<KeyRound className="w-4 h-4 text-primary" />
</div>
<span className="font-mono text-[10px] text-muted-foreground tracking-[0.25em] uppercase">
Identity locked
</span>
</div>
<DialogHeader className="text-left space-y-1">
<DialogTitle className="font-display text-2xl tracking-[0.06em] text-foreground">
Unlock your identity
</DialogTitle>
<p className="text-sm text-muted-foreground leading-relaxed">
Enter your master password to enable signing for this session.
</p>
</DialogHeader>
</div>
<form onSubmit={handleUnlock} className="px-6 py-5 space-y-4">
<div className="space-y-1.5">
<label className="font-mono text-[11px] tracking-[0.15em] uppercase text-muted-foreground">
Master Password
</label>
<div className="relative">
<Input
ref={inputRef}
type={showPassword ? "text" : "password"}
value={password}
onChange={(e) => { setPassword(e.target.value); setError(null); }}
className="h-11 text-base bg-background border-border/60 pr-10 focus-visible:ring-primary/50 focus-visible:border-primary/50"
placeholder="••••••••••••"
disabled={loading}
/>
<button
type="button"
onClick={() => setShowPassword((v) => !v)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
tabIndex={-1}
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
{error && (
<p className="font-mono text-[10px] tracking-wide text-destructive">{error}</p>
)}
</div>
<Button
type="submit"
className="w-full h-11 font-mono text-[11px] tracking-[0.2em] uppercase"
disabled={loading || !password}
>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Unlock"}
</Button>
</form>
</DialogContent>
</Dialog>
);
}

View file

@ -1,20 +0,0 @@
"use client"
import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
export function ModeToggle() {
const { theme, setTheme } = useTheme()
return (
<Button variant="ghost" size="icon" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
)
}

View file

@ -1,99 +0,0 @@
"use client";
import { requestNotificationPermission } from "@/lib/notifications";
import { Bell, BellOff } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
export function NotificationSettings({ userStatus }: { userStatus: "online" | "busy" | "offline" | "away" }) {
const [permission, setPermission] = useState<NotificationPermission>("default");
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if ("Notification" in window) {
setPermission(Notification.permission);
}
}, []);
const handleRequestPermission = async () => {
setIsLoading(true);
try {
const newPermission = await requestNotificationPermission();
setPermission(newPermission);
if (newPermission === "granted") {
if (userStatus === "busy") return;
// Show a test notification
new Notification("Notifications enabled!", {
body: "You'll now receive message notifications",
icon: "/logo.png",
});
}
} catch (error) {
console.error("Failed to request notification permission:", error);
} finally {
setIsLoading(false);
}
};
if (!("Notification" in window)) {
return null; // Browser doesn't support notifications
}
if (permission === "granted") {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Bell className="h-4 w-4 text-green-500" />
<span>Notifications enabled</span>
</div>
);
}
if (permission === "denied") {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<BellOff className="h-4 w-4 text-red-500" />
<span>Notifications blocked. Enable in browser settings.</span>
</div>
);
}
return (
<Button
variant="outline"
size="sm"
onClick={handleRequestPermission}
disabled={isLoading}
className="gap-2"
>
<Bell className="h-4 w-4" />
{isLoading ? "Requesting..." : "Enable Notifications"}
</Button>
);
}
/**
* Auto-request notification permission component
* Place in your app layout to automatically request permission on load
*/
export function AutoRequestNotifications() {
useEffect(() => {
if ("Notification" in window && Notification.permission === "default") {
// Auto-request permission after a short delay (to not interrupt page load)
const timer = setTimeout(async () => {
try {
const permission = await requestNotificationPermission();
if (permission === "granted") {
console.log("[Notifications] Permission granted automatically");
}
} catch (error) {
console.debug("[Notifications] Auto-request failed or was dismissed:", error);
}
}, 2000); // Wait 2 seconds after page load
return () => clearTimeout(timer);
}
}, []);
return null; // This component doesn't render anything
}

View file

@ -1,122 +0,0 @@
import { useOlmContext } from "@/contexts/olm-context";
import { AlertCircle, Info, KeyRound, ShieldCheck } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../ui/dialog";
import { Input } from "../ui/input";
export default function OlmPasswordDialog({ userId }: { userId: string }) {
const [needsPassword, setNeedsPassword] = useState(false);
const [password, setPasswordInput] = useState("");
const { setPassword, passwordError, clearPasswordError } = useOlmContext();
useEffect(() => {
// The context handles loading & decrypting the password from sessionStorage.
// We only need to show the dialog if the context doesn't have a password.
// This will be handled by the passwordError effect below.
// For initial load, we check if there's encrypted data - if not, show dialog.
const hasStoredPassword = sessionStorage.getItem(`olm_password_${userId}`);
if (!hasStoredPassword) {
setNeedsPassword(true);
}
// If there IS stored data, the context will decrypt it and load it.
// If decryption fails or password is wrong, passwordError will be set.
}, [userId]);
// Show dialog when there's a password error (wrong password was entered)
useEffect(() => {
if (passwordError) {
setNeedsPassword(true);
setPasswordInput(""); // Clear the input for retry
}
}, [passwordError]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (password.trim()) {
setPassword(password);
setNeedsPassword(false);
}
};
return (
<Dialog open={needsPassword}>
<DialogContent className="sm:max-w-[440px]" showCloseButton={false} onPointerDownOutside={(e) => e.preventDefault()} onEscapeKeyDown={(e) => e.preventDefault()}>
<DialogHeader className="space-y-4">
<div className="flex flex-col items-center text-center space-y-3">
<div className="h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center ring-8 ring-primary/5">
<KeyRound className="h-7 w-7 text-primary" />
</div>
<div className="space-y-2">
<DialogTitle className="text-2xl font-semibold tracking-tight">
Encryption Password Required
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground max-w-sm">
Enter your encryption password to access this conversation. This may be different from your login password.
</DialogDescription>
</div>
</div>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6 pt-2">
<div className="space-y-3">
<Input
type="password"
placeholder="Enter your encryption password"
className={`h-11 text-center ${passwordError ? "border-destructive focus-visible:ring-destructive" : ""}`}
autoFocus
value={password}
onChange={(e) => {
setPasswordInput(e.target.value);
if (passwordError) clearPasswordError();
}}
/>
{passwordError && (
<div className="flex items-center gap-2 rounded-md bg-destructive/10 px-3 py-2.5 text-destructive border border-destructive/20">
<AlertCircle className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
{passwordError}
</p>
</div>
)}
<div className="space-y-2">
<div className="flex items-center gap-2 rounded-md bg-chart-3/10 px-3 py-2.5 text-chart-3 border border-chart-3/20">
<Info className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
You'll be asked to re-enter this password each time you start a new browser session.
<br />
When continuing, the window will be reloaded, please do not close the window or refresh the page by yourself.
</p>
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-chart-2/10 px-3 py-2.5 text-chart-2 border border-chart-2/20">
<ShieldCheck className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
Your password is encrypted before being stored in your browser's session storage using a secure key that cannot be exported.
</p>
</div>
</div>
<div className="flex gap-3">
<Button
type="button"
variant="outline"
onClick={() => setNeedsPassword(false)}
className="flex-1"
>
Cancel
</Button>
<Button
type="submit"
className="flex-1"
disabled={!password.trim()}
>
Continue
</Button>
</div>
</form>
</DialogContent>
</Dialog>
)
}

View file

@ -1,114 +0,0 @@
"use client"
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useState } from "react";
interface OlmSetupDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
olmStatus: SiPher.OlmStatus;
onCreateAccount: (password: string) => Promise<void>;
}
export default function OlmSetupDialog({
open,
onOpenChange,
olmStatus,
onCreateAccount,
}: OlmSetupDialogProps) {
const [localPassword, setLocalPassword] = useState("");
const handleSubmit = async () => {
if (!localPassword.trim()) return;
await onCreateAccount(localPassword);
setLocalPassword("");
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
handleSubmit();
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={olmStatus !== "creating"}>
<DialogHeader>
<DialogTitle>
{olmStatus === "not_setup" && "Set Up Encryption"}
{olmStatus === "mismatched" && "Encryption Keys Out of Sync"}
{olmStatus === "creating" && "Creating Encryption Keys..."}
</DialogTitle>
<DialogDescription>
{olmStatus === "not_setup" && (
"Create a local password to encrypt your messages. This password is stored locally and never sent to our servers."
)}
{olmStatus === "mismatched" && (
"Your local encryption keys don't match the server. This can happen if you cleared your browser data or logged in from a new device."
)}
</DialogDescription>
</DialogHeader>
{olmStatus === "creating" ? (
<div className="flex items-center justify-center py-6">
<Spinner className="size-8 animate-spin" />
</div>
) : olmStatus === "not_setup" ? (
<>
<Input
type="password"
placeholder="Enter a local encryption password"
value={localPassword}
onChange={(e) => setLocalPassword(e.target.value)}
onKeyDown={handleKeyDown}
/>
<DialogFooter>
<Button onClick={handleSubmit} disabled={!localPassword.trim()}>
Create Encryption Keys
</Button>
</DialogFooter>
</>
) : olmStatus === "mismatched" ? (
<>
<div className="flex flex-col gap-2 text-sm text-muted-foreground">
<p>You have two options:</p>
<ul className="list-disc list-inside space-y-1">
<li><strong>Reset:</strong> Create new keys (you'll lose access to old messages)</li>
<li><strong>Restore:</strong> Import your backup if you have one</li>
</ul>
</div>
<Input
type="password"
placeholder="Enter password to create new keys"
value={localPassword}
onChange={(e) => setLocalPassword(e.target.value)}
onKeyDown={handleKeyDown}
/>
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Import Keys from Backup
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={!localPassword.trim()}>
Reset & Create New Keys
</Button>
</DialogFooter>
</>
) : null}
</DialogContent>
</Dialog>
);
}

View file

@ -1,12 +0,0 @@
"use client"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import * as React from "react"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View file

@ -0,0 +1,67 @@
"use client"
import { ChevronDownIcon } from "lucide-react"
import { Accordion as AccordionPrimitive } from "radix-ui"
import * as React from "react"
import { cn } from "@/lib/utils"
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="pointer-events-none size-4 shrink-0 translate-y-0.5 text-muted-foreground transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionContent, AccordionItem, AccordionTrigger }

View file

@ -1,53 +0,0 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

View file

@ -1,83 +0,0 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
const buttonGroupVariants = cva(
"flex w-fit items-stretch *:focus-visible:z-10 *:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
{
variants: {
orientation: {
horizontal:
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
vertical:
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
},
},
defaultVariants: {
orientation: "horizontal",
},
}
)
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
)
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "div"
return (
<Comp
className={cn(
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function ButtonGroupSeparator({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
"bg-input relative m-0! self-stretch data-[orientation=vertical]:h-auto",
className
)}
{...props}
/>
)
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
}

View file

@ -1,19 +1,19 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import * as React from "react"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
@ -22,12 +22,13 @@ const buttonVariants = cva(
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
"icon-xl": "size-12",
},
},
defaultVariants: {
@ -39,23 +40,25 @@ const buttonVariants = cva(
function Button({
className,
variant,
size,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
export { Button }

View file

@ -1,216 +0,0 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View file

@ -1,24 +0,0 @@
import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';
import { forwardRef, useImperativeHandle, useRef } from 'react';
export interface CaptchaRef {
reset: () => void;
}
const Captcha = forwardRef<CaptchaRef, { onSuccess: (token: string) => void }>(
({ onSuccess }, ref) => {
const turnstileRef = useRef<TurnstileInstance>(null);
useImperativeHandle(ref, () => ({
reset: () => {
turnstileRef.current?.reset();
},
}));
return <Turnstile ref={turnstileRef} siteKey='0x4AAAAAACDEvU2-PUzwj3L0' onSuccess={onSuccess} />
}
);
Captcha.displayName = 'Captcha';
export default Captcha;

View file

@ -3,90 +3,85 @@ import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
return (
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
Card, CardContent, CardHeader, CardTitle
}

View file

@ -1,32 +0,0 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View file

@ -1,184 +0,0 @@
"use client"
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="**:[[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 **:[[cmdk-input]]:h-12 **:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground **:[[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View file

@ -1,252 +0,0 @@
"use client"
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function ContextMenu({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
)
}
function ContextMenuGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
)
}
function ContextMenuPortal({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
)
}
function ContextMenuSub({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
)
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
)
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
)
}
function ContextMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function ContextMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
)
}
function ContextMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
)
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
"text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8",
className
)}
{...props}
/>
)
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function ContextMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}

View file

@ -1,143 +1,155 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function Dialog({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
}

View file

@ -1,407 +0,0 @@
import { useOlmContext } from "@/contexts/olm-context";
import { useSocketContext } from "@/contexts/socket-context";
import { clearUnread, db, sendMessage } from "@/lib/db";
import { setActiveChannel } from "@/lib/notifications";
import { useLiveQuery } from "dexie-react-hooks";
import { KeyRound, SendIcon } from "lucide-react";
import moment from "moment";
import React, { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "../avatar";
import { Button } from "../button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../dialog";
import { Input } from "../input";
interface DMChannelContentProps {
userId: string
channelId: string
participantDetails: SiPher.ParticipantDetail[]
}
export default function DMChannelContent(
{
userId,
channelId,
participantDetails,
}: DMChannelContentProps
) {
const otherUser = useMemo(() => {
return participantDetails.find((p) => p.id !== userId);
}, [participantDetails, userId]);
const [olmSession, setOlmSession] = useState<Olm.Session | null>(null);
const [sessionError, setSessionError] = useState<string | null>(null);
const [messageInput, setMessageInput] = useState("");
const [messageLimit, setMessageLimit] = useState(50);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const { sendMessage: sendMessageToServer } = useSocketContext();
const { olmAccount, password, isReady, getSession } = useOlmContext();
const messagesEndRef = React.useRef<HTMLDivElement>(null);
const scrollContainerRef = React.useRef<HTMLDivElement>(null);
const prevScrollHeightRef = React.useRef<number>(0);
// Get total message count
const totalMessageCount = useLiveQuery(
() => db.messages.where("channelId").equals(channelId).count(),
[channelId]
) ?? 0;
// Get messages from the local database with pagination
const allMessages = useLiveQuery(
() => db.messages.where("channelId").equals(channelId).sortBy("timestamp"),
[channelId]
) ?? [];
// Take only the most recent messages based on limit
const messages = useMemo(() => {
return allMessages.slice(-messageLimit);
}, [allMessages, messageLimit]);
const hasMoreMessages = messages.length < totalMessageCount;
// Reset message limit when channel changes
useEffect(() => {
setMessageLimit(50);
}, [channelId]);
// Handle scroll to load more messages
const handleScroll = React.useCallback(async (e: React.UIEvent<HTMLDivElement>) => {
const target = e.currentTarget;
const scrollTop = target.scrollTop;
// If scrolled near the top (within 100px) and there are more messages
if (scrollTop < 100 && hasMoreMessages && !isLoadingMore) {
setIsLoadingMore(true);
// Save current scroll height
prevScrollHeightRef.current = target.scrollHeight;
// Load 50 more messages
await new Promise(resolve => setTimeout(resolve, 100)); // Small delay to avoid rapid firing
setMessageLimit(prev => prev + 50);
setIsLoadingMore(false);
}
}, [hasMoreMessages, isLoadingMore]);
// Preserve scroll position after loading more messages
useEffect(() => {
if (prevScrollHeightRef.current > 0 && scrollContainerRef.current) {
const newScrollHeight = scrollContainerRef.current.scrollHeight;
const scrollDiff = newScrollHeight - prevScrollHeightRef.current;
scrollContainerRef.current.scrollTop += scrollDiff;
prevScrollHeightRef.current = 0;
}
}, [messages.length]);
// Scroll to bottom on initial load / channel change (instant)
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "auto" });
}, [channelId]);
// Auto-scroll to bottom when new messages arrive (smooth)
useEffect(() => {
if (messages.length > 0 && scrollContainerRef.current) {
const container = scrollContainerRef.current;
const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 200;
// Only auto-scroll if user is near the bottom
if (isNearBottom) {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}
}, [allMessages.length]);
// Set active channel and clear unread count when viewing this channel
useEffect(() => {
// Mark this channel as active (prevents notifications)
setActiveChannel(channelId);
// Clear any existing unread count
clearUnread(channelId);
console.debug("[DMChannelContent] Set active channel and cleared unread:", channelId);
// Cleanup: unset active channel when leaving
return () => {
setActiveChannel(null);
console.debug("[DMChannelContent] Cleared active channel");
};
}, [channelId]);
// Guard: Check if otherUser exists
if (!otherUser) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<p className="text-muted-foreground">Loading participant information...</p>
</div>
</div>
);
}
// Get or create session when OLM is ready and we have the other user's account
useEffect(() => {
const loadSession = async () => {
console.log("[DMChannelContent] loadSession effect triggered", {
isReady,
hasOlmAccount: !!olmAccount,
hasOtherUser: !!otherUser,
hasOtherUserOlmAccount: !!otherUser?.olmAccount,
otherUserId: otherUser?.id
});
if (!isReady || !olmAccount || !otherUser || !otherUser.olmAccount) {
console.log("[DMChannelContent] Not ready to load session, skipping");
return;
}
setSessionError(null);
console.log("[DMChannelContent] Calling getSession for", otherUser.id);
try {
const session = await getSession(otherUser.id, otherUser.olmAccount);
console.log("[DMChannelContent] getSession returned:", !!session);
if (session) {
setOlmSession(session);
console.log("[DMChannelContent] Session set successfully");
} else {
console.error("[DMChannelContent] getSession returned null");
setSessionError("Failed to create encryption session");
}
} catch (err) {
console.error("[DMChannelContent] Failed to get session:", err);
setSessionError(err instanceof Error ? err.message : "Unknown error");
}
};
loadSession();
}, [isReady, olmAccount, otherUser, password, getSession])
// Check if OLM is ready
if (!isReady || !olmAccount) {
return <div>Loading encryption keys...</div>
}
// Get the other user's id key and OT keys from the server to be prepared for messaging
if (!otherUser.olmAccount) {
return (
<Dialog open={true} onOpenChange={() => { }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-accent/20">
<KeyRound className="h-8 w-8 text-accent-foreground" />
</div>
<DialogTitle className="text-2xl text-center">Encryption Setup Required</DialogTitle>
</DialogHeader>
<DialogDescription className="space-y-4 pt-2">
<div className="rounded-lg bg-card border border-border p-4">
<p className="text-sm text-card-foreground/90 leading-relaxed">
<span className="font-semibold text-card-foreground">{otherUser.name}</span> hasn't set up end-to-end encryption yet.
</p>
</div>
<div className="space-y-2 text-sm text-muted-foreground">
<p className="flex items-start gap-2">
<span className="text-accent-foreground/60 mt-0.5"></span>
<span>They need to log in and complete the encryption setup</span>
</p>
<p className="flex items-start gap-2">
<span className="text-accent-foreground/60 mt-0.5"></span>
<span>Once complete, you'll be able to send encrypted messages</span>
</p>
</div>
<p className="text-xs text-center text-muted-foreground/70 pt-2">
🔒 All messages are end-to-end encrypted for your privacy
</p>
</DialogDescription>
</DialogContent>
</Dialog>
)
}
// Show error if session creation failed
if (sessionError) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<p className="text-destructive">Failed to create encryption session</p>
<p className="text-sm text-muted-foreground">{sessionError}</p>
</div>
</div>
);
}
// Wait for session to be established
if (!olmSession) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
<p className="text-sm text-muted-foreground">Establishing secure connection...</p>
</div>
</div>
);
}
return (
<div className="flex flex-col flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-hidden">
<div
ref={scrollContainerRef}
className="h-full overflow-y-auto flex flex-col"
onScroll={handleScroll}
>
{/* Spacer to push messages to the bottom when there are few messages */}
<div className="flex-1 min-h-0" />
<div className="pt-2 md:pt-4">
{/* Load more indicator */}
{hasMoreMessages && (
<div className="flex justify-center py-4">
{isLoadingMore ? (
<div className="flex items-center gap-2 text-muted-foreground">
<div className="w-4 h-4 border-2 border-muted-foreground/30 border-t-muted-foreground rounded-full animate-spin" />
<span className="text-xs">Loading older messages...</span>
</div>
) : (
<button
onClick={() => {
setIsLoadingMore(true);
prevScrollHeightRef.current = scrollContainerRef.current?.scrollHeight ?? 0;
setTimeout(() => {
setMessageLimit(prev => prev + 50);
setIsLoadingMore(false);
}, 100);
}}
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-3 py-1 rounded-md hover:bg-muted/50 active:bg-muted/70"
>
Load more messages
</button>
)}
</div>
)}
{messages.map((msg, index) => {
const sender = participantDetails.find((p) => p.id === msg.fromUserId);
const selfDetail = participantDetails.find((p) => p.id === userId);
const isSelf = msg.fromUserId === userId;
const displayName = isSelf ? selfDetail?.displayUsername ?? selfDetail?.username ?? selfDetail?.name ?? "You" : (sender?.displayUsername ?? sender?.username ?? sender?.name ?? "Unknown");
const timestamp = moment(msg.timestamp);
const timeLabel = timestamp.isSame(moment(), "day") ? timestamp.format("h:mm A") : timestamp.format("MMM D, YYYY h:mm A");
const shortTimeLabel = timestamp.format("h:mm A")
// Check if this message is from the same user as the previous one within 5 minutes
const prevMsg = index > 0 ? messages[index - 1] : null;
const isGrouped = prevMsg &&
prevMsg.fromUserId === msg.fromUserId &&
msg.timestamp && prevMsg.timestamp &&
(msg.timestamp - prevMsg.timestamp) < 5 * 60 * 1000;
return (
<div
key={msg.id}
className="group relative px-2 md:px-4 py-0.5 hover:bg-muted/50 active:bg-muted/50 transition-colors duration-100"
>
{!isGrouped ? (
// Full message with avatar and header
<div className="flex gap-2 md:gap-4 mt-3 md:mt-[17px]">
<Avatar className="w-8 h-8 md:w-10 md:h-10 shrink-0 mt-0.5">
<AvatarImage src={sender?.image ?? undefined} alt={displayName} />
<AvatarFallback className="text-xs">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-baseline gap-2 leading-snug flex-wrap">
<span className="font-semibold text-sm md:text-[15px] text-foreground hover:underline cursor-pointer">
{displayName}
</span>
<span className="text-[10px] md:text-[11px] text-muted-foreground font-medium">
{timeLabel}
</span>
</div>
<div className="text-sm md:text-[15px] leading-5.5 text-foreground mt-0.5 wrap-break-word">
{msg.content}
</div>
</div>
</div>
) : (
// Compact message without avatar (grouped)
<div className="flex gap-2 md:gap-4 leading-5.5">
<div className="w-6 md:w-10 shrink-0 flex items-start justify-end pt-0.5">
<span className="text-[9px] text-transparent group-hover:text-muted-foreground transition-colors duration-100 font-light">
{shortTimeLabel}
</span>
</div>
<div className="flex-1 min-w-0 text-sm md:text-[15px] leading-5.5 text-foreground wrap-break-word">
{msg.content}
</div>
</div>
)}
</div>
);
})}
{/* Invisible element for auto-scrolling */}
<div ref={messagesEndRef} />
</div>
</div>
</div>
{/* Message input */}
<div className="flex items-center gap-2 shrink-0 px-2 md:px-4 pb-4 md:pb-6 pt-2">
<Input
className="h-10 md:h-11 rounded-lg bg-muted border-0 focus-visible:ring-0 focus-visible:ring-offset-0 px-3 md:px-4 text-sm md:text-[15px]"
placeholder={
otherUser.status === "offline" ?
"As of now, you cannot message offline users." :
`Message @${otherUser.username ?? otherUser.name}`
}
value={messageInput}
onChange={(e) => setMessageInput(e.target.value)}
disabled={otherUser.status === "offline"}
onKeyDown={async (e) => {
if (e.key === 'Enter' && !e.shiftKey && messageInput.trim() && password) {
e.preventDefault();
console.log("[DMChannelContent] Attempting to send message", {
hasOlmSession: !!olmSession,
hasPassword: !!password,
recipientId: otherUser.id,
recipientKeyVersion: otherUser.olmAccount?.keyVersion
});
try {
const messageId = await sendMessage({
channelId,
content: messageInput,
fromUserId: userId,
to: otherUser.id,
timestamp: Date.now(),
status: "sent",
}, olmSession, sendMessageToServer, {
userId,
recipientId: otherUser.id,
password,
recipientKeyVersion: otherUser.olmAccount?.keyVersion,
recipientIdentityKey: otherUser.olmAccount?.identityKey,
});
console.log("[DMChannelContent] Message sent successfully, ID:", messageId);
if (messageId) {
setMessageInput("");
}
} catch (error) {
console.error("[DMChannelContent] Failed to send message:", error);
toast.error("Failed to send message: " + (error instanceof Error ? error.message : "Unknown error"));
}
}
}}
/>
<Button className="flex md:hidden items-center justify-center h-10 md:h-11 w-10 md:w-11" variant="outline" size="icon">
<SendIcon className="size-4" />
</Button>
</div>
</div>
);
}

View file

@ -0,0 +1,247 @@
"use client"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import * as React from "react"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-inset:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
)
}
export {
DropdownMenu, DropdownMenuContent,
DropdownMenuItem, DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger
}

View file

@ -1,104 +0,0 @@
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
className
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-header"
className={cn(
"flex max-w-sm flex-col items-center gap-2 text-center",
className
)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
}
)
function EmptyMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("text-lg font-medium tracking-tight", className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<div
data-slot="empty-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-content"
className={cn(
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
className
)}
{...props}
/>
)
}
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
}

View file

@ -1,248 +1,244 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { useMemo } from "react"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className
)}
{...props}
/>
)
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col *:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"*:data-[slot=field-label]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col *:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto",
"@md/field-group:*:data-[slot=field-label]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col *:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"*:data-[slot=field-label]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col @md/field-group:flex-row @md/field-group:items-center *:w-full @md/field-group:*:w-auto [&>.sr-only]:w-auto",
"@md/field-group:*:data-[slot=field-label]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-4",
"has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm leading-normal font-normal group-has-data-[orientation=horizontal]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
return (
<p
data-slot="field-description"
className={cn(
"text-sm leading-normal font-normal text-muted-foreground group-has-data-[orientation=horizontal]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
Field, FieldContent, FieldDescription,
FieldError,
FieldGroup, FieldLabel, FieldLegend,
FieldSeparator,
FieldSet, FieldTitle
}

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