Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e696b1cbb | ||
|
|
e54fbc36ef | ||
|
|
651bc0cb86 | ||
|
|
feb36fc501 | ||
|
|
ce14c6b713 | ||
|
|
d87b93819b | ||
|
|
73c06b864a | ||
|
|
a3abf7c73e | ||
|
|
6e85a7686d | ||
|
|
2046e45601 | ||
|
|
105ffc9f17 | ||
|
|
4fa60ea7b9 | ||
|
|
e87bdb221e | ||
|
|
aa72b4b38b | ||
|
|
aac1725c25 | ||
|
|
880f3cd958 | ||
|
|
1149989d07 | ||
|
|
ed435c5e13 | ||
|
|
c190dd9ea6 | ||
|
|
d4da322031 | ||
|
|
eca8533d70 | ||
|
|
5770b2f88e | ||
|
|
8901a3c82c | ||
|
|
3460d54fce | ||
|
|
f63efc6d88 | ||
|
|
bc52f0a608 | ||
|
|
84d19556fc | ||
|
|
f3fe2335d4 | ||
|
|
fe5960f803 | ||
|
|
70b06db192 | ||
|
|
7fdb3ee61c | ||
|
|
ad397b80d0 | ||
|
|
714b4691e9 | ||
|
|
ca0e51192a | ||
|
|
75264ee9f4 | ||
|
|
2a55f50d87 | ||
|
|
b2fd5d548d | ||
|
|
c9ad84f523 | ||
|
|
25906612f6 | ||
|
|
928907dc9d | ||
|
|
9fe64e0928 | ||
|
|
60784386ab | ||
|
|
a4118b92a9 | ||
|
|
11cf7428eb | ||
|
|
1872dac8b4 | ||
|
|
4050f1362e | ||
|
|
f94a813d79 | ||
|
|
cdf9136866 | ||
|
|
4abc8ec202 | ||
|
|
ca54653a11 | ||
|
|
c91d0e53ca | ||
|
|
ee0cd7dcbd | ||
|
|
a4e1abfaae | ||
|
|
d25e20733e | ||
|
|
ca785f5648 | ||
|
|
91757752b8 | ||
|
|
bb2c5e200c | ||
|
|
8474b8eb02 | ||
|
|
e81f825ab8 | ||
|
|
3d50a264ed | ||
|
|
522e016a29 | ||
|
|
cf6e52bcc5 | ||
|
|
3a8f528693 | ||
|
|
ed22579bed | ||
|
|
7ee3ffbfc9 | ||
|
|
53e7a97c44 | ||
|
|
e7ecb9789b | ||
|
|
3c5ccfb787 | ||
|
|
1f745b6e59 | ||
|
|
a9f94ce806 | ||
|
|
dbcdd1b7cd | ||
|
|
c89d064eb8 | ||
|
|
9c0bd7abb9 | ||
|
|
f25ed8bc5d | ||
|
|
9490b8d25a | ||
|
|
b840bffeba | ||
|
|
5075374abe | ||
|
|
0008b8ce0c | ||
|
|
1dd8a3b28a | ||
|
|
9a5eaed00b | ||
|
|
785fafcaf9 | ||
|
|
ca59c19fa4 | ||
|
|
e059ca1554 | ||
|
|
86eb821780 | ||
|
|
e589428315 | ||
|
|
d18bbb7064 | ||
|
|
cb58a51bab | ||
|
|
98ea7eefa9 | ||
|
|
44cff7e718 | ||
|
|
fa702eb8b1 |
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
Palette - self-hosted pastebin with paste cans
|
Palette - self-hosted pastebin
|
||||||
Copyright (C) 2026 poslop
|
Copyright (C) 2026 poslop
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Palette
|
# Palette
|
||||||
|
|
||||||
Palette is a fast, self-hosted pastebin. One Go binary, a SQLite database, and
|
Palette is a fast, self-hosted pastebin. One Go binary, a SQLite database, and
|
||||||
a web UI for sharing text and small files
|
a web UI for sharing text and small files.
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> <table><tr><td>
|
> <table><tr><td>
|
||||||
@@ -10,22 +10,27 @@ a web UI for sharing text and small files
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Multiple files in one paste
|
- Text pastes
|
||||||
|
- File attachments (one file per paste, up to 25 MB)
|
||||||
- Password protected pastes
|
- Password protected pastes
|
||||||
- Expir after a specified time
|
- Expire after a specified time
|
||||||
- Burn after a number of views
|
- Burn after a number of views
|
||||||
- Custom URLs
|
- Custom URLs
|
||||||
- Syntax highlighting with language auto-detection (go-enry)
|
- Syntax highlighting with language auto-detection (go-enry)
|
||||||
- Local cookie based submission history
|
- Public paste listing with search, sort and pagination
|
||||||
- Cookie based settings
|
- Cookie based saved pastes and settings
|
||||||
- Themes!
|
- Five base themes (midnight, smooth, pastel-lavender, pastel-peach, pastel-cloud), each with a dark and light variant
|
||||||
|
- Dark mode toggle in the topbar and settings, with a configurable default
|
||||||
|
- Polished code viewer: line-number gutter sized to the widest number and pinned during horizontal scroll, optional line wrap, jump-to-top/bottom buttons, and theme-aware scrollbars
|
||||||
|
|
||||||
## Screenshots
|
## Screenshots
|
||||||
|
|
||||||
| | |
|
| | |
|
||||||
|---|---|
|
|---|---|
|
||||||
|  |  |
|
|  |  |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Get Started
|
## Get Started
|
||||||
|
|
||||||
@@ -61,12 +66,13 @@ go build -o palette ./cmd/palette
|
|||||||
| `PALETTE_ADDR` | `:8080` | Listen address |
|
| `PALETTE_ADDR` | `:8080` | Listen address |
|
||||||
| `PALETTE_DB` | `palette.db` | SQLite database path |
|
| `PALETTE_DB` | `palette.db` | SQLite database path |
|
||||||
| `PALETTE_MAX_TEXT` | `5242880` | Max paste size in bytes (5 MB) |
|
| `PALETTE_MAX_TEXT` | `5242880` | Max paste size in bytes (5 MB) |
|
||||||
| `PALETTE_MAX_ITEM` | `26214400` | Max can item size in bytes (25 MB) |
|
| `PALETTE_MAX_ITEM` | `26214400` | Max file attachment / multipart size in bytes (25 MB) |
|
||||||
| `PALETTE_ADMIN_KEY` | generated | Admin key; if unset a 32-char hex key is generated and persisted to `<db-dir>/admin-key` (0600) |
|
| `PALETTE_ADMIN_KEY` | generated | Admin key; if unset a 32-char hex key is generated and persisted to `<db-dir>/admin-key` (0600) |
|
||||||
| `PALETTE_DEFAULT_DARK` | dark on | Default dark mode for new visitors. Set `false`, `0`, or `off` to default to light mode. Visitors who toggle dark mode keep their choice in their browser. |
|
| `PALETTE_DEFAULT_DARK` | dark on | Default dark mode for new visitors. Set `false`, `0`, or `off` to default to light mode. Visitors who toggle dark mode keep their choice in their browser. |
|
||||||
|
| `PALETTE_UNLOCK_SECRET` | random per start | HMAC secret for password-unlock cookies. Set a fixed value to keep unlock sessions across restarts or across replicas. |
|
||||||
|
|
||||||
An `/admin` page exists for runtime settings, protected by a key set at
|
An `/admin` page exists for runtime settings, protected by a key set at
|
||||||
install (`PALETTE_ADMIN_KEY` env var) and resettable locally — see
|
install (`PALETTE_ADMIN_KEY` env var) and resettable locally. See
|
||||||
[API](https://git.archfox.org/poslop/palette/wiki/API) and the [design docs](https://git.archfox.org/poslop/palette/wiki/Home) in the wiki for details.
|
[API](https://git.archfox.org/poslop/palette/wiki/API) and the [design docs](https://git.archfox.org/poslop/palette/wiki/Home) in the wiki for details.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
@@ -95,4 +101,4 @@ data loss, or legal issues arising from use of the software. You use it
|
|||||||
at your own risk.
|
at your own risk.
|
||||||
|
|
||||||
If you run a modified version of Palette as a network service, the AGPL
|
If you run a modified version of Palette as a network service, the AGPL
|
||||||
requires you to offer your modified source code to its users.
|
requires you to offer your modified source code to its users.
|
||||||
+7
-1
@@ -32,10 +32,16 @@ services:
|
|||||||
# Default: 5242880 (5 MiB).
|
# Default: 5242880 (5 MiB).
|
||||||
# PALETTE_MAX_TEXT: "5242880"
|
# PALETTE_MAX_TEXT: "5242880"
|
||||||
|
|
||||||
# Max size in bytes of a single can item (file/text inside a can).
|
# Max size in bytes for multipart request parsing (paste file
|
||||||
|
# attachments are capped at 25 MB).
|
||||||
# Default: 26214400 (25 MiB).
|
# Default: 26214400 (25 MiB).
|
||||||
# PALETTE_MAX_ITEM: "26214400"
|
# PALETTE_MAX_ITEM: "26214400"
|
||||||
|
|
||||||
|
# Default dark mode for new visitors. Unset = dark on; set to "false",
|
||||||
|
# "0" or "off" to default to light mode. Visitors who toggle dark mode
|
||||||
|
# keep their choice in their browser.
|
||||||
|
# PALETTE_DEFAULT_DARK: "false"
|
||||||
|
|
||||||
# HMAC secret for password-unlock cookies. Default: random per start,
|
# HMAC secret for password-unlock cookies. Default: random per start,
|
||||||
# which logs out every unlocked browser session on restart. Set a fixed
|
# which logs out every unlocked browser session on restart. Set a fixed
|
||||||
# secret (any random string) to keep unlock sessions across restarts,
|
# secret (any random string) to keep unlock sessions across restarts,
|
||||||
|
|||||||
+256
@@ -0,0 +1,256 @@
|
|||||||
|
# Palette API
|
||||||
|
|
||||||
|
Palette's REST API lives under `/api` on the same port that serves the web UI. All request and response bodies are JSON unless noted otherwise. This document describes the API as implemented in `internal/api`.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
### Base URL
|
||||||
|
|
||||||
|
The server listens on the address set by `PALETTE_ADDR` (default `:8080`). In production palette runs behind a reverse proxy, so API URLs are relative to the site root, for example:
|
||||||
|
|
||||||
|
```
|
||||||
|
https://paste.example.com/api/pastes
|
||||||
|
```
|
||||||
|
|
||||||
|
The examples below use `http://localhost:8080` as a placeholder.
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
There is no user account system. Access control works through three mechanisms:
|
||||||
|
|
||||||
|
- Viewer cookie. Every request gets an anonymous, random viewer id in an HttpOnly `vwr` cookie. This cookie identifies the browser that created a paste, and authorizes browser-scoped actions such as `GET /api/mine` and creator-only deletion.
|
||||||
|
- Deletion token. Creating a paste returns a one-time `deletion_token`. Sending it in the `Authorization` header (Bearer or Token prefix, or the bare value) authorizes deletion of that paste. The token is deliberately not accepted as a URL query parameter, because query strings leak into access logs and browser history.
|
||||||
|
- Admin key. The admin settings endpoints require an install-time key sent in the `X-Admin-Key` header. The key comes from `PALETTE_ADMIN_KEY` or is generated and persisted server-side at first start.
|
||||||
|
|
||||||
|
Password-protected pastes are unlocked with the `X-Paste-Password` request header (or the browser unlock flow on the web pages). Password checks are rate limited per IP and per paste.
|
||||||
|
|
||||||
|
### Rate limiting
|
||||||
|
|
||||||
|
Rate limits are token buckets keyed by client IP (the rightmost `X-Forwarded-For` entry, then `X-Real-Ip`, then the remote address). Current limits:
|
||||||
|
|
||||||
|
| Scope | Limit | Refill |
|
||||||
|
|---|---|---|
|
||||||
|
| Paste create | 5 burst (admin tunable) | 60 per minute (admin tunable) |
|
||||||
|
| Language guess | 5 burst | 1 per second |
|
||||||
|
| Password unlock | 5 burst, per IP and paste | 5 per minute |
|
||||||
|
| Admin key check | 5 burst, per IP | 5 per minute |
|
||||||
|
|
||||||
|
Exceeding a limit returns `429` with a `Retry-After` header and the error code `rate_limited`. Create and guess responses include `X-RateLimit-Limit` and `X-RateLimit-Burst` headers.
|
||||||
|
|
||||||
|
### Size limits
|
||||||
|
|
||||||
|
- Paste content: `PALETTE_MAX_TEXT` (default 5 MB), admin tunable. Larger content is rejected with `413`.
|
||||||
|
- Attached files: 25 MB per file, one file per paste.
|
||||||
|
- The request body itself is capped server side; oversized bodies fail with `413` before handlers run.
|
||||||
|
|
||||||
|
### Error format
|
||||||
|
|
||||||
|
Errors are JSON with a human-readable `error` message and, for create/validation failures, a machine-readable `code`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"error": "slug already taken", "code": "slug_taken"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Known codes: `content_empty`, `content_too_large`, `slug_invalid`, `slug_taken`, `slug_reserved`, `expiry_invalid`, `invalid_visibility`, `one_file_only`, `file_too_large`, `rate_limited`, `invalid_request`. Unknown codes should be treated as a generic failure.
|
||||||
|
|
||||||
|
## Endpoint reference
|
||||||
|
|
||||||
|
### Pastes
|
||||||
|
|
||||||
|
#### POST /api/pastes
|
||||||
|
|
||||||
|
Create a paste. Rate limited.
|
||||||
|
|
||||||
|
Two body formats:
|
||||||
|
|
||||||
|
1. `application/json` with these fields:
|
||||||
|
|
||||||
|
| Field | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `content` | string | required; non-whitespace; up to the content cap |
|
||||||
|
| `title` | string | optional, trimmed, truncated to 200 chars |
|
||||||
|
| `language` | string | optional, max 40 chars, `^[a-zA-Z0-9+#-]{1,40}$` |
|
||||||
|
| `custom_slug` | string | optional custom URL slug |
|
||||||
|
| `password` | string | optional; hash stored server side |
|
||||||
|
| `expires_in` | string | Go duration (`90m`, `6h`, `168h`); 1 minute to 1 year |
|
||||||
|
| `burn_after_read` | bool | convenience for a single-read budget |
|
||||||
|
| `burn_after_reads` | int | number of reads the paste survives (min 1) |
|
||||||
|
| `visibility` | string | `public` or `unlisted`; default `public` |
|
||||||
|
| `public` | bool | alias for `visibility`; takes precedence when both are sent |
|
||||||
|
|
||||||
|
2. `multipart/form-data` with the same fields as form values plus a `file` part. A paste is either text or one file; if both are sent the file wins and the text is ignored. The MIME type is sniffed from the file content, never from client headers.
|
||||||
|
|
||||||
|
If the admin has set a default expiry, pastes created without `expires_in` inherit it.
|
||||||
|
|
||||||
|
Response `201`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "ab12cd34",
|
||||||
|
"deletion_token": "one-time token",
|
||||||
|
"url": "/ab12cd34",
|
||||||
|
"raw_url": "/raw/ab12cd34",
|
||||||
|
"api_url": "/api/pastes/ab12cd34",
|
||||||
|
"expires_at": 1735689600,
|
||||||
|
"created_at": 1735603200,
|
||||||
|
"rate_limit": {"create_per_sec": 1, "burst": 5}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With a multipart file, an extra `attachment` object is returned: `id`, `filename`, `mime`, `size`, `sha256`, `url` (`/f/{aid}/{filename}`).
|
||||||
|
|
||||||
|
The deletion token is also set as a short-lived `tok_{id}` cookie for the creating browser.
|
||||||
|
|
||||||
|
Errors: `400` invalid JSON or validation (codes `content_empty`, `slug_invalid`, `slug_taken`, `slug_reserved`, `expiry_invalid`, `one_file_only`), `413` (`content_too_large`, `file_too_large`), `429` rate limited.
|
||||||
|
|
||||||
|
#### GET /api/pastes/{id}
|
||||||
|
|
||||||
|
Fetch a paste's JSON representation. For password-protected pastes send `X-Paste-Password`; wrong or missing passwords return `401` and count against the unlock rate limit.
|
||||||
|
|
||||||
|
Response `200`: `id`, `content`, `content_type`, `language`, `title`, `created_at`, `view_count`, `visibility`, and `reads_remaining` (number or `null` when no read budget is set).
|
||||||
|
|
||||||
|
Errors: `404` not found, expired, or burned out; `401` password required; `429` too many unlock attempts.
|
||||||
|
|
||||||
|
#### DELETE /api/pastes/{id}
|
||||||
|
|
||||||
|
Soft delete a paste. Requires either the deletion token in the `Authorization` header or the creating browser's `vwr` cookie.
|
||||||
|
|
||||||
|
Response `200`: `{"status": "soft-deleted"}`.
|
||||||
|
|
||||||
|
Errors: `403` deletion token required, `404` not found.
|
||||||
|
|
||||||
|
#### DELETE /api/pastes/{id}/redeem
|
||||||
|
|
||||||
|
Hard delete immediately using the one-time deletion token in the `Authorization` header. The paste row is removed entirely instead of waiting for the sweeper.
|
||||||
|
|
||||||
|
Response `200`: `{"status": "deleted"}`.
|
||||||
|
|
||||||
|
Errors: `400` token required, `403` invalid token, `404` not found.
|
||||||
|
|
||||||
|
#### GET /api/mine
|
||||||
|
|
||||||
|
List pastes created from this browser, via the `vwr` cookie. Query parameters: `limit` (default 50, max 100), `offset`.
|
||||||
|
|
||||||
|
Response `200`: `{"total": n, "limit": l, "offset": o, "items": [...]}` with each item carrying `id`, `title`, `language`, `created_at`, `view_count`, `size`, `custom_slug`, `visibility`.
|
||||||
|
|
||||||
|
#### GET /api/public
|
||||||
|
|
||||||
|
List public pastes. Query parameters: `limit` (default 25, max 100), `offset`. Same shape as `/api/mine`; items include `custom_slug`.
|
||||||
|
|
||||||
|
### Files and raw content
|
||||||
|
|
||||||
|
#### GET /raw/{id}
|
||||||
|
|
||||||
|
Paste content served verbatim. Content types outside a safe fixed set (plain text, markdown, JSON, PDF, common images, octet-stream) are served as `text/plain` with `nosniff`. Raw reads count against a burn-after-read budget, with the same per-viewer dedupe window as page views (15 minutes by default, admin tunable). Password-protected pastes are not available raw (`401`).
|
||||||
|
|
||||||
|
Errors: `401` password required, `404` not found, expired, or burned.
|
||||||
|
|
||||||
|
#### GET /f/{aid}/{filename}
|
||||||
|
|
||||||
|
Download a file attachment. The filename path segment is decorative; lookups key on the attachment id. Files are served with the server-sniffed MIME type, `nosniff`, and a safe `Content-Disposition`; only images and PDFs render inline, everything else downloads. Attachments inherit the paste lifecycle: expired or burned pastes make their attachments disappear.
|
||||||
|
|
||||||
|
Errors: `404` attachment or paste not found.
|
||||||
|
|
||||||
|
### Language detection
|
||||||
|
|
||||||
|
#### POST /api/guess-language
|
||||||
|
|
||||||
|
Body: `{"content": "package main"}`. Rate limited like create.
|
||||||
|
|
||||||
|
Response `200`: `{"language": "go"}`. The result is a best-effort guess and may be `""`.
|
||||||
|
|
||||||
|
Errors: `400` invalid JSON body, `429` rate limited.
|
||||||
|
|
||||||
|
### Admin
|
||||||
|
|
||||||
|
#### GET /admin/api/settings and POST /admin/api/settings
|
||||||
|
|
||||||
|
Read or update runtime settings. Requires the `X-Admin-Key` header; wrong keys return `401` and all admin key checks are rate limited to 5 per minute per IP. The admin key is never accepted as a query parameter.
|
||||||
|
|
||||||
|
Settings object (POST accepts the full object and persists it):
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `rate_limit_burst` | 5 | paste-create token bucket burst |
|
||||||
|
| `rate_limit_per_minute` | 60 | paste-create refill rate |
|
||||||
|
| `max_content_bytes` | 5242880 | paste content cap |
|
||||||
|
| `default_expiry` | `""` | expiry applied to pastes created without one |
|
||||||
|
| `custom_slug_reservation_days` | 30 | how long a released slug stays reserved |
|
||||||
|
| `burn_viewer_window_minutes` | 15 | per-viewer dedupe window for burn reads |
|
||||||
|
|
||||||
|
Errors: `400` invalid JSON or validation (all numeric settings must be positive, `default_expiry` must be a duration between 1 minute and 1 year or empty), `401` unauthorized, `429` rate limited.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Create a text paste:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8080/api/pastes \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"content": "print(hello)",
|
||||||
|
"title": "my snippet",
|
||||||
|
"language": "python",
|
||||||
|
"expires_in": "168h",
|
||||||
|
"visibility": "public"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "ab12cd34",
|
||||||
|
"deletion_token": "TOKEN",
|
||||||
|
"url": "/ab12cd34",
|
||||||
|
"raw_url": "/raw/ab12cd34",
|
||||||
|
"api_url": "/api/pastes/ab12cd34",
|
||||||
|
"expires_at": 1735689600,
|
||||||
|
"created_at": 1735603200,
|
||||||
|
"rate_limit": {"create_per_sec": 1, "burst": 5}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Save the `deletion_token`; it is shown once and authorizes deletion.
|
||||||
|
|
||||||
|
Create a file paste:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8080/api/pastes \
|
||||||
|
-F "title=quarterly report" \
|
||||||
|
-F "file=@report.pdf"
|
||||||
|
```
|
||||||
|
|
||||||
|
Fetch a paste:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8080/api/pastes/ab12cd34
|
||||||
|
|
||||||
|
# password-protected paste (header only; query parameters are not accepted):
|
||||||
|
curl -H "X-Paste-Password: secret" http://localhost:8080/api/pastes/ab12cd34
|
||||||
|
```
|
||||||
|
|
||||||
|
Fetch raw content:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8080/raw/ab12cd34
|
||||||
|
```
|
||||||
|
|
||||||
|
Soft delete (paste becomes unavailable but is recoverable during the grace period):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X DELETE -H "Authorization: Bearer TOKEN" http://localhost:8080/api/pastes/ab12cd34
|
||||||
|
```
|
||||||
|
|
||||||
|
Hard delete immediately (row removed):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X DELETE -H "Authorization: Bearer TOKEN" http://localhost:8080/api/pastes/ab12cd34/redeem
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deletion and expiry behavior
|
||||||
|
|
||||||
|
- Expired pastes are soft-deleted by a background sweeper that runs every minute.
|
||||||
|
- Soft-deleted pastes are hard-deleted after a 7-day grace period.
|
||||||
|
- The deletion token allows immediate hard delete via the redeem endpoint.
|
||||||
|
- Burn-after-read pastes are soft-deleted once the read budget is exhausted. A read is counted once per unique viewer within the dedupe window (15 minutes by default); the same viewer returning inside the window does not consume another read.
|
||||||
@@ -306,3 +306,64 @@ func TestMultipartPasswordFieldAccepted(t *testing.T) {
|
|||||||
t.Fatalf("paste should require password, got %d", rec2.Code)
|
t.Fatalf("paste should require password, got %d", rec2.Code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #281: /raw/{id} must stream the attachment blob for ALL attachment mimes,
|
||||||
|
// not just raster images (the old isImageMime gate left non-image
|
||||||
|
// attachments serving an empty body from row.Content).
|
||||||
|
func TestRawStreamsNonImageAttachment(t *testing.T) {
|
||||||
|
s := testServer(t)
|
||||||
|
h := s.routes()
|
||||||
|
|
||||||
|
body := []byte("hello, this is a plain text attachment body")
|
||||||
|
rec, resp := multipartCreate(t, h, "notes.txt", body, nil)
|
||||||
|
if rec.Code != 201 {
|
||||||
|
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if resp["attachment"] == nil {
|
||||||
|
t.Fatalf("no attachment in response: %v", resp)
|
||||||
|
}
|
||||||
|
id, _ := resp["id"].(string)
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/raw/"+id, nil)
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != 200 {
|
||||||
|
t.Fatalf("raw: %d %s", rec2.Code, rec2.Body.String())
|
||||||
|
}
|
||||||
|
if got := rec2.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" {
|
||||||
|
t.Fatalf("Content-Type = %q", got)
|
||||||
|
}
|
||||||
|
if got := rec2.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||||
|
t.Fatalf("nosniff = %q", got)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(rec2.Body.Bytes(), body) {
|
||||||
|
t.Fatalf("raw bytes differ: got %d bytes want %d", rec2.Body.Len(), len(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// #281: active-content attachment types still get forced to text/plain on
|
||||||
|
// /raw, same rule as the /f/ serving path (#34).
|
||||||
|
func TestRawHtmlAttachmentServesAsPlainText(t *testing.T) {
|
||||||
|
s := testServer(t)
|
||||||
|
h := s.routes()
|
||||||
|
|
||||||
|
html := []byte("<html><body><script>alert(1)</script></body></html>")
|
||||||
|
rec, resp := multipartCreate(t, h, "page.html", html, nil)
|
||||||
|
if rec.Code != 201 {
|
||||||
|
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
id, _ := resp["id"].(string)
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/raw/"+id, nil)
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != 200 {
|
||||||
|
t.Fatalf("raw: %d %s", rec2.Code, rec2.Body.String())
|
||||||
|
}
|
||||||
|
if got := rec2.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" {
|
||||||
|
t.Fatalf("Content-Type = %q", got)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(rec2.Body.Bytes(), html) {
|
||||||
|
t.Fatal("raw bytes differ from upload")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"palette/internal/store"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
|
|
||||||
"palette/internal/web"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CreateCan makes a can with N items (multipart form).
|
|
||||||
// Fields: title, description, visibility, expires_in, password, files (one or more), or json_items for text items.
|
|
||||||
func (a *apiServer) handleCreateCan(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := r.ParseMultipartForm(a.cfg.MaxItemBytes); err != nil {
|
|
||||||
writeErr(w, 400, "multipart form required")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
title := r.FormValue("title")
|
|
||||||
visibility := r.FormValue("visibility")
|
|
||||||
if visibility == "" {
|
|
||||||
visibility = "public"
|
|
||||||
}
|
|
||||||
if visibility != "public" && visibility != "unlisted" {
|
|
||||||
writeErrCode(w, 400, "invalid_visibility", "visibility must be public or unlisted")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expiresIn := r.FormValue("expires_in")
|
|
||||||
password := r.FormValue("password")
|
|
||||||
customSlug := r.FormValue("custom_slug")
|
|
||||||
|
|
||||||
var expiresAt *int64
|
|
||||||
now := time.Now().Unix()
|
|
||||||
if expiresIn != "" {
|
|
||||||
d, err := time.ParseDuration(expiresIn)
|
|
||||||
if err != nil {
|
|
||||||
writeErrCode(w, 400, "expiry_invalid", "invalid expires_in")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// #60/#48: clamp at the API boundary like the pastes API does -
|
|
||||||
// reject zero/negative and durations past the 1-year UI cap.
|
|
||||||
if !store.ValidExpiry(d) {
|
|
||||||
writeErrCode(w, 400, "expiry_invalid", "expires_in must be between 1 minute and 1 year")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := now + int64(d.Seconds())
|
|
||||||
expiresAt = &t
|
|
||||||
}
|
|
||||||
var pwHash *string
|
|
||||||
if password != "" {
|
|
||||||
h, err := store.Argon2IDHash(password)
|
|
||||||
if err != nil {
|
|
||||||
writeErr(w, 500, "hash error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pwHash = &h
|
|
||||||
}
|
|
||||||
|
|
||||||
canID := store.GenSlug(8)
|
|
||||||
var slugPtr *string
|
|
||||||
if customSlug != "" {
|
|
||||||
slugPtr = &customSlug
|
|
||||||
}
|
|
||||||
err := a.store.CreateCan(canID, title, r.FormValue("description"), visibility, pwHash, now, expiresAt, slugPtr)
|
|
||||||
if err != nil {
|
|
||||||
switch err {
|
|
||||||
case store.ErrSlugTaken, store.ErrInvalidSlug, store.ErrReservedSlug:
|
|
||||||
writeErrCode(w, 409, createErrCode(err), err.Error())
|
|
||||||
default:
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if slugPtr != nil {
|
|
||||||
canID = customSlug // #4: custom slug becomes the can id
|
|
||||||
}
|
|
||||||
// #4: remember the creating browser so /mine and viewer-scoped delete work
|
|
||||||
a.store.Exec(`UPDATE paste_cans SET viewer_id=? WHERE id=?`, currentViewerID(r), canID)
|
|
||||||
|
|
||||||
// text items passed as JSON array: [{"title":"notes.txt","content":"..."}]
|
|
||||||
itemCount := 0
|
|
||||||
if itemsJSON := r.FormValue("json_items"); itemsJSON != "" {
|
|
||||||
var items []map[string]string
|
|
||||||
if err := json.Unmarshal([]byte(itemsJSON), &items); err != nil {
|
|
||||||
writeErr(w, 400, "invalid json_items")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, it := range items {
|
|
||||||
content := it["content"]
|
|
||||||
if int64(len(content)) > a.cfg.MaxItemBytes {
|
|
||||||
writeErr(w, 413, fmt.Sprintf("item %q exceeds max", it["title"]))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
lang := it["language"]
|
|
||||||
if err := a.store.InsertCanItem(canID, it["title"], content, "text/plain", &lang, nil, nil, now); err != nil {
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
itemCount++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// uploaded files
|
|
||||||
if r.MultipartForm != nil {
|
|
||||||
for _, headers := range r.MultipartForm.File {
|
|
||||||
for _, fh := range headers {
|
|
||||||
f, err := fh.Open()
|
|
||||||
if err != nil {
|
|
||||||
writeErr(w, 400, "cannot read uploaded file")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
content, err := io.ReadAll(f)
|
|
||||||
f.Close()
|
|
||||||
if err != nil {
|
|
||||||
writeErr(w, 400, "cannot read uploaded file")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if int64(len(content)) > a.cfg.MaxItemBytes {
|
|
||||||
writeErr(w, 413, fmt.Sprintf("file %q exceeds max %d bytes", fh.Filename, a.cfg.MaxItemBytes))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
contentStr := string(content)
|
|
||||||
if err := a.store.InsertCanItem(canID, fh.Filename, contentStr, detectContentType(fh.Filename, content), nil, nil, &contentStr, now); err != nil {
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
itemCount++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if itemCount == 0 {
|
|
||||||
a.store.DeleteCan(canID)
|
|
||||||
writeErrCode(w, 400, "content_empty", "can needs at least one item (files or json_items)")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJSON(w, 201, map[string]any{
|
|
||||||
"id": canID, "url": "/can/" + canID, "items": itemCount,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleDeleteCan soft-deletes a can (parity with paste deletion, #63):
|
|
||||||
// requires the vwr viewer cookie matching the can's viewer (cans carry no
|
|
||||||
// deletion token since they are built in the browser).
|
|
||||||
func (a *apiServer) handleDeleteCan(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
can, err := a.store.GetCan(id)
|
|
||||||
if err != nil || can == nil {
|
|
||||||
writeErr(w, 404, "can not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
vid := currentViewerID(r)
|
|
||||||
if !(vid != "" && viewerSentCookie(r) && can.ViewerID.Valid &&
|
|
||||||
can.ViewerID.String != "" && can.ViewerID.String == vid) {
|
|
||||||
writeErr(w, 403, "deletion not authorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, err := a.store.SoftDeleteCan(can.ID); err != nil {
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, 200, map[string]string{"status": "soft-deleted"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func detectContentType(name string, content []byte) string {
|
|
||||||
lower := strings.ToLower(name)
|
|
||||||
switch {
|
|
||||||
case strings.HasSuffix(lower, ".png"):
|
|
||||||
return "image/png"
|
|
||||||
case strings.HasSuffix(lower, ".jpg"), strings.HasSuffix(lower, ".jpeg"):
|
|
||||||
return "image/jpeg"
|
|
||||||
case strings.HasSuffix(lower, ".gif"):
|
|
||||||
return "image/gif"
|
|
||||||
case strings.HasSuffix(lower, ".webp"):
|
|
||||||
return "image/webp"
|
|
||||||
case strings.HasSuffix(lower, ".pdf"):
|
|
||||||
return "application/pdf"
|
|
||||||
}
|
|
||||||
if len(content) > 8 && content[0] == 0x89 && content[1] == 'P' {
|
|
||||||
return "image/png"
|
|
||||||
}
|
|
||||||
return "text/plain"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *apiServer) handleGetCan(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
can, err := a.store.GetCan(id)
|
|
||||||
if err != nil {
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if can == nil {
|
|
||||||
writeErr(w, 404, "can not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if can.ExpiresAt.Valid && can.ExpiresAt.Int64 < time.Now().Unix() {
|
|
||||||
writeErr(w, 404, "can expired")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if can.PasswordHash.Valid {
|
|
||||||
pw := r.Header.Get("X-Paste-Password")
|
|
||||||
if pw == "" || !store.CheckPassword(can.PasswordHash.String, pw) {
|
|
||||||
writeErr(w, 401, "password required")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
items, err := a.store.ListCanItems(can.ID)
|
|
||||||
if err != nil {
|
|
||||||
writeErr(w, 500, "db error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
type itemMeta struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Title *string `json:"title"`
|
|
||||||
ContentType string `json:"content_type"`
|
|
||||||
Size int `json:"size"`
|
|
||||||
URL string `json:"url"`
|
|
||||||
}
|
|
||||||
metas := make([]itemMeta, 0, len(items))
|
|
||||||
for _, it := range items {
|
|
||||||
metas = append(metas, itemMeta{
|
|
||||||
ID: it.ID, Title: store.NullStrPtr(it.Title), ContentType: it.ContentType,
|
|
||||||
Size: len(it.Content), URL: "/api/pastes/" + it.ID,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
writeJSON(w, 200, map[string]any{
|
|
||||||
"id": can.ID, "title": store.NullStrPtr(can.Title), "visibility": can.Visibility,
|
|
||||||
"created_at": can.CreatedAt, "items": metas,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *apiServer) handleCanItem(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id := chi.URLParam(r, "item")
|
|
||||||
row, err := a.store.GetPaste(id)
|
|
||||||
if err != nil || row == nil {
|
|
||||||
writeErr(w, 404, "item not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// must belong to a can
|
|
||||||
if !row.CanID.Valid {
|
|
||||||
writeErr(w, 404, "not a can item")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// inherit can password protection: password via header/query, or the
|
|
||||||
// same pw_<can> unlock cookie the can page sets (#4 cookie parity).
|
|
||||||
can, _ := a.store.GetCan(row.CanID.String)
|
|
||||||
if can != nil && can.PasswordHash.Valid {
|
|
||||||
pw := r.Header.Get("X-Paste-Password")
|
|
||||||
if pw == "" || !store.CheckPassword(can.PasswordHash.String, pw) {
|
|
||||||
// fall back to the browser's unlock cookie for this can
|
|
||||||
c, cerr := r.Cookie("pw_" + can.ID)
|
|
||||||
if cerr != nil || c.Value != web.UnlockToken(can.ID) {
|
|
||||||
writeErr(w, 401, "password required")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// #34: same content-type guard as /raw — never serve active content types.
|
|
||||||
ct := row.ContentType
|
|
||||||
if !safeRawContentType(ct) {
|
|
||||||
ct = "text/plain; charset=utf-8"
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", ct)
|
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
||||||
w.Write([]byte(row.Content))
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// #60: the cans API must clamp expires_in at the boundary exactly like the
|
|
||||||
// pastes API — reject zero/negative durations and anything over the 1-year
|
|
||||||
// UI cap, accept the exact boundaries.
|
|
||||||
func TestCreateCanExpiryBounds(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
|
|
||||||
cases := []struct {
|
|
||||||
expiresIn string
|
|
||||||
wantCode int
|
|
||||||
}{
|
|
||||||
{"-1h", 400}, // negative
|
|
||||||
{"-0s", 400}, // negative zero
|
|
||||||
{"0s", 400}, // zero
|
|
||||||
{"1ns", 400}, // positive but below the 1-minute floor
|
|
||||||
{"59s", 400}, // just under the floor
|
|
||||||
{"1m", 201}, // exactly the floor
|
|
||||||
{"90s", 201}, // just over the floor
|
|
||||||
{"8760h", 201}, // exactly 1 year
|
|
||||||
{"8785h", 400}, // 1 year + 1 day: over the cap
|
|
||||||
{"87600h", 400}, // 10 years, the originally reported case
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
globalLimiter = newLimiter() // avoid create rate limit between cases
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
"expires_in": c.expiresIn,
|
|
||||||
}, "files", "pic.txt", "file data")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != c.wantCode {
|
|
||||||
t.Errorf("expires_in %q: got %d want %d (%s)",
|
|
||||||
c.expiresIn, rec.Code, c.wantCode, rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,414 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"palette/internal/store"
|
|
||||||
)
|
|
||||||
|
|
||||||
// #4: cans appear in /api/public as normal rows with is_can=true.
|
|
||||||
func TestCanInPublicListing(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
|
|
||||||
// a can and a regular paste
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Listed can",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 201 {
|
|
||||||
t.Fatalf("create can: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
req = httptest.NewRequest("POST", "/api/pastes", strings.NewReader(`{"content":"plain"}`))
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
req = httptest.NewRequest("GET", "/api/public", nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("public: %d", rec.Code)
|
|
||||||
}
|
|
||||||
var got struct {
|
|
||||||
Total int `json:"total"`
|
|
||||||
Items []struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
IsCan bool `json:"is_can"`
|
|
||||||
Title any `json:"title"`
|
|
||||||
} `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
|
||||||
if got.Total != 2 {
|
|
||||||
t.Fatalf("expected total 2 (can + paste), got %d", got.Total)
|
|
||||||
}
|
|
||||||
foundCan := false
|
|
||||||
for _, it := range got.Items {
|
|
||||||
if it.ID == created.ID {
|
|
||||||
if !it.IsCan {
|
|
||||||
t.Fatalf("can row missing is_can flag")
|
|
||||||
}
|
|
||||||
foundCan = true
|
|
||||||
} else if it.IsCan {
|
|
||||||
t.Fatalf("plain paste flagged as can")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !foundCan {
|
|
||||||
t.Fatalf("can not present in /api/public")
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: unlisted can must not be listed
|
|
||||||
body2, ct2 := multipartBody(t, map[string]string{
|
|
||||||
"title": "Hidden can",
|
|
||||||
"visibility": "unlisted",
|
|
||||||
"json_items": `[{"title":"b.txt","content":"BBB"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req = httptest.NewRequest("POST", "/api/pastes/can", body2)
|
|
||||||
req.Header.Set("Content-Type", ct2)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 201 {
|
|
||||||
t.Fatalf("unlisted can create: %d", rec.Code)
|
|
||||||
}
|
|
||||||
req = httptest.NewRequest("GET", "/api/public", nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if strings.Contains(rec.Body.String(), "Hidden can") {
|
|
||||||
t.Fatalf("unlisted can leaked into /api/public")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: custom slug support for cans + conflict with existing paste slug.
|
|
||||||
func TestCanCustomSlug(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Slugged",
|
|
||||||
"custom_slug": "my-bundle",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 201 {
|
|
||||||
t.Fatalf("create can with slug: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var created struct{ ID, URL string }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
if created.ID != "my-bundle" {
|
|
||||||
t.Fatalf("expected id my-bundle, got %q", created.ID)
|
|
||||||
}
|
|
||||||
// custom slug resolves on the can page route
|
|
||||||
req = httptest.NewRequest("GET", "/can/my-bundle", nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Slugged") {
|
|
||||||
t.Fatalf("can page by slug: %d", rec.Code)
|
|
||||||
}
|
|
||||||
// duplicate slug rejected 409
|
|
||||||
body, ct = multipartBody(t, map[string]string{
|
|
||||||
"title": "Again", "custom_slug": "my-bundle",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req = httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 409 {
|
|
||||||
t.Fatalf("duplicate slug expected 409, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
// reserved slug rejected
|
|
||||||
body, ct = multipartBody(t, map[string]string{
|
|
||||||
"title": "R", "custom_slug": "admin",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req = httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 409 {
|
|
||||||
t.Fatalf("reserved slug expected 409, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: invalid expiry rejected on cans, mirroring paste behavior (#48).
|
|
||||||
func TestCanExpiryValidation(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Bad expiry", "expires_in": "30s",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 400 {
|
|
||||||
t.Fatalf("expected 400 for 30s expiry, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: expired cans 404 on the page and API.
|
|
||||||
func TestCanExpiryAccess(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Dying", "expires_in": "1h",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
// backdate expiry to force the expired path
|
|
||||||
s.store.Exec(`UPDATE paste_cans SET expires_at=? WHERE id=?`, 100, created.ID)
|
|
||||||
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 404 {
|
|
||||||
t.Fatalf("expired can API expected 404, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
req = httptest.NewRequest("GET", "/can/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 404 {
|
|
||||||
t.Fatalf("expired can page expected 404, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: password-protected can page uses the same unlock flow as pastes.
|
|
||||||
func TestCanUnlockFlow(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Locked can", "password": "pw123",
|
|
||||||
"json_items": `[{"title":"secret.txt","content":"sec content"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
// GET page without cookie -> unlock form
|
|
||||||
req = httptest.NewRequest("GET", "/can/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "locked") {
|
|
||||||
t.Fatalf("expected unlock form, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// POST wrong password -> unlock form with error
|
|
||||||
fd := strings.NewReader("password=wrong")
|
|
||||||
req = httptest.NewRequest("POST", "/can/"+created.ID, fd)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if !strings.Contains(rec.Body.String(), "Wrong password") {
|
|
||||||
t.Fatalf("expected wrong-password message")
|
|
||||||
}
|
|
||||||
|
|
||||||
// POST correct password -> page renders, cookie set
|
|
||||||
fd = strings.NewReader("password=pw123")
|
|
||||||
req = httptest.NewRequest("POST", "/can/"+created.ID, fd)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if !strings.Contains(rec.Body.String(), "sec content") {
|
|
||||||
t.Fatalf("unlocked can page missing item content")
|
|
||||||
}
|
|
||||||
var pwCookie *http.Cookie
|
|
||||||
for _, c := range rec.Result().Cookies() {
|
|
||||||
if c.Name == "pw_"+created.ID {
|
|
||||||
pwCookie = c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if pwCookie == nil {
|
|
||||||
t.Fatalf("unlock cookie not set")
|
|
||||||
}
|
|
||||||
|
|
||||||
// GET with cookie -> unlocked
|
|
||||||
req = httptest.NewRequest("GET", "/can/"+created.ID, nil)
|
|
||||||
req.AddCookie(pwCookie)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if !strings.Contains(rec.Body.String(), "sec content") {
|
|
||||||
t.Fatalf("cookie unlock failed: %d", rec.Code)
|
|
||||||
}
|
|
||||||
// a forged cookie value must not unlock
|
|
||||||
req = httptest.NewRequest("GET", "/can/"+created.ID, nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "pw_" + created.ID, Value: "forged"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if strings.Contains(rec.Body.String(), "sec content") {
|
|
||||||
t.Fatalf("forged cookie unlocked the can")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: can item access inherits the can unlock cookie (not just query param).
|
|
||||||
func TestCanItemCookieParity(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Cookie can", "password": "pw123",
|
|
||||||
"json_items": `[{"title":"s.txt","content":"sec"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
// unlock via page to get the cookie
|
|
||||||
fd := strings.NewReader("password=pw123")
|
|
||||||
req = httptest.NewRequest("POST", "/can/"+created.ID, fd)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var pwCookie *http.Cookie
|
|
||||||
for _, c := range rec.Result().Cookies() {
|
|
||||||
if c.Name == "pw_"+created.ID {
|
|
||||||
pwCookie = c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if pwCookie == nil {
|
|
||||||
t.Fatalf("no unlock cookie")
|
|
||||||
}
|
|
||||||
|
|
||||||
// item id from API (with password query)
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
req.Header.Set("X-Paste-Password", "pw123")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var can struct {
|
|
||||||
Items []struct{ ID string `json:"id"` } `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &can)
|
|
||||||
itemID := can.Items[0].ID
|
|
||||||
|
|
||||||
// API item with the unlock cookie but no password -> 200
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID+"/items/"+itemID, nil)
|
|
||||||
req.AddCookie(pwCookie)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("item via cookie expected 200, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
// forged cookie -> 401
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID+"/items/"+itemID, nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "pw_" + created.ID, Value: "forged"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 401 {
|
|
||||||
t.Fatalf("forged cookie on item expected 401, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: viewer-scoped soft delete of cans.
|
|
||||||
func TestCanDeleteParity(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Doomed", "json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "vwr", Value: "creator"})
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
// delete without matching viewer -> 403
|
|
||||||
req = httptest.NewRequest("DELETE", "/api/cans/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 403 {
|
|
||||||
t.Fatalf("unauthorized delete expected 403, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
// creator's browser -> 200
|
|
||||||
req = httptest.NewRequest("DELETE", "/api/cans/"+created.ID, nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "vwr", Value: "creator"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("creator delete expected 200, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
// gone from API and page
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 404 {
|
|
||||||
t.Fatalf("deleted can expected 404, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
// gone from listings
|
|
||||||
req = httptest.NewRequest("GET", "/api/public", nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if strings.Contains(rec.Body.String(), "Doomed") {
|
|
||||||
t.Fatalf("deleted can still listed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: cans appear in /api/mine for the creating browser.
|
|
||||||
func TestCanInMine(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "Mine can", "json_items": `[{"title":"a.txt","content":"AAA"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "vwr", Value: "v-mine"})
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 201 {
|
|
||||||
t.Fatalf("create: %d", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
req = httptest.NewRequest("GET", "/api/mine", nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: "vwr", Value: "v-mine"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var got struct {
|
|
||||||
Items []struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
IsCan bool `json:"is_can"`
|
|
||||||
} `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
|
||||||
if len(got.Items) != 1 || !got.Items[0].IsCan {
|
|
||||||
t.Fatalf("can missing from /api/mine: %s", rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #4: sweep soft-deletes expired cans (parity with pastes).
|
|
||||||
func TestCanSweepExpired(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
s.store.CreateCan("sweepcan", "sweep", "", "public", nil, 1, nil, nil)
|
|
||||||
s.store.InsertCanItem("sweepcan", "a.txt", "AAA", "text/plain", nil, nil, nil, 1)
|
|
||||||
s.store.Exec(`UPDATE paste_cans SET expires_at=? WHERE id=?`, 100, "sweepcan")
|
|
||||||
s.store.SweepExpired()
|
|
||||||
if can, _ := s.store.GetCan("sweepcan"); can != nil {
|
|
||||||
t.Fatalf("expired can survived sweep")
|
|
||||||
}
|
|
||||||
_ = store.GenSlug(4) // keep import if store pkg shrinks
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"mime/multipart"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func multipartBody(t *testing.T, fields map[string]string, fileField, fileName, fileContent string) (*bytes.Buffer, string) {
|
|
||||||
t.Helper()
|
|
||||||
var buf bytes.Buffer
|
|
||||||
w := multipart.NewWriter(&buf)
|
|
||||||
for k, v := range fields {
|
|
||||||
w.WriteField(k, v)
|
|
||||||
}
|
|
||||||
if fileField != "" {
|
|
||||||
fw, _ := w.CreateFormFile(fileField, fileName)
|
|
||||||
fw.Write([]byte(fileContent))
|
|
||||||
}
|
|
||||||
w.Close()
|
|
||||||
return &buf, w.FormDataContentType()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCreateAndGetCan(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "My can",
|
|
||||||
"json_items": `[{"title":"a.txt","content":"AAA"},{"title":"b.txt","content":"BBB"}]`,
|
|
||||||
"expires_in": "1h",
|
|
||||||
}, "files", "pic.txt", "file data")
|
|
||||||
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 201 {
|
|
||||||
t.Fatalf("create can: got %d: %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var created struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Items int `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
if created.Items != 3 {
|
|
||||||
t.Fatalf("expected 3 items, got %d", created.Items)
|
|
||||||
}
|
|
||||||
|
|
||||||
// get can
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("get can: got %d", rec.Code)
|
|
||||||
}
|
|
||||||
var can struct {
|
|
||||||
Items []struct{ ID string `json:"id"` } `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &can)
|
|
||||||
if len(can.Items) != 3 {
|
|
||||||
t.Fatalf("expected 3 items in get, got %d", len(can.Items))
|
|
||||||
}
|
|
||||||
|
|
||||||
// fetch item
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID+"/items/"+can.Items[0].ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("item fetch: got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEmptyCanRejected(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
body, ct := multipartBody(t, map[string]string{"title": "empty"}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 400 {
|
|
||||||
t.Fatalf("expected 400 for empty can, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCanPasswordInheritedByItems(t *testing.T) {
|
|
||||||
s := testServer(t)
|
|
||||||
h := s.routes()
|
|
||||||
|
|
||||||
body, ct := multipartBody(t, map[string]string{
|
|
||||||
"title": "locked",
|
|
||||||
"password": "pw123",
|
|
||||||
"json_items": `[{"title":"s.txt","content":"sec"}]`,
|
|
||||||
}, "", "", "")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", body)
|
|
||||||
req.Header.Set("Content-Type", ct)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var created struct{ ID string `json:"id"` }
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &created)
|
|
||||||
|
|
||||||
// can without pw -> 401
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 401 {
|
|
||||||
t.Fatalf("expected 401, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// get item id with pw
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID, nil)
|
|
||||||
req.Header.Set("X-Paste-Password", "pw123")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
var can struct {
|
|
||||||
Items []struct{ ID string `json:"id"` } `json:"items"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &can)
|
|
||||||
itemID := can.Items[0].ID
|
|
||||||
|
|
||||||
// item without pw -> 401
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID+"/items/"+itemID, nil)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 401 {
|
|
||||||
t.Fatalf("item expected 401, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// item with pw -> 200
|
|
||||||
req = httptest.NewRequest("GET", "/api/cans/"+created.ID+"/items/"+itemID, nil)
|
|
||||||
req.Header.Set("X-Paste-Password", "pw123")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != 200 {
|
|
||||||
t.Fatalf("item expected 200, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
if !strings.Contains(rec.Body.String(), "sec") {
|
|
||||||
t.Fatalf("item content mismatch: %s", rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// clientIP extracts the client IP for rate-limit keying.
|
||||||
|
//
|
||||||
|
// Trust boundary (issue #280): the bucket key MUST NOT come from any header a
|
||||||
|
// client can influence. The previous rightmost-X-Forwarded-For scheme (#85)
|
||||||
|
// assumed Traefik appends the real client IP, but the deployed ingress does
|
||||||
|
// not rewrite XFF, so a client rotating its own XFF value got a fresh bucket
|
||||||
|
// per request and the limit was unenforceable (pentest H1: 6x201 across 8
|
||||||
|
// rotating-XFF creates).
|
||||||
|
//
|
||||||
|
// The bucket key is the actual peer address (RemoteAddr) only. Behind any
|
||||||
|
// reverse proxy this is the proxy's address, so all clients share one bucket
|
||||||
|
// per endpoint — coarse, but safe. Client-supplied IP headers
|
||||||
|
// (X-Forwarded-For, X-Real-Ip) are never trusted.
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func clientIP(r *http.Request) string {
|
||||||
|
host := r.RemoteAddr
|
||||||
|
if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||||
|
host = h
|
||||||
|
}
|
||||||
|
return host
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
// #143: create responses must set the short-lived tok_<id> HttpOnly cookie
|
// #143: create responses must set the short-lived tok_<id> HttpOnly+Secure
|
||||||
// that the paste view reads for the one-time created banner.
|
// cookie that the paste view reads for the one-time created banner.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -29,6 +29,9 @@ func TestCreateSetsDeletionTokenCookie(t *testing.T) {
|
|||||||
if !c.HttpOnly {
|
if !c.HttpOnly {
|
||||||
t.Error("tok_ cookie not HttpOnly")
|
t.Error("tok_ cookie not HttpOnly")
|
||||||
}
|
}
|
||||||
|
if !c.Secure {
|
||||||
|
t.Error("tok_ cookie not Secure")
|
||||||
|
}
|
||||||
if c.MaxAge != 60 {
|
if c.MaxAge != 60 {
|
||||||
t.Errorf("tok_ cookie MaxAge = %d, want 60", c.MaxAge)
|
t.Errorf("tok_ cookie MaxAge = %d, want 60", c.MaxAge)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,38 +86,3 @@ func TestErrorCodeRateLimited(t *testing.T) {
|
|||||||
}
|
}
|
||||||
t.Fatalf("never got rate_limited, last code = %q", code)
|
t.Fatalf("never got rate_limited, last code = %q", code)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestErrorCodeCanValidation(t *testing.T) {
|
|
||||||
h := testServer(t).routes()
|
|
||||||
|
|
||||||
post := func(fields map[string]string) *httptest.ResponseRecorder {
|
|
||||||
var b strings.Builder
|
|
||||||
for k, v := range fields {
|
|
||||||
b.WriteString("--B\r\nContent-Disposition: form-data; name=\"" + k + "\"\r\n\r\n" + v + "\r\n")
|
|
||||||
}
|
|
||||||
b.WriteString("--B--\r\n")
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes/can", strings.NewReader(b.String()))
|
|
||||||
req.Header.Set("Content-Type", "multipart/form-data; boundary=B")
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rec, req)
|
|
||||||
return rec
|
|
||||||
}
|
|
||||||
|
|
||||||
// bad visibility
|
|
||||||
if _, _, code := decodeErr(t, post(map[string]string{"title": "x", "visibility": "nope"})); code != "invalid_visibility" {
|
|
||||||
t.Fatalf("visibility code = %q, want invalid_visibility", code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// invalid expiry
|
|
||||||
if _, _, code := decodeErr(t, post(map[string]string{"title": "x", "expires_in": "1s"})); code != "expiry_invalid" {
|
|
||||||
t.Fatalf("expiry code = %q, want expiry_invalid", code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// slug taken on can create
|
|
||||||
if rec := postCreate(h, `{"content":"a","custom_slug":"can-slug"}`); rec.Code != 201 {
|
|
||||||
t.Fatalf("seed create: %d", rec.Code)
|
|
||||||
}
|
|
||||||
if _, _, code := decodeErr(t, post(map[string]string{"title": "x", "custom_slug": "can-slug", "json_items": `[{"title":"a","content":"b"}]`})); code != "slug_taken" {
|
|
||||||
t.Fatalf("can slug code = %q, want slug_taken", code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -29,7 +29,7 @@ func newTestServer138(t *testing.T) *httptest.ResponseRecorder {
|
|||||||
globalSettingsFn = ss.get
|
globalSettingsFn = ss.get
|
||||||
t.Cleanup(func() { globalSettingsFn = nil })
|
t.Cleanup(func() { globalSettingsFn = nil })
|
||||||
a := &apiServer{store: st, cfg: cfg, ui: ui, settings: ss, adminKey: "test-admin-key"}
|
a := &apiServer{store: st, cfg: cfg, ui: ui, settings: ss, adminKey: "test-admin-key"}
|
||||||
req := httptest.NewRequest("GET", "/history", nil)
|
req := httptest.NewRequest("GET", "/public", nil)
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
a.routes().ServeHTTP(rec, req)
|
a.routes().ServeHTTP(rec, req)
|
||||||
return rec
|
return rec
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// #235: Type column. Text pastes show the language, attachment pastes show
|
||||||
|
// the file extension (lowercase, no dot).
|
||||||
|
func TestDisplayType(t *testing.T) {
|
||||||
|
lang := "python"
|
||||||
|
cases := []struct {
|
||||||
|
lang *string
|
||||||
|
att string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{nil, "", "text"},
|
||||||
|
{&lang, "", "python"},
|
||||||
|
{&lang, "report.pdf", "pdf"},
|
||||||
|
{nil, "photo.PNG", "png"},
|
||||||
|
{&lang, "archive.tar.gz", "gz"},
|
||||||
|
{&lang, "noext", "python"}, // no extension: fall back to language
|
||||||
|
{&lang, ".hidden", "python"}, // dotfile: no extension
|
||||||
|
{&lang, "dir/name.txt", "txt"}, // path component only
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := displayType(c.lang, c.att); got != c.want {
|
||||||
|
t.Errorf("displayType(%v, %q) = %q, want %q", c.lang, c.att, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttachmentExtName(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"a.txt": "txt", "A.PNG": "png", "noext": "", ".hidden": "",
|
||||||
|
"x.": "", "dir/b.md": "md", "": "",
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := attachmentExtName(in); got != want {
|
||||||
|
t.Errorf("attachmentExtName(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,7 +58,7 @@ func TestMineCreateListDelete(t *testing.T) {
|
|||||||
a := &apiServer{store: st, cfg: cfg, ui: ui, settings: ss, adminKey: "test-admin-key"}
|
a := &apiServer{store: st, cfg: cfg, ui: ui, settings: ss, adminKey: "test-admin-key"}
|
||||||
h := a.routes()
|
h := a.routes()
|
||||||
|
|
||||||
alice := viewerCookieFor(t, h, "/history")
|
alice := viewerCookieFor(t, h, "/public")
|
||||||
if alice == "" {
|
if alice == "" {
|
||||||
t.Fatal("no viewer cookie issued")
|
t.Fatal("no viewer cookie issued")
|
||||||
}
|
}
|
||||||
@@ -89,7 +89,7 @@ func TestMineCreateListDelete(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// a different browser's cookie does NOT see it
|
// a different browser's cookie does NOT see it
|
||||||
bob := viewerCookieFor(t, h, "/history")
|
bob := viewerCookieFor(t, h, "/public")
|
||||||
rec = doReq(t, h, "GET", "/api/mine", bob, "")
|
rec = doReq(t, h, "GET", "/api/mine", bob, "")
|
||||||
json.Unmarshal(rec.Body.Bytes(), &list)
|
json.Unmarshal(rec.Body.Bytes(), &list)
|
||||||
if list.Total != 0 {
|
if list.Total != 0 {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package api
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -48,35 +47,6 @@ func (l *limiter) allow(key string, rate, burst float64) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// clientIP extracts the client IP for rate-limit keying (#85).
|
|
||||||
//
|
|
||||||
// Trust boundary: palette runs behind exactly ONE trusted reverse proxy
|
|
||||||
// (Traefik in the k3s pod network). Traefik APPENDS the real client IP to
|
|
||||||
// X-Forwarded-For, so the RIGHTMOST entry is the last value the trusted
|
|
||||||
// proxy observed and is unspoofable by the client (a client-supplied fake
|
|
||||||
// entry only lands on the LEFT and is ignored). This matches chi's
|
|
||||||
// middleware.RealIP semantics for a single trusted proxy hop.
|
|
||||||
//
|
|
||||||
// Direct connections (no XFF header) fall back to RemoteAddr. Directly
|
|
||||||
// reachable deployments must NOT expose the app to untrusted networks
|
|
||||||
// without a proxy in front, or attackers could forge the rightmost entry.
|
|
||||||
func clientIP(r *http.Request) string {
|
|
||||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
|
||||||
if i := strings.LastIndex(xff, ","); i >= 0 {
|
|
||||||
return strings.TrimSpace(xff[i+1:])
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(xff)
|
|
||||||
}
|
|
||||||
if xr := r.Header.Get("X-Real-Ip"); xr != "" {
|
|
||||||
return strings.TrimSpace(xr)
|
|
||||||
}
|
|
||||||
host := r.RemoteAddr
|
|
||||||
if i := strings.LastIndex(host, ":"); i > 0 {
|
|
||||||
host = host[:i]
|
|
||||||
}
|
|
||||||
return host
|
|
||||||
}
|
|
||||||
|
|
||||||
var globalLimiter = newLimiter()
|
var globalLimiter = newLimiter()
|
||||||
|
|
||||||
// globalSettingsFn is set at startup; tests can point it at fixed settings.
|
// globalSettingsFn is set at startup; tests can point it at fixed settings.
|
||||||
|
|||||||
@@ -1,85 +1,50 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
// Issue #85: the rate limit key must use the rightmost X-Forwarded-For entry
|
|
||||||
// (appended by the trusted Traefik proxy), never the raw/leftmost header
|
|
||||||
// value a client can forge. A spoofed FIRST XFF entry must not bypass the
|
|
||||||
// limit or rotate buckets.
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"fmt"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestClientIPTakesRightmostXFF(t *testing.T) {
|
func TestClientIPUsesRemoteAddrNotXFF(t *testing.T) {
|
||||||
r := httptest.NewRequest("POST", "/", nil)
|
r := httptest.NewRequest("POST", "/api/pastes", nil)
|
||||||
r.RemoteAddr = "10.42.0.7:51000" // trusted Traefik pod
|
r.RemoteAddr = "203.0.113.7:4432"
|
||||||
r.Header.Set("X-Forwarded-For", "1.2.3.4, 1.2.3.5, 203.0.113.9")
|
r.Header.Set("X-Forwarded-For", "1.2.3.4, 1.2.3.5, 203.0.113.9")
|
||||||
if got := clientIP(r); got != "203.0.113.9" {
|
|
||||||
t.Fatalf("clientIP = %q, want rightmost 203.0.113.9", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClientIPXRealIPFallback(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("POST", "/", nil)
|
|
||||||
r.RemoteAddr = "10.42.0.7:51000"
|
|
||||||
r.Header.Set("X-Real-Ip", "203.0.113.10")
|
r.Header.Set("X-Real-Ip", "203.0.113.10")
|
||||||
if got := clientIP(r); got != "203.0.113.10" {
|
if got := clientIP(r); got != "203.0.113.7" {
|
||||||
t.Fatalf("clientIP = %q, want 203.0.113.10", got)
|
t.Fatalf("clientIP = %q, want peer 203.0.113.7", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClientIPDirectFallback(t *testing.T) {
|
// A proxy-controlled header is not honored even when set: #280 revision
|
||||||
r := httptest.NewRequest("POST", "/", nil)
|
// removed the PALETTE_TRUSTED_IP_HEADER mechanism per owner decision, so the
|
||||||
r.RemoteAddr = "198.51.100.5:51000"
|
// bucket key is the peer address only.
|
||||||
if got := clientIP(r); got != "198.51.100.5" {
|
func TestClientIPNeverTrustsHeaders(t *testing.T) {
|
||||||
t.Fatalf("clientIP = %q, want 198.51.100.5", got)
|
r := httptest.NewRequest("POST", "/api/pastes", nil)
|
||||||
|
r.RemoteAddr = "10.0.1.47:9999"
|
||||||
|
r.Header.Set("CF-Connecting-IP", "198.51.100.9")
|
||||||
|
if got := clientIP(r); got != "10.0.1.47" {
|
||||||
|
t.Fatalf("clientIP = %q, want peer 10.0.1.47", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRateLimitSpoofedFirstXFFDoesNotBypass: an attacker rotating a fake
|
// Issue #280: rotating X-Forwarded-For must NOT reset the bucket. Pentest
|
||||||
// leftmost XFF entry stays limited on their real (rightmost) IP.
|
// repro was 8 creates with rotating XFF -> 6x201.
|
||||||
func TestRateLimitSpoofedFirstXFFDoesNotBypass(t *testing.T) {
|
func TestRotatingXFFDoesNotResetBucket(t *testing.T) {
|
||||||
srv := newTestServer(t)
|
globalLimiter = newLimiter()
|
||||||
h := srv.routes()
|
s := defaultSettings(Config{}) // burst/limit defaults; header values are ignored anyway
|
||||||
for i := 0; i < 5; i++ {
|
var allowed, limited int
|
||||||
req := httptest.NewRequest("POST", "/api/pastes", bytes.NewReader([]byte(`{"content":"hi"}`)))
|
for i := 0; i < 8; i++ {
|
||||||
req.RemoteAddr = "10.42.0.7:51000"
|
r := httptest.NewRequest("POST", "/api/pastes", nil)
|
||||||
// each request spoofs a DIFFERENT leftmost entry
|
r.RemoteAddr = "198.51.100.1:5000"
|
||||||
req.Header.Set("X-Forwarded-For", spoofN(i)+", 203.0.113.9")
|
r.Header.Set("X-Forwarded-For", fmt.Sprintf("9.9.9.%d", i))
|
||||||
rr := httptest.NewRecorder()
|
if rateLimitCreate(r, s) {
|
||||||
h.ServeHTTP(rr, req)
|
allowed++
|
||||||
if rr.Code != 201 {
|
} else {
|
||||||
t.Fatalf("req %d: want 201, got %d", i, rr.Code)
|
limited++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 6th request, still the same real IP, new spoofed prefix: must 429
|
if float64(allowed) != s.RateLimitBurst || limited != 8-int(s.RateLimitBurst) {
|
||||||
req := httptest.NewRequest("POST", "/api/pastes", bytes.NewReader([]byte(`{"content":"hi"}`)))
|
t.Fatalf("rotating XFF: allowed=%d limited=%d, want allowed=%v (burst), limited=%d", allowed, limited, s.RateLimitBurst, 8-int(s.RateLimitBurst))
|
||||||
req.RemoteAddr = "10.42.0.7:51000"
|
|
||||||
req.Header.Set("X-Forwarded-For", "9.9.9.9, 203.0.113.9")
|
|
||||||
rr := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rr, req)
|
|
||||||
if rr.Code != 429 {
|
|
||||||
t.Fatalf("spoofed 6th req: want 429, got %d", rr.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func spoofN(i int) string {
|
|
||||||
return "1.2.3." + string(rune('0'+i))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Distinct real IPs must still get distinct buckets (no over-limiting).
|
|
||||||
func TestRateLimitDistinctRightmostIPsIndependent(t *testing.T) {
|
|
||||||
srv := newTestServer(t)
|
|
||||||
h := srv.routes()
|
|
||||||
for _, ip := range []string{"203.0.113.20", "203.0.113.21"} {
|
|
||||||
req := httptest.NewRequest("POST", "/api/pastes", bytes.NewReader([]byte(`{"content":"hi"}`)))
|
|
||||||
req.RemoteAddr = "10.42.0.7:51000"
|
|
||||||
req.Header.Set("X-Forwarded-For", "6.6.6.6, "+ip)
|
|
||||||
rr := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(rr, req)
|
|
||||||
if rr.Code != 201 {
|
|
||||||
t.Fatalf("ip %s: want 201, got %d", ip, rr.Code)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// #256: renamed page routes; old URLs redirect.
|
||||||
|
import (
|
||||||
|
"palette/internal/store"
|
||||||
|
"palette/internal/web"
|
||||||
|
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRenamedPageRoutes(t *testing.T) {
|
||||||
|
globalLimiter = newLimiter() // fresh rate-limit buckets
|
||||||
|
st, err := store.OpenStore(":memory:")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ui, err := web.New()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := Config{MaxTextBytes: 5 * 1024 * 1024}
|
||||||
|
ss := NewTestSettingsStore(t, cfg)
|
||||||
|
globalSettingsFn = ss.get
|
||||||
|
t.Cleanup(func() { globalSettingsFn = nil })
|
||||||
|
a := &apiServer{store: st, cfg: cfg, ui: ui, settings: ss, adminKey: "test-admin-key"}
|
||||||
|
h := a.routes()
|
||||||
|
|
||||||
|
// new routes render pages
|
||||||
|
for _, path := range []string{"/public", "/saved"} {
|
||||||
|
req := httptest.NewRequest("GET", path, nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET %s: %d, want 200", path, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// old routes redirect
|
||||||
|
for _, tc := range [][2]string{{"/history", "/public"}, {"/mine", "/saved"}, {"/", "/public"}} {
|
||||||
|
req := httptest.NewRequest("GET", tc[0], nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusMovedPermanently && rec.Code != http.StatusFound {
|
||||||
|
t.Fatalf("GET %s: %d, want redirect", tc[0], rec.Code)
|
||||||
|
}
|
||||||
|
if loc := rec.Header().Get("Location"); loc != tc[1] {
|
||||||
|
t.Fatalf("GET %s redirects to %s, want %s", tc[0], loc, tc[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
-146
@@ -1,5 +1,5 @@
|
|||||||
// Package api implements palette's REST handlers and the HTTP router:
|
// Package api implements palette's REST handlers and the HTTP router:
|
||||||
// pastes, cans, guess-language, rate limiting middleware, and the admin API.
|
// pastes, guess-language, rate limiting middleware, and the admin API.
|
||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -18,7 +17,6 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
|
||||||
langpkg "palette/internal/lang"
|
|
||||||
"palette/internal/store"
|
"palette/internal/store"
|
||||||
"palette/internal/web"
|
"palette/internal/web"
|
||||||
)
|
)
|
||||||
@@ -59,8 +57,7 @@ func writeErrCode(w http.ResponseWriter, status int, code, msg string) {
|
|||||||
writeJSON(w, status, map[string]string{"error": msg, "code": code})
|
writeJSON(w, status, map[string]string{"error": msg, "code": code})
|
||||||
}
|
}
|
||||||
|
|
||||||
// createErrCode maps a store.CreatePaste/CreateCan error to its UI error
|
// createErrCode maps a store.CreatePaste error to its UI error code (#105).
|
||||||
// code (#105).
|
|
||||||
func createErrCode(err error) string {
|
func createErrCode(err error) string {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, store.ErrSlugTaken):
|
case errors.Is(err, store.ErrSlugTaken):
|
||||||
@@ -103,26 +100,21 @@ func (a *apiServer) routes() http.Handler {
|
|||||||
r.Delete("/pastes/{id}/redeem", a.handleRedeemDeletion)
|
r.Delete("/pastes/{id}/redeem", a.handleRedeemDeletion)
|
||||||
r.Get("/public", a.handleListPublic)
|
r.Get("/public", a.handleListPublic)
|
||||||
r.Post("/guess-language", a.handleGuessLang)
|
r.Post("/guess-language", a.handleGuessLang)
|
||||||
r.Post("/pastes/can", a.handleCreateCan)
|
|
||||||
r.Get("/cans/{id}", a.handleGetCan)
|
|
||||||
r.Delete("/cans/{id}", a.handleDeleteCan)
|
|
||||||
r.Get("/cans/{id}/items/{item}", a.handleCanItem)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// can page (#4): GET renders, POST unlocks (same flow as pastes)
|
|
||||||
r.Get("/can/{id}", a.handleCanPage)
|
|
||||||
r.Post("/can/{id}", a.handleCanPage)
|
|
||||||
|
|
||||||
// raw + #38 attachment serving
|
// raw + #38 attachment serving
|
||||||
r.Get("/f/{aid}/{filename}", a.handleServeAttachment)
|
r.Get("/f/{aid}/{filename}", a.handleServeAttachment)
|
||||||
r.Get("/raw/{id}", a.handleRaw)
|
r.Get("/raw/{id}", a.handleRaw)
|
||||||
|
|
||||||
// web pages
|
// web pages
|
||||||
r.Get("/", http.RedirectHandler("/history", http.StatusFound).ServeHTTP)
|
r.Get("/", http.RedirectHandler("/public", http.StatusFound).ServeHTTP)
|
||||||
r.Get("/new", a.ui.Handlers().HandleNewPage)
|
r.Get("/new", a.ui.Handlers().HandleNewPage)
|
||||||
r.Get("/history", a.ui.Handlers().HandleHistoryPage)
|
r.Get("/public", a.ui.Handlers().HandleHistoryPage)
|
||||||
|
r.Get("/saved", a.ui.Handlers().HandleMinePage)
|
||||||
r.Get("/settings", a.ui.Handlers().HandleSettingsPage)
|
r.Get("/settings", a.ui.Handlers().HandleSettingsPage)
|
||||||
r.Get("/mine", a.ui.Handlers().HandleMinePage)
|
// #256: old URLs redirect to the renamed pages
|
||||||
|
r.Get("/history", http.RedirectHandler("/public", http.StatusMovedPermanently).ServeHTTP)
|
||||||
|
r.Get("/mine", http.RedirectHandler("/saved", http.StatusMovedPermanently).ServeHTTP)
|
||||||
r.Handle("/static/*", a.ui.StaticHandler())
|
r.Handle("/static/*", a.ui.StaticHandler())
|
||||||
r.Get("/unlock/{id}", a.handlePasteView)
|
r.Get("/unlock/{id}", a.handlePasteView)
|
||||||
r.Post("/unlock/{id}", a.handlePasteView)
|
r.Post("/unlock/{id}", a.handlePasteView)
|
||||||
@@ -186,7 +178,7 @@ func viewerSentCookie(r *http.Request) bool {
|
|||||||
func setDeletionTokenCookie(w http.ResponseWriter, pasteID, token string) {
|
func setDeletionTokenCookie(w http.ResponseWriter, pasteID, token string) {
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "tok_" + pasteID, Value: token, Path: "/",
|
Name: "tok_" + pasteID, Value: token, Path: "/",
|
||||||
MaxAge: 60, HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
MaxAge: 60, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,11 +307,26 @@ func (a *apiServer) handleGetPaste(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, 200, map[string]any{
|
writeJSON(w, 200, map[string]any{
|
||||||
"id": row.ID, "content": row.Content, "content_type": row.ContentType,
|
"id": row.ID, "content": row.Content, "content_type": row.ContentType,
|
||||||
"language": store.NullStrPtr(row.Language), "title": store.NullStrPtr(row.Title), "created_at": row.CreatedAt,
|
"language": store.NullStrPtr(row.Language), "title": store.NullStrPtr(row.Title), "created_at": row.CreatedAt,
|
||||||
|
"type": a.pasteTypeLabel(row),
|
||||||
"view_count": row.ViewCount, "visibility": row.Visibility,
|
"view_count": row.ViewCount, "visibility": row.Visibility,
|
||||||
"reads_remaining": rem,
|
"reads_remaining": rem,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pasteTypeLabel computes the Type value for a single paste (#235): file
|
||||||
|
// extension for attachment pastes, else the stored language, else "text".
|
||||||
|
func (a *apiServer) pasteTypeLabel(row *store.PasteRow) string {
|
||||||
|
if att, err := a.store.GetAttachmentForPaste(row.ID); err == nil && att != nil {
|
||||||
|
if ext := attachmentExtName(att.Filename); ext != "" {
|
||||||
|
return ext
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !row.Language.Valid || row.Language.String == "" {
|
||||||
|
return "text"
|
||||||
|
}
|
||||||
|
return row.Language.String
|
||||||
|
}
|
||||||
|
|
||||||
func (a *apiServer) handleDeletePaste(w http.ResponseWriter, r *http.Request) {
|
func (a *apiServer) handleDeletePaste(w http.ResponseWriter, r *http.Request) {
|
||||||
id := chi.URLParam(r, "id")
|
id := chi.URLParam(r, "id")
|
||||||
row, err := a.store.GetPaste(id)
|
row, err := a.store.GetPaste(id)
|
||||||
@@ -376,6 +383,33 @@ func (a *apiServer) deletionAuthorized(r *http.Request, row *store.PasteRow) boo
|
|||||||
row.ViewerID.String != "" && row.ViewerID.String == vid
|
row.ViewerID.String != "" && row.ViewerID.String == vid
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// displayType returns the Type-column value for a list row (#235): the file
|
||||||
|
// extension for attachment pastes, otherwise the detected language (default
|
||||||
|
// "text").
|
||||||
|
func displayType(lang *string, attFilename string) string {
|
||||||
|
if ext := attachmentExtName(attFilename); ext != "" {
|
||||||
|
return ext
|
||||||
|
}
|
||||||
|
if lang == nil || *lang == "" {
|
||||||
|
return "text"
|
||||||
|
}
|
||||||
|
return *lang
|
||||||
|
}
|
||||||
|
|
||||||
|
// attachmentExtName returns the lowercase extension (without dot) of a
|
||||||
|
// filename, or "" when there is none.
|
||||||
|
func attachmentExtName(filename string) string {
|
||||||
|
name := filename
|
||||||
|
if i := strings.LastIndexByte(name, '/'); i >= 0 {
|
||||||
|
name = name[i+1:]
|
||||||
|
}
|
||||||
|
i := strings.LastIndexByte(name, '.')
|
||||||
|
if i <= 0 || i == len(name)-1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.ToLower(name[i+1:])
|
||||||
|
}
|
||||||
|
|
||||||
// handleListMine serves /api/mine: pastes created from this browser (#37).
|
// handleListMine serves /api/mine: pastes created from this browser (#37).
|
||||||
func (a *apiServer) handleListMine(w http.ResponseWriter, r *http.Request) {
|
func (a *apiServer) handleListMine(w http.ResponseWriter, r *http.Request) {
|
||||||
vid := currentViewerID(r)
|
vid := currentViewerID(r)
|
||||||
@@ -394,10 +428,9 @@ func (a *apiServer) handleListMine(w http.ResponseWriter, r *http.Request) {
|
|||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
lang, title := store.NullStrPtr(row.Language), store.NullStrPtr(row.Title)
|
lang, title := store.NullStrPtr(row.Language), store.NullStrPtr(row.Title)
|
||||||
items = append(items, map[string]any{
|
items = append(items, map[string]any{
|
||||||
"id": row.ID, "title": title, "language": lang,
|
"id": row.ID, "title": title, "language": lang, "type": displayType(lang, row.AttFilename),
|
||||||
"created_at": row.CreatedAt, "view_count": row.ViewCount, "size": row.Size,
|
"created_at": row.CreatedAt, "view_count": row.ViewCount, "size": row.Size,
|
||||||
"custom_slug": store.NullStrPtr(row.CustomSlug), "visibility": row.Visibility,
|
"custom_slug": store.NullStrPtr(row.CustomSlug), "visibility": row.Visibility,
|
||||||
"is_can": row.IsCan,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
writeJSON(w, 200, map[string]any{"total": total, "limit": limit, "offset": offset, "items": items})
|
writeJSON(w, 200, map[string]any{"total": total, "limit": limit, "offset": offset, "items": items})
|
||||||
@@ -415,10 +448,9 @@ func (a *apiServer) handleListPublic(w http.ResponseWriter, r *http.Request) {
|
|||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
lang, title := store.NullStrPtr(row.Language), store.NullStrPtr(row.Title)
|
lang, title := store.NullStrPtr(row.Language), store.NullStrPtr(row.Title)
|
||||||
items = append(items, map[string]any{
|
items = append(items, map[string]any{
|
||||||
"id": row.ID, "title": title, "language": lang,
|
"id": row.ID, "title": title, "language": lang, "type": displayType(lang, row.AttFilename),
|
||||||
"created_at": row.CreatedAt, "view_count": row.ViewCount, "size": row.Size,
|
"created_at": row.CreatedAt, "view_count": row.ViewCount, "size": row.Size,
|
||||||
"custom_slug": store.NullStrPtr(row.CustomSlug),
|
"custom_slug": store.NullStrPtr(row.CustomSlug), "visibility": row.Visibility,
|
||||||
"is_can": row.IsCan,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
writeJSON(w, 200, map[string]any{"total": total, "limit": limit, "offset": offset, "items": items})
|
writeJSON(w, 200, map[string]any{"total": total, "limit": limit, "offset": offset, "items": items})
|
||||||
@@ -451,6 +483,25 @@ func (a *apiServer) handleRaw(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "not found", 404)
|
http.Error(w, "not found", 404)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// #221: raw view of a paste backed by an attachment serves the stored
|
||||||
|
// blob bytes with the sniffed mime, not the (empty) text content — for
|
||||||
|
// ALL attachment mimes (#281); /raw/{id} is the raw fetch for the file
|
||||||
|
// too. serveContentType still forces active-content types (html, svg,
|
||||||
|
// xml) to text/plain per the #34 rule below.
|
||||||
|
if att, err := a.store.GetAttachmentForPaste(row.ID); err == nil && att != nil {
|
||||||
|
blobs := a.store.Blobs()
|
||||||
|
if blobs != nil {
|
||||||
|
if blob, err := blobs.Get(row.ID + "/" + att.SHA256); err == nil {
|
||||||
|
defer blob.Close()
|
||||||
|
a.store.IncrementViews(row.ID, "", 0) // raw views always count (#49/#95)
|
||||||
|
w.Header().Set("Content-Type", serveContentType(att.Mime))
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", att.Size))
|
||||||
|
http.ServeContent(w, r, "", time.Unix(att.CreatedAt, 0), blob)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
// #34: content_type is attacker-controlled via the create API. Serving it
|
// #34: content_type is attacker-controlled via the create API. Serving it
|
||||||
// verbatim let a paste be stored with text/html (or image/svg+xml) and
|
// verbatim let a paste be stored with text/html (or image/svg+xml) and
|
||||||
// render as active content on this origin when fetched from /raw —
|
// render as active content on this origin when fetched from /raw —
|
||||||
@@ -484,130 +535,6 @@ func safeRawContentType(ct string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *apiServer) handleCanPage(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
can, err := a.store.GetCan(id)
|
|
||||||
if err != nil || can == nil {
|
|
||||||
http.NotFound(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if can.ExpiresAt.Valid && can.ExpiresAt.Int64 < time.Now().Unix() {
|
|
||||||
http.NotFound(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// #4: password-protected cans go through the same unlock flow as pastes:
|
|
||||||
// the pw_<id> cookie carries an HMAC token bound to this can id. Items
|
|
||||||
// inherit the protection (handleCanItem checks the same cookie).
|
|
||||||
if can.PasswordHash.Valid {
|
|
||||||
h := a.webHandlers()
|
|
||||||
if r.Method == http.MethodPost {
|
|
||||||
if !rateLimitUnlock(can.ID, r) {
|
|
||||||
h.WriteRateLimited(w, 60)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
r.ParseForm()
|
|
||||||
pw := r.FormValue("password")
|
|
||||||
if pw != "" && store.CheckPassword(can.PasswordHash.String, pw) {
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: "pw_" + can.ID, Value: web.UnlockToken(can.ID), Path: "/",
|
|
||||||
MaxAge: 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
|
||||||
})
|
|
||||||
a.renderCan(w, can)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.RenderPage(w, "unlock.html", map[string]any{
|
|
||||||
"Page": "unlock", "ID": can.ID, "Wrong": true,
|
|
||||||
"CreatedAgo": web.AgoString(can.CreatedAt), "CreatedAtUnix": can.CreatedAt,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c, err := r.Cookie("pw_" + can.ID)
|
|
||||||
if err != nil || c.Value != web.UnlockToken(can.ID) {
|
|
||||||
h.RenderPage(w, "unlock.html", map[string]any{
|
|
||||||
"Page": "unlock", "ID": can.ID, "Wrong": false,
|
|
||||||
"CreatedAgo": web.AgoString(can.CreatedAt), "CreatedAtUnix": can.CreatedAt,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.renderCan(w, can)
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderCan renders the can view page: title/description and items as cards.
|
|
||||||
// Text items expand inline; files link to download.
|
|
||||||
func (a *apiServer) renderCan(w http.ResponseWriter, can *store.CanRow) {
|
|
||||||
h := a.webHandlers()
|
|
||||||
items, err := a.store.ListCanItems(can.ID)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "db error", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
type canItem struct {
|
|
||||||
ID string
|
|
||||||
Title string
|
|
||||||
ContentType string
|
|
||||||
Size string
|
|
||||||
IsFile bool
|
|
||||||
Content string
|
|
||||||
ContentHTML template.HTML
|
|
||||||
Language string
|
|
||||||
}
|
|
||||||
cards := make([]canItem, 0, len(items))
|
|
||||||
totalSize := 0
|
|
||||||
for _, it := range items {
|
|
||||||
totalSize += len(it.Content)
|
|
||||||
isFile := it.ContentType != "text/plain" && !strings.HasPrefix(it.ContentType, "text/")
|
|
||||||
ci := canItem{
|
|
||||||
ID: it.ID,
|
|
||||||
Title: nullStrOr(it.Title, it.ID),
|
|
||||||
ContentType: it.ContentType,
|
|
||||||
Size: web.HumanSize(len(it.Content)),
|
|
||||||
IsFile: isFile,
|
|
||||||
Language: it.Language.String,
|
|
||||||
}
|
|
||||||
if !isFile {
|
|
||||||
ci.ContentHTML = template.HTML(langpkg.HighlightCode(it.Content, it.Language.String))
|
|
||||||
}
|
|
||||||
cards = append(cards, ci)
|
|
||||||
}
|
|
||||||
h.RenderPage(w, "can.html", map[string]any{
|
|
||||||
"Page": "can",
|
|
||||||
"ID": can.ID,
|
|
||||||
"Title": nullStrOr(can.Title, "Untitled can"),
|
|
||||||
"Description": can.Description.String,
|
|
||||||
"HasDescription": can.Description.Valid && can.Description.String != "",
|
|
||||||
"HasPassword": can.PasswordHash.Valid,
|
|
||||||
"Items": cards,
|
|
||||||
"ItemCount": len(cards),
|
|
||||||
"SizeHuman": web.HumanSize(totalSize),
|
|
||||||
"CreatedAgo": web.AgoString(can.CreatedAt),
|
|
||||||
"CreatedAtUnix": can.CreatedAt,
|
|
||||||
"ExpiresAt": can.ExpiresAt.Valid,
|
|
||||||
"ExpiresIn": expiryStringIfValid(can.ExpiresAt),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// expiryStringIfValid formats remaining time for a valid expiry, "" otherwise.
|
|
||||||
func expiryStringIfValid(ns sql.NullInt64) string {
|
|
||||||
if !ns.Valid {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
remaining := ns.Int64 - time.Now().Unix()
|
|
||||||
s := remaining
|
|
||||||
switch {
|
|
||||||
case s < 3600:
|
|
||||||
return fmt.Sprintf("%dm", s/60)
|
|
||||||
case s < 86400:
|
|
||||||
return fmt.Sprintf("%dh", s/3600)
|
|
||||||
default:
|
|
||||||
return fmt.Sprintf("%dd", s/86400)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func templateEsc(s string) string {
|
|
||||||
r := strings.NewReplacer("&", "&", "<", "<", ">", ">")
|
|
||||||
return r.Replace(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *apiServer) handlePasteView(w http.ResponseWriter, r *http.Request) {
|
func (a *apiServer) handlePasteView(w http.ResponseWriter, r *http.Request) {
|
||||||
h := a.webHandlers()
|
h := a.webHandlers()
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// #68 input-validation helpers. Paste/can payloads are size-capped and list
|
// #68 input-validation helpers. Paste payloads are size-capped and list
|
||||||
// endpoints get a single place where limit/offset are parsed and clamped.
|
// endpoints get a single place where limit/offset are parsed and clamped.
|
||||||
|
|
||||||
// maxRequestBody returns the HTTP body cap for JSON create endpoints: the
|
// maxRequestBody returns the HTTP body cap for JSON create endpoints: the
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ type Attachment struct {
|
|||||||
SizeHuman string `json:"-"` // template-only: human-readable size
|
SizeHuman string `json:"-"` // template-only: human-readable size
|
||||||
}
|
}
|
||||||
|
|
||||||
const MaxFilenameLen = 255
|
// MaxFilenameLen caps stored attachment filenames (bytes) to bound DB
|
||||||
|
// rows and Content-Disposition echoes. 128 keeps names readable while
|
||||||
|
// stopping filename-bloat abuse; longer names truncate.
|
||||||
|
const MaxFilenameLen = 128
|
||||||
|
|
||||||
// ErrFileTooLarge is returned when an attachment exceeds the per-file cap.
|
// ErrFileTooLarge is returned when an attachment exceeds the per-file cap.
|
||||||
var ErrFileTooLarge = errors.New("file too large")
|
var ErrFileTooLarge = errors.New("file too large")
|
||||||
|
|||||||
@@ -105,4 +105,9 @@ func TestSanitizeFilename(t *testing.T) {
|
|||||||
if got := SanitizeFilename(long); len(got) != MaxFilenameLen {
|
if got := SanitizeFilename(long); len(got) != MaxFilenameLen {
|
||||||
t.Errorf("long name len = %d want %d", len(got), MaxFilenameLen)
|
t.Errorf("long name len = %d want %d", len(got), MaxFilenameLen)
|
||||||
}
|
}
|
||||||
|
// issue #248: a 250-char multipart filename must truncate to the cap
|
||||||
|
repro := strings.Repeat("b", 246) + ".txt"
|
||||||
|
if got := SanitizeFilename(repro); len(got) != MaxFilenameLen {
|
||||||
|
t.Errorf("repro name len = %d want %d", len(got), MaxFilenameLen)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -10,9 +10,10 @@ var slugRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9-_]{0,63}$`)
|
|||||||
|
|
||||||
// reserved words that would collide with routes
|
// reserved words that would collide with routes
|
||||||
var reservedSlugs = map[string]bool{
|
var reservedSlugs = map[string]bool{
|
||||||
"api": true, "raw": true, "can": true, "cans": true, "public": true,
|
"api": true, "raw": true, "public": true,
|
||||||
"history": true, "static": true, "assets": true, "favicon.ico": true,
|
"history": true, "static": true, "assets": true, "favicon.ico": true,
|
||||||
"new": true, "login": true, "logout": true, "admin": true, "settings": true,
|
"new": true, "login": true, "logout": true, "admin": true, "settings": true,
|
||||||
|
"mine": true, "saved": true, "unlock": true, "guess": true, "f": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
var ErrInvalidSlug = errors.New("custom slug must be 1-64 chars: letters, digits, dash, underscore; must start with letter or digit")
|
var ErrInvalidSlug = errors.New("custom slug must be 1-64 chars: letters, digits, dash, underscore; must start with letter or digit")
|
||||||
@@ -35,12 +36,5 @@ func (s *Store) SlugTaken(slug string) (bool, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
if n > 0 {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
err = s.db.QueryRow(`SELECT COUNT(*) FROM paste_cans WHERE id = ?`, slug).Scan(&n)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return n > 0, nil
|
return n > 0, nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cans feature removal (2026-10-16): opening a store on a pre-removal
|
||||||
|
// database must drop the paste_cans table (only when empty) and the
|
||||||
|
// pastes.can_id column. A non-empty paste_cans table is left in place.
|
||||||
|
func TestMigrateDropsCansSchema(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
legacy := func(name string, canRows int) string {
|
||||||
|
db, err := sql.Open("sqlite", filepath.Join(dir, name))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open raw db: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
stmts := []string{
|
||||||
|
`CREATE TABLE pastes (
|
||||||
|
id TEXT PRIMARY KEY, custom_slug TEXT UNIQUE, content TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL DEFAULT 'text/plain', language TEXT, title TEXT,
|
||||||
|
password_hash TEXT, expires_at INTEGER, burn_after_read INTEGER DEFAULT 0,
|
||||||
|
visibility TEXT NOT NULL DEFAULT 'public', can_id TEXT,
|
||||||
|
created_at INTEGER NOT NULL, deleted_at INTEGER,
|
||||||
|
view_count INTEGER NOT NULL DEFAULT 0, deletion_token TEXT
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE paste_cans (
|
||||||
|
id TEXT PRIMARY KEY, title TEXT, description TEXT,
|
||||||
|
visibility TEXT NOT NULL DEFAULT 'public', password_hash TEXT,
|
||||||
|
created_at INTEGER NOT NULL, deleted_at INTEGER, expires_at INTEGER
|
||||||
|
)`,
|
||||||
|
`ALTER TABLE paste_cans ADD COLUMN viewer_id TEXT`,
|
||||||
|
`INSERT INTO pastes (id, content, content_type, visibility, can_id, created_at)
|
||||||
|
VALUES ('p1', 'x', 'text/plain', 'public', NULL, 1)`,
|
||||||
|
}
|
||||||
|
for _, q := range stmts {
|
||||||
|
if _, err := db.Exec(q); err != nil {
|
||||||
|
t.Fatalf("seed %q: %v", q, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i < canRows; i++ {
|
||||||
|
if _, err := db.Exec(`INSERT INTO paste_cans (id, created_at) VALUES (?, 1)`, string(rune('a'+i))); err != nil {
|
||||||
|
t.Fatalf("seed can row: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
intCol := func(s *Store, table, col string) int {
|
||||||
|
var n int
|
||||||
|
s.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?`, table, col).Scan(&n)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
tableExists := func(s *Store, table string) bool {
|
||||||
|
var n int
|
||||||
|
s.db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?`, table).Scan(&n)
|
||||||
|
return n > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty paste_cans: table and column both dropped.
|
||||||
|
s1, err := OpenStore(legacy("empty.db", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open: %v", err)
|
||||||
|
}
|
||||||
|
defer s1.db.Close()
|
||||||
|
if tableExists(s1, "paste_cans") {
|
||||||
|
t.Error("paste_cans still exists after migrate (was empty; should be dropped)")
|
||||||
|
}
|
||||||
|
if intCol(s1, "pastes", "can_id") != 0 {
|
||||||
|
t.Error("pastes.can_id still exists after migrate; should be dropped")
|
||||||
|
}
|
||||||
|
// The store still works end to end.
|
||||||
|
if _, err := s1.CreatePaste(&Paste{Content: "hello", Visibility: "public"}); err != nil {
|
||||||
|
t.Fatalf("create paste on migrated db: %v", err)
|
||||||
|
}
|
||||||
|
if got := s1.QueryInt(`SELECT COUNT(*) FROM pastes`); got != 2 {
|
||||||
|
t.Errorf("pastes count = %d, want 2", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-empty paste_cans: table kept, can_id still dropped.
|
||||||
|
s2, err := OpenStore(legacy("full.db", 2))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open: %v", err)
|
||||||
|
}
|
||||||
|
defer s2.db.Close()
|
||||||
|
if !tableExists(s2, "paste_cans") {
|
||||||
|
t.Error("non-empty paste_cans was dropped; must be kept until cleaned")
|
||||||
|
}
|
||||||
|
if intCol(s2, "pastes", "can_id") != 0 {
|
||||||
|
t.Error("pastes.can_id still exists after migrate; should be dropped")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fresh database: neither the table nor the column is ever created.
|
||||||
|
s3, err := OpenStore(filepath.Join(dir, "fresh.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open fresh: %v", err)
|
||||||
|
}
|
||||||
|
defer s3.db.Close()
|
||||||
|
if tableExists(s3, "paste_cans") {
|
||||||
|
t.Error("fresh db created paste_cans")
|
||||||
|
}
|
||||||
|
if intCol(s3, "pastes", "can_id") != 0 {
|
||||||
|
t.Error("fresh db created pastes.can_id")
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
-148
@@ -32,7 +32,6 @@ type Paste struct {
|
|||||||
Visibility string `json:"visibility"`
|
Visibility string `json:"visibility"`
|
||||||
// #83: accept "public": true/false as an alias for visibility.
|
// #83: accept "public": true/false as an alias for visibility.
|
||||||
Public *bool `json:"public,omitempty"`
|
Public *bool `json:"public,omitempty"`
|
||||||
CanID *string `json:"can_id,omitempty"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
DeletedAt *int64 `json:"deleted_at,omitempty"`
|
DeletedAt *int64 `json:"deleted_at,omitempty"`
|
||||||
ExpiresAt *int64 `json:"expires_at,omitempty"`
|
ExpiresAt *int64 `json:"expires_at,omitempty"`
|
||||||
@@ -55,26 +54,13 @@ type PasteRow struct {
|
|||||||
ReadsLimit sql.NullInt64
|
ReadsLimit sql.NullInt64
|
||||||
ReadsUsed int
|
ReadsUsed int
|
||||||
Visibility string
|
Visibility string
|
||||||
CanID sql.NullString
|
|
||||||
CreatedAt int64
|
CreatedAt int64
|
||||||
DeletedAt sql.NullInt64
|
DeletedAt sql.NullInt64
|
||||||
ViewCount int
|
ViewCount int
|
||||||
Size int
|
Size int
|
||||||
DeletionToken sql.NullString
|
DeletionToken sql.NullString
|
||||||
ViewerID sql.NullString
|
ViewerID sql.NullString
|
||||||
IsCan bool // set on list rows that are cans (#4)
|
AttFilename string // attachment filename when the paste is a file paste (#235); empty otherwise
|
||||||
}
|
|
||||||
|
|
||||||
type CanRow struct {
|
|
||||||
ID string
|
|
||||||
Title sql.NullString
|
|
||||||
Visibility string
|
|
||||||
PasswordHash sql.NullString
|
|
||||||
CreatedAt int64
|
|
||||||
DeletedAt sql.NullInt64
|
|
||||||
ExpiresAt sql.NullInt64
|
|
||||||
Description sql.NullString
|
|
||||||
ViewerID sql.NullString
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Store struct {
|
type Store struct {
|
||||||
@@ -118,7 +104,6 @@ func (s *Store) migrate() error {
|
|||||||
expires_at INTEGER,
|
expires_at INTEGER,
|
||||||
burn_after_read INTEGER DEFAULT 0,
|
burn_after_read INTEGER DEFAULT 0,
|
||||||
visibility TEXT NOT NULL DEFAULT 'public',
|
visibility TEXT NOT NULL DEFAULT 'public',
|
||||||
can_id TEXT,
|
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
deleted_at INTEGER,
|
deleted_at INTEGER,
|
||||||
view_count INTEGER NOT NULL DEFAULT 0,
|
view_count INTEGER NOT NULL DEFAULT 0,
|
||||||
@@ -127,22 +112,32 @@ deletion_token TEXT
|
|||||||
CREATE INDEX IF NOT EXISTS idx_pastes_visibility_created ON pastes(visibility, created_at DESC);
|
CREATE INDEX IF NOT EXISTS idx_pastes_visibility_created ON pastes(visibility, created_at DESC);
|
||||||
CREATE INDEX IF NOT EXISTS idx_pastes_expires ON pastes(expires_at) WHERE expires_at IS NOT NULL;
|
CREATE INDEX IF NOT EXISTS idx_pastes_expires ON pastes(expires_at) WHERE expires_at IS NOT NULL;
|
||||||
CREATE INDEX IF NOT EXISTS idx_pastes_deleted ON pastes(deleted_at) WHERE deleted_at IS NOT NULL;
|
CREATE INDEX IF NOT EXISTS idx_pastes_deleted ON pastes(deleted_at) WHERE deleted_at IS NOT NULL;
|
||||||
CREATE TABLE IF NOT EXISTS paste_cans (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
title TEXT,
|
|
||||||
description TEXT,
|
|
||||||
visibility TEXT NOT NULL DEFAULT 'public',
|
|
||||||
password_hash TEXT,
|
|
||||||
created_at INTEGER NOT NULL,
|
|
||||||
deleted_at INTEGER,
|
|
||||||
expires_at INTEGER
|
|
||||||
);
|
|
||||||
`)
|
`)
|
||||||
s.db.Exec(`ALTER TABLE pastes ADD COLUMN deletion_token TEXT`) // ignore if exists
|
s.db.Exec(`ALTER TABLE pastes ADD COLUMN deletion_token TEXT`) // ignore if exists
|
||||||
s.db.Exec(`ALTER TABLE pastes ADD COLUMN viewer_id TEXT`) // ignore if exists (#37)
|
s.db.Exec(`ALTER TABLE pastes ADD COLUMN viewer_id TEXT`) // ignore if exists (#37)
|
||||||
s.db.Exec(`ALTER TABLE pastes ADD COLUMN reads_limit INTEGER`) // ignore if exists (#49)
|
s.db.Exec(`ALTER TABLE pastes ADD COLUMN reads_limit INTEGER`) // ignore if exists (#49)
|
||||||
s.db.Exec(`ALTER TABLE pastes ADD COLUMN reads_used INTEGER DEFAULT 0`) // ignore if exists (#49)
|
s.db.Exec(`ALTER TABLE pastes ADD COLUMN reads_used INTEGER DEFAULT 0`) // ignore if exists (#49)
|
||||||
s.db.Exec(`ALTER TABLE paste_cans ADD COLUMN viewer_id TEXT`) // ignore if exists (#4)
|
// Cans feature removal (owner decision 2026-10-16): drop the leftover
|
||||||
|
// schema. paste_cans is only dropped when empty so no data is silently
|
||||||
|
// destroyed; a non-empty table is left in place and logged. The dormant
|
||||||
|
// pastes.can_id column is dropped too (prod verified clean 2026-10-16:
|
||||||
|
// zero rows referenced a can).
|
||||||
|
var tbl int
|
||||||
|
s.db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='paste_cans'`).Scan(&tbl)
|
||||||
|
if tbl > 0 {
|
||||||
|
var rows int
|
||||||
|
s.db.QueryRow(`SELECT COUNT(*) FROM paste_cans`).Scan(&rows)
|
||||||
|
if rows == 0 {
|
||||||
|
s.db.Exec(`DROP TABLE paste_cans`)
|
||||||
|
} else {
|
||||||
|
log.Printf("store: paste_cans still holds %d row(s); leaving the table in place (cans feature removed)", rows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var col int
|
||||||
|
s.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('pastes') WHERE name='can_id'`).Scan(&col)
|
||||||
|
if col > 0 {
|
||||||
|
s.db.Exec(`ALTER TABLE pastes DROP COLUMN can_id`)
|
||||||
|
}
|
||||||
s.db.Exec(`CREATE TABLE IF NOT EXISTS paste_views (
|
s.db.Exec(`CREATE TABLE IF NOT EXISTS paste_views (
|
||||||
paste_id TEXT NOT NULL,
|
paste_id TEXT NOT NULL,
|
||||||
viewer_id TEXT NOT NULL,
|
viewer_id TEXT NOT NULL,
|
||||||
@@ -289,10 +284,10 @@ func (s *Store) CreatePaste(p *Paste) (*Paste, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) GetPaste(idOrSlug string) (*PasteRow, error) {
|
func (s *Store) GetPaste(idOrSlug string) (*PasteRow, error) {
|
||||||
row := s.db.QueryRow(`SELECT id, custom_slug, content, content_type, language, title, password_hash, expires_at, burn_after_read, visibility, can_id, created_at, deleted_at, view_count, deletion_token, viewer_id, reads_limit, COALESCE(reads_used, 0)
|
row := s.db.QueryRow(`SELECT id, custom_slug, content, content_type, language, title, password_hash, expires_at, burn_after_read, visibility, created_at, deleted_at, view_count, deletion_token, viewer_id, reads_limit, COALESCE(reads_used, 0)
|
||||||
FROM pastes WHERE (id = ? OR custom_slug = ?) AND deleted_at IS NULL`, idOrSlug, idOrSlug)
|
FROM pastes WHERE (id = ? OR custom_slug = ?) AND deleted_at IS NULL`, idOrSlug, idOrSlug)
|
||||||
var r PasteRow
|
var r PasteRow
|
||||||
err := row.Scan(&r.ID, &r.CustomSlug, &r.Content, &r.ContentType, &r.Language, &r.Title, &r.PasswordHash, &r.ExpiresAt, &r.BurnAfterRead, &r.Visibility, &r.CanID, &r.CreatedAt, &r.DeletedAt, &r.ViewCount, &r.DeletionToken, &r.ViewerID, &r.ReadsLimit, &r.ReadsUsed)
|
err := row.Scan(&r.ID, &r.CustomSlug, &r.Content, &r.ContentType, &r.Language, &r.Title, &r.PasswordHash, &r.ExpiresAt, &r.BurnAfterRead, &r.Visibility, &r.CreatedAt, &r.DeletedAt, &r.ViewCount, &r.DeletionToken, &r.ViewerID, &r.ReadsLimit, &r.ReadsUsed)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -300,18 +295,15 @@ func (s *Store) GetPaste(idOrSlug string) (*PasteRow, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListPublic backs /api/public and the public listing page. Visibility rules
|
// ListPublic backs /api/public and the public listing page. Visibility rules
|
||||||
// mirror the history page: only non-deleted, non-expired, non-can pastes are
|
// mirror the history page: only non-deleted, non-expired pastes are listed,
|
||||||
// listed, and password-protected pastes are excluded at the query level
|
// and password-protected pastes are excluded at the query level (#65) so
|
||||||
// (#65) so their metadata (title, slug, existence) never leaks.
|
// their metadata (title, slug, existence) never leaks.
|
||||||
func (s *Store) ListPublic(limit, offset int) ([]PasteRow, int, error) {
|
func (s *Store) ListPublic(limit, offset int) ([]PasteRow, int, error) {
|
||||||
rows, err := s.db.Query(`SELECT id, custom_slug, content_type, language, title, visibility, created_at, view_count, LENGTH(content), 0
|
rows, err := s.db.Query(`SELECT p.id, p.custom_slug, p.content_type, p.language, p.title, p.visibility, p.created_at, p.view_count, LENGTH(p.content), COALESCE(a.filename, '')
|
||||||
FROM pastes
|
FROM pastes p
|
||||||
WHERE visibility='public' AND deleted_at IS NULL AND can_id IS NULL AND password_hash IS NULL AND (expires_at IS NULL OR expires_at > ?)
|
LEFT JOIN attachments a ON a.paste_id = p.id
|
||||||
UNION ALL
|
WHERE p.visibility='public' AND p.deleted_at IS NULL AND p.password_hash IS NULL AND (p.expires_at IS NULL OR p.expires_at > ?)
|
||||||
SELECT id, NULL, 'text/plain', NULL, title, visibility, created_at, 0, 0, 1
|
ORDER BY p.created_at DESC LIMIT ? OFFSET ?`, time.Now().Unix(), limit, offset)
|
||||||
FROM paste_cans
|
|
||||||
WHERE visibility='public' AND deleted_at IS NULL AND (expires_at IS NULL OR expires_at > ?)
|
|
||||||
ORDER BY created_at DESC LIMIT ? OFFSET ?`, time.Now().Unix(), time.Now().Unix(), limit, offset)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -320,33 +312,27 @@ func (s *Store) ListPublic(limit, offset int) ([]PasteRow, int, error) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var r PasteRow
|
var r PasteRow
|
||||||
var cs, lang, title sql.NullString
|
var cs, lang, title sql.NullString
|
||||||
var isCan int
|
if err := rows.Scan(&r.ID, &cs, &r.ContentType, &lang, &title, &r.Visibility, &r.CreatedAt, &r.ViewCount, &r.Size, &r.AttFilename); err != nil {
|
||||||
if err := rows.Scan(&r.ID, &cs, &r.ContentType, &lang, &title, &r.Visibility, &r.CreatedAt, &r.ViewCount, &r.Size, &isCan); err != nil {
|
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
r.CustomSlug = cs
|
r.CustomSlug = cs
|
||||||
r.Language = lang
|
r.Language = lang
|
||||||
r.Title = title
|
r.Title = title
|
||||||
r.IsCan = isCan == 1
|
|
||||||
out = append(out, r)
|
out = append(out, r)
|
||||||
}
|
}
|
||||||
var total int
|
var total int
|
||||||
s.db.QueryRow(`SELECT (SELECT COUNT(*) FROM pastes WHERE visibility='public' AND deleted_at IS NULL AND can_id IS NULL AND password_hash IS NULL AND (expires_at IS NULL OR expires_at > ?))
|
s.db.QueryRow(`SELECT COUNT(*) FROM pastes WHERE visibility='public' AND deleted_at IS NULL AND password_hash IS NULL AND (expires_at IS NULL OR expires_at > ?)`,
|
||||||
+ (SELECT COUNT(*) FROM paste_cans WHERE visibility='public' AND deleted_at IS NULL AND (expires_at IS NULL OR expires_at > ?))`,
|
time.Now().Unix()).Scan(&total)
|
||||||
time.Now().Unix(), time.Now().Unix()).Scan(&total)
|
|
||||||
return out, total, nil
|
return out, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMine lists pastes created from the given viewer id (browser cookie), newest first.
|
// ListMine lists pastes created from the given viewer id (browser cookie), newest first.
|
||||||
func (s *Store) ListMine(viewerID string, limit, offset int) ([]PasteRow, int, error) {
|
func (s *Store) ListMine(viewerID string, limit, offset int) ([]PasteRow, int, error) {
|
||||||
rows, err := s.db.Query(`SELECT id, custom_slug, language, title, visibility, created_at, view_count, LENGTH(content), 0
|
rows, err := s.db.Query(`SELECT p.id, p.custom_slug, p.language, p.title, p.visibility, p.created_at, p.view_count, LENGTH(p.content), COALESCE(a.filename, '')
|
||||||
FROM pastes
|
FROM pastes p
|
||||||
WHERE viewer_id = ? AND deleted_at IS NULL AND can_id IS NULL AND (expires_at IS NULL OR expires_at > ?)
|
LEFT JOIN attachments a ON a.paste_id = p.id
|
||||||
UNION ALL
|
WHERE p.viewer_id = ? AND p.deleted_at IS NULL AND (p.expires_at IS NULL OR p.expires_at > ?)
|
||||||
SELECT id, NULL, NULL, title, visibility, created_at, 0, 0, 1
|
ORDER BY p.created_at DESC LIMIT ? OFFSET ?`, viewerID, time.Now().Unix(), limit, offset)
|
||||||
FROM paste_cans
|
|
||||||
WHERE viewer_id = ? AND deleted_at IS NULL AND (expires_at IS NULL OR expires_at > ?)
|
|
||||||
ORDER BY created_at DESC LIMIT ? OFFSET ?`, viewerID, time.Now().Unix(), viewerID, time.Now().Unix(), limit, offset)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -355,18 +341,15 @@ func (s *Store) ListMine(viewerID string, limit, offset int) ([]PasteRow, int, e
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var r PasteRow
|
var r PasteRow
|
||||||
var cs, lang, title sql.NullString
|
var cs, lang, title sql.NullString
|
||||||
var isCan int
|
if err := rows.Scan(&r.ID, &cs, &lang, &title, &r.Visibility, &r.CreatedAt, &r.ViewCount, &r.Size, &r.AttFilename); err != nil {
|
||||||
if err := rows.Scan(&r.ID, &cs, &lang, &title, &r.Visibility, &r.CreatedAt, &r.ViewCount, &r.Size, &isCan); err != nil {
|
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
r.CustomSlug, r.Language, r.Title = cs, lang, title
|
r.CustomSlug, r.Language, r.Title = cs, lang, title
|
||||||
r.IsCan = isCan == 1
|
|
||||||
out = append(out, r)
|
out = append(out, r)
|
||||||
}
|
}
|
||||||
var total int
|
var total int
|
||||||
s.db.QueryRow(`SELECT (SELECT COUNT(*) FROM pastes WHERE viewer_id = ? AND deleted_at IS NULL AND can_id IS NULL AND (expires_at IS NULL OR expires_at > ?))
|
s.db.QueryRow(`SELECT COUNT(*) FROM pastes WHERE viewer_id = ? AND deleted_at IS NULL AND (expires_at IS NULL OR expires_at > ?)`,
|
||||||
+ (SELECT COUNT(*) FROM paste_cans WHERE viewer_id = ? AND deleted_at IS NULL AND (expires_at IS NULL OR expires_at > ?))`,
|
viewerID, time.Now().Unix()).Scan(&total)
|
||||||
viewerID, time.Now().Unix(), viewerID, time.Now().Unix()).Scan(&total)
|
|
||||||
return out, total, nil
|
return out, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,8 +412,6 @@ func (s *Store) IncrementViews(id, viewerID string, burnWindowMinutes int) bool
|
|||||||
func (s *Store) SweepExpired() {
|
func (s *Store) SweepExpired() {
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
s.db.Exec(`UPDATE pastes SET deleted_at=? WHERE expires_at IS NOT NULL AND expires_at < ? AND deleted_at IS NULL`, now, now)
|
s.db.Exec(`UPDATE pastes SET deleted_at=? WHERE expires_at IS NOT NULL AND expires_at < ? AND deleted_at IS NULL`, now, now)
|
||||||
// #4: cans expire too — mirror paste behavior
|
|
||||||
s.db.Exec(`UPDATE paste_cans SET deleted_at=? WHERE expires_at IS NOT NULL AND expires_at < ? AND deleted_at IS NULL`, now, now)
|
|
||||||
grace := now - SoftDeleteGraceDays*86400
|
grace := now - SoftDeleteGraceDays*86400
|
||||||
s.db.Exec(`DELETE FROM pastes WHERE deleted_at IS NOT NULL AND deleted_at < ?`, grace)
|
s.db.Exec(`DELETE FROM pastes WHERE deleted_at IS NOT NULL AND deleted_at < ?`, grace)
|
||||||
}
|
}
|
||||||
@@ -487,92 +468,6 @@ func (s *Store) HardDelete(id string) {
|
|||||||
s.db.Exec(`DELETE FROM pastes WHERE id = ?`, id)
|
s.db.Exec(`DELETE FROM pastes WHERE id = ?`, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateCan inserts a paste_can row with optional custom slug (parity with
|
|
||||||
// pastes: validated by the same rules, checked against both tables).
|
|
||||||
// Returns ErrSlugTaken / ErrInvalidSlug / ErrReservedSlug on conflict.
|
|
||||||
func (s *Store) CreateCan(canID, title, description, visibility string, pwHash *string, createdAt int64, expiresAt *int64, customSlug *string) error {
|
|
||||||
if customSlug != nil && *customSlug != "" {
|
|
||||||
slug := *customSlug
|
|
||||||
if err := ValidateCustomSlug(slug); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
taken, err := s.SlugTaken(slug)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if taken {
|
|
||||||
return ErrSlugTaken
|
|
||||||
}
|
|
||||||
canID = slug
|
|
||||||
}
|
|
||||||
if visibility == "" {
|
|
||||||
visibility = "public"
|
|
||||||
}
|
|
||||||
if visibility != "public" && visibility != "unlisted" {
|
|
||||||
return errors.New("visibility must be public or unlisted")
|
|
||||||
}
|
|
||||||
_, err := s.db.Exec(`INSERT INTO paste_cans (id, title, description, visibility, password_hash, created_at, expires_at)
|
|
||||||
VALUES (?,?,?,?,?,?,?)`, canID, title, description, visibility, pwHash, createdAt, expiresAt)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SoftDeleteCan marks a can deleted (its items stay; they are unlisted and
|
|
||||||
// hidden from listings by can_id and disappear with the can's page).
|
|
||||||
func (s *Store) SoftDeleteCan(canID string) (bool, error) {
|
|
||||||
res, err := s.db.Exec(`UPDATE paste_cans SET deleted_at=? WHERE id=? AND deleted_at IS NULL`, time.Now().Unix(), canID)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
n, err := res.RowsAffected()
|
|
||||||
return n > 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteCan removes an (empty/aborted) can row.
|
|
||||||
func (s *Store) DeleteCan(canID string) {
|
|
||||||
s.db.Exec(`DELETE FROM paste_cans WHERE id=?`, canID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// InsertCanItem adds an item paste belonging to a can.
|
|
||||||
func (s *Store) InsertCanItem(canID, title, content, contentType string, language *string, expiresAt, binary *string, now int64) error {
|
|
||||||
// language/expiresAt unused here for now; content stored as text (binary-safe in sqlite)
|
|
||||||
_, err := s.db.Exec(`INSERT INTO pastes
|
|
||||||
(id, content, content_type, language, title, visibility, can_id, created_at)
|
|
||||||
VALUES (?,?,?,?,?,?,?,?)`,
|
|
||||||
genSlug(6), content, contentType, language, &title, "unlisted", canID, now)
|
|
||||||
_ = expiresAt
|
|
||||||
_ = binary
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) GetCan(id string) (*CanRow, error) {
|
|
||||||
row := s.db.QueryRow(`SELECT id, title, visibility, password_hash, created_at, deleted_at, expires_at, description, viewer_id
|
|
||||||
FROM paste_cans WHERE (id = ?) AND deleted_at IS NULL`, id)
|
|
||||||
var c CanRow
|
|
||||||
err := row.Scan(&c.ID, &c.Title, &c.Visibility, &c.PasswordHash, &c.CreatedAt, &c.DeletedAt, &c.ExpiresAt, &c.Description, &c.ViewerID)
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return &c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) ListCanItems(canID string) ([]PasteRow, error) {
|
|
||||||
rows, err := s.db.Query(`SELECT id, custom_slug, content, content_type, language, title, password_hash, expires_at, burn_after_read, visibility, can_id, created_at, deleted_at, view_count
|
|
||||||
FROM pastes WHERE can_id = ? AND deleted_at IS NULL ORDER BY created_at ASC`, canID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var out []PasteRow
|
|
||||||
for rows.Next() {
|
|
||||||
var r PasteRow
|
|
||||||
if err := rows.Scan(&r.ID, &r.CustomSlug, &r.Content, &r.ContentType, &r.Language, &r.Title, &r.PasswordHash, &r.ExpiresAt, &r.BurnAfterRead, &r.Visibility, &r.CanID, &r.CreatedAt, &r.DeletedAt, &r.ViewCount); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out = append(out, r)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GenSlug is the exported slug generator.
|
// GenSlug is the exported slug generator.
|
||||||
func GenSlug(n int) string { return genSlug(n) }
|
func GenSlug(n int) string { return genSlug(n) }
|
||||||
|
|
||||||
|
|||||||
+121
-39
@@ -216,7 +216,10 @@ body {
|
|||||||
.tag { font-size: 19.8px; color: var(--muted-fg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 2px 9px; }
|
.tag { font-size: 19.8px; color: var(--muted-fg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 2px 9px; }
|
||||||
.paste-title-bar { display: flex; align-items: center; gap: 12px; padding: 12px 18px; flex-wrap: wrap; }
|
.paste-title-bar { display: flex; align-items: center; gap: 12px; padding: 12px 18px; flex-wrap: wrap; }
|
||||||
.paste-title-bar h1 { font-size: 29.2px; font-weight: 600; margin: 0; word-break: normal; overflow-wrap: anywhere; }
|
.paste-title-bar h1 { font-size: 29.2px; font-weight: 600; margin: 0; word-break: normal; overflow-wrap: anywhere; }
|
||||||
.stats-pill { border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
|
/* #222: .float already draws the border + radius and clips corners; the pill's own
|
||||||
|
tighter border curve was getting clipped thin at the corners. Let .float be the
|
||||||
|
only border/paint surface for the details pill (collapsed and expanded). */
|
||||||
|
.stats-pill { border: 0; border-radius: 0; overflow: hidden; }
|
||||||
.stats-head { display: flex; align-items: center; gap: 16px; width: 100%; background: none; border: 0; border-bottom: 1px solid var(--border); color: var(--muted-fg); font: inherit; font-size: 21.6px; padding: 14px 18px; cursor: pointer; text-align: left; }
|
.stats-head { display: flex; align-items: center; gap: 16px; width: 100%; background: none; border: 0; border-bottom: 1px solid var(--border); color: var(--muted-fg); font: inherit; font-size: 21.6px; padding: 14px 18px; cursor: pointer; text-align: left; }
|
||||||
.stats-head:hover { color: var(--fg); background: var(--surface-2); }
|
.stats-head:hover { color: var(--fg); background: var(--surface-2); }
|
||||||
.stats-chev { width: 18px; height: 18px; flex: none; transition: transform 0.15s ease; }
|
.stats-chev { width: 18px; height: 18px; flex: none; transition: transform 0.15s ease; }
|
||||||
@@ -296,8 +299,14 @@ html[data-wrap] .float { overflow-x: hidden; }
|
|||||||
.code-head .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }
|
.code-head .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }
|
||||||
.code {
|
.code {
|
||||||
font-family: var(--font-mono); font-size: var(--code-fs); line-height: var(--code-lh);
|
font-family: var(--font-mono); font-size: var(--code-fs); line-height: var(--code-lh);
|
||||||
padding: 14px 0; display: flex; overflow-x: auto;
|
padding: 14px 0; display: flex; overflow-x: hidden;
|
||||||
}
|
}
|
||||||
|
/* #261: horizontal scroll must live on the codebody, not the .code flex
|
||||||
|
container — a container-level scroll takes the gutter with it when the
|
||||||
|
user scrolls long lines. The gutter sits OUTSIDE the scroll container and
|
||||||
|
stays visible; the codebody shrinks to the remaining space and scrolls
|
||||||
|
(min-width: 0 lets it shrink below its content width inside the flex row). */
|
||||||
|
.code .codebody { flex: 1 1 auto; min-width: 0; overflow-x: auto; }
|
||||||
/* #167: the gutter must not drive the flex layout — its content width
|
/* #167: the gutter must not drive the flex layout — its content width
|
||||||
(row count × number width) shrinks the code column, which re-wraps lines,
|
(row count × number width) shrinks the code column, which re-wraps lines,
|
||||||
which grows the gutter: a feedback loop. Pin the gutter with a fixed
|
which grows the gutter: a feedback loop. Pin the gutter with a fixed
|
||||||
@@ -307,11 +316,13 @@ html[data-wrap] .float { overflow-x: hidden; }
|
|||||||
.code .gutter { flex-shrink: 0; }
|
.code .gutter { flex-shrink: 0; }
|
||||||
/* gutter/code share line metrics; the editor gutter keeps its own padding (#50) */
|
/* gutter/code share line metrics; the editor gutter keeps its own padding (#50) */
|
||||||
.code .gutter { padding-top: 0; padding-bottom: 0; }
|
.code .gutter { padding-top: 0; padding-bottom: 0; }
|
||||||
.codebody { padding: 0 18px; white-space: pre; }
|
.codebody { padding: 0 18px; white-space: pre; overflow-x: auto; }
|
||||||
/* #167: each logical line is its own block so offsetTop identifies its first visual row */
|
/* #167: each logical line is its own block so offsetTop identifies its first visual row */
|
||||||
.codeline { display: block; }
|
.codeline { display: block; }
|
||||||
/* #167 rev: gutter number spans must stack one per visual row (wrap on) */
|
/* #167: gutter number spans must stack one per visual row (wrap on).
|
||||||
.code .gutter .gutline { display: block; }
|
#274: the /new editor gutter uses the same .gutline blocks when its own
|
||||||
|
wrap toggle is on, so scope the rule to any gutter, not just .code. */
|
||||||
|
.code .gutter .gutline, .editor-wrap .gutter .gutline { display: block; }
|
||||||
/* #194: codeline blocks are adjacent (no '\n' text between them), so an
|
/* #194: codeline blocks are adjacent (no '\n' text between them), so an
|
||||||
empty block (blank source line) needs its own line box to stay one row */
|
empty block (blank source line) needs its own line box to stay one row */
|
||||||
.codeline:empty::before { content: "\200B"; }
|
.codeline:empty::before { content: "\200B"; }
|
||||||
@@ -343,10 +354,15 @@ tr:last-child td { border-bottom: none; }
|
|||||||
tr.row { cursor: pointer; }
|
tr.row { cursor: pointer; }
|
||||||
tr.row:hover td { background: var(--surface-2); }
|
tr.row:hover td { background: var(--surface-2); }
|
||||||
tr.row:hover td a.slug { color: var(--accent); }
|
tr.row:hover td a.slug { color: var(--accent); }
|
||||||
|
/* #292: highlight the paste NAME uniformly on row hover, titled or not */
|
||||||
|
tr.row:hover td .paste-name { color: var(--accent); }
|
||||||
td a.slug { font-family: var(--font-mono); font-size: 21.6px; color: var(--fg); text-decoration: none; }
|
td a.slug { font-family: var(--font-mono); font-size: 21.6px; color: var(--fg); text-decoration: none; }
|
||||||
|
td a.url-link { font-family: inherit; font-size: inherit; color: inherit; text-decoration: none; }
|
||||||
|
td a.url-link:hover { color: var(--accent); }
|
||||||
td a.slug:hover { color: var(--accent); }
|
td a.slug:hover { color: var(--accent); }
|
||||||
/* PASTE column fallback for untitled pastes: plain text, identical to a titled paste. URL/ID chips keep .slug styling. */
|
/* PASTE column fallback for untitled pastes: plain text, identical to a titled paste. URL/ID chips keep .slug styling. */
|
||||||
td a.slug.paste-name { background: none; padding: 0; border-radius: 0; font-family: inherit; font-size: inherit; color: var(--fg); }
|
td a.slug.paste-name { background: none; padding: 0; border-radius: 0; font-family: inherit; font-size: inherit; color: var(--fg); }
|
||||||
|
td a.paste-name { color: var(--fg); text-decoration: none; font-family: inherit; font-size: inherit; }
|
||||||
.badge { font-size: 18.9px; border: 1px solid var(--border); color: var(--muted-fg); border-radius: var(--radius-sm); padding: 1px 8px; }
|
.badge { font-size: 18.9px; border: 1px solid var(--border); color: var(--muted-fg); border-radius: var(--radius-sm); padding: 1px 8px; }
|
||||||
.badge.lock { color: var(--accent); border-color: var(--accent); }
|
.badge.lock { color: var(--accent); border-color: var(--accent); }
|
||||||
.dim { color: var(--muted-fg); white-space: nowrap; }
|
.dim { color: var(--muted-fg); white-space: nowrap; }
|
||||||
@@ -432,13 +448,15 @@ td a.slug.paste-name { background: none; padding: 0; border-radius: 0; font-fami
|
|||||||
|
|
||||||
/* protection section rhythm (#20) */
|
/* protection section rhythm (#20) */
|
||||||
.protect { display: flex; flex-direction: column; gap: 2px; }
|
.protect { display: flex; flex-direction: column; gap: 2px; }
|
||||||
.protect .pw-row { padding: 2px 8px 4px; }
|
.protect .pw-row:not(.submenu) { padding: 2px 8px 4px; }
|
||||||
|
|
||||||
/* submenu number boxes (#157): styled number inputs + unit selects,
|
/* submenu number boxes (#157): styled number inputs + unit selects,
|
||||||
padded + indented to line up with parent option labels */
|
padded + indented to line up with parent option labels */
|
||||||
.submenu {
|
.submenu {
|
||||||
margin: 6px 0 4px 8px;
|
/* #240: indent the box under the parent option LABEL text (8px row padding
|
||||||
padding: 8px 10px;
|
+ 16px control + 8px gap = 32px), and match the row control padding rhythm */
|
||||||
|
margin: 4px 0 4px 32px;
|
||||||
|
padding: 6px 10px;
|
||||||
background: var(--bg);
|
background: var(--bg);
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
@@ -515,7 +533,7 @@ td a.slug.paste-name { background: none; padding: 0; border-radius: 0; font-fami
|
|||||||
/* paste name under slug pill in Paste column (#43) */
|
/* paste name under slug pill in Paste column (#43) */
|
||||||
.paste-sub { font-size: 19.8px; color: var(--muted-fg); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.paste-sub { font-size: 19.8px; color: var(--muted-fg); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.paste-sub.dim { color: var(--muted); }
|
.paste-sub.dim { color: var(--muted); }
|
||||||
td a.slug.url-link { max-width: 100%; display: inline-block; vertical-align: middle; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; box-sizing: border-box; }
|
td a.url-link { max-width: 100%; display: inline-block; vertical-align: middle; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; box-sizing: border-box; }
|
||||||
td .id-link { color: var(--muted-fg); text-decoration: none; font-family: var(--font-mono); font-size: 19.8px; }
|
td .id-link { color: var(--muted-fg); text-decoration: none; font-family: var(--font-mono); font-size: 19.8px; }
|
||||||
td .id-link:hover { color: var(--accent); }
|
td .id-link:hover { color: var(--accent); }
|
||||||
|
|
||||||
@@ -575,6 +593,20 @@ a.admin-link:hover { color: var(--fg); text-decoration: underline; }
|
|||||||
border-color: var(--ok);
|
border-color: var(--ok);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* #260: static-width success feedback. Label and checkmark stack in one
|
||||||
|
grid cell, so the button is always as wide as the wider of the two and
|
||||||
|
never shifts on click. Feedback is a pure .ok class toggle. */
|
||||||
|
.swapbtn {
|
||||||
|
display: inline-grid;
|
||||||
|
}
|
||||||
|
.swapbtn > * {
|
||||||
|
grid-area: 1 / 1;
|
||||||
|
justify-self: center;
|
||||||
|
}
|
||||||
|
.swapbtn .swap-check { visibility: hidden; }
|
||||||
|
.swapbtn.ok .swap-check { visibility: visible; }
|
||||||
|
.swapbtn.ok .swap-label { visibility: hidden; }
|
||||||
|
|
||||||
/* headings: unified treatment (mirrors .side-section h3) */
|
/* headings: unified treatment (mirrors .side-section h3) */
|
||||||
.settings-head h1, .paste-title-bar h1, .head-row h1, .inner h1 {
|
.settings-head h1, .paste-title-bar h1, .head-row h1, .inner h1 {
|
||||||
letter-spacing: -0.01em;
|
letter-spacing: -0.01em;
|
||||||
@@ -662,26 +694,6 @@ a.admin-link:hover { color: var(--fg); text-decoration: underline; }
|
|||||||
.center .foot { font-size: 13px; }
|
.center .foot { font-size: 13px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* #4: can view page + can builder */
|
|
||||||
.can-page h1 { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
|
||||||
.can-items { display: flex; flex-direction: column; gap: 12px; margin-top: 14px; }
|
|
||||||
.can-item { padding: 12px 14px; }
|
|
||||||
.can-item-head { display: flex; align-items: center; gap: 10px; }
|
|
||||||
.can-item-head strong { flex: 1; word-break: break-all; }
|
|
||||||
.can-item-body { margin-top: 8px; }
|
|
||||||
.can-item-body summary { cursor: pointer; font-size: 19px; color: var(--muted, #888); }
|
|
||||||
/* #169: divider between the dropdown title and body must be persistent
|
|
||||||
(not hover dependent) and extend the full width of the card left and right */
|
|
||||||
.can-item-body[open] summary {
|
|
||||||
border-bottom: 1px solid var(--border);
|
|
||||||
margin: 0 -14px 8px;
|
|
||||||
padding: 0 14px 8px;
|
|
||||||
}
|
|
||||||
.can-item-body pre.code { margin: 8px 0 0; overflow-x: auto; }
|
|
||||||
.can-item-row { margin-top: 8px; }
|
|
||||||
.can-item-row .can-item-title { width: 100%; margin-bottom: 6px; }
|
|
||||||
.can-item-row .can-item-content { width: 100%; font-family: var(--mono, monospace); resize: vertical; }
|
|
||||||
|
|
||||||
/* ============================================================
|
/* ============================================================
|
||||||
Styled controls (#123) — buttons, selects, checkboxes, radios
|
Styled controls (#123) — buttons, selects, checkboxes, radios
|
||||||
match the custom URL box house pattern: 1px var(--border) on
|
match the custom URL box house pattern: 1px var(--border) on
|
||||||
@@ -809,23 +821,63 @@ button[type="submit"]:focus-visible,
|
|||||||
font-size: 22px; padding: 0 4px; border-radius: var(--radius-sm);
|
font-size: 22px; padding: 0 4px; border-radius: var(--radius-sm);
|
||||||
}
|
}
|
||||||
.file-chip .file-chip-remove:hover { color: var(--danger, #c0392b); }
|
.file-chip .file-chip-remove:hover { color: var(--danger, #c0392b); }
|
||||||
.attachment-bar { display: flex; flex-direction: column; gap: 10px; }
|
.attachment-bar { display: flex; flex-direction: column; gap: 10px; padding: 12px; }
|
||||||
.attachment-chip {
|
/* #221: the link pill under an image preview stays a small inline chip,
|
||||||
|
left-aligned under the image, not stretched above it. */
|
||||||
|
.attachment-bar .attachment-chip {
|
||||||
display: inline-flex; align-items: center; gap: 12px; align-self: flex-start;
|
display: inline-flex; align-items: center; gap: 12px; align-self: flex-start;
|
||||||
border: 1px solid var(--border); border-radius: var(--radius);
|
border: 1px solid var(--border); border-radius: var(--radius);
|
||||||
padding: 8px 16px; text-decoration: none; color: var(--fg);
|
padding: 6px 14px; text-decoration: none; color: var(--fg);
|
||||||
background: var(--surface-2); font-size: 21.6px;
|
background: var(--surface-2); font-size: 19px;
|
||||||
|
}
|
||||||
|
.attachment-bar .attachment-chip:hover { border-color: var(--accent); }
|
||||||
|
.attachment-bar .attachment-chip .attachment-name {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
/* #232: long filenames are truncated but the pill stays a reasonable
|
||||||
|
width; on narrow viewports it shrinks to the container instead of
|
||||||
|
overflowing the card. */
|
||||||
|
.attachment-bar .attachment-chip {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.attachment-bar .attachment-chip .attachment-name:hover {
|
||||||
|
white-space: normal;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
/* #221: images scale to fit the viewer box, aspect ratio preserved. */
|
||||||
|
.attachment-preview {
|
||||||
|
max-width: 100%;
|
||||||
|
align-self: flex-start;
|
||||||
|
/* #229: no inner border/radius of its own; the .float wrapper already
|
||||||
|
frames the pill (inner borders get corner-clipped by overflow:hidden).
|
||||||
|
Padding on .attachment-bar gives the image breathing room from the
|
||||||
|
pill border. */
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
background: var(--surface-2);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.attachment-preview img {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 70vh;
|
||||||
|
width: auto;
|
||||||
|
height: auto;
|
||||||
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
.attachment-chip:hover { border-color: var(--accent); }
|
|
||||||
.attachment-chip .attachment-size { color: var(--muted-fg); font-size: 19px; }
|
|
||||||
.attachment-preview img { max-width: 480px; max-height: 360px; border-radius: var(--radius); border: 1px solid var(--border); }
|
|
||||||
|
|
||||||
/* #139: CSP-safe replacements for inline style attributes (style-src 'self') */
|
/* #139: CSP-safe replacements for inline style attributes (style-src 'self') */
|
||||||
.hidden { display: none; }
|
.hidden { display: none; }
|
||||||
.can-page { max-width: 900px; width: 100%; }
|
|
||||||
.col-a { width: 260px; } .col-b { width: 140px; } .col-c { width: 120px; }
|
.col-a { width: 260px; } .col-b { width: 140px; } .col-c { width: 120px; }
|
||||||
.col-d { width: 96px; } .col-d2 { width: 150px; } .col-e { width: 190px; }
|
.col-d { width: 90px; } .col-d2 { width: 150px; } .col-e { width: 150px; }
|
||||||
.col-f { width: 100px; } .col-g { width: 190px; }
|
.col-f { width: 100px; } .col-g { width: 120px; }
|
||||||
|
/* #255: history's URL column had its own narrow width (col-f doubles as
|
||||||
|
/mine's ID column); give it a dedicated class. */
|
||||||
|
.col-url { width: 230px; }
|
||||||
/* #210: /mine rows render a delete button cell that had no declared column,
|
/* #210: /mine rows render a delete button cell that had no declared column,
|
||||||
so under table-layout:fixed it overlapped the ID column. */
|
so under table-layout:fixed it overlapped the ID column. */
|
||||||
.col-del { width: 64px; }
|
.col-del { width: 64px; }
|
||||||
@@ -841,3 +893,33 @@ button[type="submit"]:focus-visible,
|
|||||||
.created-banner { display: block; }
|
.created-banner { display: block; }
|
||||||
/* #167: gutter rows for wrapped paste view — one row per visual code line */
|
/* #167: gutter rows for wrapped paste view — one row per visual code line */
|
||||||
.gutline { display: block; }
|
.gutline { display: block; }
|
||||||
|
|
||||||
|
/* #267: jump to top/bottom pills for long pastes and the editor.
|
||||||
|
Hidden unless JS (jump.js) detects content more than 2x the viewport. */
|
||||||
|
.jumpnav {
|
||||||
|
position: fixed;
|
||||||
|
right: 18px;
|
||||||
|
bottom: 18px;
|
||||||
|
z-index: 50;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.jumpnav.hidden { display: none; }
|
||||||
|
.jump-btn { box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25); }
|
||||||
|
|
||||||
|
/* #273: theme-aware scrollbars. Standard properties first (Firefox, and
|
||||||
|
Chromium >= 121 honors scrollbar-color), then ::-webkit rules for finer
|
||||||
|
Chromium styling. Colors come from CSS vars so they track the preset. */
|
||||||
|
* {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: var(--border) transparent;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||||
|
::-webkit-scrollbar-track { background: transparent; }
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: var(--border);
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb:hover { background: var(--muted-fg); }
|
||||||
|
::-webkit-scrollbar-corner { background: transparent; }
|
||||||
@@ -6,12 +6,12 @@ const t = PaletteTable.init({
|
|||||||
rowHtml: it =>
|
rowHtml: it =>
|
||||||
`<tr class="row" data-href="/${t.esc(it.id)}"><td>` +
|
`<tr class="row" data-href="/${t.esc(it.id)}"><td>` +
|
||||||
(it.title
|
(it.title
|
||||||
? `${t.esc(it.title)}${it.is_can ? ' <span class="badge" title="Can — bundle of items">can</span>' : ''}`
|
? `<a class="paste-name" href="/${t.esc(it.id)}">${t.esc(it.title)}</a>`
|
||||||
: `<a class="slug paste-name" href="/${t.esc(it.id)}">${t.esc(it.id)}</a>${it.is_can ? ' <span class="badge" title="Can — bundle of items">can</span>' : ''}`) +
|
: `<a class="slug paste-name" href="/${t.esc(it.id)}">${t.esc(it.id)}</a>`) +
|
||||||
`</td>` +
|
`</td>` +
|
||||||
`<td><span class="badge">${t.esc(it.language || 'text')}</span></td>` +
|
`<td><span class="badge">${t.esc(it.type || it.language || 'text')}</span></td>` +
|
||||||
`<td class="dim">${t.fmtSize(it.size)}</td><td class="dim">${it.view_count}</td><td class="dim" data-ts="${it.created_at}">${t.ago(it.created_at)}</td>` +
|
`<td class="dim">${t.fmtSize(it.size)}</td><td class="dim">${it.view_count}</td><td class="dim" data-ts="${it.created_at}">${t.ago(it.created_at)}</td>` +
|
||||||
(it.custom_slug ? `<td><a class="slug url-link" href="/${t.esc(it.custom_slug)}">/${t.esc(it.custom_slug)}</a></td>` : `<td class="dim">none</td>`) +
|
(it.custom_slug ? `<td class="dim"><a class="url-link" href="/${t.esc(it.custom_slug)}">/${t.esc(it.custom_slug)}</a></td>` : `<td class="dim">none</td>`) +
|
||||||
`<td class="dim"><a class="id-link" href="/${t.esc(it.id)}">${t.esc(it.id)}</a></td></tr>`,
|
`<td class="dim"><a class="id-link" href="/${t.esc(it.id)}">${t.esc(it.id)}</a></td></tr>`,
|
||||||
emptyFiltered: 'No pastes match your search.',
|
emptyFiltered: 'No pastes match your search.',
|
||||||
emptyAll: 'No pastes yet. Create the first one.',
|
emptyAll: 'No pastes yet. Create the first one.',
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/* #267: jump to top / bottom controls for long content.
|
||||||
|
Paste view scrolls the window; the /new editor scrolls its textarea.
|
||||||
|
The active scroller is chosen via data-jump-scroll on the script tag. */
|
||||||
|
(function () {
|
||||||
|
var nav = document.getElementById('jumpnav');
|
||||||
|
if (!nav) return;
|
||||||
|
var scroller = window;
|
||||||
|
var sel = nav.dataset.jumpScroll;
|
||||||
|
if (sel) scroller = document.querySelector(sel);
|
||||||
|
|
||||||
|
function el() {
|
||||||
|
return scroller === window ? document.scrollingElement : scroller;
|
||||||
|
}
|
||||||
|
function isLarge() {
|
||||||
|
var e = el();
|
||||||
|
if (!e) return false;
|
||||||
|
var visible = scroller === window ? window.innerHeight : e.clientHeight;
|
||||||
|
return e.scrollHeight > visible * 2;
|
||||||
|
}
|
||||||
|
function refresh() {
|
||||||
|
nav.classList.toggle('hidden', !isLarge());
|
||||||
|
}
|
||||||
|
function jump(toTop) {
|
||||||
|
var e = el();
|
||||||
|
if (!e) return;
|
||||||
|
if (scroller === window) {
|
||||||
|
window.scrollTo({ top: toTop ? 0 : e.scrollHeight });
|
||||||
|
} else {
|
||||||
|
e.scrollTop = toTop ? 0 : e.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nav.addEventListener('click', function (ev) {
|
||||||
|
var b = ev.target.closest('[data-jump]');
|
||||||
|
if (!b) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
jump(b.dataset.jump === 'top');
|
||||||
|
});
|
||||||
|
window.addEventListener('resize', refresh);
|
||||||
|
if (scroller !== window && scroller) scroller.addEventListener('input', refresh);
|
||||||
|
refresh();
|
||||||
|
/* #282: the first evaluation can run before the layout settles (media
|
||||||
|
queries, web fonts, async highlighting) and under-measure the content,
|
||||||
|
leaving the nav hidden on long pages. Re-check once a real layout exists
|
||||||
|
and after load; the ResizeObserver also catches late content growth. */
|
||||||
|
requestAnimationFrame(function () { requestAnimationFrame(refresh); });
|
||||||
|
window.addEventListener('load', refresh);
|
||||||
|
window.setTimeout(refresh, 300);
|
||||||
|
if (window.ResizeObserver && scroller === window && document.body) {
|
||||||
|
new ResizeObserver(refresh).observe(document.body);
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -18,12 +18,12 @@ const t = PaletteTable.init({
|
|||||||
rowHtml: it =>
|
rowHtml: it =>
|
||||||
`<tr class="row" data-href="/${t.esc(it.id)}"><td>` +
|
`<tr class="row" data-href="/${t.esc(it.id)}"><td>` +
|
||||||
(it.title
|
(it.title
|
||||||
? `${t.esc(it.title)}${it.is_can ? ' <span class="badge" title="Can — bundle of items">can</span>' : ''}`
|
? `<a class="paste-name" href="/${t.esc(it.id)}">${t.esc(it.title)}</a>`
|
||||||
: `<a class="slug paste-name" href="/${t.esc(it.id)}">${t.esc(it.id)}</a>${it.is_can ? ' <span class="badge" title="Can — bundle of items">can</span>' : ''}`) +
|
: `<a class="slug paste-name" href="/${t.esc(it.id)}">${t.esc(it.id)}</a>`) +
|
||||||
`</td>` +
|
`</td>` +
|
||||||
`<td><span class="badge">${t.esc(it.language || 'text')}</span></td>` +
|
`<td><span class="badge">${t.esc(it.type || it.language || 'text')}</span></td>` +
|
||||||
`<td class="dim">${t.fmtSize(it.size)}</td><td class="dim" data-ts="${it.created_at}">${t.ago(it.created_at)}</td>` +
|
`<td class="dim">${t.fmtSize(it.size)}</td><td class="dim" data-ts="${it.created_at}">${t.ago(it.created_at)}</td>` +
|
||||||
(it.custom_slug ? `<td><a class="slug url-link" href="/${t.esc(it.custom_slug)}">/${t.esc(it.custom_slug)}</a></td>` : `<td class="dim">none</td>`) +
|
(it.custom_slug ? `<td class="dim"><a class="url-link" href="/${t.esc(it.custom_slug)}">/${t.esc(it.custom_slug)}</a></td>` : `<td class="dim">none</td>`) +
|
||||||
`<td class="dim"><a class="id-link" href="/${t.esc(it.id)}">${t.esc(it.id)}</a></td>` +
|
`<td class="dim"><a class="id-link" href="/${t.esc(it.id)}">${t.esc(it.id)}</a></td>` +
|
||||||
`<td><button class="btn btn-icon del" data-id="${t.esc(it.id)}" title="Delete paste" aria-label="Delete paste">×</button></td></tr>`,
|
`<td><button class="btn btn-icon del" data-id="${t.esc(it.id)}" title="Delete paste" aria-label="Delete paste">×</button></td></tr>`,
|
||||||
emptyFiltered: 'No pastes from this browser match your search.',
|
emptyFiltered: 'No pastes from this browser match your search.',
|
||||||
|
|||||||
+79
-20
@@ -2,13 +2,73 @@
|
|||||||
const $ = id => document.getElementById(id);
|
const $ = id => document.getElementById(id);
|
||||||
const content = $('content'), gutter = $('gutter');
|
const content = $('content'), gutter = $('gutter');
|
||||||
|
|
||||||
|
// #274: with wrap on, a logical line occupies several VISUAL rows in the
|
||||||
|
// textarea, so one number per logical line drifts off its text (same bug the
|
||||||
|
// paste view fixed in #167). A textarea can't be split into spans, so the
|
||||||
|
// wrapped row count per logical line is measured with a hidden mirror div
|
||||||
|
// that shares the editor's font, line metrics and wrapping rules, and the
|
||||||
|
// gutter renders one .gutline block per visual row with the number on the
|
||||||
|
// FIRST row of its logical line (fillers elsewhere).
|
||||||
|
let mirror = null;
|
||||||
|
function measureRows(lines) {
|
||||||
|
if (!mirror) {
|
||||||
|
mirror = document.createElement('div');
|
||||||
|
mirror.style.position = 'absolute';
|
||||||
|
mirror.style.visibility = 'hidden';
|
||||||
|
mirror.style.top = '0';
|
||||||
|
mirror.style.left = '-9999px';
|
||||||
|
document.body.appendChild(mirror);
|
||||||
|
}
|
||||||
|
const cs = getComputedStyle(content);
|
||||||
|
mirror.style.font = cs.font;
|
||||||
|
mirror.style.lineHeight = cs.lineHeight;
|
||||||
|
mirror.style.whiteSpace = 'pre-wrap';
|
||||||
|
mirror.style.overflowWrap = 'anywhere';
|
||||||
|
mirror.style.wordBreak = 'break-all';
|
||||||
|
mirror.style.width = (content.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight)) + 'px';
|
||||||
|
const lh = parseFloat(cs.lineHeight) || 1;
|
||||||
|
const starts = [];
|
||||||
|
let total = 0;
|
||||||
|
const n = Math.max(lines.length, 1);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
// A trailing newline yields an empty last line: it still occupies one row.
|
||||||
|
mirror.textContent = lines[i] + '\n';
|
||||||
|
let rows = Math.max(1, Math.round(mirror.getBoundingClientRect().height / lh));
|
||||||
|
starts.push(total);
|
||||||
|
total += rows;
|
||||||
|
}
|
||||||
|
return { starts, total };
|
||||||
|
}
|
||||||
|
|
||||||
function updateGutter() {
|
function updateGutter() {
|
||||||
const lines = content.value.split('\n').length;
|
const lines = content.value.split('\n');
|
||||||
let s = '';
|
const n = Math.max(lines.length, 1);
|
||||||
for (let i = 1; i <= Math.max(lines, 1); i++) s += i + '\n';
|
if (!document.documentElement.hasAttribute('data-wrap')) {
|
||||||
gutter.textContent = s;
|
let s = '';
|
||||||
|
for (let i = 1; i <= n; i++) s += i + '\n';
|
||||||
|
gutter.textContent = s.slice(0, -1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { starts, total } = measureRows(lines);
|
||||||
|
gutter.textContent = '';
|
||||||
|
const frag = document.createDocumentFragment();
|
||||||
|
const spans = [];
|
||||||
|
for (let r = 0; r < total; r++) {
|
||||||
|
const c = document.createElement('span');
|
||||||
|
c.className = 'gutline';
|
||||||
|
c.textContent = '\u00a0';
|
||||||
|
spans.push(c);
|
||||||
|
frag.appendChild(c);
|
||||||
|
}
|
||||||
|
gutter.appendChild(frag);
|
||||||
|
for (let j = 0; j < starts.length; j++) spans[starts[j]].textContent = String(j + 1);
|
||||||
}
|
}
|
||||||
content.addEventListener('input', updateGutter);
|
content.addEventListener('input', updateGutter);
|
||||||
|
// #274: the wrap toggle and width changes re-wrap the textarea; re-measure.
|
||||||
|
new MutationObserver(updateGutter).observe(document.documentElement, { attributes: true, attributeFilter: ['data-wrap'] });
|
||||||
|
window.addEventListener('resize', updateGutter);
|
||||||
|
// #259: the editor scrolls itself; keep the gutter's numbers in step with it.
|
||||||
|
content.addEventListener('scroll', () => { gutter.scrollTop = content.scrollTop; });
|
||||||
updateGutter();
|
updateGutter();
|
||||||
|
|
||||||
function toast(msg, kind) {
|
function toast(msg, kind) {
|
||||||
@@ -190,15 +250,16 @@ async function create() {
|
|||||||
// button, password auto-unlock, then redirect to the paste.
|
// button, password auto-unlock, then redirect to the paste.
|
||||||
function finishCreate(data) {
|
function finishCreate(data) {
|
||||||
const url = location.origin + '/' + (data.custom_slug || data.id);
|
const url = location.origin + '/' + (data.custom_slug || data.id);
|
||||||
showResult('<a href="' + url + '">' + url + '</a> <button class="btn btn-icon" id="result-copy" title="Copy URL" type="button">⧉</button>', 'ok');
|
// #260 attempt 2: .swapbtn markup — label and checkmark share one grid
|
||||||
|
// cell, so the button width is static and feedback is a class toggle.
|
||||||
|
showResult('<a href="' + url + '">' + url + '</a> <button class="btn btn-icon swapbtn" id="result-copy" title="Copy URL" type="button"><span class="swap-label">Copy</span><span class="swap-check">✓</span></button>', 'ok');
|
||||||
$('result').dataset.token = data.deletion_token || '';
|
$('result').dataset.token = data.deletion_token || '';
|
||||||
const copyBtn = document.getElementById('result-copy');
|
const copyBtn = document.getElementById('result-copy');
|
||||||
copyBtn.addEventListener('click', () => {
|
copyBtn.addEventListener('click', () => {
|
||||||
try {
|
try {
|
||||||
navigator.clipboard.writeText(url);
|
navigator.clipboard.writeText(url);
|
||||||
copyBtn.classList.add('ok'); // in-place success feedback (#53)
|
copyBtn.classList.add('ok'); // in-place success feedback (#53)
|
||||||
copyBtn.textContent = 'Success!';
|
setTimeout(() => copyBtn.classList.remove('ok'), 2000);
|
||||||
setTimeout(() => { copyBtn.classList.remove('ok'); copyBtn.textContent = '⧉'; }, 2000);
|
|
||||||
} catch(e) { toast('Copy failed', 'error'); }
|
} catch(e) { toast('Copy failed', 'error'); }
|
||||||
});
|
});
|
||||||
// token carried via sessionStorage, never in the URL (#143)
|
// token carried via sessionStorage, never in the URL (#143)
|
||||||
@@ -307,21 +368,19 @@ function setAttachedFile(file) {
|
|||||||
attachedFile = file;
|
attachedFile = file;
|
||||||
renderFileChip();
|
renderFileChip();
|
||||||
setHidden('file-text-note', false);
|
setHidden('file-text-note', false);
|
||||||
// #171/#184: title auto-fill — images take the file name; text files
|
// #233: title auto-fill — the file's own name always wins when the
|
||||||
// use the language-placeholder convention (e.g. Python.py, fallback
|
// title is still blank; fallback is date.fileextension (e.g.
|
||||||
// Text.txt). Only when the title is still blank; never overwrite a
|
// 2026-09-10.txt) when the name is missing or unusable. Never
|
||||||
// typed title.
|
// overwrite a typed title.
|
||||||
if (!$('title').value.trim()) {
|
if (!$('title').value.trim()) {
|
||||||
if (IMAGE_RE.test(file.type)) {
|
const raw = (file.name || '').trim();
|
||||||
$('title').value = file.name;
|
if (raw) {
|
||||||
|
$('title').value = raw;
|
||||||
} else {
|
} else {
|
||||||
const lang = LANG_BY_EXT[extOf(file.name)];
|
const d = new Date();
|
||||||
if (lang) {
|
const iso = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
|
||||||
const fn = defaultFilename(lang);
|
const ext = extOf(raw || file.name);
|
||||||
if (fn) $('title').value = fn;
|
$('title').value = ext ? iso + '.' + ext : iso;
|
||||||
} else if (TEXT_EXTS.has(extOf(file.name))) {
|
|
||||||
$('title').value = defaultFilename('text') || 'Text.txt';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
showFileInEditor(file);
|
showFileInEditor(file);
|
||||||
|
|||||||
@@ -44,6 +44,23 @@
|
|||||||
// measured, not derived from span counts or heights.
|
// measured, not derived from span counts or heights.
|
||||||
function renumber() {
|
function renumber() {
|
||||||
var lines = body.querySelectorAll('.codeline');
|
var lines = body.querySelectorAll('.codeline');
|
||||||
|
// #257: size the gutter column to the widest line number so numbers in
|
||||||
|
// the 100s+ fit their own column instead of bleeding into the code text.
|
||||||
|
// The gutter is box-sizing: border-box, so the column width must be the
|
||||||
|
// digits PLUS the 10px left + 10px right padding; at the CSS default 3ch
|
||||||
|
// the padding alone leaves only ~19px of content, and any 2+ digit
|
||||||
|
// number overflows into the code. Numbers are right-aligned, and the
|
||||||
|
// width below fits the widest number exactly. Set via CSSOM (CSP
|
||||||
|
// forbids inline style attributes). Only touch the width when it
|
||||||
|
// changes: the resize observer below re-runs renumber() when the gutter
|
||||||
|
// width reflows the code column, and rewriting the same value would
|
||||||
|
// ping-pong the fixed point forever.
|
||||||
|
var digits = String(lines.length || 1).length;
|
||||||
|
var w = 'calc(' + digits + 'ch + 20px)';
|
||||||
|
if (gutter.style.width !== w) {
|
||||||
|
gutter.style.minWidth = w;
|
||||||
|
gutter.style.width = w;
|
||||||
|
}
|
||||||
if (!wrapOn() || !lines.length) {
|
if (!wrapOn() || !lines.length) {
|
||||||
// wrap OFF: one number per logical line (pre-existing behavior,
|
// wrap OFF: one number per logical line (pre-existing behavior,
|
||||||
// including the gutter scrolling with horizontal scroll).
|
// including the gutter scrolling with horizontal scroll).
|
||||||
|
|||||||
@@ -16,17 +16,26 @@ function toggleStats() {
|
|||||||
pill.classList.toggle('open', open);
|
pill.classList.toggle('open', open);
|
||||||
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
|
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||||
}
|
}
|
||||||
|
function copyFeedback(btn) {
|
||||||
|
if (!btn) return;
|
||||||
|
// #260 attempt 2: .swapbtn stacks the label and checkmark in the same grid
|
||||||
|
// cell, so the button width is always the wider of the two and never moves.
|
||||||
|
// Feedback is a pure class toggle; no width pinning, no textContent swap.
|
||||||
|
btn.classList.add('ok');
|
||||||
|
clearTimeout(btn._okh);
|
||||||
|
btn._okh = setTimeout(() => btn.classList.remove('ok'), 2000);
|
||||||
|
}
|
||||||
function copyContent(btn) {
|
function copyContent(btn) {
|
||||||
navigator.clipboard.writeText(document.getElementById('raw-content').value);
|
navigator.clipboard.writeText(document.getElementById('raw-content').value)
|
||||||
// in-place success feedback (#53)
|
.then(() => copyFeedback(btn))
|
||||||
if (btn) {
|
.catch(() => toast('Copy failed'));
|
||||||
btn.classList.add('ok');
|
}
|
||||||
btn.textContent = 'Success!';
|
// #243: copy the paste LINK (full URL), not the paste id or content
|
||||||
clearTimeout(btn._okh);
|
function copyLink(btn) {
|
||||||
btn._okh = setTimeout(() => { btn.classList.remove('ok'); btn.textContent = 'copy'; }, 2000);
|
const url = location.origin + location.pathname;
|
||||||
} else {
|
navigator.clipboard.writeText(url)
|
||||||
toast('Link Copied', 'success');
|
.then(() => copyFeedback(btn))
|
||||||
}
|
.catch(() => toast('Copy failed'));
|
||||||
}
|
}
|
||||||
function redeem() {
|
function redeem() {
|
||||||
if (!confirm('Hard delete this paste immediately?')) return;
|
if (!confirm('Hard delete this paste immediately?')) return;
|
||||||
@@ -34,13 +43,15 @@ function redeem() {
|
|||||||
try { tok = sessionStorage.getItem('deletion_token_' + PASTE_ID) || ''; } catch(e) {}
|
try { tok = sessionStorage.getItem('deletion_token_' + PASTE_ID) || ''; } catch(e) {}
|
||||||
if (!tok) { alert('deletion token not available in this browser'); return; }
|
if (!tok) { alert('deletion token not available in this browser'); return; }
|
||||||
fetch('/api/pastes/' + PASTE_ID + '/redeem', {method: 'DELETE', headers: {'Authorization': 'Bearer ' + tok}})
|
fetch('/api/pastes/' + PASTE_ID + '/redeem', {method: 'DELETE', headers: {'Authorization': 'Bearer ' + tok}})
|
||||||
.then(r => { if (r.ok) location.href = '/history'; else alert('delete failed'); });
|
.then(r => { if (r.ok) location.href = '/public'; else alert('delete failed'); });
|
||||||
}
|
}
|
||||||
|
|
||||||
// wiring (moved from inline handlers for CSP #139)
|
// wiring (moved from inline handlers for CSP #139)
|
||||||
var PASTE_ID = document.currentScript.getAttribute('data-paste-id');
|
var PASTE_ID = document.currentScript.getAttribute('data-paste-id');
|
||||||
var copyBtn = document.getElementById('copy-btn');
|
var copyBtn = document.getElementById('copy-btn');
|
||||||
if (copyBtn) copyBtn.addEventListener('click', function (e) { e.preventDefault(); copyContent(copyBtn); });
|
if (copyBtn) copyBtn.addEventListener('click', function (e) { e.preventDefault(); copyContent(copyBtn); });
|
||||||
|
var copyLinkBtn = document.getElementById('copy-link-btn');
|
||||||
|
if (copyLinkBtn) copyLinkBtn.addEventListener('click', function (e) { e.preventDefault(); copyLink(copyLinkBtn); });
|
||||||
var delBtn = document.getElementById('delete-btn');
|
var delBtn = document.getElementById('delete-btn');
|
||||||
|
|
||||||
// #168: show the compact paste-created pill in the bottom corner, then fade it out
|
// #168: show the compact paste-created pill in the bottom corner, then fade it out
|
||||||
|
|||||||
@@ -73,7 +73,10 @@
|
|||||||
});
|
});
|
||||||
btn.addEventListener('click', function () {
|
btn.addEventListener('click', function () {
|
||||||
var dark = state().dark;
|
var dark = state().dark;
|
||||||
document.documentElement.dataset.preset = dark ? t.id + '-dark' : t.id;
|
// #294: use the generic variant resolvers - midnight is dark-first
|
||||||
|
// (dark preset = 'midnight', light = 'midnight-light'), so a raw
|
||||||
|
// t.id + '-dark' build landed on nonexistent/forced-dark presets.
|
||||||
|
document.documentElement.dataset.preset = dark ? darkPreset(t.id) : lightPreset(t.id);
|
||||||
try { localStorage.setItem('palette-theme', t.id); } catch (e) {}
|
try { localStorage.setItem('palette-theme', t.id); } catch (e) {}
|
||||||
Object.keys(cards).forEach(function (k) { cards[k].setAttribute('aria-pressed', 'false'); });
|
Object.keys(cards).forEach(function (k) { cards[k].setAttribute('aria-pressed', 'false'); });
|
||||||
btn.setAttribute('aria-pressed', 'true');
|
btn.setAttribute('aria-pressed', 'true');
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const PaletteTable = (() => {
|
|||||||
const sortVal = (it, k) => {
|
const sortVal = (it, k) => {
|
||||||
let v = it[k];
|
let v = it[k];
|
||||||
if (k === 'title' || k === 'custom_slug') v = (v == null || v === '') ? null : String(v).toLowerCase();
|
if (k === 'title' || k === 'custom_slug') v = (v == null || v === '') ? null : String(v).toLowerCase();
|
||||||
if (k === 'language') v = (v == null || v === '') ? 'text' : String(v).toLowerCase();
|
if (k === 'language' || k === 'type') v = (v == null || v === '') ? 'text' : String(v).toLowerCase();
|
||||||
if (k === 'size' || k === 'view_count' || k === 'created_at') return v == null ? -1 : v;
|
if (k === 'size' || k === 'view_count' || k === 'created_at') return v == null ? -1 : v;
|
||||||
return v == null ? null : v;
|
return v == null ? null : v;
|
||||||
};
|
};
|
||||||
@@ -104,7 +104,7 @@ const PaletteTable = (() => {
|
|||||||
const btns = [];
|
const btns = [];
|
||||||
const add = (label, target, o={}) => btns.push(`<button ${o.on?'class="on"':''} ${o.dis?'disabled':''} data-p="${target}">${label}</button>`);
|
const add = (label, target, o={}) => btns.push(`<button ${o.on?'class="on"':''} ${o.dis?'disabled':''} data-p="${target}">${label}</button>`);
|
||||||
add('‹', state.page-1, {dis: state.page===1});
|
add('‹', state.page-1, {dis: state.page===1});
|
||||||
const win = new Set([1, 2, state.page-1, state.page, state.page+1, filtPages]);
|
const win = new Set([1, state.page-1, state.page, state.page+1, filtPages]);
|
||||||
let last = 0;
|
let last = 0;
|
||||||
for (let i = 1; i <= filtPages; i++) {
|
for (let i = 1; i <= filtPages; i++) {
|
||||||
if (win.has(i)) {
|
if (win.has(i)) {
|
||||||
@@ -121,7 +121,7 @@ const PaletteTable = (() => {
|
|||||||
const btns = [];
|
const btns = [];
|
||||||
const add = (label, target, o={}) => btns.push(`<button ${o.on?'class="on"':''} ${o.dis?'disabled':''} data-p="${target}">${label}</button>`);
|
const add = (label, target, o={}) => btns.push(`<button ${o.on?'class="on"':''} ${o.dis?'disabled':''} data-p="${target}">${label}</button>`);
|
||||||
add('‹', state.page-1, {dis: state.page===1});
|
add('‹', state.page-1, {dis: state.page===1});
|
||||||
const win = new Set([1, 2, state.page-1, state.page, state.page+1, pages]);
|
const win = new Set([1, state.page-1, state.page, state.page+1, pages]);
|
||||||
let last = 0;
|
let last = 0;
|
||||||
for (let i = 1; i <= pages; i++) {
|
for (let i = 1; i <= pages; i++) {
|
||||||
if (win.has(i)) {
|
if (win.has(i)) {
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
{{template "head" .}}
|
|
||||||
{{template "topbar" .}}
|
|
||||||
<div class="center">
|
|
||||||
<div class="float can-page">
|
|
||||||
<div class="inner">
|
|
||||||
<h1>{{.Title}} <span class="badge" title="This is a can — a bundle of pastes">can</span></h1>
|
|
||||||
{{if .HasDescription}}<p class="sub">{{.Description}}</p>{{end}}
|
|
||||||
<p class="hint">{{.ItemCount}} item{{if ne .ItemCount 1}}s{{end}} · {{.SizeHuman}} · created <span data-ts="{{.CreatedAtUnix}}">{{.CreatedAgo}}</span>{{if .ExpiresAt}} · expires in {{.ExpiresIn}}{{end}}{{if .HasPassword}} · password protected{{end}}</p>
|
|
||||||
|
|
||||||
<div class="can-items">
|
|
||||||
{{range .Items}}
|
|
||||||
<div class="can-item float">
|
|
||||||
<div class="can-item-head">
|
|
||||||
<strong>{{.Title}}</strong>
|
|
||||||
<span class="dim">{{.Size}}</span>
|
|
||||||
{{if .IsFile}}
|
|
||||||
<a class="btn btn-icon" href="/api/cans/{{$.ID}}/items/{{.ID}}" download="{{.Title}}" title="Download file" aria-label="Download {{.Title}}">↓</a>
|
|
||||||
{{else}}
|
|
||||||
<a class="btn btn-icon" href="/api/cans/{{$.ID}}/items/{{.ID}}" title="Raw item" aria-label="Raw {{.Title}}">⧉</a>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
|
||||||
{{if not .IsFile}}
|
|
||||||
<details class="can-item-body">
|
|
||||||
<summary>Show content</summary>
|
|
||||||
<pre class="code"><code>{{.ContentHTML}}</code></pre>
|
|
||||||
</details>
|
|
||||||
{{else}}
|
|
||||||
<div class="hint">Attached file — use the download button above.</div>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{{template "foot" .}}
|
|
||||||
@@ -8,10 +8,10 @@
|
|||||||
<div class="search"><input id="filter" placeholder="Search…"><span class="search-spinner" id="search-spinner"></span></div>
|
<div class="search"><input id="filter" placeholder="Search…"><span class="search-spinner" id="search-spinner"></span></div>
|
||||||
<div class="float">
|
<div class="float">
|
||||||
<table>
|
<table>
|
||||||
<colgroup><col class="col-a"><col class="col-b"><col class="col-c"><col class="col-d"><col class="col-e"><col class="col-f"><col class="col-g"></colgroup>
|
<colgroup><col class="col-a"><col class="col-b"><col class="col-c"><col class="col-d"><col class="col-e"><col class="col-url"><col class="col-g"></colgroup>
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th data-sort="title" class="sortable">Paste<span class="sort-ind"></span></th>
|
<th data-sort="title" class="sortable">Paste<span class="sort-ind"></span></th>
|
||||||
<th data-sort="language" class="sortable">Language<span class="sort-ind"></span></th>
|
<th data-sort="type" class="sortable">Type<span class="sort-ind"></span></th>
|
||||||
<th data-sort="size" class="sortable">Size<span class="sort-ind"></span></th>
|
<th data-sort="size" class="sortable">Size<span class="sort-ind"></span></th>
|
||||||
<th data-sort="view_count" class="sortable">Views<span class="sort-ind"></span></th>
|
<th data-sort="view_count" class="sortable">Views<span class="sort-ind"></span></th>
|
||||||
<th data-sort="created_at" class="sortable">Created<span class="sort-ind"></span></th>
|
<th data-sort="created_at" class="sortable">Created<span class="sort-ind"></span></th>
|
||||||
|
|||||||
@@ -8,11 +8,11 @@
|
|||||||
|
|
||||||
{{define "topbar"}}
|
{{define "topbar"}}
|
||||||
<div class="topbar">
|
<div class="topbar">
|
||||||
<a class="logo" href="/history">Palette <em>/ {{ version }}</em></a>
|
<a class="logo" href="/public">Palette <em>/ {{ version }}</em></a>
|
||||||
<nav>
|
<nav>
|
||||||
<a href="/new" {{if eq .Page "new"}}class="on"{{end}}>New</a>
|
<a href="/new" {{if eq .Page "new"}}class="on"{{end}}>New</a>
|
||||||
<a href="/history" {{if eq .Page "history"}}class="on"{{end}}>Public</a>
|
<a href="/public" {{if eq .Page "public"}}class="on"{{end}}>Public</a>
|
||||||
<a href="/mine" {{if eq .Page "mine"}}class="on"{{end}}>Saved</a>
|
<a href="/saved" {{if eq .Page "saved"}}class="on"{{end}}>Saved</a>
|
||||||
<a href="https://git.archfox.org/poslop/palette" target="_blank" rel="noopener">Git<svg class="ext" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></a>
|
<a href="https://git.archfox.org/poslop/palette" target="_blank" rel="noopener">Git<svg class="ext" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></a>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
|
|||||||
@@ -8,10 +8,10 @@
|
|||||||
<div class="search"><input id="filter" placeholder="Search…"><span class="search-spinner" id="search-spinner"></span></div>
|
<div class="search"><input id="filter" placeholder="Search…"><span class="search-spinner" id="search-spinner"></span></div>
|
||||||
<div class="float">
|
<div class="float">
|
||||||
<table>
|
<table>
|
||||||
<colgroup><col class="col-a"><col class="col-b"><col class="col-c"><col class="col-d2"><col class="col-e"><col class="col-f"><col class="col-del"></colgroup>
|
<colgroup><col class="col-a"><col class="col-b"><col class="col-c"><col class="col-d2"><col class="col-url"><col class="col-f"><col class="col-del"></colgroup>
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th data-sort="title" class="sortable">Paste<span class="sort-ind"></span></th>
|
<th data-sort="title" class="sortable">Paste<span class="sort-ind"></span></th>
|
||||||
<th data-sort="language" class="sortable">Language<span class="sort-ind"></span></th>
|
<th data-sort="type" class="sortable">Type<span class="sort-ind"></span></th>
|
||||||
<th data-sort="size" class="sortable">Size<span class="sort-ind"></span></th>
|
<th data-sort="size" class="sortable">Size<span class="sort-ind"></span></th>
|
||||||
<th data-sort="created_at" class="sortable">Created<span class="sort-ind"></span></th>
|
<th data-sort="created_at" class="sortable">Created<span class="sort-ind"></span></th>
|
||||||
<th data-sort="custom_slug" class="sortable">URL<span class="sort-ind"></span></th>
|
<th data-sort="custom_slug" class="sortable">URL<span class="sort-ind"></span></th>
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
<option>markdown</option><option>text</option>
|
<option>markdown</option><option>text</option>
|
||||||
</select>
|
</select>
|
||||||
<button class="btn btn-icon" id="reguess" title="Re-detect language" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/></svg></button>
|
<button class="btn btn-icon" id="reguess" title="Re-detect language" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/></svg></button>
|
||||||
<button type="button" class="btn btn-icon wrap-toggle" id="wrap-toggle" title="Toggle line wrap" aria-pressed="false">wrap</button>
|
<button type="button" class="btn btn-icon wrap-toggle" id="wrap-toggle" title="Toggle line wrap" aria-pressed="false">Wrap</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -33,6 +33,10 @@
|
|||||||
<div class="spacer spacer-flex"></div>
|
<div class="spacer spacer-flex"></div>
|
||||||
<button class="btn" id="create">Create</button>
|
<button class="btn" id="create">Create</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="jumpnav hidden" id="jumpnav" data-jump-scroll="#content">
|
||||||
|
<button type="button" class="btn jump-btn" data-jump="top">Top</button>
|
||||||
|
<button type="button" class="btn jump-btn" data-jump="bottom">Bottom</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pane-r">
|
<div class="pane-r">
|
||||||
@@ -90,4 +94,5 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/static/new.js" defer></script>
|
<script src="/static/new.js" defer></script>
|
||||||
|
<script src="/static/jump.js" defer></script>
|
||||||
{{template "foot" .}}
|
{{template "foot" .}}
|
||||||
@@ -6,10 +6,11 @@
|
|||||||
<h1>{{if .Title}}{{.Title}}{{else}}Untitled paste{{end}}</h1>
|
<h1>{{if .Title}}{{.Title}}{{else}}Untitled paste{{end}}</h1>
|
||||||
{{if .CustomSlug}}<span class="slug">/{{.CustomSlug}}</span>{{end}}
|
{{if .CustomSlug}}<span class="slug">/{{.CustomSlug}}</span>{{end}}
|
||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
<button type="button" class="iconbtn wrap-toggle" title="Toggle line wrap" aria-pressed="false">wrap</button>
|
<button type="button" class="iconbtn wrap-toggle" title="Toggle line wrap" aria-pressed="false">Wrap</button>
|
||||||
<a class="iconbtn" href="/raw/{{.ID}}">raw</a>
|
<a class="iconbtn" href="/raw/{{.ID}}">Raw</a>
|
||||||
<a class="iconbtn" href="#" id="copy-btn">copy</a>
|
<a class="iconbtn swapbtn" href="#" id="copy-link-btn"><span class="swap-label">Link</span><span class="swap-check">✓</span></a>
|
||||||
{{if .DeletionToken}}<a class="iconbtn danger" href="#" id="delete-btn">delete</a>{{end}}
|
<a class="iconbtn swapbtn" href="#" id="copy-btn"><span class="swap-label">Copy</span><span class="swap-check">✓</span></a>
|
||||||
|
{{if .DeletionToken}}<a class="iconbtn danger" href="#" id="delete-btn">Delete</a>{{end}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="float">
|
<div class="float">
|
||||||
@@ -20,7 +21,7 @@
|
|||||||
</button>
|
</button>
|
||||||
<div class="stats-body" id="stats-body" hidden>
|
<div class="stats-body" id="stats-body" hidden>
|
||||||
<div class="stats-grid">
|
<div class="stats-grid">
|
||||||
<span class="stats-k">Language</span><span class="stats-v">{{if .Language}}{{.Language}}{{else}}text{{end}}</span>
|
<span class="stats-k">Type</span><span class="stats-v">{{.TypeLabel}}</span>
|
||||||
<span class="stats-k">Size</span><span class="stats-v">{{.SizeHuman}} ({{.LineCount}} lines)</span>
|
<span class="stats-k">Size</span><span class="stats-v">{{.SizeHuman}} ({{.LineCount}} lines)</span>
|
||||||
<span class="stats-k">Views</span><span class="stats-v">{{.ViewCount}}</span>
|
<span class="stats-k">Views</span><span class="stats-v">{{.ViewCount}}</span>
|
||||||
<span class="stats-k">Created</span><span class="stats-v" data-ts="{{.CreatedAtUnix}}">{{.CreatedAgo}}</span>
|
<span class="stats-k">Created</span><span class="stats-v" data-ts="{{.CreatedAtUnix}}">{{.CreatedAgo}}</span>
|
||||||
@@ -39,21 +40,28 @@
|
|||||||
{{if .Attachment}}
|
{{if .Attachment}}
|
||||||
<div class="float">
|
<div class="float">
|
||||||
<div class="attachment-bar">
|
<div class="attachment-bar">
|
||||||
|
{{if .AttachmentImage}}
|
||||||
|
<div class="attachment-preview"><img src="/f/{{.Attachment.ID}}/{{.Attachment.Filename}}" alt="{{.Attachment.Filename}}"></div>
|
||||||
|
{{end}}
|
||||||
<a class="attachment-chip" href="/f/{{.Attachment.ID}}/{{.Attachment.Filename}}" data-mime="{{.Attachment.Mime}}">
|
<a class="attachment-chip" href="/f/{{.Attachment.ID}}/{{.Attachment.Filename}}" data-mime="{{.Attachment.Mime}}">
|
||||||
<span class="attachment-name">{{.Attachment.Filename}}</span>
|
<span class="attachment-name">{{.Attachment.Filename}}</span>
|
||||||
<span class="attachment-size">{{.Attachment.SizeHuman}}</span>
|
<span class="attachment-size">{{.Attachment.SizeHuman}}</span>
|
||||||
</a>
|
</a>
|
||||||
{{if or (eq .Attachment.Mime "image/png") (eq .Attachment.Mime "image/jpeg") (eq .Attachment.Mime "image/gif") (eq .Attachment.Mime "image/webp")}}
|
|
||||||
<div class="attachment-preview"><img src="/f/{{.Attachment.ID}}/{{.Attachment.Filename}}" alt="{{.Attachment.Filename}}"></div>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
{{if not .Attachment}}
|
||||||
<div class="float">
|
<div class="float">
|
||||||
<div class="code" id="code"><div class="gutter" id="gutter">{{.Gutter}}</div><div class="codebody" id="codebody">{{.ContentHTML}}</div></div>
|
<div class="code" id="code"><div class="gutter" id="gutter">{{.Gutter}}</div><div class="codebody" id="codebody">{{.ContentHTML}}</div></div>
|
||||||
</div>
|
</div>
|
||||||
|
{{end}}
|
||||||
|
<div class="jumpnav hidden" id="jumpnav">
|
||||||
|
<button type="button" class="btn jump-btn" data-jump="top">Top</button>
|
||||||
|
<button type="button" class="btn jump-btn" data-jump="bottom">Bottom</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<input type="hidden" id="raw-content" value="{{.ContentAttr}}">
|
<input type="hidden" id="raw-content" value="{{.ContentAttr}}">
|
||||||
<script src="/static/paste.js" defer data-paste-id="{{.ID}}"></script>
|
<script src="/static/paste.js" defer data-paste-id="{{.ID}}"></script>
|
||||||
<script src="/static/paste-lines.js" defer></script>
|
<script src="/static/paste-lines.js" defer></script>
|
||||||
|
<script src="/static/jump.js" defer></script>
|
||||||
{{template "foot" .}}
|
{{template "foot" .}}
|
||||||
+63
-36
@@ -1,5 +1,5 @@
|
|||||||
// Package web serves palette's HTML routes: paste pages, cans, unlock, and
|
// Package web serves palette's HTML routes: paste pages, unlock, and the
|
||||||
// the admin page. Templates and static assets are embedded in this package.
|
// admin page. Templates and static assets are embedded in this package.
|
||||||
package web
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -111,29 +111,6 @@ func (h *Handlers) RenderNotFoundPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.renderNotFound(w, r, r.URL.Path)
|
h.renderNotFound(w, r, r.URL.Path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RenderPage is the exported wrapper used by the api package (#4 can pages).
|
|
||||||
func (h *Handlers) RenderPage(w http.ResponseWriter, name string, data any) {
|
|
||||||
h.renderPage(w, name, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteRateLimited is the exported rate-limit response used by the api package (#4).
|
|
||||||
func (h *Handlers) WriteRateLimited(w http.ResponseWriter, retryAfterSecs int) {
|
|
||||||
h.writeRateLimited(w, retryAfterSecs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnlockToken returns the per-id HMAC unlock token (cookie value, #34).
|
|
||||||
// Exported for the api package so can pages share paste cookie semantics (#4).
|
|
||||||
func UnlockToken(id string) string { return unlockToken(id) }
|
|
||||||
|
|
||||||
// AgoString formats a relative "N ago" string (exported for the api package, #4).
|
|
||||||
func AgoString(ts int64) string { return agoString(ts) }
|
|
||||||
|
|
||||||
// HumanSize formats a byte count as a human string (exported for the api package, #4).
|
|
||||||
func HumanSize(n int) string { return humanSize(n) }
|
|
||||||
|
|
||||||
// ExpiryString formats remaining time until an epoch seconds expiry (#4).
|
|
||||||
func ExpiryString(expiresAt int64) string { return expiryString(expiresAt) }
|
|
||||||
|
|
||||||
// #34: per-paste unlock tokens. unlockSecret is generated once at startup
|
// #34: per-paste unlock tokens. unlockSecret is generated once at startup
|
||||||
// (also derivable from PALETTE_UNLOCK_SECRET for multi-instance deploys) and
|
// (also derivable from PALETTE_UNLOCK_SECRET for multi-instance deploys) and
|
||||||
// used to HMAC paste ids, so a client can only hold a valid pw_<id> cookie by
|
// used to HMAC paste ids, so a client can only hold a valid pw_<id> cookie by
|
||||||
@@ -231,6 +208,20 @@ func (h *Handlers) renderPageStatus(w http.ResponseWriter, name string, status i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// attachmentExt returns the lowercase file extension (without dot) of a
|
||||||
|
// filename, or "" when the name has none. Used by the Type display (#235).
|
||||||
|
func attachmentExt(filename string) string {
|
||||||
|
name := filename
|
||||||
|
if i := strings.LastIndexByte(name, '/'); i >= 0 {
|
||||||
|
name = name[i+1:]
|
||||||
|
}
|
||||||
|
i := strings.LastIndexByte(name, '.')
|
||||||
|
if i <= 0 || i == len(name)-1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.ToLower(name[i+1:])
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handlers) renderPaste(w http.ResponseWriter, row *store.PasteRow, justCreated bool, deletionToken string, readsRemaining *int) {
|
func (h *Handlers) renderPaste(w http.ResponseWriter, row *store.PasteRow, justCreated bool, deletionToken string, readsRemaining *int) {
|
||||||
lines := strings.Count(row.Content, "\n") + 1
|
lines := strings.Count(row.Content, "\n") + 1
|
||||||
gutter := ""
|
gutter := ""
|
||||||
@@ -245,27 +236,62 @@ func (h *Handlers) renderPaste(w http.ResponseWriter, row *store.PasteRow, justC
|
|||||||
if lang == "" {
|
if lang == "" {
|
||||||
lang = "text"
|
lang = "text"
|
||||||
}
|
}
|
||||||
summary := fmt.Sprintf("%s · %s · %d views · %s", lang, humanSize(len(row.Content)), row.ViewCount, agoString(row.CreatedAt))
|
|
||||||
// #38: one optional file attachment per paste; nil when none.
|
// #38: one optional file attachment per paste; nil when none.
|
||||||
attachment, err := h.Store.GetAttachmentForPaste(row.ID)
|
attachment, err := h.Store.GetAttachmentForPaste(row.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "db error", 500)
|
http.Error(w, "db error", 500)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// #221: for attachment pastes the stored text content is empty (the file
|
||||||
|
// replaced it), so the summary size must come from the attachment blob,
|
||||||
|
// not len(row.Content), or the summary shows "0 B".
|
||||||
|
summarySize := len(row.Content)
|
||||||
|
if attachment != nil {
|
||||||
|
summarySize = int(attachment.Size)
|
||||||
|
}
|
||||||
|
// #235: column renamed to "Type". Text pastes keep the detected
|
||||||
|
// language; attachment pastes show the file extension instead.
|
||||||
|
attExt := ""
|
||||||
|
typeLabel := lang
|
||||||
|
if attachment != nil {
|
||||||
|
if ext := attachmentExt(attachment.Filename); ext != "" {
|
||||||
|
attExt = ext
|
||||||
|
typeLabel = ext
|
||||||
|
}
|
||||||
|
}
|
||||||
|
summary := fmt.Sprintf("%s · %s · %d views · %s", typeLabel, humanSize(summarySize), row.ViewCount, agoString(row.CreatedAt))
|
||||||
|
// #221: image attachments render the image, not a text/code box. Size
|
||||||
|
// comes from the attachment's actual file size, not the text content.
|
||||||
|
attImage := false
|
||||||
|
if attachment != nil {
|
||||||
|
switch attachment.Mime {
|
||||||
|
case "image/png", "image/jpeg", "image/gif", "image/webp":
|
||||||
|
attImage = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sizeHuman := humanSize(len(row.Content))
|
||||||
|
lineCount := lines
|
||||||
|
if attachment != nil {
|
||||||
|
sizeHuman = attachment.SizeHuman
|
||||||
|
lineCount = 1
|
||||||
|
}
|
||||||
data := map[string]any{
|
data := map[string]any{
|
||||||
"Page": "paste",
|
"Page": "paste",
|
||||||
"ID": row.ID,
|
"ID": row.ID,
|
||||||
"Title": row.Title.String,
|
"Title": row.Title.String,
|
||||||
"Language": row.Language.String,
|
"Language": typeLabel,
|
||||||
|
"TypeLabel": typeLabel,
|
||||||
|
"HasAttachment": attachment != nil,
|
||||||
|
"AttachmentExt": attExt,
|
||||||
"StatsSummary": summary,
|
"StatsSummary": summary,
|
||||||
"SizeHuman": humanSize(len(row.Content)),
|
"SizeHuman": sizeHuman,
|
||||||
"HasPassword": row.PasswordHash.Valid,
|
"HasPassword": row.PasswordHash.Valid,
|
||||||
"BurnAfterRead": row.BurnAfterRead,
|
"BurnAfterRead": row.BurnAfterRead,
|
||||||
"CustomSlug": row.CustomSlug.String,
|
"CustomSlug": row.CustomSlug.String,
|
||||||
"ContentHTML": template.HTML(langpkg.HighlightCode(row.Content, row.Language.String)), // safe: HighlightCode escapes all non-span text
|
"ContentHTML": template.HTML(langpkg.HighlightCode(row.Content, row.Language.String)), // safe: HighlightCode escapes all non-span text
|
||||||
"ContentAttr": row.Content,
|
"ContentAttr": row.Content,
|
||||||
"Gutter": strings.TrimSuffix(gutter, "\n"),
|
"Gutter": strings.TrimSuffix(gutter, "\n"),
|
||||||
"LineCount": lines,
|
"LineCount": lineCount,
|
||||||
"SizeBytes": len(row.Content),
|
"SizeBytes": len(row.Content),
|
||||||
"CreatedAgo": agoString(row.CreatedAt),
|
"CreatedAgo": agoString(row.CreatedAt),
|
||||||
"CreatedAtUnix": row.CreatedAt,
|
"CreatedAtUnix": row.CreatedAt,
|
||||||
@@ -279,6 +305,7 @@ func (h *Handlers) renderPaste(w http.ResponseWriter, row *store.PasteRow, justC
|
|||||||
"ReadsTotal": int(row.ReadsLimit.Int64),
|
"ReadsTotal": int(row.ReadsLimit.Int64),
|
||||||
"JustCreated": justCreated,
|
"JustCreated": justCreated,
|
||||||
"Attachment": attachment,
|
"Attachment": attachment,
|
||||||
|
"AttachmentImage": attImage,
|
||||||
"Host": "this host",
|
"Host": "this host",
|
||||||
}
|
}
|
||||||
h.renderPage(w, "paste.html", data)
|
h.renderPage(w, "paste.html", data)
|
||||||
@@ -319,7 +346,7 @@ func (h *Handlers) HandlePasteView(w http.ResponseWriter, r *http.Request) {
|
|||||||
// the paste id under the server's random secret.
|
// the paste id under the server's random secret.
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "pw_" + row.ID, Value: unlockToken(row.ID), Path: "/",
|
Name: "pw_" + row.ID, Value: unlockToken(row.ID), Path: "/",
|
||||||
MaxAge: 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
MaxAge: 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: true,
|
||||||
})
|
})
|
||||||
// re-render without lock, or redirect if ?next= was given (#26)
|
// re-render without lock, or redirect if ?next= was given (#26)
|
||||||
if next := r.FormValue("next"); next != "" {
|
if next := r.FormValue("next"); next != "" {
|
||||||
@@ -353,7 +380,7 @@ func (h *Handlers) HandlePasteView(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
if justCreated && token != "" {
|
if justCreated && token != "" {
|
||||||
// one-time display of the deletion token via sessionStorage (#143)
|
// one-time display of the deletion token via sessionStorage (#143)
|
||||||
http.SetCookie(w, &http.Cookie{Name: "tok_" + row.ID, Value: token, Path: "/", MaxAge: 60, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
http.SetCookie(w, &http.Cookie{Name: "tok_" + row.ID, Value: token, Path: "/", MaxAge: 60, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: true})
|
||||||
}
|
}
|
||||||
// Count the view for real page renders, deduped per-viewer within the
|
// Count the view for real page renders, deduped per-viewer within the
|
||||||
// burn window (#95): a reload by the same vwr cookie doesn't inflate
|
// burn window (#95): a reload by the same vwr cookie doesn't inflate
|
||||||
@@ -383,9 +410,9 @@ func (h *Handlers) HandleNewPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.renderPage(w, "new.html", map[string]any{"Page": "new"})
|
h.renderPage(w, "new.html", map[string]any{"Page": "new"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleHistoryPage serves /history.
|
// HandleHistoryPage serves /public.
|
||||||
func (h *Handlers) HandleHistoryPage(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) HandleHistoryPage(w http.ResponseWriter, r *http.Request) {
|
||||||
h.renderPage(w, "history.html", map[string]any{"Page": "history"})
|
h.renderPage(w, "history.html", map[string]any{"Page": "public"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleSettingsPage serves /settings.
|
// HandleSettingsPage serves /settings.
|
||||||
@@ -402,9 +429,9 @@ func (h *Handlers) HandleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.renderPage(w, "settings.html", map[string]any{"Page": "settings", "Themes": themes})
|
h.renderPage(w, "settings.html", map[string]any{"Page": "settings", "Themes": themes})
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleMinePage serves /mine.
|
// HandleMinePage serves /saved.
|
||||||
func (h *Handlers) HandleMinePage(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) HandleMinePage(w http.ResponseWriter, r *http.Request) {
|
||||||
h.renderPage(w, "mine.html", map[string]any{"Page": "mine"})
|
h.renderPage(w, "mine.html", map[string]any{"Page": "saved"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleAdminPage serves /admin.
|
// HandleAdminPage serves /admin.
|
||||||
@@ -416,7 +443,7 @@ func (h *Handlers) HandleAdminPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
func (u *UI) Handlers() *Handlers { return &Handlers{UI: u} }
|
func (u *UI) Handlers() *Handlers { return &Handlers{UI: u} }
|
||||||
|
|
||||||
// #59: security headers for rendered HTML pages. Applied wherever the
|
// #59: security headers for rendered HTML pages. Applied wherever the
|
||||||
// response is text/html (page templates and the inline can page); JSON API
|
// response is text/html (page templates); JSON API
|
||||||
// responses and /raw content pass through untouched.
|
// responses and /raw content pass through untouched.
|
||||||
// #139: script-src and style-src no longer allow 'unsafe-inline'. All
|
// #139: script-src and style-src no longer allow 'unsafe-inline'. All
|
||||||
// previously-inline scripts moved to external files under static/ (page data
|
// previously-inline scripts moved to external files under static/ (page data
|
||||||
|
|||||||
Reference in new issue
Block a user