初始提交: ScriptForge 脚本快速转运行链接服务
Some checks failed
Release / build-and-release (push) Failing after 1m31s

- Go 后端 (Gin + GORM + SQLite) 提供 API 和纯文本脚本服务
- Vite + React + TypeScript + Tailwind 前端
- 单二进制部署 (Go embed 前端静态文件)
- Gitea Actions CI/CD: 打标签自动构建多平台 Release
- 支持 bash/zsh/sh/fish/python3/node/ruby/php 8种运行环境

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-28 23:48:19 +08:00
commit 10a200b96c
37 changed files with 4400 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
name: Release
on:
push:
tags:
- "v*"
jobs:
build-and-release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Build frontend
run: |
cd frontend
npm ci
npm run build
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "1.22"
cache-dependency-path: backend/go.sum
- name: Build all platforms
run: |
cp -r frontend/dist backend/internal/assets/dist/
cd backend
GOOS=linux GOARCH=amd64 go build -o scriptforge-server-linux-amd64 ./cmd/server
GOOS=linux GOARCH=arm64 go build -o scriptforge-server-linux-arm64 ./cmd/server
GOOS=windows GOARCH=amd64 go build -o scriptforge-server-windows-amd64.exe ./cmd/server
- name: Create Release
id: create_release
env:
GITEA_TOKEN: ${{ secrets.TOKEN }}
run: |
REPO="${{ gitea.repository }}"
TAG="${{ gitea.ref_name }}"
RELEASE_JSON=$(curl -s -X POST \
"https://gitea.kmux.cn/api/v1/repos/${REPO}/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{
\"tag_name\": \"${TAG}\",
\"name\": \"${TAG}\",
\"body\": \"ScriptForge ${TAG}\",
\"draft\": false,
\"prerelease\": false
}")
echo "release_id=$(echo "$RELEASE_JSON" | jq -r '.id')" >> "$GITHUB_OUTPUT"
- name: Upload Release Assets
env:
GITEA_TOKEN: ${{ secrets.TOKEN }}
run: |
REPO="${{ gitea.repository }}"
RELEASE_ID="${{ steps.create_release.outputs.release_id }}"
for FILE in backend/scriptforge-server-*; do
echo "Uploading $FILE..."
curl -s -X POST \
"https://gitea.kmux.cn/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${FILE}"
done

20
.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# Go
backend/server
backend/scriptforge.db
backend/internal/assets/dist/*
!backend/internal/assets/dist/.gitkeep
# Node
frontend/node_modules
frontend/dist
frontend/tsconfig.tsbuildinfo
# IDE
.idea
.vscode
*.swp
*.swo
# OS
.DS_Store
Thumbs.db

194
DESIGN.md Normal file
View File

@@ -0,0 +1,194 @@
# ScriptForge 设计文档
## 概述
脚本快速转运行链接服务。用户粘贴脚本内容,选择运行环境,生成一个短链。在终端执行 `curl URL | <runtime>` 即可运行脚本。
- 前端Next.js (App Router + Tailwind CSS + TypeScript)
- 后端Go (Gin + GORM + SQLite)
- 部署Go embed 前端静态文件,单二进制部署
- CI/CDGitea Actions
## 核心流程
1. 用户打开首页 `/`
2. 粘贴脚本内容(上限 16KB
3. 选择运行环境bash / zsh / sh / fish / python3 / node / ruby / php
4. 选择过期时间1小时 / 24小时 / 7天 / 30天
5. 提交 → 后端存入 SQLite → 返回短链 ID
6. 页面展示生成的命令:`curl https://example.com/raw/xK8mPq | bash`
7. 用户可以复制命令到终端执行
## API 设计
### POST /api/scripts — 创建脚本
请求体:
```json
{
"content": "#!/bin/bash\necho hello",
"runtime": "bash",
"expires_in": "24h"
}
```
响应:
```json
{
"id": "xK8mPq",
"admin_token": "dGhpcyBpcyBhIHRva2Vu",
"url": "https://example.com/raw/xK8mPq",
"command": "curl https://example.com/raw/xK8mPq | bash",
"runtime": "bash",
"expires_at": "2026-05-29T16:27:00Z"
}
```
### GET /api/scripts/:id — 获取脚本元数据
响应:
```json
{
"id": "xK8mPq",
"runtime": "bash",
"content_length": 25,
"created_at": "2026-05-28T16:27:00Z",
"expires_at": "2026-05-29T16:27:00Z",
"expired": false
}
```
> 注意:此接口不返回脚本原始内容(内容通过 `/raw/:id` 获取),避免前端二次暴露。
### GET /raw/:id — 获取脚本纯文本内容
- 响应头 `Content-Type`: 根据 runtime 设置对应 MIME见运行时配置表
- 响应头 `Content-Disposition`: `attachment; filename="script.<ext>"`(根据 runtime 设置扩展名)
- 响应体:脚本纯文本内容
- 如脚本已过期,返回 404
### DELETE /api/scripts/:id?token=xxx — 删除脚本
- 需要 `admin_token` 参数
- 成功返回 204
## 数据模型
```go
type Script struct {
ID string `gorm:"primaryKey;size:8"`
Content string `gorm:"type:text;not null"`
Runtime string `gorm:"size:16;not null;index"`
AdminToken string `gorm:"size:64;not null"`
ExpiresAt time.Time `gorm:"not null;index"`
CreatedAt time.Time `gorm:"not null"`
}
```
## 运行时配置
| Runtime | 扩展名 | MIME 类型 | 命令模板 |
|---------|--------|-----------|----------|
| bash | `.sh` | `text/x-shellscript` | `curl {url} \| bash` |
| zsh | `.zsh` | `text/x-shellscript` | `curl {url} \| zsh` |
| sh | `.sh` | `text/x-shellscript` | `curl {url} \| sh` |
| fish | `.fish` | `text/x-shellscript` | `curl {url} \| fish` |
| python3 | `.py` | `text/x-python` | `curl {url} \| python3` |
| node | `.js` | `text/javascript` | `curl {url} \| node` |
| ruby | `.rb` | `text/x-ruby` | `curl {url} \| ruby` |
| php | `.php` | `text/x-php` | `curl {url} \| php` |
运行环境列表在 Go 后端定义为常量数组,用于校验请求中的 runtime 字段。
## 过期策略
- 用户保存时选择1小时 / 24小时 / 7天 / 30天
- 后端定时任务(每分钟扫描一次),删除过期记录
- 过期后 `/raw/:id` 返回 404详情页标记为已过期
## 限流策略
- 创建接口10 次/分钟/IP
- 其他接口60 次/分钟/IP
- 请求体上限17KB
## 安全设计
- 完全公开,无需注册/登录
- 创建时返回 `admin_token`(随机 64 位字符串),持有者可删除脚本
- 无内容过滤,靠过期机制和限流控制风险
- 编辑功能:无(`admin_token` 仅用于删除,不能改内容。设计上 script 是一次性的,编辑会带来版本管理等复杂问题)
## 前端路由
| 路由 | 页面 | 说明 |
|------|------|------|
| `/` | 首页 | 粘贴脚本 + 选择运行环境/过期时间 + 提交 + 结果展示 |
| `/s/[id]` | 脚本详情页 | 展示脚本内容语法高亮、元数据、curl 命令卡片 |
| `/s/[id]/delete` | 删除确认页 | 输入 admin_token 确认删除 |
## 项目目录结构
```
scriptforge/
├── frontend/ # Next.js 项目
│ ├── src/
│ │ ├── app/
│ │ │ ├── page.tsx # 首页
│ │ │ ├── layout.tsx # 根布局
│ │ │ └── s/[id]/
│ │ │ ├── page.tsx # 脚本详情页
│ │ │ └── delete/
│ │ │ └── page.tsx # 删除确认页
│ │ ├── components/
│ │ │ ├── ScriptForm.tsx # 脚本提交表单
│ │ │ ├── ResultCard.tsx # 结果展示卡(含复制按钮)
│ │ │ ├── ScriptViewer.tsx # 脚本内容展示(语法高亮)
│ │ │ └── CommandCard.tsx # curl 命令展示卡
│ │ └── lib/
│ │ └── api.ts # API 调用封装
│ ├── package.json
│ └── next.config.js
├── backend/ # Go 项目
│ ├── cmd/
│ │ └── server/
│ │ └── main.go # 入口
│ ├── internal/
│ │ ├── handler/
│ │ │ ├── script.go # 脚本 CRUD handlers
│ │ │ └── raw.go # 原始内容 handler
│ │ ├── model/
│ │ │ └── script.go # GORM model
│ │ ├── service/
│ │ │ └── script.go # 业务逻辑
│ │ ├── middleware/
│ │ │ └── ratelimit.go # 限流中间件
│ │ └── config/
│ │ └── runtime.go # 运行时配置列表
│ ├── go.mod
│ └── go.sum
├── .gitea/
│ └── workflows/
│ └── deploy.yml # Gitea Actions 部署流程
├── Makefile # 统一构建命令
├── DESIGN.md # 本设计文档
└── README.md
```
## CI/CD 部署流程Gitea Actions
1. 触发条件push 到 `main` 分支
2. 构建步骤:
- `cd frontend && npm ci && npm run build` → 输出 `out/`
- `cd backend && cp -r ../frontend/out ./internal/embed && go build -o server ./cmd/server`
3. 部署步骤:
- `scp` 二进制到服务器
- `ssh` 执行 `systemctl restart scriptforge`
## 后续可扩展方向
- 大模型集成:根据脚本内容自动推荐运行环境
- 更多运行时dockerfile、powershell、deno、bun 等
- 脚本版本管理(不基于 admin_token需要真正的用户系统
- 统计数据:脚本执行次数、来源 IP 等(需要跟踪 curl 请求)
- WebSocket 实时执行输出流

40
Makefile Normal file
View File

@@ -0,0 +1,40 @@
.PHONY: dev build clean
# === Development ===
dev-backend:
cd backend && go run ./cmd/server
dev-frontend:
cd frontend && npm run dev
dev:
@echo "Start backend and frontend in separate terminals:"
@echo " make dev-backend"
@echo " make dev-frontend"
# === Production Build ===
frontend-build:
cd frontend && npm run build
backend-build:
rm -rf backend/internal/assets/dist/
cp -r frontend/dist backend/internal/assets/
cd backend && go build -o server ./cmd/server
rm -rf backend/internal/assets/dist/
mkdir -p backend/internal/assets/dist/
touch backend/internal/assets/dist/.gitkeep
build: frontend-build backend-build
@echo "Build complete: backend/server"
# === Clean ===
clean:
rm -rf frontend/dist
rm -f backend/server
rm -f backend/scriptforge.db
rm -rf backend/internal/assets/dist/
mkdir -p backend/internal/assets/dist/
touch backend/internal/assets/dist/.gitkeep

129
backend/cmd/server/main.go Normal file
View File

@@ -0,0 +1,129 @@
package main
import (
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gitea.kmux.cn/zhilv/scriptforge/internal/assets"
"gitea.kmux.cn/zhilv/scriptforge/internal/handler"
"gitea.kmux.cn/zhilv/scriptforge/internal/middleware"
"gitea.kmux.cn/zhilv/scriptforge/internal/model"
"gitea.kmux.cn/zhilv/scriptforge/internal/service"
)
func main() {
gin.SetMode(gin.ReleaseMode)
db := initDB()
syncDB(db)
svc := service.NewScriptService(db)
go cleanupLoop(svc)
r := gin.New()
r.Use(gin.Recovery(), middleware.Logger())
api := r.Group("/api")
{
api.Use(middleware.RateLimit(60))
api.POST("/scripts", middleware.RateLimit(10), handler.CreateScript(svc))
api.GET("/scripts/:id", handler.GetScript(svc))
api.DELETE("/scripts/:id", handler.DeleteScript(svc))
}
r.GET("/raw/:id", handler.GetRawScript(svc))
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
serveStaticOrSPA(r)
port := getPort()
log.Printf("Listening on :%s", port)
go func() {
if err := r.Run(":" + port); err != nil {
log.Fatalf("server error: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down...")
}
func initDB() *gorm.DB {
dbPath := os.Getenv("DB_PATH")
if dbPath == "" {
dbPath = "scriptforge.db"
}
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
log.Fatalf("failed to connect database: %v", err)
}
return db
}
func syncDB(db *gorm.DB) {
if err := db.AutoMigrate(&model.Script{}); err != nil {
log.Fatalf("failed to migrate database: %v", err)
}
}
func cleanupLoop(svc *service.ScriptService) {
for {
time.Sleep(1 * time.Hour)
if n, err := svc.CleanupExpired(); err != nil {
log.Printf("cleanup error: %v", err)
} else if n > 0 {
log.Printf("cleaned up %d expired scripts", n)
}
}
}
func getPort() string {
if p := os.Getenv("PORT"); p != "" {
return p
}
return "8080"
}
func serveStaticOrSPA(r *gin.Engine) {
staticFS, err := fs.Sub(assets.FS, "dist")
if err != nil {
log.Printf("no embedded static files, API-only mode: %v", err)
return
}
r.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
if strings.HasPrefix(path, "/api") || strings.HasPrefix(path, "/raw") {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
file, err := staticFS.Open(path)
if err != nil {
c.FileFromFS("index.html", http.FS(staticFS))
return
}
file.Close()
c.FileFromFS(path, http.FS(staticFS))
})
r.GET("/", func(c *gin.Context) {
c.FileFromFS("index.html", http.FS(staticFS))
})
}

41
backend/go.mod Normal file
View File

@@ -0,0 +1,41 @@
module gitea.kmux.cn/zhilv/scriptforge
go 1.22
require (
github.com/gin-gonic/gin v1.10.0
gorm.io/driver/sqlite v1.5.6
gorm.io/gorm v1.25.11
)
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

99
backend/go.sum Normal file
View File

@@ -0,0 +1,99 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.6 h1:fO/X46qn5NUEEOZtnjJRWRzZMe8nqJiQ9E+0hi+hKQE=
gorm.io/driver/sqlite v1.5.6/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
gorm.io/gorm v1.25.11 h1:/Wfyg1B/je1hnDx3sMkX+gAlxrlZpn6X0BXRlwXlvHg=
gorm.io/gorm v1.25.11/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@@ -0,0 +1,6 @@
package assets
import "embed"
//go:embed dist/*
var FS embed.FS

0
backend/internal/assets/dist/.gitkeep vendored Normal file
View File

View File

@@ -0,0 +1,37 @@
package config
type RuntimeConfig struct {
Name string
Extension string
MIMEType string
}
var Runtimes = []RuntimeConfig{
{Name: "bash", Extension: ".sh", MIMEType: "text/x-shellscript"},
{Name: "zsh", Extension: ".zsh", MIMEType: "text/x-shellscript"},
{Name: "sh", Extension: ".sh", MIMEType: "text/x-shellscript"},
{Name: "fish", Extension: ".fish", MIMEType: "text/x-shellscript"},
{Name: "python3", Extension: ".py", MIMEType: "text/x-python"},
{Name: "node", Extension: ".js", MIMEType: "text/javascript"},
{Name: "ruby", Extension: ".rb", MIMEType: "text/x-ruby"},
{Name: "php", Extension: ".php", MIMEType: "text/x-php"},
}
var RuntimeMap map[string]RuntimeConfig
func init() {
RuntimeMap = make(map[string]RuntimeConfig, len(Runtimes))
for _, rt := range Runtimes {
RuntimeMap[rt.Name] = rt
}
}
func IsValidRuntime(name string) bool {
_, ok := RuntimeMap[name]
return ok
}
func GetRuntime(name string) (RuntimeConfig, bool) {
rt, ok := RuntimeMap[name]
return rt, ok
}

View File

@@ -0,0 +1,41 @@
package handler
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"gitea.kmux.cn/zhilv/scriptforge/internal/config"
"gitea.kmux.cn/zhilv/scriptforge/internal/service"
)
func GetRawScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
script, err := svc.GetByID(id)
if errors.Is(err, service.ErrNotFound) {
c.String(http.StatusNotFound, "script not found or expired\n")
return
}
if err != nil {
c.String(http.StatusInternalServerError, "internal error\n")
return
}
rt, _ := config.GetRuntime(script.Runtime)
mime := rt.MIMEType
ext := rt.Extension
if mime == "" {
mime = "text/plain"
ext = ".sh"
}
c.Header("Content-Type", mime+"; charset=utf-8")
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="script%s"`, ext))
c.Header("X-Content-Type-Options", "nosniff")
c.String(http.StatusOK, script.Content)
}
}

View File

@@ -0,0 +1,103 @@
package handler
import (
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"gitea.kmux.cn/zhilv/scriptforge/internal/service"
)
type createRequest struct {
Content string `json:"content" binding:"required,max=16384"`
Runtime string `json:"runtime" binding:"required"`
ExpiresIn string `json:"expires_in" binding:"required,oneof=1h 24h 7d 30d"`
}
func CreateScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
var req createRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
scheme := "https"
if strings.HasPrefix(c.Request.Host, "localhost") || strings.HasPrefix(c.Request.Host, "127.0.0.1") {
scheme = "http"
}
result, err := svc.Create(service.CreateInput{
Content: req.Content,
Runtime: req.Runtime,
ExpiresIn: req.ExpiresIn,
}, scheme, c.Request.Host)
if errors.Is(err, service.ErrInvalidRuntime) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid runtime, supported: bash, zsh, sh, fish, python3, node, ruby, php"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.JSON(http.StatusCreated, gin.H{
"id": result.Script.ID,
"admin_token": result.AdminToken,
"url": result.RawURL,
"command": result.Command,
"runtime": result.Script.Runtime,
"expires_at": result.Script.ExpiresAt,
})
}
}
func GetScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
script, err := svc.GetByID(id)
if errors.Is(err, service.ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "script not found or expired"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.JSON(http.StatusOK, gin.H{
"id": script.ID,
"runtime": script.Runtime,
"content": script.Content,
"content_length": len(script.Content),
"created_at": script.CreatedAt,
"expires_at": script.ExpiresAt,
"expired": false,
})
}
}
func DeleteScript(svc *service.ScriptService) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
token := c.Query("token")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "token query parameter is required"})
return
}
if err := svc.Delete(id, token); errors.Is(err, service.ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "script not found or invalid token"})
return
} else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.Status(http.StatusNoContent)
}
}

View File

@@ -0,0 +1,30 @@
package idgen
import (
"crypto/rand"
"encoding/base64"
"math/big"
)
const idChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func GenerateID(length int) (string, error) {
result := make([]byte, length)
for i := range result {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(idChars))))
if err != nil {
return "", err
}
result[i] = idChars[n.Int64()]
}
return string(result), nil
}
func GenerateToken() (string, error) {
token := make([]byte, 48)
_, err := rand.Read(token)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(token), nil
}

View File

@@ -0,0 +1,21 @@
package middleware
import (
"log"
"time"
"github.com/gin-gonic/gin"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
c.Next()
latency := time.Since(start)
status := c.Writer.Status()
log.Printf("[%d] %s %s (%s)", status, c.Request.Method, path, latency)
}
}

View File

@@ -0,0 +1,89 @@
package middleware
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type visitor struct {
count int
lastSeen time.Time
}
type rateLimiter struct {
visitors map[string]*visitor
mu sync.Mutex
limit int
window time.Duration
}
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
rl := &rateLimiter{
visitors: make(map[string]*visitor),
limit: limit,
window: window,
}
go rl.cleanup()
return rl
}
func (rl *rateLimiter) allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
v, exists := rl.visitors[ip]
if !exists {
rl.visitors[ip] = &visitor{count: 1, lastSeen: time.Now()}
return true
}
if time.Since(v.lastSeen) > rl.window {
v.count = 1
v.lastSeen = time.Now()
return true
}
v.count++
v.lastSeen = time.Now()
return v.count <= rl.limit
}
func (rl *rateLimiter) cleanup() {
for {
time.Sleep(10 * time.Minute)
rl.mu.Lock()
for ip, v := range rl.visitors {
if time.Since(v.lastSeen) > rl.window*2 {
delete(rl.visitors, ip)
}
}
rl.mu.Unlock()
}
}
var (
createLimiter = newRateLimiter(10, 1*time.Minute)
generalLimiter = newRateLimiter(60, 1*time.Minute)
)
func RateLimit(limit int) gin.HandlerFunc {
if limit == 10 {
return func(c *gin.Context) {
if !createLimiter.allow(c.ClientIP()) {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
return
}
c.Next()
}
}
return func(c *gin.Context) {
if !generalLimiter.allow(c.ClientIP()) {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
return
}
c.Next()
}
}

View File

@@ -0,0 +1,12 @@
package model
import "time"
type Script struct {
ID string `gorm:"primaryKey;size:8"`
Content string `gorm:"type:text;not null"`
Runtime string `gorm:"size:16;not null;index"`
AdminToken string `gorm:"size:64;not null"`
ExpiresAt time.Time `gorm:"not null;index"`
CreatedAt time.Time `gorm:"not null;autoCreateTime"`
}

View File

@@ -0,0 +1,113 @@
package service
import (
"errors"
"time"
"gorm.io/gorm"
"gitea.kmux.cn/zhilv/scriptforge/internal/config"
"gitea.kmux.cn/zhilv/scriptforge/internal/idgen"
"gitea.kmux.cn/zhilv/scriptforge/internal/model"
)
var (
ErrInvalidRuntime = errors.New("invalid runtime")
ErrNotFound = errors.New("script not found or expired")
)
type ScriptService struct {
db *gorm.DB
}
func NewScriptService(db *gorm.DB) *ScriptService {
return &ScriptService{db: db}
}
type CreateInput struct {
Content string
Runtime string
ExpiresIn string
}
type CreateResult struct {
Script model.Script
AdminToken string
Command string
RawURL string
}
func (s *ScriptService) Create(input CreateInput, scheme, host string) (*CreateResult, error) {
if !config.IsValidRuntime(input.Runtime) {
return nil, ErrInvalidRuntime
}
var d time.Duration
switch input.ExpiresIn {
case "1h":
d = 1 * time.Hour
case "24h":
d = 24 * time.Hour
case "7d":
d = 7 * 24 * time.Hour
case "30d":
d = 30 * 24 * time.Hour
default:
d = 24 * time.Hour
}
id, err := idgen.GenerateID(8)
if err != nil {
return nil, err
}
adminToken, err := idgen.GenerateToken()
if err != nil {
return nil, err
}
script := model.Script{
ID: id,
Content: input.Content,
Runtime: input.Runtime,
AdminToken: adminToken,
ExpiresAt: time.Now().Add(d),
CreatedAt: time.Now(),
}
if err := s.db.Create(&script).Error; err != nil {
return nil, err
}
rawURL := scheme + "://" + host + "/raw/" + id
command := "curl " + rawURL + " | " + input.Runtime
return &CreateResult{
Script: script,
AdminToken: adminToken,
Command: command,
RawURL: rawURL,
}, nil
}
func (s *ScriptService) GetByID(id string) (*model.Script, error) {
var script model.Script
err := s.db.Where("id = ? AND expires_at > ?", id, time.Now()).First(&script).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
return &script, err
}
func (s *ScriptService) Delete(id, token string) error {
result := s.db.Where("id = ? AND admin_token = ?", id, token).Delete(&model.Script{})
if result.RowsAffected == 0 {
return ErrNotFound
}
return result.Error
}
func (s *ScriptService) CleanupExpired() (int64, error) {
result := s.db.Where("expires_at <= ?", time.Now()).Delete(&model.Script{})
return result.RowsAffected, result.Error
}

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ScriptForge - 脚本快速转运行链接</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
</head>
<body class="bg-gray-950 text-gray-100 min-h-screen">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2722
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
frontend/package.json Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "scriptforge-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.39",
"tailwindcss": "^3.4.6",
"typescript": "^5.5.3",
"vite": "^5.3.4"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

31
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,31 @@
import { Routes, Route, Link } from 'react-router-dom'
import Home from './pages/Home'
import ScriptDetail from './pages/ScriptDetail'
import DeleteScript from './pages/DeleteScript'
export default function App() {
return (
<div className="min-h-screen flex flex-col">
<header className="border-b border-gray-800">
<div className="max-w-4xl mx-auto px-4 py-4 flex items-center justify-between">
<Link to="/" className="text-xl font-bold tracking-tight hover:text-blue-400 transition-colors">
<span className="text-blue-500"></span> ScriptForge
</Link>
<span className="text-sm text-gray-500"></span>
</div>
</header>
<main className="flex-1 max-w-4xl mx-auto px-4 py-8 w-full">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/s/:id" element={<ScriptDetail />} />
<Route path="/s/:id/delete" element={<DeleteScript />} />
</Routes>
</main>
<footer className="border-t border-gray-800 text-center text-xs text-gray-600 py-4">
ScriptForge
</footer>
</div>
)
}

View File

@@ -0,0 +1,35 @@
import { useState } from 'react'
interface Props {
command: string
}
export default function CommandCard({ command }: Props) {
const [copied, setCopied] = useState(false)
const handleCopy = () => {
navigator.clipboard.writeText(command).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
})
}
return (
<div className="bg-gray-900 border border-blue-500/30 rounded-lg overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-blue-500/10 border-b border-blue-500/20">
<span className="text-xs text-blue-400 font-medium"></span>
</div>
<div className="p-4 flex items-center gap-3">
<code className="flex-1 text-sm font-mono text-green-400 break-all select-all">
{command}
</code>
<button
onClick={handleCopy}
className="shrink-0 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded text-xs font-medium transition-colors"
>
{copied ? '已复制' : '复制'}
</button>
</div>
</div>
)
}

View File

@@ -0,0 +1,71 @@
import { CreateScriptResponse } from '../types'
import CommandCard from './CommandCard'
interface Props {
result: CreateScriptResponse
onReset: () => void
}
export default function ResultCard({ result, onReset }: Props) {
const detailUrl = `${window.location.origin}/s/${result.id}`
return (
<div className="space-y-6">
<div className="text-center">
<div className="text-4xl mb-2"></div>
<h2 className="text-xl font-bold"></h2>
</div>
<CommandCard command={result.command} />
<div className="bg-gray-800/50 border border-gray-700 rounded-lg p-4 space-y-3">
<div className="flex justify-between text-sm">
<span className="text-gray-400"> ID</span>
<span className="font-mono text-blue-400">{result.id}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<span>{result.runtime}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<span>{new Date(result.expires_at).toLocaleString('zh-CN')}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<a
href={detailUrl}
target="_blank"
rel="noreferrer"
className="text-blue-400 hover:underline font-mono text-xs"
>
{detailUrl}
</a>
</div>
<div className="pt-2 border-t border-gray-700">
<div className="text-xs text-gray-500 mb-1"></div>
<div className="font-mono text-xs bg-gray-900 px-3 py-2 rounded break-all select-all">
{result.admin_token}
</div>
</div>
</div>
<div className="flex gap-3 justify-center">
<button
onClick={onReset}
className="px-4 py-2 bg-gray-800 hover:bg-gray-700 rounded-lg text-sm transition-colors"
>
</button>
<a
href={detailUrl}
target="_blank"
rel="noreferrer"
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm transition-colors"
>
</a>
</div>
</div>
)
}

View File

@@ -0,0 +1,76 @@
import { useState } from 'react'
import { RUNTIME_OPTIONS, EXPIRES_OPTIONS, RuntimeOption, ExpiresIn } from '../types'
interface Props {
onSubmit: (content: string, runtime: RuntimeOption, expiresIn: ExpiresIn) => void
loading: boolean
}
export default function ScriptForm({ onSubmit, loading }: Props) {
const [content, setContent] = useState('')
const [runtime, setRuntime] = useState<RuntimeOption>('bash')
const [expiresIn, setExpiresIn] = useState<ExpiresIn>('24h')
const canSubmit = content.trim().length > 0 && content.length <= 16384 && !loading
return (
<div className="space-y-4">
<div className="flex gap-4 flex-wrap">
<div>
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={runtime}
onChange={(e) => setRuntime(e.target.value as RuntimeOption)}
className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs text-gray-500 mb-1"></label>
<select
value={expiresIn}
onChange={(e) => setExpiresIn(e.target.value as ExpiresIn)}
className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{EXPIRES_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
</div>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="在此粘贴你的脚本..."
rows={12}
className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-sm font-mono focus:outline-none focus:border-blue-500 resize-y"
/>
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500">
{content.length.toLocaleString()} / 16,384
{content.length > 16384 && (
<span className="text-red-400 ml-1"></span>
)}
</span>
<button
onClick={() => onSubmit(content, runtime, expiresIn)}
disabled={!canSubmit}
className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '生成中...' : '生成运行链接'}
</button>
</div>
</div>
)
}

View File

@@ -0,0 +1,23 @@
interface Props {
content: string
runtime: string
}
export default function ScriptViewer({ content, runtime }: Props) {
return (
<div className="bg-gray-900 border border-gray-700 rounded-lg overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-gray-800/50 border-b border-gray-700">
<span className="text-xs text-gray-400 font-mono">script.{runtime === 'node' ? 'js' : runtime === 'python3' ? 'py' : runtime}</span>
<button
onClick={() => navigator.clipboard.writeText(content)}
className="text-xs text-gray-500 hover:text-blue-400 transition-colors"
>
</button>
</div>
<pre className="p-4 text-sm font-mono overflow-x-auto leading-relaxed text-gray-200">
{content}
</pre>
</div>
)
}

3
frontend/src/index.css Normal file
View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

44
frontend/src/lib/api.ts Normal file
View File

@@ -0,0 +1,44 @@
import { CreateScriptResponse, ScriptDetail, RuntimeOption, ExpiresIn } from '../types'
const BASE = ''
async function request<T>(url: string, options?: RequestInit): Promise<T> {
const res = await fetch(BASE + url, {
headers: { 'Content-Type': 'application/json' },
...options,
})
if (!res.ok) {
const body = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(body.error || `HTTP ${res.status}`)
}
return res.json()
}
export async function createScript(params: {
content: string
runtime: RuntimeOption
expires_in: ExpiresIn
}): Promise<CreateScriptResponse> {
return request('/api/scripts', {
method: 'POST',
body: JSON.stringify(params),
})
}
export async function getScript(id: string): Promise<ScriptDetail> {
return request(`/api/scripts/${id}`)
}
export async function deleteScript(id: string, token: string): Promise<void> {
await fetch(`${BASE}/api/scripts/${id}?token=${encodeURIComponent(token)}`, {
method: 'DELETE',
}).then((res) => {
if (!res.ok && res.status !== 204) {
throw new Error('delete failed')
}
})
}
export function getCommandUrl(id: string): string {
return `${window.location.origin}/raw/${id}`
}

13
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,13 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
)

View File

@@ -0,0 +1,72 @@
import { useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { deleteScript } from '../lib/api'
export default function DeleteScript() {
const { id } = useParams<{ id: string }>()
const [token, setToken] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [deleted, setDeleted] = useState(false)
const handleDelete = async () => {
if (!id || !token.trim()) return
setLoading(true)
setError(null)
try {
await deleteScript(id, token.trim())
setDeleted(true)
} catch (e) {
setError(e instanceof Error ? e.message : '删除失败')
} finally {
setLoading(false)
}
}
if (deleted) {
return (
<div className="text-center py-20">
<div className="text-6xl mb-4">🗑</div>
<h2 className="text-xl font-bold mb-2"></h2>
<Link to="/" className="text-blue-400 hover:underline">
</Link>
</div>
)
}
return (
<div className="max-w-md mx-auto py-12">
<h1 className="text-xl font-bold mb-4"></h1>
<p className="text-gray-400 text-sm mb-6">
admin_token <code className="text-blue-400">{id}</code>
</p>
<input
type="text"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="粘贴 admin_token"
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500 mb-4"
/>
{error && <p className="text-red-400 text-sm mb-4">{error}</p>}
<div className="flex gap-3">
<button
onClick={handleDelete}
disabled={loading || !token.trim()}
className="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '删除中...' : '确认删除'}
</button>
<Link
to={`/s/${id}`}
className="px-4 py-2 bg-gray-800 hover:bg-gray-700 rounded-lg text-sm transition-colors"
>
</Link>
</div>
</div>
)
}

View File

@@ -0,0 +1,53 @@
import { useState, useCallback } from 'react'
import ScriptForm from '../components/ScriptForm'
import ResultCard from '../components/ResultCard'
import { createScript } from '../lib/api'
import { CreateScriptResponse, RuntimeOption, ExpiresIn } from '../types'
export default function Home() {
const [result, setResult] = useState<CreateScriptResponse | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleSubmit = useCallback(async (content: string, runtime: RuntimeOption, expiresIn: ExpiresIn) => {
setLoading(true)
setError(null)
setResult(null)
try {
const res = await createScript({ content, runtime, expires_in: expiresIn })
setResult(res)
} catch (e) {
setError(e instanceof Error ? e.message : '创建失败')
} finally {
setLoading(false)
}
}, [])
const handleReset = useCallback(() => {
setResult(null)
setError(null)
}, [])
return (
<div>
{!result ? (
<>
<div className="mb-8 text-center">
<h1 className="text-3xl font-bold mb-2"></h1>
<p className="text-gray-400">
<code className="text-blue-400">curl | bash</code>
</p>
</div>
<ScriptForm onSubmit={handleSubmit} loading={loading} />
{error && (
<div className="mt-4 p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm">
{error}
</div>
)}
</>
) : (
<ResultCard result={result} onReset={handleReset} />
)}
</div>
)
}

View File

@@ -0,0 +1,79 @@
import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import ScriptViewer from '../components/ScriptViewer'
import CommandCard from '../components/CommandCard'
import { getScript } from '../lib/api'
import { ScriptDetail as ScriptDetailType } from '../types'
export default function ScriptDetail() {
const { id } = useParams<{ id: string }>()
const [script, setScript] = useState<ScriptDetailType | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!id) return
getScript(id)
.then(setScript)
.catch((e) => setError(e instanceof Error ? e.message : '加载失败'))
.finally(() => setLoading(false))
}, [id])
if (loading) {
return (
<div className="flex justify-center py-20">
<div className="animate-pulse text-gray-500">...</div>
</div>
)
}
if (error || !script) {
return (
<div className="text-center py-20">
<div className="text-6xl mb-4">😕</div>
<h2 className="text-xl font-bold mb-2"></h2>
<p className="text-gray-400 mb-6">{error}</p>
<Link to="/" className="text-blue-400 hover:underline">
</Link>
</div>
)
}
const command = `curl ${window.location.origin}/raw/${script.id} | ${script.runtime}`
return (
<div>
<div className="mb-6">
<Link to="/" className="text-sm text-gray-500 hover:text-blue-400 transition-colors">
&larr;
</Link>
</div>
<div className="flex items-center gap-3 mb-6">
<h1 className="text-2xl font-bold font-mono">{script.id}</h1>
<span className="px-2 py-0.5 bg-blue-600/20 text-blue-400 text-xs rounded-full border border-blue-600/30">
{script.runtime}
</span>
<span className="text-xs text-gray-500">
{new Date(script.expires_at).toLocaleString('zh-CN')}
</span>
</div>
<ScriptViewer content={script.content} runtime={script.runtime} />
<div className="mt-8">
<CommandCard command={command} />
</div>
<div className="mt-8 text-center">
<Link
to={`/s/${script.id}/delete`}
className="text-xs text-gray-600 hover:text-red-400 transition-colors"
>
</Link>
</div>
</div>
)
}

39
frontend/src/types.ts Normal file
View File

@@ -0,0 +1,39 @@
export interface CreateScriptResponse {
id: string
admin_token: string
url: string
command: string
runtime: string
expires_at: string
}
export interface ScriptDetail {
id: string
runtime: string
content: string
content_length: number
created_at: string
expires_at: string
expired: boolean
}
export type RuntimeOption = 'bash' | 'zsh' | 'sh' | 'fish' | 'python3' | 'node' | 'ruby' | 'php'
export type ExpiresIn = '1h' | '24h' | '7d' | '30d'
export const RUNTIME_OPTIONS: { value: RuntimeOption; label: string }[] = [
{ value: 'bash', label: 'Bash' },
{ value: 'zsh', label: 'Zsh' },
{ value: 'sh', label: 'Sh' },
{ value: 'fish', label: 'Fish' },
{ value: 'python3', label: 'Python 3' },
{ value: 'node', label: 'Node.js' },
{ value: 'ruby', label: 'Ruby' },
{ value: 'php', label: 'PHP' },
]
export const EXPIRES_OPTIONS: { value: ExpiresIn; label: string }[] = [
{ value: '1h', label: '1 小时' },
{ value: '24h', label: '24 小时' },
{ value: '7d', label: '7 天' },
{ value: '30d', label: '30 天' },
]

1
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,8 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [],
}

20
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

13
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
proxy: {
'/api': { target: 'http://localhost:8080' },
'/raw': { target: 'http://localhost:8080' },
},
},
})