diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 4f9b6c02..aa657a94 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -54,3 +54,9 @@ Out-of-scope (unless chainable to significant impact): - Missing best-practice headers only - Self-XSS without escalation path - Rate-limit bypass with no practical abuse impact + +## Acknowledgements + +Thank you to everyone who has reported security issues responsibly. + +- **birb ([@parabirb](https://github.com/parabirb))**, whose audit of [Flare](https://github.com/FlintSH/Flare), the project Emberly was originally forked from, found issues that also affected Emberly: stored XSS through uploaded SVG and HTML files, unlimited file password guessing, and unthrottled OCR. Fixed in Emberly 3.2.1. diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 5e67f42c..5b2a2fc0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -13,6 +13,10 @@ jobs: dashboard: if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') runs-on: ubuntu-latest + env: + # Docker Hub is optional: set DOCKERHUB_USERNAME and DOCKERHUB_TOKEN secrets to publish there too + DOCKERHUB_ENABLED: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }} + DOCKERHUB_IMAGE: docker.io/${{ vars.DOCKERHUB_NAMESPACE || secrets.DOCKERHUB_USERNAME }}/emberly steps: - uses: actions/checkout@v6 @@ -25,10 +29,18 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - if: env.DOCKERHUB_ENABLED == 'true' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - id: meta uses: docker/metadata-action@v5 with: - images: ghcr.io/${{ github.repository_owner }}/emberly + images: | + ghcr.io/${{ github.repository_owner }}/emberly + ${{ env.DOCKERHUB_ENABLED == 'true' && env.DOCKERHUB_IMAGE || '' }} tags: | type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} diff --git a/.gitignore b/.gitignore index ed4eaaa1..11617f57 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,7 @@ Thumbs.db .idea *.traineddata .tmp/uploads + +# Generated by scripts/site-licenses.mjs +THIRD_PARTY_LICENSES.txt +apps/dashboard/public/licenses/ diff --git a/Dockerfile b/Dockerfile index 07134a0f..eccc4d89 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,6 +25,8 @@ FROM deps AS build COPY turbo.json ./ COPY packages packages COPY apps/dashboard apps/dashboard +COPY LICENSE THIRD_PARTY_NOTICES.md ./ +COPY scripts scripts ENV BUILD_STANDALONE=1 RUN bun run --cwd packages/db db:generate \ && bun run --cwd apps/dashboard build @@ -59,6 +61,8 @@ COPY --from=build --chown=emberly:emberly /repo/apps/dashboard/.next/standalone COPY --from=build --chown=emberly:emberly /repo/apps/dashboard/.next/static ./apps/dashboard/.next/static COPY --from=build --chown=emberly:emberly /repo/apps/dashboard/public ./apps/dashboard/public COPY --chmod=755 apps/dashboard/docker-entrypoint.sh /usr/local/bin/emberly-entrypoint +COPY LICENSE THIRD_PARTY_NOTICES.md ./ +COPY --from=build /repo/apps/dashboard/public/licenses/packages.txt ./THIRD_PARTY_LICENSES.txt USER emberly VOLUME ["/data"] diff --git a/README.md b/README.md index a8b9fb66..0983e50e 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ See [CONTRIBUTING.md](.github/CONTRIBUTING.md). Please report security issues pr - [Discord](https://discord.gg/36spBmzZVB) - [support@embrly.ca](mailto:support@embrly.ca) +## Acknowledgements + +Emberly started as a fork of [Flare](https://github.com/FlintSH/Flare) by Zachary Lowery ([@FlintSH](https://github.com/FlintSH)). Thank you to Zach and Flare's contributors for the foundation Emberly is built on. Portions derived from Flare remain under its MIT license, reproduced in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). + ## License Emberly is licensed under the [Elastic License 2.0](LICENSE). You can use, modify and self-host it, including for your business. You may not offer it to others as a hosted service, or get around its license keys. Releases before the switch remain available under the GNU AGPL v3. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..f6b09a48 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,57 @@ +# Third-party notices + +Emberly includes work from the projects below. Their licenses apply to the portions of Emberly derived from them. + +The Docker image also includes `THIRD_PARTY_LICENSES.txt`, generated at build time, with the license of every open-source package Emberly ships with. + +## Flare + +Emberly started as a fork of [Flare](https://github.com/FlintSH/Flare) by Zachary Lowery ([@FlintSH](https://github.com/FlintSH)). Portions derived from Flare remain under its MIT license: + +```text +MIT License + +Copyright (c) Zachary Lowery + +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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. +``` + +## shadcn/ui + +The components in `apps/dashboard/components/ui` are adapted from [shadcn/ui](https://github.com/shadcn-ui/ui): + +```text +MIT License + +Copyright (c) 2023 shadcn + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +``` + +## Inter + +Emberly bundles the [Inter](https://github.com/rsms/inter) typeface by Rasmus Andersson and the Inter Project Authors, licensed under the SIL Open Font License 1.1. The full license is included with the font files in `apps/dashboard/public/fonts/inter/OFL.txt`. + +## Font Awesome + +The Windows, Apple and Linux logos on the Downloads page are [Font Awesome Free](https://fontawesome.com) icons by Fonticons, Inc., used unmodified under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/). Full license: https://fontawesome.com/license/free. diff --git a/apps/dashboard/CHANGELOG.md b/apps/dashboard/CHANGELOG.md index 28e3252c..dc226dd6 100644 --- a/apps/dashboard/CHANGELOG.md +++ b/apps/dashboard/CHANGELOG.md @@ -10,6 +10,31 @@ The format is based on "Keep a Changelog" and follows [Semantic Versioning](http - **A Downloads page.** `/downloads` offers Flicker, Emberly's desktop app, with a button for the visitor's system (Windows, macOS or Linux) and every installer listed by platform, with sizes. The version, date and files come from the latest Flicker release on GitHub, cached for 10 minutes, and the last good copy is shown if GitHub is unavailable. The page also covers ShareX, Flameshot, Spectacle, scripts and the API, with setup guides. It's linked from the navbar, the footer and **Profile → Uploads**, and works on self-hosted instances too. +### Fixed + +- **Admin → Reports and Admin → Applications crashed when there was nothing to show**, with "Something went wrong" instead of the empty list. +- **Eight emails used a generic fallback layout**: role changed, account suspended and restored, API key created and revoked, backup codes generated and used, session revoked, and suspicious activity. Each now has its own wording and details, and links to the right settings page. +- **Files missing from storage returned an error instead of "not found".** Raw links and `/api/files` now return `404` when the stored object is gone. Other storage failures are logged with the file, its storage path and the storage provider's status and request ID, instead of `[object Object]`. With S3, a `403` usually means the object is missing and the access key can't list the bucket, or the key can't read it. + +### Changed + +- **File passwords must be at least 8 characters.** This applies to new passwords only; existing ones keep working until they're changed. +- **Credit to Flare.** Emberly began as a fork of [Flare](https://github.com/FlintSH/Flare) by Zachary Lowery. The README now says so, `LICENSE` points to Flare's MIT license in `THIRD_PARTY_NOTICES.md`, and the Docker image now includes both. +- **Open-source credits.** `THIRD_PARTY_NOTICES.md` now also credits shadcn/ui (whose components `components/ui` is built on), the Inter typeface, and the Font Awesome icons on the Downloads page, and Inter's license now ships with the font files. A new **Licenses** page (`/licenses`), linked from the footer, shows Emberly's own license, these notices, and the license of all 799 open-source packages Emberly ships with, with a search box. The list is generated on every build, and the Docker image also includes it as `THIRD_PARTY_LICENSES.txt`; run `bun run licenses` to generate it yourself. The About page has a new **Built on open source** section that credits Flare and links to it. +- **The Docker image can also be published to Docker Hub.** Set the `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN` repository secrets (and optionally a `DOCKERHUB_NAMESPACE` variable) and each release is pushed there as well as to GitHub Packages. + +### Security + +These issues were found by birb ([@parabirb](https://github.com/parabirb)) in an audit of Flare, the project Emberly was originally forked from, and also affected Emberly. Thank you. + +- **Uploaded SVG and HTML files could run scripts on the Emberly site.** Raw file links and thumbnails served them with the uploader's file type and no Content-Security-Policy, so opening one ran its JavaScript with the viewer's session. Every response that serves an uploaded file now sends `Content-Security-Policy: sandbox` and `X-Content-Type-Options: nosniff`, and thumbnails are only served for raster images. Related: [GHSA-4fr7-p4rm-r2f6](https://github.com/FlintSH/Flare/security/advisories/GHSA-4fr7-p4rm-r2f6). +- **File passwords could be guessed without limit.** After 10 wrong passwords for a file from one address in 15 minutes, that address gets `429` for the file, and after 100 wrong passwords in total the file stops accepting guesses for the rest of the window. A correct password is remembered for 10 minutes, so streaming a protected video no longer checks it on every request. Related: [GHSA-qxr9-m5ff-27rv](https://github.com/FlintSH/Flare/security/advisories/GHSA-qxr9-m5ff-27rv). +- **Anyone could start text extraction (OCR) repeatedly** on a public image, exhausting CPU and memory. On-demand OCR now runs one image at a time with at most 10 waiting (more get `503`), each account or address can start 20 per 10 minutes (then `429`), an image that failed isn't retried for 5 minutes, and failed images are only retried by their owner. Errors no longer include storage details. Related: [GHSA-7p5v-2m9m-3p9m](https://github.com/FlintSH/Flare/security/advisories/GHSA-7p5v-2m9m-3p9m). +- **Theme colors weren't validated** before being written into the page's styles. Colors and theme names must now be plain values, and anything else saved earlier is dropped when the page is rendered. This wasn't exploitable against other people in Emberly, since only superadmins set the site's colors and your own colors only apply to you. Related: [GHSA-jf87-vxjh-6gv2](https://github.com/FlintSH/Flare/security/advisories/GHSA-jf87-vxjh-6gv2). +- **Downloads of private and password-protected files** now send `Cache-Control: private, no-store`, so a CDN can't keep a copy. Raw links already did. Related: [GHSA-5gjg-xfq3-pp83](https://github.com/FlintSH/Flare/security/advisories/GHSA-5gjg-xfq3-pp83). + +After upgrading, purge `/*/*/raw`, `/api/files/*` and `/api/files/*/thumbnail` from any CDN or caching proxy, since public files were cached with the old headers. + --- ## [3.2.0] - 2026-10-24 diff --git a/apps/dashboard/app/(main)/[userUrlId]/[filename]/page.tsx b/apps/dashboard/app/(main)/[userUrlId]/[filename]/page.tsx index c061d859..345148d6 100644 --- a/apps/dashboard/app/(main)/[userUrlId]/[filename]/page.tsx +++ b/apps/dashboard/app/(main)/[userUrlId]/[filename]/page.tsx @@ -4,7 +4,6 @@ import { headers } from 'next/headers' import Link from 'next/link' import { notFound } from 'next/navigation' -import { compare } from 'bcryptjs' import { ShieldAlert } from 'lucide-react' import { getServerSession } from 'next-auth' @@ -26,6 +25,7 @@ import { } from '@/lib/embeds/metadata' import { queuePreview } from '@/lib/embeds/preview' import { findFileByUrlPath } from '@/lib/files/lookup' +import { checkFilePassword, clientAddress } from '@/lib/files/password-guard' import { formatFileSize } from '@/lib/utils' export const dynamic = 'force-dynamic' @@ -288,11 +288,12 @@ export default async function FilePage({ ) } - const isPasswordValid = await compare( + const passwordCheck = await checkFilePassword( + serializedFile.password, providedPassword, - serializedFile.password + clientAddress(await headers()) ) - if (!isPasswordValid) { + if (!passwordCheck.ok) { return (
@@ -307,10 +308,14 @@ export default async function FilePage({

- Incorrect Password + {passwordCheck.limited + ? 'Too many attempts' + : 'Incorrect Password'}

- The password you entered is incorrect + {passwordCheck.limited + ? `Too many wrong passwords. Try again in ${Math.ceil(passwordCheck.retryAfter / 60)} minutes.` + : 'The password you entered is incorrect'}

diff --git a/apps/dashboard/app/(main)/[userUrlId]/[filename]/player/route.ts b/apps/dashboard/app/(main)/[userUrlId]/[filename]/player/route.ts index 616ef1e2..c42aab40 100644 --- a/apps/dashboard/app/(main)/[userUrlId]/[filename]/player/route.ts +++ b/apps/dashboard/app/(main)/[userUrlId]/[filename]/player/route.ts @@ -20,7 +20,7 @@ export const dynamic = 'force-dynamic' */ export async function GET( request: NextRequest, - { params }: { params: Promise<{ userUrlId: string; filename: string }> }, + { params }: { params: Promise<{ userUrlId: string; filename: string }> } ) { const { userUrlId, filename } = await params const urlPath = `/${userUrlId}/${filename}` @@ -29,7 +29,13 @@ export async function GET( // Fetch file record (handles space→dash fallback automatically) const file = await findFileByUrlPath(userUrlId, filename, { - select: { name: true, mimeType: true, visibility: true, password: true, userId: true }, + select: { + name: true, + mimeType: true, + visibility: true, + password: true, + userId: true, + }, }) if (!file || !file.mimeType.startsWith('video/')) { @@ -37,8 +43,16 @@ export async function GET( } const session = await getServerSession(authOptions) - const deny = await checkFileAccess(file, { userId: (session?.user as { id?: string })?.id, providedPassword: password }) - if (deny) return new NextResponse(deny.status === 404 ? 'Forbidden' : 'Unauthorized', { status: deny.status }) + const deny = await checkFileAccess(file, { + userId: (session?.user as { id?: string })?.id, + providedPassword: password, + request, + }) + if (deny) + return new NextResponse( + deny.status === 404 ? 'Forbidden' : 'Unauthorized', + { status: deny.status } + ) const rawUrl = buildRawUrl(urlPath, password) diff --git a/apps/dashboard/app/(marketing)/about/page.tsx b/apps/dashboard/app/(marketing)/about/page.tsx index 32820b05..c03416ff 100644 --- a/apps/dashboard/app/(marketing)/about/page.tsx +++ b/apps/dashboard/app/(marketing)/about/page.tsx @@ -421,6 +421,39 @@ export default async function AboutPage() { )} + +
+
+

Built on open source

+

+ Emberly started as a fork of{' '} + + Flare + {' '} + by Zachary Lowery, and is built with Next.js, React, Prisma, + Radix, shadcn/ui, CodeMirror and Tesseract.js, along with + hundreds of other open-source projects. Thank you to everyone + who makes them. +

+
+ +
+
+ {/* CTA Section */}
diff --git a/apps/dashboard/app/(marketing)/licenses/page.tsx b/apps/dashboard/app/(marketing)/licenses/page.tsx new file mode 100644 index 00000000..bde49300 --- /dev/null +++ b/apps/dashboard/app/(marketing)/licenses/page.tsx @@ -0,0 +1,22 @@ +import { LicensesView } from '@/components/licenses/licenses-view' +import PageShell from '@/components/layout/PageShell' + +import { buildPageMetadata } from '@/lib/embeds/metadata' + +export const metadata = buildPageMetadata({ + title: 'Licenses', + description: + 'Emberly’s license, and the open-source software it’s built with.', +}) + +export default function LicensesPage() { + return ( + + + + ) +} diff --git a/apps/dashboard/app/(raw)/[userUrlId]/[filename]/direct/route.ts b/apps/dashboard/app/(raw)/[userUrlId]/[filename]/direct/route.ts index 7e1c60dd..dd2d7d66 100644 --- a/apps/dashboard/app/(raw)/[userUrlId]/[filename]/direct/route.ts +++ b/apps/dashboard/app/(raw)/[userUrlId]/[filename]/direct/route.ts @@ -30,6 +30,7 @@ export async function GET( const deny = await checkFileAccess(file, { userId: session?.user?.id, providedPassword, + request: req, }) if (deny) return deny diff --git a/apps/dashboard/app/(raw)/[userUrlId]/[filename]/raw/route.ts b/apps/dashboard/app/(raw)/[userUrlId]/[filename]/raw/route.ts index 6af693c1..267225cc 100644 --- a/apps/dashboard/app/(raw)/[userUrlId]/[filename]/raw/route.ts +++ b/apps/dashboard/app/(raw)/[userUrlId]/[filename]/raw/route.ts @@ -7,6 +7,10 @@ import { emptyResponse, serveStoredFile, } from '@/lib/files/serve' +import { loggers } from '@/lib/logger' +import { describeStorageError, isStorageNotFound } from '@/lib/storage/errors' + +const logger = loggers.files type Params = { params: Promise<{ userUrlId: string; filename: string }> } @@ -15,6 +19,7 @@ export async function OPTIONS() { } async function handle(req: Request, { params }: Params, head: boolean) { + let logContext: Record = {} try { const { userUrlId, filename } = await params const file = await findFileByUrlPath(userUrlId, filename) @@ -23,13 +28,22 @@ async function handle(req: Request, { params }: Params, head: boolean) { const deny = await denyFileAccess(req, file) if (deny) return deny + logContext = { + urlPath: `/${userUrlId}/${filename}`, + storagePath: file.path, + storageBucketId: file.storageBucketId, + } return await serveStoredFile(req, file, { head }) } catch (error) { - if (error instanceof Error && error.message.includes('NoSuchKey')) { + if (isStorageNotFound(error)) { + logger.warn('Stored file is missing', logContext) return emptyResponse(404) } - console.error('File serve error:', error) - return emptyResponse(500) + logger.error('File serve error', error, { + ...logContext, + storage: describeStorageError(error), + }) + return emptyResponse(502) } } diff --git a/apps/dashboard/app/api/files/[...path]/route.ts b/apps/dashboard/app/api/files/[...path]/route.ts index ae79f2c7..67df95e1 100644 --- a/apps/dashboard/app/api/files/[...path]/route.ts +++ b/apps/dashboard/app/api/files/[...path]/route.ts @@ -8,6 +8,8 @@ import { prisma } from '@emberly/db' import { loggers } from '@/lib/logger' import { getProviderForStoredFile } from '@/lib/storage' import { handleCORSPreflight, getCORSHeaders } from '@/lib/api/cors' +import { fileSecurityHeaders } from '@/lib/files/safe-headers' +import { describeStorageError, isStorageNotFound } from '@/lib/storage/errors' const logger = loggers.files @@ -27,6 +29,7 @@ export async function GET( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ): Promise { + let logContext: Record = {} try { const { path } = await params const session = await getServerSession(authOptions) @@ -71,9 +74,17 @@ export async function GET( const deny = await checkFileAccess(file, { userId: session?.user?.id, providedPassword, + request, }) if (deny) return deny + logContext = { + fileId: file.id, + urlPath, + storagePath: file.path, + storageBucketId: file.storageBucket?.id ?? null, + } + if (isDownloadRequest) { await prisma.file.update({ where: { id: file.id }, @@ -109,6 +120,7 @@ export async function GET( 'Content-Type': file.mimeType, 'Content-Disposition': `${shouldForceDownload ? 'attachment' : 'inline'}; filename=${encodeFilename(file.name)}`, 'Cache-Control': fileCacheControl(file), + ...fileSecurityHeaders(file.mimeType), ...getCORSHeaders(), } @@ -125,24 +137,23 @@ export async function GET( 'Accept-Ranges': 'bytes', 'Content-Length': size.toString(), 'Cache-Control': fileCacheControl(file), + ...fileSecurityHeaders(file.mimeType), ...getCORSHeaders(), } return new NextResponse(stream as unknown as ReadableStream, { headers }) } catch (error) { - const errAny = error as any - logger.error('File serve error:', error as Error) - try { - logger.error('File serve error details', { - name: errAny?.name, - code: errAny?.code || errAny?.name, - fault: errAny?.$fault, - awsMetadata: errAny?.$metadata, - message: errAny?.message, + if (isStorageNotFound(error)) { + logger.warn('Stored file is missing', logContext) + return new Response(null, { + status: 404, + headers: { 'Cache-Control': NO_STORE }, }) - } catch { - // ignore logging errors } + logger.error('File serve error', error, { + ...logContext, + storage: describeStorageError(error), + }) // A storage failure is not "not found"; never let it be cached as one return new Response(null, { diff --git a/apps/dashboard/app/api/files/[id]/download/route.ts b/apps/dashboard/app/api/files/[id]/download/route.ts index c2a11536..432c28aa 100644 --- a/apps/dashboard/app/api/files/[id]/download/route.ts +++ b/apps/dashboard/app/api/files/[id]/download/route.ts @@ -1,12 +1,14 @@ import { getAuthenticatedUser } from '@/lib/auth/api-auth' import { NextRequest, NextResponse } from 'next/server' -import { compare } from 'bcryptjs' +import { checkFilePassword, clientAddress } from '@/lib/files/password-guard' import { prisma } from '@emberly/db' import { loggers } from '@/lib/logger' import { getProviderForStoredFile } from '@/lib/storage' import { handleCORSPreflight, getCORSHeaders } from '@/lib/api/cors' +import { fileCacheControl } from '@/lib/files/access' +import { fileSecurityHeaders } from '@/lib/files/safe-headers' const logger = loggers.files @@ -66,9 +68,18 @@ export async function GET( return new Response(null, { status: 401 }) } - const isPasswordValid = await compare(providedPassword, file.password) - if (!isPasswordValid) { - return new Response(null, { status: 401 }) + const result = await checkFilePassword( + file.password, + providedPassword, + clientAddress(request.headers) + ) + if (!result.ok) { + return new Response(null, { + status: result.limited ? 429 : 401, + headers: result.limited + ? { 'Retry-After': String(result.retryAfter) } + : undefined, + }) } } @@ -99,6 +110,8 @@ export async function GET( 'Content-Length': chunkSize.toString(), 'Content-Type': file.mimeType, 'Content-Disposition': `attachment; filename=${encodeFilename(file.name)}`, + ...fileSecurityHeaders(file.mimeType), + 'Cache-Control': fileCacheControl(file), ...getCORSHeaders(), } @@ -112,6 +125,8 @@ export async function GET( const headers = { 'Content-Type': file.mimeType, 'Content-Disposition': `attachment; filename=${encodeFilename(file.name)}`, + ...fileSecurityHeaders(file.mimeType), + 'Cache-Control': fileCacheControl(file), 'Accept-Ranges': 'bytes', 'Content-Length': size.toString(), ...getCORSHeaders(), @@ -172,9 +187,18 @@ export async function POST( return new Response(null, { status: 401 }) } - const isPasswordValid = await compare(providedPassword, file.password) - if (!isPasswordValid) { - return new Response(null, { status: 401 }) + const result = await checkFilePassword( + file.password, + providedPassword, + clientAddress(request.headers) + ) + if (!result.ok) { + return new Response(null, { + status: result.limited ? 429 : 401, + headers: result.limited + ? { 'Retry-After': String(result.retryAfter) } + : undefined, + }) } } @@ -191,6 +215,8 @@ export async function POST( const headers = { 'Content-Type': file.mimeType, 'Content-Disposition': `attachment; filename=${encodeFilename(file.name)}`, + ...fileSecurityHeaders(file.mimeType), + 'Cache-Control': fileCacheControl(file), 'Accept-Ranges': 'bytes', 'Content-Length': size.toString(), } diff --git a/apps/dashboard/app/api/files/[id]/ocr/route.ts b/apps/dashboard/app/api/files/[id]/ocr/route.ts index 22614c38..b397f4c8 100644 --- a/apps/dashboard/app/api/files/[id]/ocr/route.ts +++ b/apps/dashboard/app/api/files/[id]/ocr/route.ts @@ -1,11 +1,12 @@ import { NextResponse } from 'next/server' import { getAuthenticatedUser } from '@/lib/auth/api-auth' -import { compare } from 'bcryptjs' +import { checkFilePassword, clientAddress } from '@/lib/files/password-guard' import { prisma } from '@emberly/db' import { loggers } from '@/lib/logger' -import { processImageOCR } from '@/lib/ocr' +import { rateLimiter } from '@/lib/cache/rate-limit' +import { runOnDemandOCR } from '@/lib/ocr/on-demand' const logger = loggers.files @@ -76,33 +77,69 @@ export async function GET( ) } - const isPasswordValid = await compare(providedPassword, file.password) - if (!isPasswordValid) { + const result = await checkFilePassword( + file.password, + providedPassword, + clientAddress(req.headers) + ) + if (!result.ok) { return NextResponse.json( { success: false, - error: 'Invalid password', + error: result.limited + ? 'Too many wrong passwords. Try again later.' + : 'Invalid password', }, - { status: 401 } + { + status: result.limited ? 429 : 401, + headers: result.limited + ? { 'Retry-After': String(result.retryAfter) } + : undefined, + } ) } } - if (!file.isOcrProcessed || (file.isOcrProcessed && !file.ocrText)) { - const result = await processImageOCR(file.path, id) + // Anyone can re-run an image that was never processed; only the owner can retry one that found nothing + const needsRun = !file.isOcrProcessed || (isOwner && !file.ocrText) - if (result.success && result.text) { - await prisma.file.update({ - where: { id }, - data: { - isOcrProcessed: true, - ocrText: result.text, - ocrConfidence: result.confidence, - }, - }) + if (needsRun) { + const limit = await rateLimiter.check( + `ocr:${user?.id ?? clientAddress(req.headers)}`, + 20, + 10 * 60 + ) + if (!limit.allowed) { + return NextResponse.json( + { success: false, error: 'Too many requests. Try again later.' }, + { + status: 429, + headers: { + 'Retry-After': String( + Math.max(1, Math.ceil((limit.resetAt - Date.now()) / 1000)) + ), + }, + } + ) } - return NextResponse.json(result) + const run = await runOnDemandOCR(file.path, id) + if (run.status === 'busy') { + return NextResponse.json( + { success: false, error: 'Text extraction is busy. Try again soon.' }, + { status: 503, headers: { 'Retry-After': '30' } } + ) + } + if (run.status === 'cooling-down') { + return NextResponse.json( + { + success: false, + error: 'Couldn’t read text from this image. Try again later.', + }, + { status: 503, headers: { 'Retry-After': '300' } } + ) + } + return NextResponse.json(run.result) } return NextResponse.json({ @@ -115,8 +152,7 @@ export async function GET( return NextResponse.json( { success: false, - error: - error instanceof Error ? error.message : 'Failed to fetch OCR text', + error: 'Failed to fetch OCR text', }, { status: 500 } ) diff --git a/apps/dashboard/app/api/files/[id]/route.ts b/apps/dashboard/app/api/files/[id]/route.ts index a890b520..874256ca 100644 --- a/apps/dashboard/app/api/files/[id]/route.ts +++ b/apps/dashboard/app/api/files/[id]/route.ts @@ -9,6 +9,7 @@ import { emitAuditEvent } from '@/lib/events/audit-helper' import { loggers } from '@/lib/logger' import { getProviderForStoredFile } from '@/lib/storage' import { removePreview } from '@/lib/embeds/preview' +import { filePasswordProblem } from '@/lib/files/password-guard' const logger = loggers.files @@ -64,6 +65,10 @@ export async function PATCH( } if (typeof password !== 'undefined') { + const problem = password ? filePasswordProblem(password) : null + if (problem) { + return NextResponse.json({ error: problem }, { status: 400 }) + } updates.password = password ? await hash(password, 10) : null } diff --git a/apps/dashboard/app/api/files/[id]/thumbnail/route.ts b/apps/dashboard/app/api/files/[id]/thumbnail/route.ts index 01d72d40..8438960b 100644 --- a/apps/dashboard/app/api/files/[id]/thumbnail/route.ts +++ b/apps/dashboard/app/api/files/[id]/thumbnail/route.ts @@ -8,6 +8,7 @@ import { getProviderForStoredFile } from '@/lib/storage' import { handleCORSPreflight, getCORSHeaders } from '@/lib/api/cors' import { readPreview } from '@/lib/embeds/preview' import { PREVIEW_TYPE, isPreviewable } from '@/lib/embeds/preview-rules' +import { fileSecurityHeaders, isRasterImage } from '@/lib/files/safe-headers' const logger = loggers.files @@ -98,12 +99,20 @@ export async function GET( headers: { 'Content-Type': PREVIEW_TYPE, 'Cache-Control': fileCacheControl(file), + ...fileSecurityHeaders(PREVIEW_TYPE), ...getCORSHeaders(), }, }) } } + // Only plain raster images are safe to send back as-is; SVG can carry scripts + if (!isRasterImage(file.mimeType)) { + const baseUrl = request.headers.get('host') || 'localhost:3000' + const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http' + return NextResponse.redirect(`${protocol}://${baseUrl}/banner.png`) + } + const storageProvider = await getProviderForStoredFile(file.storageBucketId) const fileStream = await storageProvider.getFileStream(file.path) @@ -111,6 +120,7 @@ export async function GET( headers: { 'Content-Type': file.mimeType, 'Cache-Control': fileCacheControl(file), + ...fileSecurityHeaders(file.mimeType), ...getCORSHeaders(), }, }) diff --git a/apps/dashboard/app/api/files/route.ts b/apps/dashboard/app/api/files/route.ts index 55970cc0..e4e26fcb 100644 --- a/apps/dashboard/app/api/files/route.ts +++ b/apps/dashboard/app/api/files/route.ts @@ -23,6 +23,7 @@ import { scheduleFileExpiration, } from '@/lib/events/handlers/file-expiry' import { getUniqueFilename } from '@/lib/files/filename' +import { filePasswordProblem } from '@/lib/files/password-guard' import { validateUploadRequest } from '@/lib/files/upload-validation' import { validateFileSecurityChecks, @@ -121,6 +122,11 @@ export async function POST(req: Request) { } } + const passwordProblem = password ? filePasswordProblem(password) : null + if (passwordProblem) { + return apiError(passwordProblem, HTTP_STATUS.BAD_REQUEST) + } + if (!result.success) { return apiError(result.error.issues[0].message, HTTP_STATUS.BAD_REQUEST) } diff --git a/apps/dashboard/app/api/profile/route.ts b/apps/dashboard/app/api/profile/route.ts index d96caf7a..dda8e9d5 100644 --- a/apps/dashboard/app/api/profile/route.ts +++ b/apps/dashboard/app/api/profile/route.ts @@ -15,6 +15,7 @@ import { recordPasswordHistory, } from '@/lib/security/password-reuse-checker' import { removePreview } from '@/lib/embeds/preview' +import { isSafeColors, isSafeThemeName } from '@/lib/theme/safe-colors' const logger = loggers.users @@ -173,8 +174,18 @@ export async function PUT(req: Request) { updateData.randomizeFileUrls = body.randomizeFileUrls if (typeof body.enableRichEmbeds === 'boolean') updateData.enableRichEmbeds = body.enableRichEmbeds - if (typeof body.theme === 'string') updateData.theme = body.theme - if (body.customColors) updateData.customColors = body.customColors + if (typeof body.theme === 'string') { + if (!isSafeThemeName(body.theme)) { + return apiError('Invalid theme', HTTP_STATUS.BAD_REQUEST) + } + updateData.theme = body.theme + } + if (body.customColors) { + if (!isSafeColors(body.customColors)) { + return apiError('Invalid theme colors', HTTP_STATUS.BAD_REQUEST) + } + updateData.customColors = body.customColors + } // theme: null clears the user's choice so they follow the system theme again if (body.theme === null) { updateData.theme = null diff --git a/apps/dashboard/app/api/users/[id]/files/[fileId]/route.ts b/apps/dashboard/app/api/users/[id]/files/[fileId]/route.ts index ff8129d9..74a4fb21 100644 --- a/apps/dashboard/app/api/users/[id]/files/[fileId]/route.ts +++ b/apps/dashboard/app/api/users/[id]/files/[fileId]/route.ts @@ -1,4 +1,6 @@ import { hash } from 'bcryptjs' + +import { filePasswordProblem } from '@/lib/files/password-guard' import { NextResponse } from 'next/server' import { getServerSession } from 'next-auth' @@ -88,6 +90,11 @@ export async function PATCH( const body = await request.json() const { visibility, password } = body + const passwordProblem = password ? filePasswordProblem(password) : null + if (passwordProblem) { + return NextResponse.json({ error: passwordProblem }, { status: 400 }) + } + const file = await prisma.file.update({ where: { id: fileId, diff --git a/apps/dashboard/components/dashboard/file-card/index.tsx b/apps/dashboard/components/dashboard/file-card/index.tsx index a33653d2..b83c9160 100644 --- a/apps/dashboard/components/dashboard/file-card/index.tsx +++ b/apps/dashboard/components/dashboard/file-card/index.tsx @@ -241,7 +241,10 @@ export function FileCard({ }, body: JSON.stringify({ password: password || null }), }) - if (!response.ok) throw new Error() + if (!response.ok) { + const data = await response.json().catch(() => null) + throw new Error(data?.error) + } toast({ title: password ? 'Password protection enabled' @@ -252,10 +255,10 @@ export function FileCard({ }) setIsPasswordDialogOpen(false) setFile((prev) => ({ ...prev, password: password || null })) - } catch { + } catch (error) { toast({ title: 'Failed to update password', - description: 'Please try again', + description: (error as Error).message || 'Please try again', variant: 'destructive', }) } @@ -546,7 +549,7 @@ export function FileCard({ type="password" value={password} onChange={(e) => setPassword(e.target.value)} - placeholder="Leave empty to remove protection" + placeholder="At least 8 characters, or empty to remove" />
diff --git a/apps/dashboard/components/dashboard/paste-form.tsx b/apps/dashboard/components/dashboard/paste-form.tsx index 45d9e19c..cca735a2 100644 --- a/apps/dashboard/components/dashboard/paste-form.tsx +++ b/apps/dashboard/components/dashboard/paste-form.tsx @@ -372,7 +372,7 @@ export function PasteForm() { autoComplete="new-password" data-1p-ignore data-lpignore="true" - placeholder="No password" + placeholder="None, or at least 8 characters" value={password} onChange={(e) => setPassword(e.target.value)} className="h-9 border-border/50 bg-background/50 pr-9" diff --git a/apps/dashboard/components/dashboard/user-list.tsx b/apps/dashboard/components/dashboard/user-list.tsx index 2d385b4d..02635d70 100644 --- a/apps/dashboard/components/dashboard/user-list.tsx +++ b/apps/dashboard/components/dashboard/user-list.tsx @@ -387,7 +387,7 @@ function FileSettingsDialog({ data-lpignore="true" value={password} onChange={(e) => setPassword(e.target.value)} - placeholder="Leave empty for no password" + placeholder="None, or at least 8 characters" />
diff --git a/apps/dashboard/components/file/upload-form.tsx b/apps/dashboard/components/file/upload-form.tsx index aed39afc..bc49bb01 100644 --- a/apps/dashboard/components/file/upload-form.tsx +++ b/apps/dashboard/components/file/upload-form.tsx @@ -411,7 +411,7 @@ export function UploadForm({ autoComplete="new-password" data-1p-ignore data-lpignore="true" - placeholder="No password" + placeholder="None, or at least 8 characters" value={password} onChange={(e) => setPassword(e.target.value)} className="h-9 border-border/50 bg-background/50 pr-9" diff --git a/apps/dashboard/components/layout/footer.tsx b/apps/dashboard/components/layout/footer.tsx index 16437ac1..4e9202e9 100644 --- a/apps/dashboard/components/layout/footer.tsx +++ b/apps/dashboard/components/layout/footer.tsx @@ -47,6 +47,7 @@ const COLUMNS: Array<{ title: string; links: FooterLink[] }> = [ { href: '/changelogs', label: 'Changelog' }, { href: '/discord', label: 'Community' }, { href: '/legal', label: 'Legal' }, + { href: '/licenses', label: 'Licenses' }, ], }, ] @@ -140,6 +141,13 @@ export function Footer() { ) : ( )} + · + + Licenses +

diff --git a/apps/dashboard/components/licenses/licenses-view.tsx b/apps/dashboard/components/licenses/licenses-view.tsx new file mode 100644 index 00000000..e997397f --- /dev/null +++ b/apps/dashboard/components/licenses/licenses-view.tsx @@ -0,0 +1,235 @@ +'use client' + +import { useEffect, useMemo, useState } from 'react' + +import { ChevronDown, ExternalLink, Search } from 'lucide-react' +import ReactMarkdown from 'react-markdown' +import remarkGfm from 'remark-gfm' + +import { Panel } from '@/components/layout/page-kit' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' + +const REPO = 'https://github.com/EmberlyOSS/Emberly/blob/master' +const RULE = '='.repeat(78) + +interface Group { + packages: string[] + text: string +} + +async function readText(path: string) { + const res = await fetch(path) + if (!res.ok) throw new Error(`${res.status}`) + return res.text() +} + +function parsePackages(text: string): Group[] { + return text + .split(RULE) + .slice(1) + .map((block) => { + const trimmed = block.replace(/^\n+/, '') + const split = trimmed.indexOf('\n\n') + return { + packages: trimmed.slice(0, split).split('\n').filter(Boolean), + text: trimmed.slice(split + 2).trim(), + } + }) +} + +function Missing({ file }: { file: string }) { + return ( +

+ This is added when Emberly is built.{' '} + + Read it on GitHub + + . +

+ ) +} + +export function LicensesView() { + const [license, setLicense] = useState(null) + const [notices, setNotices] = useState(null) + const [groups, setGroups] = useState(null) + const [showLicense, setShowLicense] = useState(false) + const [query, setQuery] = useState('') + + useEffect(() => { + readText('/licenses/LICENSE.txt').then(setLicense, () => setLicense(false)) + readText('/licenses/NOTICES.md').then( + (md) => setNotices(md.replace(/^# .*\n+/, '')), + () => setNotices(false) + ) + readText('/licenses/packages.txt').then( + (text) => setGroups(parsePackages(text)), + () => setGroups(false) + ) + }, []) + + const packageCount = groups + ? groups.reduce((n, g) => n + g.packages.length, 0) + : 0 + const shown = useMemo(() => { + if (!groups) return [] + const q = query.trim().toLowerCase() + return q + ? groups.filter((g) => + g.packages.some((p) => p.toLowerCase().includes(q)) + ) + : groups + }, [groups, query]) + + return ( +
+ +
+

+ You can use, modify and self-host Emberly, including for your + business. You may not offer it to others as a hosted service, or get + around its license keys. Portions derived from Flare remain under + the MIT License; see below. +

+ {license === false ? ( + + ) : ( + <> + + {showLicense && license && ( +
+                  {license}
+                
+ )} + + )} +
+
+ + + {notices === false ? ( + + ) : notices ? ( +
+ {notices} +
+ ) : ( +
+ )} + + + + + Plain text + + + + ) : undefined + } + flush={!!groups} + > + {groups === false ? ( + + ) : !groups ? ( +
+ ) : ( + <> +
+
+ + setQuery(e.target.value)} + placeholder={`Search ${packageCount} packages`} + aria-label="Search packages" + className="h-9 border-border/60 bg-background/50 pl-9" + /> +
+
+ {shown.length === 0 ? ( +

+ No packages match. +

+ ) : ( +
    + {shown.slice(0, 200).map((group, i) => ( +
  • +
    + + + {group.packages.slice(0, 3).map((p) => ( + + {p} + + ))} + {group.packages.length > 3 && ( + + and {group.packages.length - 3} more with the same + license + + )} + + + +
    + {group.packages.length > 3 && ( +

    + {group.packages.slice(3).join(' · ')} +

    + )} +
    +                          {group.text}
    +                        
    +
    +
    +
  • + ))} +
+ )} + {shown.length > 200 && ( +

+ Showing 200 of {shown.length} license groups. Search to find a + specific package. +

+ )} + + )} + +
+ ) +} diff --git a/apps/dashboard/components/theme/theme-initializer.tsx b/apps/dashboard/components/theme/theme-initializer.tsx index 3da6ed4b..d0be7fb3 100644 --- a/apps/dashboard/components/theme/theme-initializer.tsx +++ b/apps/dashboard/components/theme/theme-initializer.tsx @@ -1,5 +1,6 @@ import { getConfig } from '@/lib/config' import { generateHueColors, parseHueThemeId } from '@/lib/theme/hue' +import { safeColors } from '@/lib/theme/safe-colors' type ThemeInitializerProps = { userTheme?: string | null @@ -37,7 +38,7 @@ export async function ThemeInitializer({ colorsToUse = generateHueColors(hue) } - const cssVariables = Object.entries(colorsToUse) + const cssVariables = Object.entries(safeColors(colorsToUse)) .map(([key, value]) => { const cssKey = key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`) return `--${cssKey}: ${value};` diff --git a/apps/dashboard/lib/emails/index.ts b/apps/dashboard/lib/emails/index.ts index 94a42ffc..1a324cc1 100644 --- a/apps/dashboard/lib/emails/index.ts +++ b/apps/dashboard/lib/emails/index.ts @@ -144,6 +144,8 @@ export { VerificationCodeEmail } from './templates/verification-code' export { MagicLinkEmail } from './templates/magic-link' export { PasswordResetEmail } from './templates/password-reset' export { AccountChangeEmail } from './templates/account-change' +export { AccountNoticeEmail } from './templates/account-notice' +export { buildAccountNotice } from './notices' export { NewLoginEmail } from './templates/new-login' export { AdminBroadcastEmail } from './templates/admin-broadcast' export { PerkGainedEmail } from './templates/perk-gained' diff --git a/apps/dashboard/lib/emails/notices.ts b/apps/dashboard/lib/emails/notices.ts new file mode 100644 index 00000000..16298b09 --- /dev/null +++ b/apps/dashboard/lib/emails/notices.ts @@ -0,0 +1,237 @@ +import { humanize } from '@/lib/utils/humanize' + +import { formatEmailDate } from './components' +import type { AccountNoticeEmailProps } from './templates/account-notice' + +type Vars = Record + +const text = (value: unknown) => + typeof value === 'string' && value.trim() && value !== 'Unknown' + ? value.trim() + : undefined + +const when = (value: unknown) => + typeof value === 'string' || typeof value === 'number' + ? formatEmailDate(value) + : undefined + +function rows(...entries: Array<[string, string | undefined]>) { + return entries.filter((row): row is [string, string] => !!row[1]) +} + +const ROLE_RANK: Record = { + USER: 0, + MODERATOR: 1, + ADMIN: 2, + SUPERADMIN: 3, +} + +const REVOKED_BY: Record = { + user: 'You', + admin: 'An administrator', + system: 'Automatically', +} + +const SECURITY_REASON = + 'We email you about security changes to your account so you can spot anything you didn’t do.' +const ACCOUNT_REASON = 'We email you about important changes to your account.' + +/** + * Builds the account and security notices that share one layout. Returns null + * for templates that aren't notices. + */ +export function buildAccountNotice( + template: string, + v: Vars, + siteUrl: string +): AccountNoticeEmailProps | null { + const security = `${siteUrl}/me?tab=security` + const apiKeys = `${siteUrl}/me?tab=api` + + switch (template) { + case 'role-changed': { + const oldRole = String(v.oldRole ?? 'USER') + const newRole = String(v.newRole ?? 'USER') + const promoted = (ROLE_RANK[newRole] ?? 0) > (ROLE_RANK[oldRole] ?? 0) + return { + preview: `Your role is now ${humanize(newRole)}`, + heading: 'Your role has changed', + intro: `An administrator changed your account’s role from ${humanize(oldRole)} to ${humanize(newRole)}.`, + details: rows( + ['Previous role', humanize(oldRole)], + ['New role', humanize(newRole)], + ['Changed', when(v.changedAt)] + ), + callout: + promoted && (ROLE_RANK[newRole] ?? 0) >= ROLE_RANK.ADMIN + ? { + tone: 'info', + title: 'You can now open the admin area', + text: 'Your account can change other people’s accounts and the site’s settings, so keep it safe: use a strong password and turn on two-factor authentication.', + } + : undefined, + button: { label: 'Open your dashboard', href: `${siteUrl}/dashboard` }, + reason: ACCOUNT_REASON, + } + } + + case 'account-suspended': { + const until = v.isPermanent ? 'Until further notice' : when(v.expiresAt) + return { + preview: 'Your account has been suspended', + heading: 'Your account has been suspended', + intro: + 'An administrator suspended your account. While it’s suspended you can’t sign in, upload or share files.', + details: rows( + ['Reason', text(v.reason)], + ['Suspended until', until], + ['Suspended', when(v.suspendedAt)] + ), + callout: { + tone: 'info', + title: 'Think this is a mistake?', + text: 'Contact us and tell us why, and we’ll review the suspension.', + }, + button: text(v.appealUrl) + ? { label: 'Contact support', href: String(v.appealUrl) } + : undefined, + reason: ACCOUNT_REASON, + } + } + + case 'account-unsuspended': + return { + preview: 'Your account is active again', + heading: 'Your account has been restored', + intro: + 'Your account is active again. You can sign in and use it as normal.', + details: rows(['Restored', when(v.restoredAt)]), + button: { label: 'Sign in', href: `${siteUrl}/auth/login` }, + reason: ACCOUNT_REASON, + } + + case 'api-key-created': + return { + preview: `API key “${text(v.keyName) ?? 'Untitled'}” was created`, + heading: 'New API key created', + intro: 'An API key was just created for your account.', + details: rows( + ['Name', text(v.keyName)], + ['Permissions', text(v.scopes)], + [ + 'Expires', + v.expiresAt === 'Never' ? 'Never' : (when(v.expiresAt) ?? 'Never'), + ], + ['IP address', text(v.ip)], + ['Created', when(v.createdAt)] + ), + callout: { + tone: 'warning', + title: 'Didn’t create this key?', + text: 'Revoke it in your API settings and change your password straight away.', + }, + button: { label: 'Manage API keys', href: apiKeys }, + reason: SECURITY_REASON, + } + + case 'api-key-revoked': + return { + preview: `API key “${text(v.keyName) ?? 'Untitled'}” was revoked`, + heading: 'API key revoked', + intro: + 'An API key on your account was revoked. Anything still using it will stop working.', + details: rows( + ['Name', text(v.keyName)], + ['Revoked by', REVOKED_BY[String(v.revokedBy)]], + ['Reason', text(v.reason)], + ['Revoked', when(v.revokedAt)] + ), + button: { label: 'Manage API keys', href: apiKeys }, + reason: SECURITY_REASON, + } + + case 'backup-codes-generated': + return { + preview: 'New two-factor backup codes were created', + heading: 'New backup codes created', + intro: + 'New two-factor backup codes were created for your account. Your old codes no longer work.', + details: rows( + ['Codes', v.codesCount != null ? String(v.codesCount) : undefined], + ['Created', when(v.generatedAt)] + ), + callout: { + tone: 'warning', + title: 'Didn’t do this?', + text: 'Change your password and create new backup codes straight away.', + }, + button: { label: 'Security settings', href: security }, + reason: SECURITY_REASON, + } + + case 'backup-code-used': { + const left = Number(v.codesRemaining) + return { + preview: 'A backup code was used to sign in', + heading: 'A backup code was used to sign in', + intro: + 'Someone signed in to your account using one of your two-factor backup codes.', + details: rows( + ['Codes left', Number.isFinite(left) ? String(left) : undefined], + ['IP address', text(v.ip)], + ['When', when(v.usedAt)] + ), + callout: { + tone: 'danger', + title: 'Wasn’t you?', + text: 'Change your password and create new backup codes straight away.', + }, + button: { + label: + Number.isFinite(left) && left <= 2 + ? 'Create new backup codes' + : 'Security settings', + href: security, + }, + reason: SECURITY_REASON, + } + } + + case 'session-revoked': + return { + preview: 'A session was signed out of your account', + heading: 'A session was signed out', + intro: 'One of the sessions signed in to your account was signed out.', + details: rows( + ['Signed out by', REVOKED_BY[String(v.revokedBy)]], + ['Reason', text(v.reason)], + ['When', when(v.revokedAt)] + ), + button: { label: 'Review your devices', href: security }, + reason: SECURITY_REASON, + } + + case 'suspicious-activity': + return { + preview: 'We noticed unusual activity on your account', + heading: 'Unusual activity on your account', + intro: `We noticed something unusual on your account: ${humanize(String(v.activityType ?? 'unusual activity')).toLowerCase()}.`, + details: rows( + ['Details', text(v.details)], + ['Location', text(v.location)], + ['IP address', text(v.ip)], + ['When', when(v.detectedAt)] + ), + callout: { + tone: 'danger', + title: 'Wasn’t you?', + text: 'Change your password, sign out your other devices and turn on two-factor authentication.', + }, + button: { label: 'Review your security', href: security }, + reason: SECURITY_REASON, + } + + default: + return null + } +} diff --git a/apps/dashboard/lib/emails/templates/account-notice.tsx b/apps/dashboard/lib/emails/templates/account-notice.tsx new file mode 100644 index 00000000..9b4f15bb --- /dev/null +++ b/apps/dashboard/lib/emails/templates/account-notice.tsx @@ -0,0 +1,47 @@ +import React from 'react' + +import { + EmailButton, + EmailCallout, + EmailDetails, + EmailHeading, + EmailLayout, + EmailText, + type Tone, +} from '../components' + +export interface AccountNoticeEmailProps { + preview: string + heading: string + intro: string + details?: Array<[string, string]> + callout?: { tone: Tone; title: string; text: string } + button?: { label: string; href: string } + /** Why the reader got this email, shown in the footer */ + reason: string +} + +/** Short account and security notices: what happened, the details, and what to do. */ +export function AccountNoticeEmail({ + preview, + heading, + intro, + details, + callout, + button, + reason, +}: AccountNoticeEmailProps) { + return ( + + {heading} + {intro} + {details && details.length > 0 && } + {callout && ( + + {callout.text} + + )} + {button && {button.label}} + + ) +} diff --git a/apps/dashboard/lib/events/handlers/email.ts b/apps/dashboard/lib/events/handlers/email.ts index 11516913..0d84b9f2 100644 --- a/apps/dashboard/lib/events/handlers/email.ts +++ b/apps/dashboard/lib/events/handlers/email.ts @@ -8,6 +8,8 @@ import { BasicEmail, AdminBroadcastEmail, AccountChangeEmail, + AccountNoticeEmail, + buildAccountNotice, PerkGainedEmail, QuotaReachedEmail, StorageAssignedEmail, @@ -684,6 +686,18 @@ async function sendEmail(options: { return { messageId: result.id || `email-${Date.now()}` } } + const notice = buildAccountNotice(template, variables, appUrl()) + if (notice) { + const result = await sendTemplateEmail({ + to, + subject, + template: AccountNoticeEmail, + props: notice, + skipTracking: true, + }) + return { messageId: result.id || `email-${Date.now()}` } + } + logger.warn('Unknown email template, using fallback', { template }) const result = await sendTemplateEmail({ to, diff --git a/apps/dashboard/lib/files/access.ts b/apps/dashboard/lib/files/access.ts index 156b7a26..b5e42016 100644 --- a/apps/dashboard/lib/files/access.ts +++ b/apps/dashboard/lib/files/access.ts @@ -13,7 +13,7 @@ * in extra headers (e.g. CORS headers for the raw route) by wrapping the * result, but usually the bare Response is all that's needed. */ -import { compare } from 'bcryptjs' +import { checkFilePassword, clientAddress } from '@/lib/files/password-guard' // --------------------------------------------------------------------------- // Types @@ -32,6 +32,8 @@ interface AccessOptions { providedPassword?: string | null /** HTTP status to use for "not found / private" responses (default 404). */ privateStatus?: number + /** The incoming request, so wrong password guesses are limited per address. */ + request?: Request } // --------------------------------------------------------------------------- @@ -72,7 +74,7 @@ export function fileCacheControl( export async function checkFileAccess( file: FileAccessFields, - { userId, providedPassword, privateStatus = 404 }: AccessOptions + { userId, providedPassword, privateStatus = 404, request }: AccessOptions ): Promise { const isOwner = !!userId && userId === file.userId @@ -92,11 +94,20 @@ export async function checkFileAccess( headers: { 'Cache-Control': NO_STORE }, }) } - const valid = await compare(providedPassword, file.password) - if (!valid) { + const result = await checkFilePassword( + file.password, + providedPassword, + clientAddress(request?.headers) + ) + if (!result.ok) { return new Response(null, { - status: 401, - headers: { 'Cache-Control': NO_STORE }, + status: result.limited ? 429 : 401, + headers: { + 'Cache-Control': NO_STORE, + ...(result.limited + ? { 'Retry-After': String(result.retryAfter) } + : {}), + }, }) } } diff --git a/apps/dashboard/lib/files/password-guard.ts b/apps/dashboard/lib/files/password-guard.ts new file mode 100644 index 00000000..b8460cfb --- /dev/null +++ b/apps/dashboard/lib/files/password-guard.ts @@ -0,0 +1,116 @@ +import { compare } from 'bcryptjs' +import { createHash } from 'crypto' + +const WINDOW_MS = 15 * 60 * 1000 +const PER_CLIENT_LIMIT = 10 +const PER_FILE_LIMIT = 100 +const REMEMBER_MS = 10 * 60 * 1000 + +export const MIN_FILE_PASSWORD_LENGTH = 8 +export const MAX_FILE_PASSWORD_BYTES = 72 + +interface Attempts { + failures: number + pending: number + resetAt: number +} + +const attempts = new Map() +const accepted = new Map() + +const digest = (...parts: string[]) => + createHash('sha256').update(parts.join('\0')).digest('hex') + +function sweep(now: number) { + if (attempts.size + accepted.size < 10_000) return + for (const [key, value] of attempts) + if (value.resetAt <= now && value.pending === 0) attempts.delete(key) + for (const [key, expires] of accepted) + if (expires <= now) accepted.delete(key) +} + +function bucket(key: string, now: number): Attempts { + let entry = attempts.get(key) + if (!entry || (entry.resetAt <= now && entry.pending === 0)) { + entry = { failures: 0, pending: 0, resetAt: now + WINDOW_MS } + attempts.set(key, entry) + } + return entry +} + +/** The caller's address, as reported by Cloudflare or the reverse proxy. */ +export function clientAddress(headers?: Headers | null): string { + if (!headers) return 'unknown' + return ( + headers.get('cf-connecting-ip') || + headers.get('x-forwarded-for')?.split(',')[0]?.trim() || + headers.get('x-real-ip') || + 'unknown' + ) +} + +/** Why a new file password can't be used, or null when it's fine. */ +export function filePasswordProblem(password: string): string | null { + if (password.length < MIN_FILE_PASSWORD_LENGTH) + return `File passwords must be at least ${MIN_FILE_PASSWORD_LENGTH} characters` + if (Buffer.byteLength(password, 'utf8') > MAX_FILE_PASSWORD_BYTES) + return 'File password is too long' + return null +} + +export type FilePasswordResult = + | { ok: true } + | { ok: false; limited: false } + | { ok: false; limited: true; retryAfter: number } + +/** + * Checks a password for a protected file. Wrong guesses are limited per + * address and per file, and a correct password is remembered briefly so + * streaming a video doesn't run bcrypt for every range request. + */ +export async function checkFilePassword( + storedHash: string, + password: string, + client: string +): Promise { + const now = Date.now() + sweep(now) + + const rememberKey = digest(storedHash, client, password) + if ((accepted.get(rememberKey) ?? 0) > now) return { ok: true } + + const file = digest(storedHash) + const perClient = bucket(`${file}:${client}`, now) + const perFile = bucket(file, now) + + for (const [entry, limit] of [ + [perClient, PER_CLIENT_LIMIT], + [perFile, PER_FILE_LIMIT], + ] as const) { + if (entry.failures + entry.pending >= limit) { + return { + ok: false, + limited: true, + retryAfter: Math.max(1, Math.ceil((entry.resetAt - now) / 1000)), + } + } + } + + perClient.pending++ + perFile.pending++ + let valid = false + try { + valid = await compare(password, storedHash) + } finally { + perClient.pending-- + perFile.pending-- + } + + if (valid) { + accepted.set(rememberKey, now + REMEMBER_MS) + return { ok: true } + } + perClient.failures++ + perFile.failures++ + return { ok: false, limited: false } +} diff --git a/apps/dashboard/lib/files/safe-headers.ts b/apps/dashboard/lib/files/safe-headers.ts new file mode 100644 index 00000000..e067d25a --- /dev/null +++ b/apps/dashboard/lib/files/safe-headers.ts @@ -0,0 +1,36 @@ +import { baseMime } from '@/lib/embeds/preview-rules' + +const RASTER_IMAGES = new Set([ + 'image/png', + 'image/jpeg', + 'image/jpg', + 'image/gif', + 'image/webp', + 'image/avif', + 'image/bmp', + 'image/tiff', + 'image/x-icon', + 'image/vnd.microsoft.icon', +]) + +/** Image types that can't contain markup or scripts, unlike SVG. */ +export function isRasterImage(mimeType: string) { + return RASTER_IMAGES.has(baseMime(mimeType)) +} + +/** + * Headers for any response that serves an uploaded file's bytes. The stored + * type comes from the uploader, so an SVG or HTML file opened directly would + * otherwise run its scripts on our origin with the viewer's session. + */ +export function fileSecurityHeaders(mimeType: string): Record { + const headers: Record = { + 'X-Content-Type-Options': 'nosniff', + } + // Browsers refuse to show PDFs in a sandboxed document, and their PDF + // viewers never run a PDF's scripts on the site's origin + if (baseMime(mimeType) !== 'application/pdf') { + headers['Content-Security-Policy'] = 'sandbox' + } + return headers +} diff --git a/apps/dashboard/lib/files/serve.ts b/apps/dashboard/lib/files/serve.ts index 4d849587..c355786a 100644 --- a/apps/dashboard/lib/files/serve.ts +++ b/apps/dashboard/lib/files/serve.ts @@ -5,6 +5,7 @@ import { Readable } from 'stream' import { authOptions } from '@/lib/auth' import { NO_STORE, checkFileAccess, fileCacheControl } from '@/lib/files/access' +import { fileSecurityHeaders } from '@/lib/files/safe-headers' import { getProviderForStoredFile } from '@/lib/storage' export const CORS_HEADERS = { @@ -52,6 +53,7 @@ export async function denyFileAccess( const deny = await checkFileAccess(file, { userId: session?.user?.id, providedPassword: new URL(req.url).searchParams.get('password'), + request: req, }) return deny ? emptyResponse(deny.status) : null } @@ -117,6 +119,7 @@ export async function serveStoredFile( 'Content-Type': file.mimeType, 'Content-Disposition': `inline; filename=${encodeFilename(file.name)}`, 'Cache-Control': fileCacheControl(file), + ...fileSecurityHeaders(file.mimeType), } const range = head ? null : req.headers.get('range') diff --git a/apps/dashboard/lib/files/service.ts b/apps/dashboard/lib/files/service.ts index fe67f55c..224ce57b 100644 --- a/apps/dashboard/lib/files/service.ts +++ b/apps/dashboard/lib/files/service.ts @@ -16,7 +16,12 @@ import { prisma } from '@emberly/db' import { loggers } from '@/lib/logger' import { getProviderForStoredFile } from '@/lib/storage' import { File, Prisma, User } from '@emberly/db' -import { compare, hash } from 'bcryptjs' +import { hash } from 'bcryptjs' + +import { + checkFilePassword, + filePasswordProblem, +} from '@/lib/files/password-guard' import { removePreview } from '@/lib/embeds/preview' const logger = loggers.files @@ -37,7 +42,8 @@ export interface FileAccessResult { export async function verifyFileAccess( fileId: string, userId: string | null, - password?: string + password?: string, + client = 'unknown' ): Promise { const file = await prisma.file.findUnique({ where: { id: fileId }, @@ -63,9 +69,13 @@ export async function verifyFileAccess( return { allowed: false, reason: 'Password required', file } } - const passwordMatches = await compare(password, file.password) - if (!passwordMatches) { - return { allowed: false, reason: 'Invalid password', file } + const result = await checkFilePassword(file.password, password, client) + if (!result.ok) { + return { + allowed: false, + reason: result.limited ? 'Too many attempts' : 'Invalid password', + file, + } } } @@ -111,6 +121,8 @@ export async function updateFileMetadata( if (updates.password !== undefined) { if (updates.password) { + const problem = filePasswordProblem(updates.password) + if (problem) throw new Error(problem) updateData.password = await hash(updates.password, 10) } else { updateData.password = null diff --git a/apps/dashboard/lib/files/upload-validation.ts b/apps/dashboard/lib/files/upload-validation.ts index f1bd9acf..0c075315 100644 --- a/apps/dashboard/lib/files/upload-validation.ts +++ b/apps/dashboard/lib/files/upload-validation.ts @@ -88,10 +88,7 @@ export async function validateCustomDomain( // Check if domain is the main app domain - no validation needed const appDomain = trimTrailingSlashes( - (appUrl()).replace( - /^https?:\/\//, - '' - ) + appUrl().replace(/^https?:\/\//, '') ).toLowerCase() if ( @@ -161,10 +158,7 @@ export async function validateSquadCustomDomain( ).toLowerCase() const appDomain = trimTrailingSlashes( - (appUrl()).replace( - /^https?:\/\//, - '' - ) + appUrl().replace(/^https?:\/\//, '') ).toLowerCase() if ( diff --git a/apps/dashboard/lib/ocr/on-demand.ts b/apps/dashboard/lib/ocr/on-demand.ts new file mode 100644 index 00000000..1d49eb63 --- /dev/null +++ b/apps/dashboard/lib/ocr/on-demand.ts @@ -0,0 +1,62 @@ +import { processImageOCRTask, type OCRResult } from './processor' + +const MAX_WAITING = 10 +const FAILURE_COOLDOWN_MS = 5 * 60 * 1000 + +let chain: Promise = Promise.resolve() +let waiting = 0 +const inFlight = new Map>() +const failedAt = new Map() + +export type OnDemandResult = + | { status: 'done'; result: OCRResult } + | { status: 'busy' } + | { status: 'cooling-down' } + +/** + * Runs OCR for a viewer's "Extract text" request. Recognitions run one at a + * time per process, repeat requests for the same image share one run, and an + * image that just failed isn't retried for a few minutes. + */ +export async function runOnDemandOCR( + filePath: string, + fileId: string +): Promise { + const existing = inFlight.get(fileId) + if (existing) return { status: 'done', result: await existing } + + const failed = failedAt.get(fileId) + if (failed && Date.now() - failed < FAILURE_COOLDOWN_MS) { + return { status: 'cooling-down' } + } + + if (waiting >= MAX_WAITING) return { status: 'busy' } + + waiting++ + const run = chain + .catch(() => {}) + .then(() => processImageOCRTask({ filePath, fileId })) + .catch(() => ({ success: false }) as OCRResult) + .finally(() => { + waiting-- + inFlight.delete(fileId) + }) + chain = run + inFlight.set(fileId, run) + + const result = await run + if (result.success) failedAt.delete(fileId) + else failedAt.set(fileId, Date.now()) + if (failedAt.size > 1000) { + const cutoff = Date.now() - FAILURE_COOLDOWN_MS + for (const [id, at] of failedAt) if (at < cutoff) failedAt.delete(id) + } + + // Storage errors can include internal paths, so callers only see a generic message + return { + status: 'done', + result: result.success + ? result + : { success: false, error: 'Couldn’t read text from this image' }, + } +} diff --git a/apps/dashboard/lib/storage/errors.ts b/apps/dashboard/lib/storage/errors.ts new file mode 100644 index 00000000..5f76be6c --- /dev/null +++ b/apps/dashboard/lib/storage/errors.ts @@ -0,0 +1,37 @@ +interface StorageErrorShape { + name?: string + code?: string + Code?: string + message?: string + $fault?: string + $metadata?: { httpStatusCode?: number; requestId?: string } +} + +/** The parts of a storage error worth logging, without dumping the whole SDK object. */ +export function describeStorageError(error: unknown) { + const e = (error ?? {}) as StorageErrorShape + const status = e.$metadata?.httpStatusCode + return { + code: e.Code ?? e.code ?? e.name, + status, + requestId: e.$metadata?.requestId, + message: e.message, + // S3 answers 403 rather than 404 for a missing object when the key can't list the bucket, + // and HEAD responses carry no body, so the SDK can only report "UnknownError" + hint: + status === 403 + ? 'Access denied: the object may be missing, or the storage key may lack read access to it' + : undefined, + } +} + +export function isStorageNotFound(error: unknown) { + const { code, status } = describeStorageError(error) + return ( + status === 404 || + code === 'NoSuchKey' || + code === 'NotFound' || + code === 'ENOENT' || + (error instanceof Error && error.message.includes('NoSuchKey')) + ) +} diff --git a/apps/dashboard/lib/theme/safe-colors.ts b/apps/dashboard/lib/theme/safe-colors.ts new file mode 100644 index 00000000..8f3de869 --- /dev/null +++ b/apps/dashboard/lib/theme/safe-colors.ts @@ -0,0 +1,34 @@ +const COLOR_KEY = /^[a-zA-Z][a-zA-Z0-9-]{0,47}$/ +// HSL triplets, hex and rgb()/hsl() values, and named colors; nothing that can close a ' }) + ).toBe(false) + expect( + safeColors({ primary: '24 95% 53%', evil: '}