replace frontend with webpack bundeled webpack

This commit is contained in:
Jonas Leder 2026-07-20 21:09:01 +02:00
commit 7d06e354c1
12 changed files with 2428 additions and 384 deletions

View file

@ -5,5 +5,4 @@ node_modules
*.swp
*.swo
data
*.DS_Store
config.js
*.DS_Store

3
.gitignore vendored
View file

@ -4,4 +4,5 @@ node_modules
*.swo
data
*.DS_Store
static/application.min.js
static/dist
/haste-server

View file

@ -1,10 +1,12 @@
FROM node:24-alpine@sha256:7fddd9ddeae8196abf4a3ef2de34e11f7b1a722119f91f28ddf1e99dcafdf114 AS assets
FROM node:24-alpine@sha256:7fddd9ddeae8196abf4a3ef2de34e11f7b1a722119f91f28ddf1e99dcafdf114 AS frontend
WORKDIR /src
COPY package.json package-lock.json ./
COPY package.json package-lock.json webpack.config.js ./
RUN npm ci
RUN npm install --omit=dev
COPY frontend ./frontend
RUN npm run build
FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.9.0 AS xx
FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine AS build
@ -18,6 +20,7 @@ COPY go.mod ./
RUN go mod download
COPY . .
COPY --from=frontend /src/static/dist ./static/dist
RUN CGO_ENABLED=0 GOOS=linux xx-go build -ldflags "-w -s" -o /out/haste-server .
@ -28,8 +31,8 @@ WORKDIR /usr/src/app
COPY --from=build /out/haste-server ./haste-server
COPY ./static ./static
USER appuser
COPY --from=frontend /src/static/dist ./static/dist
COPY ./about.md ./about.md
ENV STORAGE_TYPE=redis \
STORAGE_HOST=127.0.0.1 \
@ -41,7 +44,6 @@ ENV STORAGE_TYPE=redis \
KEY_LENGTH=10 \
MAX_LENGTH=400000 \
STATIC_MAX_AGE=86400 \
RECOMPRESS_STATIC_ASSETS=true \
KEYGENERATOR_TYPE=phonetic \
RATELIMITS_NORMAL_TOTAL_REQUESTS=500 \
RATELIMITS_NORMAL_EVERY_MILLISECONDS=60000 \

View file

@ -28,33 +28,30 @@ STDOUT. Check the README there for more details and usages.
## Installation
1. Download the package, and expand it
2. Explore the settings inside of config.js, but the defaults should be good
2. Explore the environment variables below, but the defaults should be good
3. `go build`
4. `./haste-server` (you may specify an optional `<config-path>` as well)
4. `./haste-server`
## Settings
* `host` - the host the server runs on (default localhost)
* `port` - the port the server runs on (default 7777)
* `keyLength` - the length of the keys to user (default 10)
* `maxLength` - maximum length of a paste (default 400000)
* `staticMaxAge` - max age for static assets (86400)
* `recompressStaticAssets` - whether or not to compile static js assets (true)
* `documents` - static documents to serve (ex: http://hastebin.com/about.com)
Haste is configured entirely through environment variables - see the
[Docker Configuration](#configuration) section below for the full list.
* `HOST` - the host the server runs on (default localhost)
* `PORT` - the port the server runs on (default 7777)
* `KEY_LENGTH` - the length of the keys to use (default 10)
* `MAX_LENGTH` - maximum length of a paste (default 400000)
* `STATIC_MAX_AGE` - max age for static assets (86400)
* `DOCUMENTS` - static documents to serve (ex: http://hastebin.com/about.com)
in addition to static assets. These will never expire.
* `storage` - storage options (see below)
* `logging` - logging preferences
* `keyGenerator` - key generator options (see below)
* `rateLimits` - settings for rate limiting (see below)
* `STORAGE_*` - storage options (see below)
* `KEYGENERATOR_*` - key generator options (see below)
* `RATELIMITS_*` - settings for rate limiting (see below)
## Rate Limiting
When present, the `rateLimits` option enables built-in rate limiting courtesy
of `connect-ratelimit`. Any of the options supported by that library can be
used and set in `config.js`.
See the README for [connect-ratelimit](https://github.com/dharmafly/connect-ratelimit)
for more information!
Built-in rate limiting can be enabled through the `RATELIMITS_*` environment
variables (see below). By default no limits are enforced.
## Key Generation

View file

@ -1,4 +1,6 @@
/* global $, hljs, window, document */
import $ from 'jquery';
/* global hljs, window, document */
///// represents a single document
@ -361,38 +363,4 @@ haste.prototype.configureShortcuts = function() {
});
};
///// Tab behavior in the textarea - 2 spaces per tab
$(function() {
$('textarea').keydown(function(evt) {
if (evt.keyCode === 9) {
evt.preventDefault();
var myValue = ' ';
// http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery
// For browsers like Internet Explorer
if (document.selection) {
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
// Mozilla and Webkit
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue +
this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
}
});
});
export { haste_document, haste };

64
frontend/src/index.js Normal file
View file

@ -0,0 +1,64 @@
import $ from 'jquery';
import { haste } from './haste';
/* global window, document */
var app = null;
// Handle pops
function handlePop(evt) {
var path = evt.target.location.pathname;
if (path === '/') { app.newDocument(true); }
else { app.loadDocument(path.substring(1, path.length)); }
}
// Set up the pop state to handle loads, skipping the first load
// to make chrome behave like others:
// http://code.google.com/p/chromium/issues/detail?id=63040
setTimeout(function() {
window.onpopstate = function(evt) {
try { handlePop(evt); } catch(err) { /* not loaded yet */ }
};
}, 1000);
// Construct app and load initial path
$(function() {
app = new haste('hastebin', { twitter: true });
handlePop({ target: window });
});
///// Tab behavior in the textarea - 2 spaces per tab
$(function() {
$('textarea').keydown(function(evt) {
if (evt.keyCode === 9) {
evt.preventDefault();
var myValue = ' ';
// http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery
// For browsers like Internet Explorer
if (document.selection) {
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
// Mozilla and Webkit
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue +
this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
}
});
});

123
main.go
View file

@ -27,49 +27,41 @@ import (
var embeddedStatic embed.FS
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
KeyLength int `json:"keyLength"`
MaxLength int `json:"maxLength"`
StaticMaxAge int `json:"staticMaxAge"`
RecompressStaticAssets bool `json:"recompressStaticAssets"`
Logging []LoggingConfig `json:"logging"`
KeyGenerator KeyGeneratorConfig `json:"keyGenerator"`
RateLimits RateLimitsConfig `json:"rateLimits"`
Storage StorageConfig `json:"storage"`
Documents map[string]string `json:"documents"`
}
type LoggingConfig struct {
Level string `json:"level"`
Type string `json:"type"`
Colorize any `json:"colorize"`
Host string
Port int
KeyLength int
MaxLength int
StaticMaxAge int
KeyGenerator KeyGeneratorConfig
RateLimits RateLimitsConfig
Storage StorageConfig
Documents map[string]string
}
type KeyGeneratorConfig struct {
Type string `json:"type"`
Keyspace string `json:"keyspace"`
Path string `json:"path"`
Type string
Keyspace string
Path string
}
type RateLimitsConfig struct {
Whitelist []string `json:"whitelist"`
Blacklist []string `json:"blacklist"`
Categories map[string]RateLimitBucket `json:"categories"`
Whitelist []string
Blacklist []string
Categories map[string]RateLimitBucket
}
type RateLimitBucket struct {
TotalRequests int `json:"totalRequests"`
Every int `json:"every"`
TotalRequests int
Every int
}
type StorageConfig struct {
Type string `json:"type"`
Host string `json:"host"`
Port int `json:"port"`
Expire int `json:"expire"`
DB int `json:"db"`
Password string `json:"password"`
Type string
Host string
Port int
Expire int
DB int
Password string
}
type DocumentStore interface {
@ -210,21 +202,12 @@ type Server struct {
rateLimiter *RateLimiter
staticDocs map[string]struct{}
staticDir string
nodeModules string
}
func main() {
seedMathRand()
configPath := "config.js"
if len(os.Args) > 1 {
configPath = os.Args[1]
}
cfg, err := loadConfig(configPath)
if err != nil {
log.Fatalf("load config: %v", err)
}
cfg := loadConfig()
if cfg.Storage.Type == "" {
cfg.Storage.Type = "redis"
@ -250,7 +233,6 @@ func main() {
rateLimiter: NewRateLimiter(cfg.RateLimits),
staticDocs: make(map[string]struct{}, len(cfg.Documents)),
staticDir: filepath.Join(".", "static"),
nodeModules: filepath.Join(".", "node_modules"),
}
if err := srv.loadStaticDocuments(); err != nil {
@ -283,39 +265,21 @@ func seedMathRand() {
mathrand.Seed(time.Now().UnixNano())
}
func loadConfig(path string) (Config, error) {
func loadConfig() Config {
cfg := Config{
Host: "localhost",
Port: 7777,
KeyLength: 10,
MaxLength: 400000,
StaticMaxAge: 86400,
RecompressStaticAssets: true,
KeyGenerator: KeyGeneratorConfig{Type: "random"},
RateLimits: RateLimitsConfig{Categories: map[string]RateLimitBucket{}},
Storage: StorageConfig{Type: "redis", Host: "localhost", Port: 6379},
Documents: map[string]string{},
}
if data, err := os.ReadFile(path); err == nil {
if err := json.Unmarshal(data, &cfg); err != nil {
return Config{}, err
}
} else if !errors.Is(err, os.ErrNotExist) {
return Config{}, err
Host: "localhost",
Port: 7777,
KeyLength: 10,
MaxLength: 400000,
StaticMaxAge: 86400,
KeyGenerator: KeyGeneratorConfig{Type: "random"},
RateLimits: RateLimitsConfig{Categories: map[string]RateLimitBucket{}},
Storage: StorageConfig{Type: "redis", Host: "localhost", Port: 6379},
Documents: map[string]string{},
}
applyEnvOverrides(&cfg)
if cfg.Documents == nil {
cfg.Documents = map[string]string{}
}
if cfg.RateLimits.Categories == nil {
cfg.RateLimits.Categories = map[string]RateLimitBucket{}
}
if cfg.KeyGenerator.Type == "" {
cfg.KeyGenerator.Type = "random"
}
return cfg, nil
return cfg
}
func applyEnvOverrides(cfg *Config) {
@ -334,9 +298,6 @@ func applyEnvOverrides(cfg *Config) {
if v := os.Getenv("STATIC_MAX_AGE"); v != "" {
cfg.StaticMaxAge = atoiDefault(v, cfg.StaticMaxAge)
}
if v := os.Getenv("RECOMPRESS_STATIC_ASSETS"); v != "" {
cfg.RecompressStaticAssets = parseBool(v)
}
if v := os.Getenv("KEYGENERATOR_TYPE"); v != "" {
cfg.KeyGenerator.Type = v
}
@ -451,7 +412,6 @@ func (s *Server) routes() http.Handler {
mux.HandleFunc("/documents", s.handleDocumentsPost)
mux.HandleFunc("/documents/", s.handleDocumentsGet)
mux.HandleFunc("/raw/", s.handleRawGet)
mux.Handle("/node_modules/", s.staticFileHandler(http.Dir(s.nodeModules), false))
mux.Handle("/", s)
if s.rateLimiter != nil {
return s.rateLimiter.Middleware(mux)
@ -555,14 +515,6 @@ func setStaticHeaders(w http.ResponseWriter, path string, maxAge int) {
}
}
func (s *Server) staticFileHandler(fs http.FileSystem, stripPrefix bool) http.Handler {
handler := http.FileServer(fs)
if stripPrefix {
return http.StripPrefix("/node_modules/", handler)
}
return http.StripPrefix("/node_modules/", handler)
}
func (s *Server) handleDocumentsPost(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/documents" {
http.NotFound(w, r)
@ -772,11 +724,6 @@ func clientIP(r *http.Request) string {
return r.RemoteAddr
}
func parseBool(v string) bool {
parsed, err := strconv.ParseBool(v)
return err == nil && parsed
}
func atoiDefault(v string, fallback int) int {
parsed, err := strconv.Atoi(v)
if err != nil {

2283
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,37 +1,20 @@
{
"name": "haste",
"name": "haste-frontend",
"version": "0.1.0",
"private": true,
"description": "Private Pastebin Server",
"description": "Frontend assets for the haste pastebin server",
"keywords": [
"paste",
"pastebin"
],
"author": {
"name": "John Crepezzi",
"email": "john.crepezzi@gmail.com",
"url": "http://seejohncode.com/"
"scripts": {
"build": "webpack --mode production"
},
"main": "haste",
"dependencies": {
"jquery": "^4.0.0"
},
"devDependencies": {},
"bundledDependencies": [],
"bin": {
"haste-server": "./server.js"
},
"files": [
"server.js",
"lib",
"static"
],
"directories": {
"lib": "./lib"
},
"scripts": {
"start": "./haste-server",
"test": "go test ./..."
},
"bundleDependencies": []
"devDependencies": {
"webpack": "^5.108.4",
"webpack-cli": "^7.2.1"
}
}

178
server.js
View file

@ -1,178 +0,0 @@
var http = require('http');
var fs = require('fs');
var uglify = require('uglify-js');
var winston = require('winston');
var connect = require('connect');
var route = require('connect-route');
var connect_st = require('st');
var connect_rate_limit = require('connect-ratelimit');
var DocumentHandler = require('./lib/document_handler');
// Load the configuration and set some defaults
const configPath = process.argv.length <= 2 ? 'config.js' : process.argv[2];
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
config.port = process.env.PORT || config.port || 7777;
config.host = process.env.HOST || config.host || 'localhost';
async function server() {// Set up the logger
if (config.logging) {
try {
winston.remove(winston.transports.Console);
} catch (e) {
/* was not present */
}
var detail, type;
for (var i = 0; i < config.logging.length; i++) {
detail = config.logging[i];
type = detail.type;
delete detail.type;
let transport = new winston.transports[type]();
winston.add(transport, detail);
}
}
// build the store from the config on-demand - so that we don't load it
// for statics
if (!config.storage) {
config.storage = { type: 'file' };
}
if (!config.storage.type) {
config.storage.type = 'file';
}
var Store, preferredStore;
if (process.env.REDISTOGO_URL && config.storage.type === 'redis') {
var redisClient = await require('redis-url').connect(process.env.REDISTOGO_URL);
Store = require('./lib/document_stores/redis');
preferredStore = new Store(config.storage, redisClient);
} else if (config.storage.type === 'redis') {
const RedisDocumentStore = require('./lib/document_stores/redis');
preferredStore = await RedisDocumentStore.create({ host: config.storage.host, port: config.storage.port });
}
else {
Store = require('./lib/document_stores/' + config.storage.type);
preferredStore = new Store(config.storage);
}
// Compress the static javascript assets
if (config.recompressStaticAssets) {
var list = fs.readdirSync('./static');
for (var j = 0; j < list.length; j++) {
var item = list[j];
if ((item.indexOf('.js') === item.length - 3) && (item.indexOf('.min.js') === -1)) {
var dest = item.substring(0, item.length - 3) + '.min' + item.substring(item.length - 3);
var orig_code = fs.readFileSync('./static/' + item, 'utf8');
fs.writeFileSync('./static/' + dest, uglify.minify(orig_code).code, 'utf8');
winston.info('compressed ' + item + ' into ' + dest);
}
}
}
// Send the static documents into the preferred store, skipping expirations
var path, data;
for (var name in config.documents) {
path = config.documents[name];
data = fs.readFileSync(path, 'utf8');
winston.info('loading static document', { name: name, path: path });
if (data) {
preferredStore.set(name, data, function (cb) {
winston.debug('loaded static document', { success: cb });
}, true);
}
else {
winston.warn('failed to load static document', { name: name, path: path });
}
}
// Pick up a key generator
var pwOptions = config.keyGenerator || {};
pwOptions.type = pwOptions.type || 'random';
var gen = require('./lib/key_generators/' + pwOptions.type);
var keyGenerator = new gen(pwOptions);
// Configure the document handler
var documentHandler = new DocumentHandler({
store: preferredStore,
maxLength: config.maxLength,
keyLength: config.keyLength,
keyGenerator: keyGenerator
});
var app = connect();
// Rate limit all requests
if (config.rateLimits) {
config.rateLimits.end = true;
app.use(connect_rate_limit(config.rateLimits));
}
// first look at API calls
app.use(route(function (router) {
// get raw documents - support getting with extension
router.get('/raw/:id', function (request, response) {
return documentHandler.handleRawGet(request, response, config);
});
router.head('/raw/:id', function (request, response) {
return documentHandler.handleRawGet(request, response, config);
});
// add documents
router.post('/documents', function (request, response) {
return documentHandler.handlePost(request, response);
});
// get documents
router.get('/documents/:id', function (request, response) {
return documentHandler.handleGet(request, response, config);
});
router.head('/documents/:id', function (request, response) {
return documentHandler.handleGet(request, response, config);
});
}));
// Otherwise, try to match node modules
app.use(connect_st({
path: __dirname + '/node_modules',
content: { maxAge: config.staticMaxAge },
url: "/node_modules"
}));
// Otherwise, try to match static files
app.use(connect_st({
path: __dirname + '/static',
content: { maxAge: config.staticMaxAge },
passthrough: true,
index: false
}));
// Then we can loop back - and everything else should be a token,
// so route it back to /
app.use(route(function (router) {
router.get('/:id', function (request, response, next) {
request.sturl = '/';
next();
});
}));
// And match index
app.use(connect_st({
path: __dirname + '/static',
content: { maxAge: config.staticMaxAge },
index: 'index.html'
}));
http.createServer(app).listen(config.port, config.host);
winston.info('listening on ' + config.host + ':' + config.port);
}
server();

View file

@ -9,35 +9,11 @@
<link rel="stylesheet" type="text/css" href="solarized_dark.css"/>
<link rel="stylesheet" type="text/css" href="application.css"/>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="highlight.min.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="dist/bundle.js"></script>
<meta name="robots" content="noindex,nofollow"/>
<script type="text/javascript">
var app = null;
// Handle pops
var handlePop = function(evt) {
var path = evt.target.location.pathname;
if (path === '/') { app.newDocument(true); }
else { app.loadDocument(path.substring(1, path.length)); }
};
// Set up the pop state to handle loads, skipping the first load
// to make chrome behave like others:
// http://code.google.com/p/chromium/issues/detail?id=63040
setTimeout(function() {
window.onpopstate = function(evt) {
try { handlePop(evt); } catch(err) { /* not loaded yet */ }
};
}, 1000);
// Construct app and load initial path
$(function() {
app = new haste('hastebin', { twitter: true });
handlePop({ target: window });
});
</script>
</head>
<body>

10
webpack.config.js Normal file
View file

@ -0,0 +1,10 @@
const path = require('path');
module.exports = {
mode: 'production',
entry: path.resolve(__dirname, 'frontend/src/index.js'),
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/dist'),
},
};