Author SHA1 Message Date
mr.zero 546201c886 WarpEngine dropdown emoji
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-06 16:23:52 +02:00
mr.zero c853cfadbc WarpEngine dropdown 2026-08-06 16:22:17 +02:00
Zsolt Tasnadi b1139a43bc wp admin to compose 2026-08-06 16:05:07 +02:00
mr.zero bae6fc06a6 pipeline fix 2026-08-06 16:04:50 +02:00
mr.zero 731b267aa1 wp config fix 2 2026-08-06 15:05:55 +02:00
mr.zero 508e869080 wp config fix 2026-08-06 14:08:18 +02:00
mr.zero 435d22b71d wp config 2026-08-06 14:04:42 +02:00
Zsolt Tasnadi f499b7f2af schema update 2026-08-06 14:00:13 +02:00
mr.zero 267a13b600 woodpecker integration 2026-08-06 13:58:58 +02:00
mr.zeroandClaude Opus 4.6 b530dcd50d Update README template path to match platform directory structure
ci/woodpecker/push/woodpecker Pipeline was successful
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-08-06 10:34:06 +02:00
mr.zero 068c4db3f8 platform files refact
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-06 10:00:34 +02:00
mr.zero 565c086a0d Pin the pipeline update server URL: base_url is http behind the host nginx 2026-08-06 08:58:18 +02:00
mr.zero dd69dd79ab Register the config extension endpoint globally on the Woodpecker server 2026-08-06 08:26:10 +02:00
mr.zero fd0b64850f Serve the tic80 pipeline on the existing tic80pro image
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-06 08:16:47 +02:00
mr.zero 61ad1a87f2 godot builder image version update 2026-08-06 07:59:07 +02:00
mr.zero 7c9c8ff510 Verify RFC 9421 signatures on the Woodpecker config endpoint
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-06 07:24:47 +02:00
mr.zero 4b32252d2b Translate code comments and admin strings to English
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-06 01:25:53 +02:00
mr.zero dc45f2eb35 Serve Woodpecker pipeline configs from the engine (/build/config) 2026-08-06 01:14:22 +02:00
mr.zero c067d303bb Remove the droparea: artifacts arrive over /build/upload
ci/woodpecker/push/woodpecker Pipeline was successful
2026-08-05 22:16:34 +02:00
95 changed files with 2974 additions and 347 deletions
+28 -5
View File
@@ -1,13 +1,36 @@
# WarpEngine host-konfiguráció. to_prepare: reload után is újrafut, ezért
# értékadás (nem <<), hogy idempotens legyen.
# WarpEngine host configuration. to_prepare: re-runs after reloads, hence
# assignment (not <<) to stay idempotent.
Rails.application.config.to_prepare do
WarpEngine.configure do |c|
# A /build/* DB-tokenjeinek tulajdonosa. A :database módra váltás
# (c.application_token_source = :database) csak azután jöhet, hogy a CI már
# DB-tokent használ — az átkapcsolás azonnal érvényteleníti az UPDATE_SECRET-et.
# Owner of the /build/* DB tokens. Switching to :database mode
# (c.application_token_source = :database) must wait until CI uses DB
# tokens — the flip invalidates UPDATE_SECRET immediately.
c.application_token_source = :database
c.application_token_owner_class = "AdminUser"
# Woodpecker configuration extension (/build/config): the served platforms
# and their builder images. An image bump is one line here, rolled out to
# every repo by the deploy.
c.ci_platforms = {
"godot" => { builder: "git.teletypegames.org/internal/godot-builder:4.7.1" },
"phaser" => { builder: "git.teletypegames.org/internal/phaser-builder:latest" },
"love" => { builder: "git.teletypegames.org/internal/love-builder:latest" },
"bevy" => { builder: "git.teletypegames.org/internal/bevy-builder:latest" },
"c64" => { builder: "git.teletypegames.org/internal/c64-builder:latest" },
"ebitengine" => { builder: "git.teletypegames.org/internal/ebitengine-builder:latest" },
"tic80" => { builder: "git.teletypegames.org/internal/tic80pro:latest" }
}
# Explicit URL: request.base_url would yield http:// behind the host nginx
# (no X-Forwarded-Proto reaches Rails), and the resulting 301 makes the
# pipeline's curl steps silently no-op.
c.ci_update_server = "https://teletypegames.org"
c.ci_extension_public_key_url = "https://ci.teletypegames.org/api/signature/public-key"
# Woodpecker CI management (repo sync, secret provisioning, pipeline control)
c.woodpecker_url = ENV["WOODPECKER_URL"] # e.g. "https://ci.teletypegames.org"
c.woodpecker_api_token = ENV["WOODPECKER_API_TOKEN"] # Woodpecker PAT with admin access
c.woodpecker_repo_owner = ENV["WOODPECKER_REPO_OWNER"] # forge org (e.g. "games")
c.image_owners = [
{
label: "member",
+20 -1
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_08_05_000003) do
ActiveRecord::Schema[8.1].define(version: 2026_08_06_000001) do
create_table "admin_users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "deleted_at", precision: 3
@@ -45,6 +45,24 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_05_000003) do
t.index ["token_digest"], name: "idx_application_tokens_token_digest", unique: true
end
create_table "ci_repositories", id: { type: :bigint, unsigned: true }, charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.boolean "active", default: true, null: false
t.datetime "created_at", precision: 3
t.datetime "deleted_at", precision: 3
t.datetime "last_pipeline_at", precision: 3
t.string "last_pipeline_status", limit: 32
t.string "platform", limit: 32, null: false
t.string "repo_name", limit: 128, null: false
t.string "repo_owner", limit: 128, null: false
t.bigint "software_id", unsigned: true
t.datetime "updated_at", precision: 3
t.bigint "woodpecker_repo_id", null: false, unsigned: true
t.index ["deleted_at"], name: "idx_ci_repos_deleted"
t.index ["repo_owner", "repo_name"], name: "idx_ci_repos_owner_name", unique: true
t.index ["software_id"], name: "idx_ci_repos_software"
t.index ["woodpecker_repo_id"], name: "idx_ci_repos_wp_id", unique: true
end
create_table "downloads", id: { type: :bigint, unsigned: true }, charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.datetime "created_at", precision: 3
t.datetime "deleted_at", precision: 3
@@ -264,6 +282,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_08_05_000003) do
end
add_foreign_key "admin_users", "members"
add_foreign_key "ci_repositories", "softwares", name: "fk_ci_repos_software", on_delete: :nullify
add_foreign_key "downloads", "releases", name: "fk_downloads_release", on_delete: :nullify
add_foreign_key "external_links", "softwares", name: "fk_softwares_external_links", on_delete: :cascade
add_foreign_key "members", "images"
+7 -19
View File
@@ -54,6 +54,10 @@ services:
WOODPECKER_GITEA_SECRET: ${GITEA_CLIENT_SECRET}
WOODPECKER_SERVER_ADDR: ":8000"
WOODPECKER_AGENT_SECRET: ${WOODPECKER_AGENT_SECRET}
# Global configuration extension: every pipeline start asks the update
# server for the config; non-marker repos fall back to their own YAML (204).
WOODPECKER_CONFIG_EXTENSION_ENDPOINT: "https://${WEBAPP_DOMAIN}/build/config"
WOODPECKER_ADMIN: mr.zero
volumes:
- ./data/woodpecker:/var/lib/woodpecker
labels:
@@ -162,6 +166,9 @@ services:
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@teletype.hu}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-password123}
- WIKI_GRAV_URL=${WIKI_GRAV_URL:-https://wiki.teletypegames.org}
- WOODPECKER_URL=${WOODPECKER_URL:-http://woodpecker-server:8000}
- WOODPECKER_API_TOKEN=${WOODPECKER_API_TOKEN:-}
- WOODPECKER_REPO_OWNER=${WOODPECKER_REPO_OWNER:-}
depends_on:
mysql:
condition: service_healthy
@@ -192,25 +199,6 @@ services:
- proxy
- interstack
droparea:
image: linuxserver/openssh-server
container_name: droparea
environment:
PUID: 1
PGID: 1
TZ: Europe/Budapest
SUDO_ACCESS: "false"
PASSWORD_ACCESS: "true"
USER_NAME: drop
USER_PASSWORD: ${DROP_PASSWORD}
volumes:
- ./data/softwares:/home/drop
ports:
- "${DROPAREA_SSH_PORT}:2222"
networks:
- proxy
- interstack
volumes:
gitea:
woodpecker:
-2
View File
@@ -13,7 +13,6 @@ PHPMYADMIN_DOMAIN=db.teletype.hu
# Ports
GITEA_SSH_PORT=2222
DROPAREA_SSH_PORT=2223
TRAEFIK_WEB_PORT=9100
TRAEFIK_API_PORT=9101
@@ -23,7 +22,6 @@ WOODPECKER_AGENT_SECRET=
MYSQL_ROOT_PASSWORD=
DB_PASSWORD=
UPDATE_SECRET=
DROP_PASSWORD=
WEBAPP_WIKIJS_TOKEN=
DISCORD_INVITE_LINK=
+1
View File
@@ -8,5 +8,6 @@ group :development, :test do
gem "rspec-rails", "~> 7.0"
gem "factory_bot_rails"
gem "shoulda-matchers", "~> 6.0"
gem "webmock", "~> 3.0"
gem "debug", platforms: %i[mri windows]
end
+35 -14
View File
@@ -12,9 +12,9 @@ Repository: `https://git.teletypegames.org/tools/warp_engine`
- **Catalog domain**: `Software`, `Release`, `ReleaseAsset`, `ExternalLink`,
`PlatformLink`, `Image`, `SoftwareImage`, `Download` models with soft-delete
semantics and download statistics.
- **CI-callable updater**: your build pipeline drops artifacts into a
directory and calls one endpoint — WarpEngine extracts archives, parses
metadata and upserts the catalog records. Supported platforms out of the
- **CI-callable updater**: your build pipeline uploads artifacts over HTTP
and calls one endpoint — WarpEngine extracts archives, parses metadata
and upserts the catalog records. Supported platforms out of the
box: TIC-80, Ebitengine, LÖVE, C64, Godot, Bevy, Phaser. Authenticated by
a shared secret or by per-owner database tokens with expiry and scopes
(`ApplicationToken`, managed in the admin).
@@ -36,19 +36,18 @@ Repository: `https://git.teletypegames.org/tools/warp_engine`
## Example stack (docker compose)
`examples/compose` boots everything the engine's workflow assumes, end to
end: the catalog app itself, the SSH drop area the updater contract feeds
from and — behind a compose profile — a Gitea forge with Woodpecker CI, so
you can watch a pipeline publish a release into the catalog.
end: the catalog app itself and — behind a compose profile — a Gitea forge
with Woodpecker CI, so you can watch a pipeline publish a release into the
catalog.
| Service | Role | Where |
| --- | --- | --- |
| `app` | Minimal Rails host with the engine mounted as a path gem (headless: API + updater) | `http://localhost:8080` |
| `mysql` | Catalog database | internal |
| `droparea` | SSH server where pipelines drop build artifacts; shares the `softwares` volume with `app` | `ssh drop@localhost -p 2222` |
| `gitea` | Git forge (profile `ci`) | `http://gitea:3000` |
| `woodpecker` + agent | CI wired to gitea (profile `ci`) | `http://woodpecker:8000` |
### Quickstart — catalog + drop area
### Quickstart — catalog only
```sh
cd examples/compose
@@ -89,10 +88,6 @@ curl -X POST -H "X-Update-Secret: example-update-secret" \
"http://localhost:8080/build/publish?platform=love&name=demo&version=0.1.0"
```
(Dropping the files in over the SSH drop area — `scp -P 2222 demo-0.1.0.*
drop@localhost:drop/`, password `DROP_PASSWORD` from `.env` — works just as
well; the updater only cares that the files end up in `file_container_path`.)
`GET /api/software` now lists *Demo Game* with `html` and `win_x64` assets,
`http://localhost:8080/file/demo-0.1.0/index.html` serves the extracted web
build, and `GET /api/download?path=demo-0.1.0-win-x64.zip` serves the
@@ -221,8 +216,7 @@ Publishing a release from CI is two steps:
1. **Upload** build artifacts into `file_container_path`, named by convention:
`<name>-<version>.metadata.json`, `<name>-<version>.html.zip`,
`<name>-<version>-win-x64.zip`, `<name>-<version>.tic`, ... (each platform
declares which asset kinds it expects — see `GET /api/builds`). Either
drop the files in over the shared volume (SSH drop area), or push them
declares which asset kinds it expects — see `GET /api/builds`). Push them
over HTTP — one request per file, `upload` scope, optional `sha256`
integrity check:
@@ -264,6 +258,33 @@ accepts both:
When switching to `:database`, create the tokens and move your pipelines to
them first — the flip invalidates the shared secret immediately.
## CI pipeline configs (Woodpecker)
WarpEngine can act as a [Woodpecker configuration extension](https://woodpecker-ci.org/docs/usage/extensions/configuration-extension):
instead of a copy-pasted `.woodpecker.yaml` in every game repo, the repo holds a
one-line marker and the engine serves the full per-platform pipeline
(version → build → upload → publish, calling `/build/upload` + `/build/publish`
with the `application_token` Woodpecker secret):
```yaml
# .woodpecker.yaml in a game repo
platform: godot
```
- `POST /build/config` — the extension endpoint Woodpecker calls on every
pipeline start (httpsig/ed25519-signed request, verified against
`ci_extension_public_key(_url)`). Non-marker configs get a `204` so the
repo's own YAML keeps running — opt-in migration, and putting a full
pipeline back into the repo is the opt-out.
- `GET /build/config?platform=godot` — renders the same pipeline as a preview.
Configuration: `ci_platforms` maps platform names to builder images
(`{ "godot" => { builder: "..." }, "tic80" => { builder: ..., exporter: ... } }`);
an empty map (default) disables the feature. Set the Woodpecker side with
`WOODPECKER_CONFIG_EXTENSION_ENDPOINT=https://your-host/build/config` (or
per-repo in Settings → Extensions). Templates live in
`app/services/warp_engine/platforms/<platform>/pipeline.yaml.erb`.
## Public API
| Endpoint | Purpose |
@@ -2,7 +2,7 @@ ActiveAdmin.register WarpEngine::ApplicationToken, as: "Application Token" do
actions :index, :show, :new, :create, :edit, :update, :destroy
permit_params :name, :owner_id, :expires_at, :scopes_string, :unrestricted
menu priority: 9, label: "🎟️ App Tokens"
menu parent: "🌀 WarpEngine", priority: 9, label: "🎟️ App Tokens"
config.sort_order = "created_at_desc"
config.batch_actions = false
@@ -39,29 +39,48 @@ ActiveAdmin.register WarpEngine::ApplicationToken, as: "Application Token" do
include_blank: false
else
f.template.concat(f.template.content_tag(:li,
"application_token_owner_class nincs beállítva — token nem hozható létre.",
"application_token_owner_class is not configured — tokens cannot be created.",
class: "flash flash_error"))
end
end
f.input :name
f.input :scopes_string, label: "Scopes (comma separated)",
hint: %(A /build/publish (és a legacy /update) végponthoz az "update", a /build/upload-hoz az "upload" scope kell.)
f.input :unrestricted, hint: "Belső token: az owner-izoláció (enforce_software_ownership) nem vonatkozik rá."
f.input :expires_at, hint: "Üresen hagyva sosem jár le."
hint: %(The "update" scope is required for /build/publish, the "upload" scope for /build/upload.)
f.input :unrestricted, hint: "Internal token: exempt from owner isolation (enforce_software_ownership)."
f.input :expires_at, hint: "Leave empty for a token that never expires."
end
f.actions
end
action_item :rotate, only: :show do
if WarpEngine.woodpecker_configured?
link_to "Rotate Token", rotate_admin_application_token_path(resource),
method: :post, data: { confirm: "This will revoke the current token, create a new one, and push it to Woodpecker. Continue?" }
end
end
member_action :rotate, method: :post do
result = WarpEngine::CiSecretSyncService.new.rotate(resource)
if result[:rotated]
session[:warp_engine_plain_token] = result[:new_token].plain_token
redirect_to resource_path(result[:new_token]),
notice: "Token rotated and synced to #{result.dig(:sync_result, :synced)&.size || 0} repo(s)"
else
redirect_to resource_path(resource),
alert: "Rotation failed: #{result[:reason]}"
end
end
show do
if (plain = controller.instance_variable_get(:@plain_token))
panel "⚠️ Token — csak most látható, másold ki!" do
panel "⚠️ Token — shown only once, copy it now!" do
pre plain, style: "font-family:monospace;font-size:14px;padding:8px;background:#fff3cd;user-select:all;"
end
end
attributes_table do
row :id
row :name
row("Token") { |t| code "#{t.token_prefix}… (SHA256 digest tárolva)" }
row("Token") { |t| code "#{t.token_prefix}… (SHA256 digest stored)" }
row("Owner") { |t| "#{t.owner_type} ##{t.owner_id}#{t.owner.try(:email) || t.owner.try(:name)}" }
row("Scopes") { |t| t.scopes_string }
row :unrestricted
@@ -73,13 +92,26 @@ ActiveAdmin.register WarpEngine::ApplicationToken, as: "Application Token" do
end
controller do
# A plain token csak közvetlenül a létrehozás után létezik; a session-ön át
# jut el az egyszeri megjelenítésig (a flash nem jó: az AA layout minden
# flash kulcsot üzenetsávként renderel).
# The plain token only exists right after creation; it travels via the
# session to its one-time display (flash is unsuitable: the AA layout
# renders every flash key as a message bar).
def create
create! do |success, _failure|
success.html do
session[:warp_engine_plain_token] = resource.plain_token
if WarpEngine.woodpecker_configured?
service = WarpEngine::CiSecretSyncService.new
repos = service.repos_for_token(resource)
if repos.any?
result = service.provision(resource.plain_token, repos: repos)
flash[:notice] = "Token created and synced to #{result[:synced].size} repo(s)."
if result[:failed].any?
flash[:alert] = "Failed to sync to #{result[:failed].size} repo(s)."
end
end
end
redirect_to resource_path(resource) and return
end
end
@@ -90,10 +122,12 @@ ActiveAdmin.register WarpEngine::ApplicationToken, as: "Application Token" do
show!
end
# Revoke = soft delete, audit-nyommal.
def destroy
if WarpEngine.woodpecker_configured?
WarpEngine::CiSecretSyncService.new.deprovision(resource)
end
resource.revoke!
redirect_to collection_path, notice: "Token revoked."
redirect_to collection_path, notice: "Token revoked and Woodpecker secrets cleaned up."
end
end
end
@@ -0,0 +1,49 @@
ActiveAdmin.register_page "CI Dashboard" do
menu parent: "🌀 WarpEngine", priority: 11, label: "🚀 CI Dashboard"
content do
if WarpEngine.woodpecker_configured?
begin
entries = WarpEngine::CiPipelineService.new.dashboard
rescue => e
entries = []
div class: "flash flash_alert" do
"Error connecting to Woodpecker: #{e.message}"
end
end
entries.group_by { |e| e[:repo].platform }.sort.each do |platform, group|
panel platform.titleize do
table_for group do
column("Repository") { |e| link_to e[:repo].full_name, admin_ci_repository_path(e[:repo]) }
column("Software") { |e| e[:repo].software ? link_to(e[:repo].software.title, admin_software_path(e[:repo].software)) : "-" }
column("Status") { |e|
if e[:pipeline]
status_tag e[:pipeline]["status"],
class: e[:pipeline]["status"] == "success" ? "ok" : "error"
else
status_tag "unknown", class: "warning"
end
}
column("Branch") { |e| e.dig(:pipeline, "branch") || "-" }
column("When") { |e| e.dig(:pipeline, "created_at") || "-" }
column("Actions") { |e|
if e[:repo].active
text_node link_to("Trigger", trigger_admin_ci_repository_path(e[:repo]),
method: :post, class: "member_link")
end
}
end
end
end
if entries.empty?
para "No CI repositories tracked. Sync repos from the CI Repos page.",
style: "color:#999;text-align:center;padding:40px 0;"
end
else
para "Woodpecker is not configured. Set woodpecker_url and woodpecker_api_token in the WarpEngine initializer.",
style: "color:#999;text-align:center;padding:40px 0;"
end
end
end
@@ -0,0 +1,118 @@
ActiveAdmin.register WarpEngine::CiRepository, as: "CI Repository" do
actions :index, :show, :edit, :update
menu parent: "🌀 WarpEngine", priority: 10, label: "🔧 CI Repos"
config.sort_order = "repo_name_asc"
config.batch_actions = false
scope :all, default: true
scope("Active") { |s| s.where(active: true) }
scope("Inactive") { |s| s.where(active: false) }
WarpEngine::PlatformLink::SUPPORTED_PLATFORMS.each do |p|
scope(p.capitalize) { |s| s.where(platform: p) }
end
index do
id_column
column :repo_owner
column :repo_name
column :platform
column("Software") { |r| r.software ? link_to(r.software.title, admin_software_path(r.software)) : "-" }
column(:active) { |r| status_tag(r.active ? "active" : "inactive", class: r.active ? "ok" : "warning") }
column("Pipeline") { |r|
if r.last_pipeline_status
status_tag r.last_pipeline_status,
class: r.last_pipeline_status == "success" ? "ok" : "error"
else
"-"
end
}
column :last_pipeline_at
actions defaults: true do |repo|
if repo.active && WarpEngine.woodpecker_configured?
item "Trigger", trigger_admin_ci_repository_path(repo), method: :post, class: "member_link"
end
end
end
filter :repo_name
filter :platform, as: :select, collection: WarpEngine::PlatformLink::SUPPORTED_PLATFORMS
filter :active
form do |f|
f.inputs do
f.input :platform, as: :select, collection: WarpEngine::PlatformLink::SUPPORTED_PLATFORMS
f.input :software_id, as: :select,
collection: WarpEngine::Software.order(:title).map { |s| [ s.title, s.id ] },
include_blank: "- none -"
end
f.actions
end
show do
attributes_table do
row :id
row :woodpecker_repo_id
row :repo_owner
row :repo_name
row :platform
row("Software") { |r| r.software ? link_to(r.software.title, admin_software_path(r.software)) : "-" }
row(:active) { |r| status_tag(r.active ? "active" : "inactive") }
row :last_pipeline_status
row :last_pipeline_at
row :created_at
row :updated_at
end
if WarpEngine.woodpecker_configured? && resource.active
panel "Recent Pipelines" do
begin
pipelines = WarpEngine::CiPipelineService.new.list_pipelines(resource, page: 1)
if pipelines.is_a?(Array) && pipelines.any?
table_for pipelines.first(10) do
column("Number") { |p| p["number"] }
column("Status") { |p| status_tag p["status"], class: p["status"] == "success" ? "ok" : "error" }
column("Branch") { |p| p["branch"] }
column("Message") { |p| p["message"]&.truncate(60) }
column("Created") { |p| p["created_at"] }
end
else
para "No pipelines found.", style: "color:#999;"
end
rescue => e
para "Error fetching pipelines: #{e.message}", style: "color:red;"
end
end
end
end
member_action :trigger, method: :post do
repo = WarpEngine::CiRepository.find(params[:id])
WarpEngine::CiPipelineService.new.trigger(repo)
redirect_to resource_path(repo), notice: "Pipeline triggered for #{repo.full_name}"
rescue => e
redirect_to resource_path(repo), alert: "Trigger failed: #{e.message}"
end
collection_action :sync, method: :post do
result = WarpEngine::CiRepoSyncService.new.sync_all
redirect_to collection_path,
notice: "Synced: #{result[:created].size} new, #{result[:updated].size} updated, #{result[:deactivated].size} deactivated"
rescue => e
redirect_to collection_path, alert: "Sync failed: #{e.message}"
end
action_item :sync_repos, only: :index do
if WarpEngine.woodpecker_configured?
link_to "Sync from Woodpecker", sync_admin_ci_repositories_path, method: :post
end
end
controller do
def scoped_collection
super.includes(:software)
end
end
end
+1 -1
View File
@@ -1,7 +1,7 @@
ActiveAdmin.register WarpEngine::Download, as: "Download" do
actions :index, :show
menu priority: 7, label: "📊 Download Stats"
menu parent: "🌀 WarpEngine", priority: 7, label: "📊 Download Stats"
scope :all, default: true
scope("Today") { |scope| scope.where("downloads.created_at >= ?", Date.current.beginning_of_day) }
+1 -1
View File
@@ -1,5 +1,5 @@
ActiveAdmin.register_page "Files" do
menu priority: 6, label: "📁 Files"
menu parent: "🌀 WarpEngine", priority: 6, label: "📁 Files"
content do
service = WarpEngine::FileManagerService.new
+1 -1
View File
@@ -1,7 +1,7 @@
ActiveAdmin.register WarpEngine::Image, as: "Image" do
permit_params :file_upload
menu priority: 5, label: "🖼️ Images"
menu parent: "🌀 WarpEngine", priority: 5, label: "🖼️ Images"
# SoftwareImage a natív használó; a hoston regisztrált image_owners
# (WarpEngine.config) további használókat adhat hozzá (pl. TTG Member).
@@ -1,7 +1,7 @@
ActiveAdmin.register WarpEngine::PlatformLink, as: "Platform Link" do
permit_params :name, :url, :platform, :position
menu priority: 5, label: "🔗 Platform Links"
menu parent: "🌀 WarpEngine", priority: 5, label: "🔗 Platform Links"
config.sort_order = "platform_asc"
+1 -1
View File
@@ -6,7 +6,7 @@ ActiveAdmin.register WarpEngine::Software, as: "Software" do
releases_attributes: [ :id, :version, :_destroy,
{ release_assets_attributes: [ :id, :kind, :path, :_destroy ] } ]
menu priority: 2, label: "🎮 Softwares"
menu parent: "🌀 WarpEngine", priority: 2, label: "🎮 Softwares"
actions :all, except: [ :edit ]
@@ -1,7 +1,7 @@
module WarpEngine
# Token-hitelesítés a publikáló (/build/*) endpointokhoz.
# A hitelesítési forrás kizárólagos: :database módban a shared secret nem
# érvényes, :env módban a DB-tokenek nem.
# Token authentication for the publishing (/build/*) endpoints.
# The auth source is exclusive: in :database mode the shared secret is not
# accepted, in :env mode DB tokens are not.
module UpdateAuthentication
extend ActiveSupport::Concern
@@ -9,8 +9,8 @@ module WarpEngine
attr_reader :current_application_token
# A token kizárólag az X-Update-Secret headerből jöhet — URL-ben a secret
# proxy- és access-logokba szivárogna.
# The token is accepted from the X-Update-Secret header only — in the URL
# it would leak into proxy and access logs.
def update_authorized?(required_scope:)
token = request.headers["X-Update-Secret"].presence
return false if token.blank?
@@ -23,13 +23,13 @@ module WarpEngine
def env_secret_authorized?(token)
expected = WarpEngine.config.update_secret
# Konfigurálatlan secret esetén az endpoint zárva marad.
# With no secret configured the endpoint stays closed.
expected.present? && ActiveSupport::SecurityUtils.secure_compare(token, expected)
end
def database_token_authorized?(token, required_scope)
if WarpEngine.config.application_token_owner_class.blank?
Rails.logger.error("[#{self.class.name}] application_token_source=:database, de application_token_owner_class nincs beállítva — minden kérés elutasítva")
Rails.logger.error("[#{self.class.name}] application_token_source=:database but application_token_owner_class is not set — rejecting every request")
return false
end
@@ -41,9 +41,9 @@ module WarpEngine
true
end
# Owner-kényszer: csak :database módban (van token) és bekapcsolt
# enforce_software_ownership mellett szűr. Owner nélküli software a
# backfillig szabad préda — a kényszer bekapcsolása előtt kell backfillelni.
# Ownership enforcement applies only in :database mode (there is a token)
# with enforce_software_ownership on. An ownerless software is up for grabs
# until the backfill — backfill before enabling the enforcement.
def software_ownership_authorized?(name)
return true unless WarpEngine.config.enforce_software_ownership
@@ -56,8 +56,8 @@ module WarpEngine
software.owner_type == token.owner_type && software.owner_id == token.owner_id
end
# Az először publikált (vagy backfill előtti, gazdátlan) software a beküldő
# token ownerét kapja. Unrestricted (belső) token nem foglal ownert.
# A first-published (or pre-backfill, ownerless) software gets the
# submitting token's owner. Unrestricted (internal) tokens claim nothing.
def claim_software_ownership(name)
token = current_application_token
return if token.nil? || token.unrestricted?
@@ -0,0 +1,74 @@
module WarpEngine
module Api
class CiController < ApiController
include UpdateAuthentication
before_action :require_woodpecker!
resource_description do
short "CI repository and pipeline management"
end
api :GET, "/api/ci/repos", "List active CI repositories"
returns code: 200, desc: "JSON array of tracked repos"
error code: 503, desc: "Woodpecker not configured"
def repos
records = CiRepository.active.includes(:software)
render json: records.map { |r| repo_json(r) }
end
api :GET, "/api/ci/repos/:id/status", "Get a CI repository with its latest pipeline"
param :id, :number, required: true, desc: "CiRepository id"
returns code: 200, desc: "JSON with repo and pipeline data"
error code: 503, desc: "Woodpecker not configured"
def status
repo = CiRepository.find(params[:id])
pipeline = begin
CiPipelineService.new.pipeline_detail(repo, "latest")
rescue WoodpeckerClient::ApiError
nil
end
render json: { repo: repo_json(repo), pipeline: pipeline }
end
api :POST, "/api/ci/repos/:id/trigger", "Trigger a pipeline for a CI repository"
header "X-Update-Secret", "Shared secret or application token (update scope)", required: true
param :id, :number, required: true, desc: "CiRepository id"
param :branch, String, required: false, desc: "Branch to build (default: main)"
returns code: 200, desc: "JSON with triggered pipeline data"
error code: 401, desc: "Invalid secret"
error code: 503, desc: "Woodpecker not configured"
def trigger
unless update_authorized?(required_scope: ApplicationToken::UPDATE_SCOPE)
return render json: { error: "Unauthorized" }, status: :unauthorized
end
repo = CiRepository.find(params[:id])
result = CiPipelineService.new.trigger(repo, branch: params[:branch] || "main")
render json: { triggered: true, pipeline: result }
end
private
def require_woodpecker!
return if WarpEngine.woodpecker_configured?
render json: { error: "Woodpecker not configured" }, status: :service_unavailable
end
def repo_json(repo)
{
id: repo.id,
woodpecker_repo_id: repo.woodpecker_repo_id,
repo_owner: repo.repo_owner,
repo_name: repo.repo_name,
platform: repo.platform,
active: repo.active,
software_name: repo.software&.name,
last_pipeline_status: repo.last_pipeline_status,
last_pipeline_at: repo.last_pipeline_at
}
end
end
end
end
@@ -0,0 +1,83 @@
module WarpEngine
module Build
# Woodpecker configuration-extension endpoint: on every pipeline start the
# CI server POSTs the repo's marker file and receives the platform's full
# pipeline YAML. GET renders the same thing as a preview.
class ConfigsController < ApiController
resource_description do
short "Woodpecker CI pipeline configs"
end
api :GET, "/build/config", "Preview the generated pipeline config for a platform"
param :platform, String, required: true, desc: "Platform (a configured ci_platforms key, e.g. tic80)"
param :name, String, required: false, desc: "Software name substituted into the pipeline (default: example)"
returns code: 200, desc: "Pipeline YAML (text/yaml)"
error code: 404, desc: "Unknown platform"
def show
yaml = render_config(platform: params[:platform], name: params[:name].presence || "example")
return render json: { error: "Unknown platform" }, status: :not_found if yaml.nil?
render plain: yaml, content_type: "text/yaml"
end
api :POST, "/build/config", "Woodpecker configuration extension endpoint"
description <<~DESC
Called by the Woodpecker server on every pipeline start (httpsig-signed request).
If the repo's .woodpecker.yaml is a marker (has a `platform:` key), responds with
the generated pipeline; otherwise responds 204 so the repo's own config runs.
DESC
returns code: 200, desc: %(JSON: {"configs": [{"name": ..., "data": "<pipeline YAML>"}]})
returns code: 204, desc: "Not a marker config — keep the repo's own configuration"
error code: 403, desc: "Missing or invalid request signature"
error code: 422, desc: "Marker requests an unknown platform"
def create
unless WarpEngine::CiSignatureVerifier.new(request).valid?
return render json: { error: "Invalid signature" }, status: :forbidden
end
marker = find_marker
return head :no_content if marker.nil?
platform = marker["platform"].to_s
name = marker["name"].presence || repo_name
yaml = render_config(platform: platform, name: name)
if yaml.nil?
return render json: { error: "Unknown platform: #{platform}" }, status: :unprocessable_entity
end
render json: { configs: [ { name: platform, data: yaml } ] }
end
private
def render_config(platform:, name:)
WarpEngine::CiConfigService.new.render(
platform: platform,
name: name,
update_server: WarpEngine.config.ci_update_server.presence || request.base_url
)
end
# The first submitted config that parses as a marker (Hash with a `platform`
# key). The docs call the key "configuration", the example-config-service
# uses "configs" — accept both.
def find_marker
configs = params[:configuration].presence || params[:configs].presence || []
configs.each do |config|
data = config[:data].to_s
parsed = begin
YAML.safe_load(data)
rescue Psych::Exception
nil
end
return parsed if parsed.is_a?(Hash) && parsed.key?("platform")
end
nil
end
def repo_name
params.dig(:repo, :name).to_s
end
end
end
end
@@ -29,13 +29,13 @@ module WarpEngine
return render json: { error: "Forbidden" }, status: :forbidden
end
input = WarpEngine::UpdateInputDto.new(
input = WarpEngine::PublishInputDto.new(
platform: params[:platform],
name: params[:name],
version: params[:version]
)
WarpEngine::UpdateService.new.update(input)
WarpEngine::PublishService.new.publish(input)
claim_software_ownership(params[:name])
render json: { published: true, name: params[:name], platform: params[:platform], version: params[:version] }
@@ -9,11 +9,11 @@ module WarpEngine
short "Build artifact upload"
end
# A release-fájlnevek kötött konvenciója: <name>-<version>.<ext> vagy
# <name>-<version>-<target>.zip — az updater is ezeket keresi.
# Release file naming convention: <name>-<version>.<ext> or
# <name>-<version>-<target>.zip — the updater looks for these too.
NAME_FORMAT = /\A[A-Za-z0-9._-]+\z/
api :POST, "/build/upload", "Upload a build artifact into the drop area"
api :POST, "/build/upload", "Upload a build artifact into the artifact directory"
header "X-Update-Secret", "Shared secret or application token (upload scope)", required: true
param :name, String, required: true, desc: "Software name (filename must be prefixed with <name>-<version>)"
param :version, String, required: true, desc: "Version string"
@@ -1,5 +1,5 @@
module WarpEngine
UpdateInputDto = Struct.new(:platform, :name, :version, keyword_init: true) do
PublishInputDto = Struct.new(:platform, :name, :version, keyword_init: true) do
def initialize(platform:, name:, version: nil)
super
end
@@ -0,0 +1,8 @@
module WarpEngine
class ApplicationJob < ActiveJob::Base
retry_on WoodpeckerClient::ConnectionError, wait: 30.seconds, attempts: 3
discard_on WoodpeckerClient::ApiError do |job, error|
Rails.logger.error("[#{job.class.name}] discarded: #{error.message}")
end
end
end
@@ -0,0 +1,9 @@
module WarpEngine
class CiRepoSyncJob < ApplicationJob
queue_as :default
def perform
CiRepoSyncService.new.sync_all
end
end
end
@@ -7,8 +7,8 @@ module WarpEngine
UPDATE_SCOPE = "update".freeze
UPLOAD_SCOPE = "upload".freeze
# A generált token csak létrehozáskor, memóriában érhető el — a DB-ben
# kizárólag a SHA256 digest és a nem-titkos prefix tárolódik.
# The generated token is only available in memory at creation time — the DB
# stores nothing but the SHA256 digest and the non-secret prefix.
attr_reader :plain_token
belongs_to :owner, polymorphic: true
@@ -30,7 +30,7 @@ module WarpEngine
Digest::SHA256.hexdigest(token)
end
# Az élő (nem törölt, nem lejárt), a kért scope-pal rendelkező token, különben nil.
# The live (not deleted, not expired) token carrying the required scope, else nil.
def self.authenticate(token, required_scope: nil)
return nil if token.blank?
@@ -45,7 +45,7 @@ module WarpEngine
expires_at.present? && expires_at <= Time.current
end
# Visszavonás = soft delete, az audit-nyom megmarad.
# Revocation = soft delete, the audit trail stays.
def revoke!
update_column(:deleted_at, Time.current)
end
@@ -54,7 +54,7 @@ module WarpEngine
update_column(:last_used_at, Time.current)
end
# Admin form: vesszővel elválasztott scope-lista
# Admin form: comma separated scope list
def scopes_string
Array(scopes).join(", ")
end
@@ -67,7 +67,7 @@ module WarpEngine
%w[created_at deleted_at expires_at id last_used_at name owner_id owner_type token_prefix unrestricted updated_at]
end
# A polimorf owner asszociációra a Ransack nem tud szűrni.
# Ransack cannot filter on the polymorphic owner association.
def self.ransackable_associations(auth_object = nil)
[]
end
@@ -0,0 +1,32 @@
module WarpEngine
class CiRepository < ApplicationRecord
self.table_name = "ci_repositories"
belongs_to :software, class_name: "WarpEngine::Software", optional: true
default_scope { where(deleted_at: nil) }
validates :woodpecker_repo_id, presence: true, uniqueness: true
validates :repo_owner, presence: true
validates :repo_name, presence: true
validates :platform, presence: true,
inclusion: { in: WarpEngine::PlatformLink::SUPPORTED_PLATFORMS }
scope :active, -> { where(active: true) }
def full_name
"#{repo_owner}/#{repo_name}"
end
def self.ransackable_attributes(auth_object = nil)
%w[active created_at deleted_at id last_pipeline_at last_pipeline_status
platform repo_name repo_owner software_id woodpecker_repo_id]
end
def self.ransackable_associations(auth_object = nil)
%w[software]
end
ActiveSupport.run_load_hooks(:warp_engine_ci_repository, self)
end
end
@@ -2,8 +2,8 @@ module WarpEngine
class Software < ApplicationRecord
self.table_name = "softwares"
# A publikáló token ownere (pl. AdminUser) — 3rd party izolációhoz, ld.
# enforce_software_ownership. nil = belső / backfill előtti software.
# Owner of the publishing token (e.g. AdminUser) — for 3rd-party isolation,
# see enforce_software_ownership. nil = internal / pre-backfill software.
belongs_to :owner, polymorphic: true, optional: true
has_many :software_images, foreign_key: :software_id, dependent: :destroy
@@ -11,6 +11,7 @@ module WarpEngine
has_many :releases, foreign_key: :software_id
has_many :downloads, through: :releases
has_many :external_links, foreign_key: :software_id
has_one :ci_repository, foreign_key: :software_id
accepts_nested_attributes_for :software_images, allow_destroy: true
accepts_nested_attributes_for :external_links, allow_destroy: true
@@ -14,7 +14,7 @@ module WarpEngine
field(:license) { |sw| sw.license.to_s }
field :platform
field :status
# Publikus owner-azonosító — az /api/software?owner_id= szűrőhöz.
# Public owner id — for the /api/software?owner_id= filter.
field(:ownerId) { |sw| sw.owner_id }
field(:highlighted) { |sw| sw.highlighted ? true : false }
field(:externalLinks) { |sw| ExternalLinkSerializer.render_as_hash(sw.external_links) }
@@ -2,7 +2,7 @@ require "zip"
require "fileutils"
module WarpEngine
module SoftwareUpdater
module Platforms
module ArchiveExtraction
private
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildCartridge
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildDocs
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildLinuxX64
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildMacArm64
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildMacUniversal
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildMacX64
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildSource
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildWeb
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildWinX64
extend ActiveSupport::Concern
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Builds
module BuildWinX86
extend ActiveSupport::Concern
@@ -1,7 +1,7 @@
require "json"
module WarpEngine
module SoftwareUpdater
module Platforms
module MetadataParsing
METADATA_KEYS = %i[name title author desc site repo license].freeze
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module SoftwarePersistence
private
@@ -1,5 +1,5 @@
module WarpEngine
module SoftwareUpdater
module Platforms
module Updatable
extend ActiveSupport::Concern
include ArchiveExtraction
@@ -9,7 +9,7 @@ module WarpEngine
class_methods do
def platform(value = nil)
@platform = value if value
@platform ||= name.demodulize.delete_suffix("Service").downcase
@platform ||= name.deconstantize.demodulize.downcase
end
def label(value = nil)
@@ -2,7 +2,7 @@ module WarpEngine
class BuildsService
def index
platforms = WarpEngine::PlatformLink::SUPPORTED_PLATFORMS.each_with_object({}) do |platform, hash|
service_class = "WarpEngine::SoftwareUpdater::#{platform.camelize}Service".constantize
service_class = "WarpEngine::Platforms::#{platform.camelize}::Service".constantize
hash[platform] = {
label: service_class.label,
kinds: service_class.expected_kinds
@@ -16,7 +16,7 @@ module WarpEngine
def show(name)
software = WarpEngine::Software.find_by!(name: name)
service_class = "WarpEngine::SoftwareUpdater::#{software.platform.camelize}Service".constantize
service_class = "WarpEngine::Platforms::#{software.platform.camelize}::Service".constantize
expected = service_class.expected_kinds
releases = software.releases.includes(:release_assets).order(updated_at: :desc)
@@ -0,0 +1,40 @@
require "erb"
module WarpEngine
# Renders the /build/config platform templates: the pipeline logic lives in
# app/services/warp_engine/platforms/<platform>/pipeline.yaml.erb, the
# per-platform builder images come from WarpEngine.config.ci_platforms.
class CiConfigService
PLATFORM_FORMAT = /\A[a-z0-9_-]+\z/
# The rendered pipeline YAML, or nil when the platform is not served.
def render(platform:, name:, update_server:)
platform = platform.to_s
return nil unless platform.match?(PLATFORM_FORMAT)
spec = platform_spec(platform)
return nil if spec.nil?
path = templates_dir.join(platform, "pipeline.yaml.erb")
return nil unless path.exist?
ERB.new(path.read, trim_mode: "-").result_with_hash(
name: name.to_s,
update_server: update_server.to_s,
builder: spec[:builder],
exporter: spec[:exporter]
)
end
private
def platform_spec(platform)
spec = WarpEngine.config.ci_platforms.stringify_keys[platform]
spec&.symbolize_keys
end
def templates_dir
WarpEngine::Engine.root.join("app", "services", "warp_engine", "platforms")
end
end
end
@@ -0,0 +1,38 @@
module WarpEngine
class CiPipelineService
def initialize(client: WoodpeckerClient.new)
@client = client
end
def dashboard
CiRepository.active.includes(:software).map do |repo|
pipeline = begin
@client.latest_pipeline(repo.woodpecker_repo_id)
rescue WoodpeckerClient::ApiError
nil
end
if pipeline
repo.update_columns(
last_pipeline_status: pipeline["status"],
last_pipeline_at: pipeline["created_at"]
)
end
{ repo: repo, pipeline: pipeline }
end
end
def trigger(repo, branch: "main")
@client.trigger_pipeline(repo.woodpecker_repo_id, branch: branch)
end
def list_pipelines(repo, page: 1)
@client.list_pipelines(repo.woodpecker_repo_id, page: page)
end
def pipeline_detail(repo, number)
@client.get_pipeline(repo.woodpecker_repo_id, number)
end
end
end
@@ -0,0 +1,73 @@
module WarpEngine
class CiRepoSyncService
def initialize(client: WoodpeckerClient.new)
@client = client
end
def sync_all
remote_repos = @client.list_repos
results = { created: [], updated: [], deactivated: [] }
remote_ids = remote_repos.map { |r| r["id"] }
remote_repos.each do |remote|
record = CiRepository.unscoped.find_or_initialize_by(
woodpecker_repo_id: remote["id"]
)
was_new = record.new_record?
record.assign_attributes(
repo_name: remote["name"],
repo_owner: remote["owner"],
active: remote["active"],
deleted_at: nil
)
if record.platform.blank? || record.platform == "unknown"
sw = Software.find_by(name: remote["name"])
record.platform = sw&.platform || "unknown"
record.software = sw if sw
end
next unless record.save
results[was_new ? :created : :updated] << record
end
CiRepository.where.not(woodpecker_repo_id: remote_ids).find_each do |orphan|
orphan.update!(active: false) if orphan.active?
results[:deactivated] << orphan
end
results
end
def activate(repo_id)
@client.activate_repo(repo_id)
sync_single(repo_id)
end
def deactivate(repo_id)
@client.deactivate_repo(repo_id)
record = CiRepository.find_by!(woodpecker_repo_id: repo_id)
record.update!(active: false)
end
private
def sync_single(repo_id)
remote = @client.get_repo(repo_id)
record = CiRepository.unscoped.find_or_initialize_by(woodpecker_repo_id: repo_id)
record.assign_attributes(
repo_name: remote["name"], repo_owner: remote["owner"],
active: remote["active"], deleted_at: nil
)
if record.platform.blank?
sw = Software.find_by(name: remote["name"])
record.platform = sw&.platform || "unknown"
record.software = sw if sw
end
record.save!
record
end
end
end
@@ -0,0 +1,80 @@
module WarpEngine
class CiSecretSyncService
SECRET_NAME = "application_token".freeze
def initialize(client: WoodpeckerClient.new)
@client = client
end
def provision(plain_token, repos:)
results = { synced: [], failed: [] }
repos.each do |repo|
if secret_exists?(repo.woodpecker_repo_id)
@client.update_secret(repo.woodpecker_repo_id, SECRET_NAME, value: plain_token)
else
@client.create_secret(repo.woodpecker_repo_id, name: SECRET_NAME, value: plain_token)
end
results[:synced] << repo
rescue WoodpeckerClient::ApiError, WoodpeckerClient::ConnectionError => e
Rails.logger.error("[CiSecretSyncService] failed for #{repo.full_name}: #{e.message}")
results[:failed] << { repo: repo, error: e.message }
end
results
end
def deprovision(application_token)
repos_for_token(application_token).each do |repo|
@client.delete_secret(repo.woodpecker_repo_id, SECRET_NAME)
rescue WoodpeckerClient::ApiError => e
Rails.logger.warn("[CiSecretSyncService] delete failed for #{repo.full_name}: #{e.message}")
end
end
def rotate(application_token)
repos = repos_for_token(application_token)
return { rotated: false, reason: "no repos" } if repos.empty?
new_token = ApplicationToken.create!(
name: "#{application_token.name} (rotated #{Date.current})",
owner_id: application_token.owner_id,
owner_type: application_token.owner_type,
scopes: application_token.scopes,
expires_at: application_token.expires_at,
unrestricted: application_token.unrestricted?
)
result = provision(new_token.plain_token, repos: repos)
if result[:synced].any?
application_token.revoke!
{ rotated: true, new_token: new_token, sync_result: result }
else
new_token.revoke!
{ rotated: false, reason: "all repos failed", sync_result: result }
end
end
def repos_for_token(application_token)
if application_token.unrestricted?
CiRepository.active.to_a
else
software_ids = Software.where(
owner_type: application_token.owner_type,
owner_id: application_token.owner_id
).pluck(:id)
CiRepository.active.where(software_id: software_ids).to_a
end
end
private
def secret_exists?(repo_id)
secrets = @client.list_secrets(repo_id)
secrets.any? { |s| s["name"] == SECRET_NAME }
rescue WoodpeckerClient::ApiError
false
end
end
end
@@ -0,0 +1,154 @@
require "openssl"
require "base64"
require "net/http"
require "digest"
module WarpEngine
# Verifies the signature of Woodpecker configuration-extension requests.
# Woodpecker 3.x signs with RFC 9421 HTTP message signatures (ed25519, via
# yaronf/httpsign): Signature-Input + Signature + Content-Digest headers,
# covered components "@request-target" and "content-digest". Older versions
# used draft-cavage http-signatures (a single Signature header) — kept as a
# fallback.
class CiSignatureVerifier
CAVAGE_PARAM = /(\w+)="([^"]*)"/
@key_cache = {}
@key_mutex = Mutex.new
class << self
# The downloaded key is cached process-wide (per URL).
def fetch_public_key(url)
@key_mutex.synchronize do
@key_cache[url] ||= Net::HTTP.get(URI.parse(url))
end
end
def reset_key_cache!
@key_mutex.synchronize { @key_cache = {} }
end
end
def initialize(request)
@request = request
end
def valid?
pem = public_key_pem
if pem.blank?
Rails.logger.error("[CiSignatureVerifier] no ci_extension_public_key(_url) configured — rejecting request")
return false
end
key = OpenSSL::PKey.read(pem)
if @request.headers["Signature-Input"].present?
rfc9421_valid?(key)
else
cavage_valid?(key)
end
rescue OpenSSL::PKey::PKeyError, ArgumentError => e
Rails.logger.error("[CiSignatureVerifier] #{e.class}: #{e.message}")
false
end
private
def public_key_pem
config = WarpEngine.config
return config.ci_extension_public_key if config.ci_extension_public_key.present?
return nil if config.ci_extension_public_key_url.blank?
self.class.fetch_public_key(config.ci_extension_public_key_url)
rescue StandardError => e
Rails.logger.error("[CiSignatureVerifier] public key fetch failed: #{e.class}: #{e.message}")
nil
end
# --- RFC 9421 ---
def rfc9421_valid?(key)
input = @request.headers["Signature-Input"].to_s
match = input.match(/\A\s*([\w.-]+)=(\(.*)\z/m)
return false if match.nil?
label, inner = match[1], match[2]
components = inner[/\((.*?)\)/m, 1].to_s.scan(/"([^"]*)"/).flatten
return false if components.empty?
signature = @request.headers["Signature"].to_s[/#{Regexp.escape(label)}=:([A-Za-z0-9+\/=]+):/, 1]
return false if signature.blank?
return false unless content_digest_valid?(components)
lines = components.map do |component|
value = component_value(component)
return false if value.nil?
%("#{component}": #{value})
end
lines << %("@signature-params": #{inner})
key.verify(nil, Base64.decode64(signature), lines.join("\n"))
end
def component_value(name)
case name
when "@request-target" then @request.fullpath
when "@method" then @request.request_method
when "@target-uri" then @request.original_url
when "@authority" then @request.host_with_port
when "@path" then @request.path
when "@query" then "?#{@request.query_string}"
when /\A@/ then nil
else @request.headers[name]
end
end
# When content-digest is a covered component, the body itself must match
# the digest header — this is what ties the signature to the payload.
def content_digest_valid?(components)
return true unless components.include?("content-digest")
digest = @request.headers["Content-Digest"].to_s[/sha-256=:([A-Za-z0-9+\/=]+):/, 1]
return false if digest.blank?
expected = Digest::SHA256.base64digest(@request.raw_post)
ActiveSupport::SecurityUtils.secure_compare(digest, expected)
end
# --- draft-cavage fallback ---
def cavage_valid?(key)
params = cavage_params
return false if params.nil? || params["signature"].blank?
signing_string = cavage_signing_string(params.fetch("headers", "date"))
return false if signing_string.nil?
key.verify(nil, Base64.decode64(params["signature"]), signing_string)
end
# Parameters of the Signature header (or the "Authorization: Signature ..." form).
def cavage_params
header = @request.headers["Signature"].presence
if header.nil?
auth = @request.headers["Authorization"].to_s
header = auth.delete_prefix("Signature ") if auth.start_with?("Signature ")
end
return nil if header.blank?
header.scan(CAVAGE_PARAM).to_h
end
def cavage_signing_string(headers_list)
lines = headers_list.split(" ").map do |name|
if name == "(request-target)"
"(request-target): #{@request.request_method.downcase} #{@request.fullpath}"
else
value = @request.headers[name]
return nil if value.nil?
"#{name.downcase}: #{value}"
end
end
lines.join("\n")
end
end
end
@@ -0,0 +1,103 @@
# Generated pipeline — WarpEngine /build/config (platform: bevy, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- apk add --no-cache git jq
- |
if [ -f metadata.json ]; then
VERSION=$(jq -r '.version' metadata.json)
else
VERSION=$(git rev-parse --short HEAD)
fi
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: build
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
mkdir -p dist
cargo build --release --target wasm32-unknown-unknown
wasm-bindgen --target web --no-typescript \
--out-dir dist --out-name game target/wasm32-unknown-unknown/release/<%= name %>.wasm
echo "==> Downloading index.html"
curl -sSL https://git.teletypegames.org/tools/bevy-tools/raw/branch/master/web/index.html -o dist/index.html
echo "==> Packaging HTML/WASM for $VERSION"
zip -r "<%= name %>-$VERSION.html.zip" -j dist/game_bg.wasm dist/game.js dist/index.html
echo "==> Cleaning temporary files"
rm -f dist/game_bg.wasm dist/game.js dist/index.html
- name: binaries
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
# Native binaries. linux-x64: glibc build in the debian-based builder
# image; win-x64: mingw-w64 cross-compile (x86_64-pc-windows-gnu).
# Mac needs osxcross, it is not built here.
# The zip gets the assets/ dir too if the project has one — bevy loads
# it at runtime, it is not embedded in the binary.
set -e
pack_binary() {
P_SLUG="$1"; P_BIN="$2"; P_NAME="$3"
PKG_DIR="<%= name %>-$VERSION-$P_SLUG"
rm -rf "$PKG_DIR" "$PKG_DIR.zip"
mkdir -p "$PKG_DIR"
cp "$P_BIN" "$PKG_DIR/$P_NAME"
chmod +x "$PKG_DIR/$P_NAME"
if [ -d assets ]; then cp -r assets "$PKG_DIR/assets"; fi
zip -qr "$PKG_DIR.zip" "$PKG_DIR"
rm -rf "$PKG_DIR"
echo "==> $PKG_DIR.zip kesz"
}
echo "==> Building linux-x64 binary"
cargo build --release
pack_binary "linux-x64" "target/release/<%= name %>" "<%= name %>"
echo "==> Building win-x64 binary"
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
cargo build --release --target x86_64-pc-windows-gnu
pack_binary "win-x64" "target/x86_64-pc-windows-gnu/release/<%= name %>.exe" "<%= name %>.exe"
- name: upload
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
FILE="<%= name %>-$VERSION.html.zip"
META_SRC="metadata.json"
META_DST="<%= name %>-$VERSION.metadata.json"
cp $META_SRC $META_DST
BINS=""
for slug in win-x64 linux-x64; do
[ -f "<%= name %>-$VERSION-$slug.zip" ] && BINS="$BINS <%= name %>-$VERSION-$slug.zip"
done
for f in $FILE $META_DST $BINS; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=bevy&version=$VERSION"
@@ -0,0 +1,14 @@
module WarpEngine
module Platforms
module Bevy
class Service
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX64
include Builds::BuildLinuxX64
label "Bevy"
end
end
end
end
@@ -0,0 +1,59 @@
# Generated pipeline — WarpEngine /build/config (platform: c64, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- |
VERSION=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' metadata.json | head -n 1)
if [ -z "$VERSION" ]; then
echo "ERROR: no \"version\" field in metadata.json!"
exit 1
fi
BRANCH=${CI_COMMIT_BRANCH:-${WOODPECKER_BRANCH}}
BRANCH=$(echo "$BRANCH" | tr '/' '-')
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ] && [ -n "$BRANCH" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: build
image: <%= builder %>
commands:
- |
VERSION=$(cat .version)
acme -f cbm -o <%= name %>.prg main.asm
echo "==> Creating versioned files for $VERSION"
cp <%= name %>.prg <%= name %>-$VERSION.prg
cp metadata.json <%= name %>-$VERSION.metadata.json
ls -lh <%= name %>-$VERSION.*
- name: artifact
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
echo "==> Uploading artifacts for version $VERSION"
for f in <%= name %>-$VERSION.prg <%= name %>-$VERSION.metadata.json; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
echo "==> Publishing version $VERSION"
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=c64&version=$VERSION"
@@ -0,0 +1,14 @@
module WarpEngine
module Platforms
module C64
class Service
include Updatable
include Builds::BuildCartridge
label "C64"
def cartridge_ext = ".prg"
end
end
end
end
@@ -0,0 +1,95 @@
# Generated pipeline — WarpEngine /build/config (platform: ebitengine, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- apk add --no-cache git jq
- |
if [ -f metadata.json ]; then
VERSION=$(jq -r '.version' metadata.json)
else
VERSION=$(git rev-parse --short HEAD)
fi
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: build
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
mkdir -p dist
GOOS=js GOARCH=wasm go build -o dist/game.wasm .
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" dist/wasm_exec.js
echo "==> Downloading index.html"
curl -sSL https://git.teletypegames.org/tools/ebitengine-tools/raw/branch/master/web/index.html -o dist/index.html
echo "==> Packaging HTML/WASM for $VERSION"
zip -r "<%= name %>-$VERSION.html.zip" -j dist/game.wasm dist/wasm_exec.js dist/index.html
echo "==> Cleaning temporary files"
rm -f dist/game.wasm dist/wasm_exec.js dist/index.html
- name: binaries
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
# win-x86 / win-x64: pure Go cross-compile (Windowson nem kell cgo)
# linux-x64: cgo build, linux/amd64 hoston fut (builder image, X11/GL dev libekkel)
# helper: builds one target + zips it with a single root folder
# (unix zip keeps the executable bit)
binary_build() {
B_GOOS="$1"; B_GOARCH="$2"; B_CGO="$3"; B_EXT="$4"; B_TARGET="$5"
PKG_DIR="<%= name %>-$VERSION-$B_TARGET"
echo "==> Building $PKG_DIR"
rm -rf "$PKG_DIR" "$PKG_DIR.zip"
mkdir -p "$PKG_DIR"
CGO_ENABLED=$B_CGO GOOS=$B_GOOS GOARCH=$B_GOARCH go build -o "$PKG_DIR/<%= name %>$B_EXT" .
if [ -f LICENSE ]; then cp LICENSE "$PKG_DIR/"; fi
if [ -f README.md ]; then cp README.md "$PKG_DIR/"; fi
zip -r "$PKG_DIR.zip" "$PKG_DIR" >/dev/null
rm -rf "$PKG_DIR"
echo "==> $PKG_DIR.zip kesz"
}
# CI (linux builder) builds these three:
binary_build "windows" "386" "0" ".exe" "win-x86"
binary_build "windows" "amd64" "0" ".exe" "win-x64"
binary_build "linux" "amd64" "1" "" "linux-x64"
- name: artifact
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
FILE="<%= name %>-$VERSION.html.zip"
META_SRC="metadata.json"
META_DST="<%= name %>-$VERSION.metadata.json"
BINS=$(ls <%= name %>-$VERSION-*.zip 2>/dev/null || true)
cp $META_SRC $META_DST
for f in $FILE $META_DST $BINS; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=ebitengine&version=$VERSION"
@@ -0,0 +1,17 @@
module WarpEngine
module Platforms
module Ebitengine
class Service
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX86
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacX64
include Builds::BuildMacArm64
label "Ebitengine"
end
end
end
end
@@ -0,0 +1,100 @@
# Generated pipeline — WarpEngine /build/config (platform: godot, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- apk add --no-cache git jq
- |
if [ -f metadata.json ]; then
VERSION=$(jq -r '.version' metadata.json)
else
VERSION=$(git rev-parse --short HEAD)
fi
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: build
image: <%= builder %>
commands:
- |
VERSION=$(cat .version)
echo "==> Importing project"
godot --headless --import
echo "==> Exporting web build (Web preset)"
mkdir -p dist/web
godot --headless --export-release "Web" dist/web/index.html
echo "==> Packaging web build for $VERSION"
(cd dist/web && zip -r "../../<%= name %>-$VERSION.html.zip" .)
rm -rf dist/web
- |
VERSION=$(cat .version)
# exports a win/linux target + zips it with a single root folder
# (embed_pck makes the export a single executable)
binary_build() {
B_PRESET="$1"; B_EXT="$2"; B_TARGET="$3"
PKG_DIR="<%= name %>-$VERSION-$B_TARGET"
echo "==> Building $PKG_DIR"
rm -rf "$PKG_DIR" "$PKG_DIR.zip"
mkdir -p "$PKG_DIR"
godot --headless --export-release "$B_PRESET" "$(pwd)/$PKG_DIR/<%= name %>$B_EXT"
if [ -f LICENSE ]; then cp LICENSE "$PKG_DIR/"; fi
if [ -f README.md ]; then cp README.md "$PKG_DIR/"; fi
zip -r "$PKG_DIR.zip" "$PKG_DIR" >/dev/null
rm -rf "$PKG_DIR"
echo "==> $PKG_DIR.zip kesz"
}
# mac: from linux Godot can only export macOS into a .zip (holding the
# .app); repackage it to the root-folder convention (zip -ry keeps
# exec bits and symlinks)
binary_build_mac() {
B_PRESET="$1"; B_TARGET="$2"
PKG_DIR="<%= name %>-$VERSION-$B_TARGET"
echo "==> Building $PKG_DIR"
rm -rf "$PKG_DIR" "$PKG_DIR.zip"
mkdir -p "$PKG_DIR"
godot --headless --export-release "$B_PRESET" "$(pwd)/$PKG_DIR/<%= name %>-mac-tmp.zip"
(cd "$PKG_DIR" && unzip -q "<%= name %>-mac-tmp.zip" && rm "<%= name %>-mac-tmp.zip")
if [ -f LICENSE ]; then cp LICENSE "$PKG_DIR/"; fi
if [ -f README.md ]; then cp README.md "$PKG_DIR/"; fi
zip -ry "$PKG_DIR.zip" "$PKG_DIR" >/dev/null
rm -rf "$PKG_DIR"
echo "==> $PKG_DIR.zip kesz"
}
binary_build "Windows x86" ".exe" "win-x86"
binary_build "Windows x64" ".exe" "win-x64"
binary_build "Linux x64" "" "linux-x64"
binary_build_mac "Mac universal" "mac-universal"
- name: upload
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
cp metadata.json "<%= name %>-$VERSION.metadata.json"
BINS=$(ls <%= name %>-$VERSION-*.zip 2>/dev/null || true)
for f in "<%= name %>-$VERSION.html.zip" "<%= name %>-$VERSION.metadata.json" $BINS; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=godot&version=$VERSION"
@@ -0,0 +1,16 @@
module WarpEngine
module Platforms
module Godot
class Service
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX86
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacUniversal
label "Godot"
end
end
end
end
@@ -0,0 +1,174 @@
# Generated pipeline — WarpEngine /build/config (platform: love, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- apk add --no-cache git jq
- |
if [ -f metadata.json ]; then
VERSION=$(jq -r '.version' metadata.json)
else
VERSION=$(git rev-parse --short HEAD)
fi
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: export
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
mkdir -p dist
echo "==> Building .love package"
zip -r dist/<%= name %>.love . \
--exclude "*.git*" \
--exclude "bin/*" \
--exclude "dist/*" \
--exclude "Makefile" \
--exclude ".version" \
--exclude "metadata.json" \
--exclude "*.zip"
mkdir -p dist/web
# The love-builder CI image pre-fetches love.js here; local builds
# fall back to GitHub.
if [ -f /opt/lovejs.zip ]; then
echo "==> Using cached love.js (/opt/lovejs.zip)"
cp /opt/lovejs.zip dist/lovejs.zip
else
echo "==> Downloading love.js (2dengine)"
curl -sSL https://github.com/2dengine/love.js/archive/refs/heads/master.zip -o dist/lovejs.zip
fi
unzip -o dist/lovejs.zip -d dist/lovejs-src
rm -f dist/lovejs.zip
echo "==> Assembling web bundle"
cp -r dist/lovejs-src/*/. dist/web/
rm -rf dist/lovejs-src
cp dist/<%= name %>.love dist/web/<%= name %>.love
echo "==> Patching player.js"
sed -i.bak "s|uri = 'nogame\.love'|uri = '<%= name %>.love'|g" dist/web/player.js && rm dist/web/player.js.bak
echo "==> Patching index.html"
sed -i.bak 's|<base href="/play/">|<base href="/file/<%= name %>-'"$VERSION"'/">|g' dist/web/index.html && rm dist/web/index.html.bak
echo "==> Web build ready in dist/web"
echo "==> Packaging Love2D for $VERSION"
zip -r <%= name %>-$VERSION.love.zip dist/<%= name %>.love
echo "==> Packaging web build for $VERSION"
(cd dist/web && zip -r ../../<%= name %>-$VERSION.html.zip .)
echo "==> Cleaning temporary files"
rm -f dist/<%= name %>.love
rm -rf dist/web
- name: binaries
image: <%= builder %>
pull: true
commands:
- |
VERSION=$(cat .version)
# The export step deleted the .love, rebuild it here (in make the
# binary-* targets' love prerequisite did the same).
mkdir -p dist
zip -r dist/<%= name %>.love . \
--exclude "*.git*" \
--exclude "bin/*" \
--exclude "dist/*" \
--exclude "Makefile" \
--exclude ".version" \
--exclude "metadata.json" \
--exclude "*.zip"
# The love-builder CI image pre-fetches the dist files to
# /opt/love-dist; local builds fall back to GitHub.
fetch_love() {
if [ -f "/opt/love-dist/$1" ]; then
echo "==> Using cached $1"
cp "/opt/love-dist/$1" "dist/$1"
elif [ ! -f "dist/$1" ]; then
echo "==> Downloading $1"
curl -sSL "https://github.com/love2d/love/releases/download/11.5/$1" -o "dist/$1"
fi
}
echo "==> Fusing windows binary"
fetch_love love-11.5-win64.zip
PKG_DIR="<%= name %>-$VERSION-win-x64"
rm -rf "$PKG_DIR" "$PKG_DIR.zip" dist/win64
unzip -q dist/love-11.5-win64.zip -d dist/win64
SRC=$(dirname $(find dist/win64 -name love.exe | head -n 1))
mkdir -p "$PKG_DIR"
cat "$SRC/love.exe" dist/<%= name %>.love > "$PKG_DIR/<%= name %>.exe"
cp "$SRC"/*.dll "$PKG_DIR/"
cp "$SRC/license.txt" "$PKG_DIR/" 2>/dev/null || true
zip -qr "$PKG_DIR.zip" "$PKG_DIR"
rm -rf "$PKG_DIR" dist/win64
echo "==> $PKG_DIR.zip kesz"
echo "==> Fusing macOS app bundle"
fetch_love love-11.5-macos.zip
PKG_DIR="<%= name %>-$VERSION-mac-universal"
rm -rf "$PKG_DIR" "$PKG_DIR.zip" dist/macos
unzip -q dist/love-11.5-macos.zip -d dist/macos
mkdir -p "$PKG_DIR"
mv dist/macos/love.app "$PKG_DIR/<%= name %>.app"
cp dist/<%= name %>.love "$PKG_DIR/<%= name %>.app/Contents/Resources/"
PLIST="$PKG_DIR/<%= name %>.app/Contents/Info.plist"
sed -i.bak "s|<string>LÖVE</string>|<string><%= name %></string>|g" "$PLIST" && rm "$PLIST.bak"
sed -i.bak "s|org\.love2d\.love|org.teletypegames.<%= name %>|g" "$PLIST" && rm "$PLIST.bak"
zip -qry "$PKG_DIR.zip" "$PKG_DIR"
rm -rf "$PKG_DIR" dist/macos
echo "==> $PKG_DIR.zip kesz"
# The AppImage runtime is glibc-dynamic and cannot run on alpine
# (musl), so we do not run the runtime: the offset is computed from
# readelf (shoff + shentsize*shnum) and the squashfs is extracted
# with unsquashfs -o.
echo "==> Fusing linux AppImage"
fetch_love love-11.5-x86_64.AppImage
PKG_DIR="<%= name %>-$VERSION-linux-x64"
APPIMAGE="dist/love-11.5-x86_64.AppImage"
rm -rf "$PKG_DIR" "$PKG_DIR.zip" squashfs-root dist/game.squashfs dist/runtime
OFFSET=$(readelf -h "$APPIMAGE" | awk '/Start of section headers/{o=$5} /Size of section headers/{s=$5} /Number of section headers/{n=$5} END{print o+s*n}')
unsquashfs -q -o $OFFSET -d squashfs-root "$APPIMAGE" >/dev/null
cat squashfs-root/bin/love dist/<%= name %>.love > squashfs-root/bin/love.fused
mv squashfs-root/bin/love.fused squashfs-root/bin/love
chmod +x squashfs-root/bin/love
mksquashfs squashfs-root dist/game.squashfs -root-owned -noappend -quiet -comp gzip
head -c $OFFSET "$APPIMAGE" > dist/runtime
mkdir -p "$PKG_DIR"
cat dist/runtime dist/game.squashfs > "$PKG_DIR/<%= name %>.AppImage"
chmod +x "$PKG_DIR/<%= name %>.AppImage"
zip -qr "$PKG_DIR.zip" "$PKG_DIR"
rm -rf "$PKG_DIR" squashfs-root dist/game.squashfs dist/runtime
echo "==> $PKG_DIR.zip kesz"
- name: upload
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
cp metadata.json "<%= name %>-$VERSION.metadata.json"
BINS=""
for slug in win-x64 mac-universal linux-x64; do
[ -f "<%= name %>-$VERSION-$slug.zip" ] && BINS="$BINS <%= name %>-$VERSION-$slug.zip"
done
for f in "<%= name %>-$VERSION.love.zip" "<%= name %>-$VERSION.html.zip" "<%= name %>-$VERSION.metadata.json" $BINS; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=love&version=$VERSION"
@@ -0,0 +1,15 @@
module WarpEngine
module Platforms
module Love
class Service
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacUniversal
label "LÖVE"
end
end
end
end
@@ -0,0 +1,69 @@
# Generated pipeline — WarpEngine /build/config (platform: phaser, name: <%= name %>)
steps:
- name: version
image: alpine
commands:
- apk add --no-cache git jq
- |
if [ -f metadata.json ]; then
VERSION=$(jq -r '.version' metadata.json)
else
VERSION=$(git rev-parse --short HEAD)
fi
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then
VERSION="dev-$VERSION-$BRANCH"
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: build
image: <%= builder %>
commands:
- |
VERSION=$(cat .version)
echo "==> Checking JS syntax"
for f in src/*.js; do node --check $f; done
mkdir -p dist/web
echo "==> Downloading Phaser 3.90.0"
curl -sSL https://cdn.jsdelivr.net/npm/phaser@3.90.0/dist/phaser.min.js -o dist/web/phaser.min.js
echo "==> Downloading index.html"
curl -sSL https://git.teletypegames.org/tools/phaser-tools/raw/branch/master/web/index.html -o dist/web/index.html
echo "==> Bundling game sources"
cat src/*.js > dist/web/game.js
echo "==> Packaging web build for $VERSION"
(cd dist/web && zip -r "../../<%= name %>-$VERSION.html.zip" .)
echo "==> Cleaning temporary files"
rm -rf dist/web
- name: upload
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
FILE="<%= name %>-$VERSION.html.zip"
META_SRC="metadata.json"
META_DST="<%= name %>-$VERSION.metadata.json"
cp $META_SRC $META_DST
for f in $FILE $META_DST; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=phaser&version=$VERSION"
@@ -0,0 +1,12 @@
module WarpEngine
module Platforms
module Phaser
class Service
include Updatable
include Builds::BuildWeb
label "Phaser"
end
end
end
end
@@ -0,0 +1,199 @@
# Generated pipeline — WarpEngine /build/config (platform: tic80, name: <%= name %>)
# The version comes from the source (inc/meta/meta.header.lua "-- version:"
# comment) — WarpEngine parses tic80 metadata from the Lua header too, hence
# no metadata.json.
steps:
- name: version
image: alpine
commands:
- |
VERSION=$(sed -n "s/^-- version: //p" inc/meta/meta.header.lua | head -n 1 | tr -d "[:space:]")
BRANCH=${CI_COMMIT_BRANCH:-${WOODPECKER_BRANCH}}
BRANCH=$(echo "$BRANCH" | tr '/' '-')
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ] && [ -n "$BRANCH" ]; then
VERSION=dev-$VERSION-$BRANCH
fi
echo "VERSION is: $VERSION"
echo $VERSION > .version
- name: lint
image: alpine
commands:
- apk add --no-cache lua5.4 lua5.4-dev luarocks gcc musl-dev
- ln -sf /usr/bin/lua5.4 /usr/bin/lua
- ln -sf /usr/bin/luarocks-5.4 /usr/bin/luarocks
- luarocks install luacheck
- |
echo "==> Merging..."
rm -f /tmp/_lint_combined.lua /tmp/_lint_map.txt
touch /tmp/_lint_combined.lua
line=1
while IFS= read -r f || [ -n "$f" ]; do
f=$(printf '%s' "$f" | tr -d '\r')
[ -z "$f" ] && continue
before=$(wc -l < /tmp/_lint_combined.lua)
cat "inc/$f" >> /tmp/_lint_combined.lua
printf '\n' >> /tmp/_lint_combined.lua
after=$(wc -l < /tmp/_lint_combined.lua)
linecount=$((after - before))
echo "$line $linecount inc/$f" >> /tmp/_lint_map.txt
line=$((line + linecount))
done < <%= name %>.inc
echo "==> luacheck..."
LINT_OUTPUT=$(luacheck --no-max-line-length /tmp/_lint_combined.lua 2>&1 | awk -v map=/tmp/_lint_map.txt '
BEGIN {
NR_map = 0;
while ((getline line < map) > 0) {
n = split(line, a, " ");
start[NR_map] = a[1]+0;
count[NR_map] = a[2]+0;
fname[NR_map] = a[3];
NR_map++;
}
}
/^[^:]+:[0-9]+:[0-9]+:/ {
colon1 = index($0, ":");
rest1 = substr($0, colon1+1);
colon2 = index(rest1, ":");
absline = substr(rest1, 1, colon2-1) + 0;
rest2 = substr(rest1, colon2+1);
colon3 = index(rest2, ":");
col = substr(rest2, 1, colon3-1);
rest = substr(rest2, colon3);
found = 0;
for (i = 0; i < NR_map; i++) {
end_line = start[i] + count[i] -1;
if (absline >= start[i] && absline <= end_line) {
relline = absline - start[i] + 1;
print fname[i] ":" relline ":" col ":" rest;
found = 1;
break;
}
}
if (!found) print $0;
next;
}
{ print }
')
echo "$LINT_OUTPUT"
NUM_ISSUES=$(echo "$LINT_OUTPUT" | grep -cE "^[^:]+:[0-9]+:[0-9]+:" || true)
if [ "$NUM_ISSUES" -gt 0 ]; then
echo "Total: $NUM_ISSUES issue(s) found, commit aborted."
exit 1
else
echo "Checking /tmp/_lint_combined.lua OK"
echo "Total: 0 warnings / 0 errors in 1 file"
fi
rm -f /tmp/_lint_combined.lua /tmp/_lint_map.txt
- name: minify
image: alpine
commands:
- apk add --no-cache lua5.4 curl
- ln -sf /usr/bin/lua5.4 /usr/bin/lua
- |
rm -f <%= name %>.lua
sed 's/\r$//' <%= name %>.inc | while read f; do
cat "inc/$f" >> <%= name %>.lua
echo "" >> <%= name %>.lua
done
test -f minify.lua || { echo "==> Downloading minify.lua"; curl -fsSL https://raw.githubusercontent.com/ztimar31/lua-minify-tic80/refs/heads/master/minify.lua -o minify.lua; }
echo "==> Minifying <%= name %>.lua"
cp <%= name %>.lua <%= name %>.original.lua
lua minify.lua minify <%= name %>.original.lua > <%= name %>.lua
- name: docs
image: alpine
commands:
- apk add --no-cache lua5.4 lua5.4-dev luarocks gcc musl-dev zip
- ln -sf /usr/bin/lua5.4 /usr/bin/lua
- ln -sf /usr/bin/luarocks-5.4 /usr/bin/luarocks
- luarocks install ldoc
- |
VERSION=$(cat .version)
echo "==> Generating docs from <%= name %>.original.lua"
ldoc <%= name %>.original.lua -d docs
echo "==> Zipping docs for version $VERSION"
(cd docs && zip -r ../<%= name %>-$VERSION-docs.zip .)
cp <%= name %>-$VERSION-docs.zip <%= name %>-docs.zip
echo "==> Docs zip created"
- name: export
image: <%= builder %>
environment:
XDG_RUNTIME_DIR: /tmp
commands:
- |
VERSION=$(cat .version)
echo "==> Exporting HTML for version $VERSION"
tic80 --cli --skip --fs=. \
--cmd="load <%= name %>.lua & save <%= name %>-$VERSION & export html <%= name %>-$VERSION.html & exit"
if [ -f "<%= name %>-$VERSION.tic" ]; then
cp <%= name %>-$VERSION.tic <%= name %>.tic
fi
if [ -f "<%= name %>-$VERSION.html.zip" ]; then
cp <%= name %>-$VERSION.html.zip <%= name %>.html.zip
fi
echo "==> Generated files:"
ls -lh <%= name %>-$VERSION.* <%= name %>.tic <%= name %>.html.zip 2>/dev/null || true
- name: binaries
image: <%= builder %>
environment:
XDG_RUNTIME_DIR: /tmp
commands:
- |
VERSION=$(cat .version)
echo "==> Exporting native players for version $VERSION"
tic80 --cli --skip --fs=. \
--cmd="load <%= name %>.lua & export win <%= name %>-win & export linux <%= name %>-linux & export mac <%= name %>-mac & exit"
# unix zip preserves the executable bit
pack_binary() {
SLUG="$1"; SRC_FILE="$2"; DST_FILE="$3"
PKG_DIR="<%= name %>-$VERSION-$SLUG"
rm -rf "$PKG_DIR" "$PKG_DIR.zip"
mkdir -p "$PKG_DIR"
mv "$SRC_FILE" "$PKG_DIR/$DST_FILE"
chmod +x "$PKG_DIR/$DST_FILE"
zip -r "$PKG_DIR.zip" "$PKG_DIR" >/dev/null
rm -rf "$PKG_DIR"
echo "==> $PKG_DIR.zip kesz"
}
pack_binary win-x64 <%= name %>-win.exe <%= name %>.exe
pack_binary linux-x64 <%= name %>-linux <%= name %>
pack_binary mac-x64 <%= name %>-mac <%= name %>
- name: upload
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
echo "==> Uploading artifacts for version $VERSION"
cp <%= name %>.lua <%= name %>-$VERSION.lua
BINS=""
for slug in win-x64 linux-x64 mac-x64; do
[ -f "<%= name %>-$VERSION-$slug.zip" ] && BINS="$BINS <%= name %>-$VERSION-$slug.zip"
done
for f in <%= name %>-$VERSION.lua <%= name %>-$VERSION.tic <%= name %>-$VERSION.html.zip <%= name %>-$VERSION-docs.zip $BINS; do
curl -fsS -H "X-Update-Secret: $UPDATE_SECRET" \
-F "file=@$f" \
"$UPDATE_SERVER/build/upload?name=<%= name %>&version=$VERSION" || exit 1
done
- name: publish
image: alpine
environment:
UPDATE_SERVER: <%= update_server %>
UPDATE_SECRET:
from_secret: application_token
commands:
- apk add --no-cache curl
- |
VERSION=$(cat .version)
echo "==> Publishing version $VERSION"
curl -fsS -X POST -H "X-Update-Secret: $UPDATE_SECRET" "$UPDATE_SERVER/build/publish?name=<%= name %>&platform=tic80&version=$VERSION"
@@ -0,0 +1,40 @@
module WarpEngine
module Platforms
module Tic80
class Service
include Updatable
include Builds::BuildCartridge
include Builds::BuildSource
include Builds::BuildWeb
include Builds::BuildDocs
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacX64
label "TIC-80"
def cartridge_ext = ".tic"
def source_ext = ".lua"
private
def parse_metadata(versioned)
parse_lua_metadata(full_path("#{versioned}.lua"))
end
def parse_lua_metadata(source_path)
metadata = {}
File.foreach(source_path) do |line|
break unless line.start_with?("--")
parts = line[2..].split(":", 2)
next if parts.length != 2
key = parts[0].strip.downcase.to_sym
value = parts[1].strip
metadata[key] = value
end
metadata.slice(*MetadataParsing::METADATA_KEYS)
end
end
end
end
end
@@ -1,11 +1,11 @@
module WarpEngine
class UpdateService
def update(input)
class PublishService
def publish(input)
unless WarpEngine::PlatformLink::SUPPORTED_PLATFORMS.include?(input.platform)
raise ArgumentError, "Unsupported platform: #{input.platform}"
end
"WarpEngine::SoftwareUpdater::#{input.platform.camelize}Service".constantize.new.update(input.name, input.version)
"WarpEngine::Platforms::#{input.platform.camelize}::Service".constantize.new.update(input.name, input.version)
end
end
end
@@ -1,12 +0,0 @@
module WarpEngine
module SoftwareUpdater
class BevyService
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX64
include Builds::BuildLinuxX64
label "Bevy"
end
end
end
@@ -1,12 +0,0 @@
module WarpEngine
module SoftwareUpdater
class C64Service
include Updatable
include Builds::BuildCartridge
label "C64"
def cartridge_ext = ".prg"
end
end
end
@@ -1,15 +0,0 @@
module WarpEngine
module SoftwareUpdater
class EbitengineService
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX86
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacX64
include Builds::BuildMacArm64
label "Ebitengine"
end
end
end
@@ -1,14 +0,0 @@
module WarpEngine
module SoftwareUpdater
class GodotService
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX86
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacUniversal
label "Godot"
end
end
end
@@ -1,13 +0,0 @@
module WarpEngine
module SoftwareUpdater
class LoveService
include Updatable
include Builds::BuildWeb
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacUniversal
label "LÖVE"
end
end
end
@@ -1,10 +0,0 @@
module WarpEngine
module SoftwareUpdater
class PhaserService
include Updatable
include Builds::BuildWeb
label "Phaser"
end
end
end
@@ -1,38 +0,0 @@
module WarpEngine
module SoftwareUpdater
class Tic80Service
include Updatable
include Builds::BuildCartridge
include Builds::BuildSource
include Builds::BuildWeb
include Builds::BuildDocs
include Builds::BuildWinX64
include Builds::BuildLinuxX64
include Builds::BuildMacX64
label "TIC-80"
def cartridge_ext = ".tic"
def source_ext = ".lua"
private
def parse_metadata(versioned)
parse_lua_metadata(full_path("#{versioned}.lua"))
end
def parse_lua_metadata(source_path)
metadata = {}
File.foreach(source_path) do |line|
break unless line.start_with?("--")
parts = line[2..].split(":", 2)
next if parts.length != 2
key = parts[0].strip.downcase.to_sym
value = parts[1].strip
metadata[key] = value
end
metadata.slice(*MetadataParsing::METADATA_KEYS)
end
end
end
end
@@ -0,0 +1,160 @@
require "net/http"
require "json"
require "uri"
module WarpEngine
class WoodpeckerClient
class ApiError < StandardError
attr_reader :status, :body
def initialize(message, status:, body: nil)
super(message)
@status = status
@body = body
end
end
class ConnectionError < StandardError; end
def initialize(base_url: nil, token: nil)
@base_url = (base_url || WarpEngine.config.woodpecker_url).to_s.chomp("/")
@token = token || WarpEngine.config.woodpecker_api_token
end
# --- Repos ---
def list_repos
get("/api/repos")
end
def get_repo(repo_id)
get("/api/repos/#{repo_id}")
end
def activate_repo(repo_id)
post("/api/repos", body: { id: repo_id })
end
def deactivate_repo(repo_id)
delete("/api/repos/#{repo_id}")
end
# --- Secrets ---
def list_secrets(repo_id)
get("/api/repos/#{repo_id}/secrets")
end
def create_secret(repo_id, name:, value:, events: %w[push tag deployment])
post("/api/repos/#{repo_id}/secrets",
body: { name: name, value: value, events: events })
end
def update_secret(repo_id, secret_name, value:)
patch("/api/repos/#{repo_id}/secrets/#{secret_name}",
body: { value: value })
end
def delete_secret(repo_id, secret_name)
delete("/api/repos/#{repo_id}/secrets/#{secret_name}")
end
# --- Pipelines ---
def list_pipelines(repo_id, page: 1, per_page: 25)
get("/api/repos/#{repo_id}/pipelines",
params: { page: page, perPage: per_page })
end
def latest_pipeline(repo_id)
get("/api/repos/#{repo_id}/pipelines/latest")
end
def get_pipeline(repo_id, number)
get("/api/repos/#{repo_id}/pipelines/#{number}")
end
def trigger_pipeline(repo_id, branch: "main")
post("/api/repos/#{repo_id}/pipelines",
body: { branch: branch })
end
private
def get(path, params: {})
uri = build_uri(path, params)
request = Net::HTTP::Get.new(uri)
execute(uri, request)
end
def post(path, body: {})
uri = build_uri(path)
request = Net::HTTP::Post.new(uri)
request.body = body.to_json
request.content_type = "application/json"
execute(uri, request)
end
def patch(path, body: {})
uri = build_uri(path)
request = Net::HTTP::Patch.new(uri)
request.body = body.to_json
request.content_type = "application/json"
execute(uri, request)
end
def delete(path)
uri = build_uri(path)
request = Net::HTTP::Delete.new(uri)
execute(uri, request)
end
def build_uri(path, params = {})
uri = URI.parse("#{@base_url}#{path}")
uri.query = URI.encode_www_form(params) if params.any?
uri
end
def execute(uri, request)
request["Authorization"] = "Bearer #{@token}"
request["Accept"] = "application/json"
response = Net::HTTP.start(uri.hostname, uri.port,
use_ssl: uri.scheme == "https",
open_timeout: 10,
read_timeout: 30) do |http|
http.request(request)
end
handle_response(uri, response)
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Net::OpenTimeout,
Net::ReadTimeout, SocketError => e
raise ConnectionError, "Cannot reach Woodpecker at #{@base_url}: #{e.message}"
end
def handle_response(uri, response)
case response
when Net::HTTPSuccess, Net::HTTPNoContent
return nil if response.body.blank?
begin
JSON.parse(response.body)
rescue JSON::ParserError
# A wrong path falls through to the Woodpecker SPA, which answers
# 200 with index.html — surface that as an API error, not a parse one.
raise ApiError.new(
"Expected JSON from #{uri.path} but got: #{response.body.truncate(80)}",
status: response.code.to_i, body: response.body
)
end
when Net::HTTPNotFound
raise ApiError.new("Not found: #{uri.path}", status: 404, body: response.body)
else
raise ApiError.new(
"Woodpecker API error #{response.code}: #{response.body&.truncate(200)}",
status: response.code.to_i,
body: response.body
)
end
end
end
end
+6
View File
@@ -6,10 +6,16 @@ WarpEngine::Engine.routes.draw do
get "download", to: "downloads#show"
get "builds", to: "builds#index"
get "softwares/:name/builds", to: "software_builds#show"
get "ci/repos", to: "ci#repos"
get "ci/repos/:id/status", to: "ci#status"
post "ci/repos/:id/trigger", to: "ci#trigger"
end
post "build/upload", to: "build/uploads#create"
post "build/publish", to: "build/publish#create"
get "build/config", to: "build/configs#show"
post "build/config", to: "build/configs#create"
get "file/*path", to: "files#show", format: false
end
@@ -3,8 +3,8 @@ class CreateApplicationTokens < ActiveRecord::Migration[8.1]
create_table :application_tokens, id: { type: :bigint, unsigned: true },
charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" do |t|
t.string :name, limit: 128, null: false
# Az owner osztályát a host adja (WarpEngine.config.application_token_owner_class),
# ezért nem lehet FK.
# The owner class comes from the host (WarpEngine.config.application_token_owner_class),
# so no FK.
t.string :owner_type, limit: 128, null: false
t.bigint :owner_id, null: false, unsigned: true
t.string :token_digest, limit: 64, null: false
@@ -1,12 +1,12 @@
class AddBuildOwnership < ActiveRecord::Migration[8.1]
def change
# A publikáló token ownere; nil = belső / backfill előtti software.
# Az owner osztályát a host adja (application_token_owner_class), ezért nem lehet FK.
# Owner of the publishing token; nil = internal / pre-backfill software.
# The owner class comes from the host (application_token_owner_class), so no FK.
add_column :softwares, :owner_type, :string, limit: 128
add_column :softwares, :owner_id, :bigint, unsigned: true
add_index :softwares, [ :owner_type, :owner_id ], name: "idx_softwares_owner"
# unrestricted = belső token: az enforce_software_ownership nem vonatkozik rá.
# unrestricted = internal token: exempt from enforce_software_ownership.
add_column :application_tokens, :unrestricted, :boolean, default: false, null: false
end
end
@@ -0,0 +1,27 @@
class CreateCiRepositories < ActiveRecord::Migration[8.1]
def change
create_table :ci_repositories, id: { type: :bigint, unsigned: true },
charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" do |t|
t.bigint :woodpecker_repo_id, null: false, unsigned: true
t.string :repo_owner, limit: 128, null: false
t.string :repo_name, limit: 128, null: false
t.string :platform, limit: 32, null: false
t.bigint :software_id, unsigned: true
t.boolean :active, default: true, null: false
t.string :last_pipeline_status, limit: 32
t.datetime :last_pipeline_at, precision: 3
t.datetime :deleted_at, precision: 3
t.timestamps precision: 3, null: true
t.index :woodpecker_repo_id, unique: true, name: "idx_ci_repos_wp_id"
t.index :software_id, name: "idx_ci_repos_software"
t.index [ :repo_owner, :repo_name ], unique: true, name: "idx_ci_repos_owner_name"
t.index :deleted_at, name: "idx_ci_repos_deleted"
end
add_foreign_key :ci_repositories, :softwares,
column: :software_id,
name: "fk_ci_repos_software",
on_delete: :nullify
end
end
@@ -6,12 +6,8 @@ MYSQL_ROOT_PASSWORD=warpengine
# Shared secret for the /build/* endpoints (X-Update-Secret header).
UPDATE_SECRET=example-update-secret
# Password of the "drop" user on the artifact drop area (SSH, port 2222).
DROP_PASSWORD=drop
# Published ports.
APP_PORT=8080
DROPAREA_SSH_PORT=2222
GITEA_SSH_PORT=2223
# --- profile "ci" only -------------------------------------------------------
@@ -22,3 +18,9 @@ WOODPECKER_AGENT_SECRET=example-agent-secret
# http://woodpecker:8000/authorize — required before the ci profile starts.
WOODPECKER_GITEA_CLIENT=
WOODPECKER_GITEA_SECRET=
# Woodpecker management (repo sync, secret provisioning, pipeline control).
# Generate a PAT in Woodpecker: profile → Personal Token.
WOODPECKER_URL=http://woodpecker:8000
WOODPECKER_API_TOKEN=
WOODPECKER_REPO_OWNER=
@@ -3,12 +3,10 @@
# mysql the catalog database
# app a minimal Rails host with the engine mounted from this
# repo checkout (headless: API + updater, no ActiveAdmin)
# droparea SSH server where build pipelines drop artifacts; shares
# the "softwares" volume with the app
# gitea (profile "ci") the git forge
# woodpecker (profile "ci") CI server + agent, wired to gitea
#
# Quickstart (catalog + drop area only):
# Quickstart (catalog only):
# cp .env.example .env
# docker compose up --build
#
@@ -41,6 +39,9 @@ services:
UPDATE_SECRET: ${UPDATE_SECRET:-example-update-secret}
FILE_CONTAINER_PATH: /softwares
IMAGE_CONTAINER_PATH: /images
WOODPECKER_URL: ${WOODPECKER_URL:-}
WOODPECKER_API_TOKEN: ${WOODPECKER_API_TOKEN:-}
WOODPECKER_REPO_OWNER: ${WOODPECKER_REPO_OWNER:-}
depends_on:
mysql:
condition: service_healthy
@@ -51,24 +52,6 @@ services:
- softwares:/softwares
- images:/images
# SSH landing zone for build artifacts. Pipelines (or you, with scp) upload
# into ~/drop here; the app sees the same files under /softwares.
droparea:
image: linuxserver/openssh-server
environment:
PUID: 1
PGID: 1
SUDO_ACCESS: "false"
PASSWORD_ACCESS: "true"
USER_NAME: drop
USER_PASSWORD: ${DROP_PASSWORD:-drop}
ports:
- "${DROPAREA_SSH_PORT:-2222}:2222"
volumes:
# A subdir of the drop user's home (/config), so sshd's own state files
# never end up in the catalog directory.
- softwares:/config/drop
# --- profile "ci": the forge + CI producing releases for the catalog ------
#
# gitea and woodpecker refer to each other by their service names, so your
@@ -113,7 +96,7 @@ services:
WOODPECKER_SERVER: "woodpecker:9000"
WOODPECKER_AGENT_SECRET: ${WOODPECKER_AGENT_SECRET:-example-agent-secret}
# Attach pipeline containers to the stack network so steps can reach
# gitea, droparea and the app by service name.
# gitea and the app by service name.
WOODPECKER_BACKEND_DOCKER_NETWORK: warp-example
volumes:
- /var/run/docker.sock:/var/run/docker.sock
@@ -3,7 +3,7 @@ Rails.application.config.to_prepare do
c.file_container_path = ENV.fetch("FILE_CONTAINER_PATH", "/softwares")
c.image_container_path = ENV.fetch("IMAGE_CONTAINER_PATH", "/images")
# Beállítatlan secret esetén a /build/* endpointok minden kérést elutasítanak.
# With no secret configured the /build/* endpoints reject every request.
c.update_secret = ENV["UPDATE_SECRET"]
end
end
@@ -11,8 +11,8 @@ class CreateWarpEngineTables < ActiveRecord::Migration[8.0]
t.string :site
t.string :status, limit: 20, default: "development"
t.boolean :highlighted, default: false
# A publikáló token ownere (enforce_software_ownership) — nem lehet FK,
# az owner osztályát a host adja.
# Owner of the publishing token (enforce_software_ownership) — no FK,
# the owner class comes from the host.
t.string :owner_type, limit: 128
t.bigint :owner_id
t.datetime :deleted_at, precision: 3
@@ -87,7 +87,7 @@ class CreateWarpEngineTables < ActiveRecord::Migration[8.0]
t.string :token_digest, limit: 64, null: false
t.string :token_prefix, limit: 12, null: false
t.json :scopes
# Belső token: az enforce_software_ownership nem vonatkozik rá.
# Internal token: exempt from enforce_software_ownership.
t.boolean :unrestricted, default: false, null: false
t.datetime :expires_at, precision: 3
t.datetime :last_used_at, precision: 3
@@ -1,32 +1,50 @@
Rails.application.config.to_prepare do
WarpEngine.configure do |c|
# A build-artifactok és képek tárolási helye (defaultok az env-ből:
# FILE_CONTAINER_PATH ill. IMAGE_CONTAINER_PATH).
# Storage locations for build artifacts and images (defaults from ENV:
# FILE_CONTAINER_PATH and IMAGE_CONTAINER_PATH).
# c.file_container_path = "/softwares"
# c.image_container_path = "/images"
# A /build/* endpointok shared secretje (default: ENV["UPDATE_SECRET"]).
# Beállítatlan secret esetén az endpointok minden kérést elutasítanak.
# Shared secret of the /build/* endpoints (default: ENV["UPDATE_SECRET"]).
# With no secret configured the endpoints reject every request.
# c.update_secret = ENV["UPDATE_SECRET"]
# A /build/* hitelesítési forrása — kizárólagos választás:
# :env — a fenti shared secret érvényes (default)
# :database — csak DB-tárolt WarpEngine::ApplicationToken érvényes
# ("update" scope-pal); a shared secret ilyenkor NEM működik.
# A :database módhoz kötelező a tokenek tulajdonos-osztálya is:
# Auth source of the /build/* endpoints — an exclusive choice:
# :env — the shared secret above is accepted (default)
# :database — only DB-stored WarpEngine::ApplicationToken records are
# accepted (with the "update" scope); the shared secret
# stops working the moment you switch.
# :database mode also requires the owner class every token belongs to:
# c.application_token_source = :database
# c.application_token_owner_class = "AdminUser"
# A /build/upload (és az admin file manager) méretplafonja bájtban (default: 500MB).
# Woodpecker configuration extension (/build/config): builder images of
# the served platforms and the CI server's signing key. An empty
# ci_platforms (default) keeps the feature inactive.
# c.ci_platforms = {
# "godot" => { builder: "registry.example/godot-builder:4.6" },
# "tic80" => { builder: "registry.example/tic80-builder:1.0",
# exporter: "registry.example/tic80pro:1.0" }
# }
# c.ci_extension_public_key_url = "https://ci.example.org/api/signature/public-key"
# c.ci_update_server = nil # nil: the request base_url
# Woodpecker CI management — repo sync, secret provisioning, pipeline control.
# All three must be set for the management features to activate.
# c.woodpecker_url = ENV["WOODPECKER_URL"] # e.g. "https://ci.example.org"
# c.woodpecker_api_token = ENV["WOODPECKER_API_TOKEN"] # Woodpecker PAT with admin access
# c.woodpecker_repo_owner = ENV["WOODPECKER_REPO_OWNER"] # forge org/user (e.g. "games")
# Size cap in bytes for /build/upload (and the admin file manager, default: 500MB).
# c.max_upload_size = 500 * 1024 * 1024
# Owner-izoláció: DB-token csak a saját ownerének szoftvereit
# uploadolhatja/publisholhatja (unrestricted token kivétel). Csak azután
# kapcsold be, hogy a meglévő szoftverek ownert kaptak (backfill)!
# Owner isolation: a DB token may only upload/publish its own owner's
# softwares (unrestricted tokens are exempt). Enable only after existing
# softwares got an owner (backfill)!
# c.enforce_software_ownership = true
# Ha a host modelljei is hivatkoznak katalógus-képekre, regisztráld őket,
# hogy az admin Images oldal orphan-detektálása figyelembe vegye:
# If host models also reference catalog images, register them so the
# admin Images page's orphan detection takes them into account:
# c.image_owners = [
# {
# label: "member",
+4
View File
@@ -19,6 +19,10 @@ module WarpEngine
def self.configure
yield(config)
end
def self.woodpecker_configured?
config.woodpecker_url.present? && config.woodpecker_api_token.present?
end
end
require "warp_engine/engine"
@@ -1,18 +1,28 @@
module WarpEngine
class Configuration
# Owner kontraktus az image_owners elemeire:
# Owner contract for image_owners elements:
# label: String
# image_ids: -> { Array<Integer> } az owner által használt image id-k
# usage_label: ->(image) { String vagy nil } — megjelenítendő címke, ha használja
# application_token_source: a /build/* endpointok hitelesítési forrása, kizárólagos.
# :env — a shared secret (update_secret) érvényes, a DB-tokenek nem
# :database — csak WarpEngine::ApplicationToken érvényes, a shared secret nem
# application_token_owner_class: a tokenek kötelező tulajdonosának osztályneve
# (pl. "AdminUser"); nil esetén a :database mód minden kérést elutasít.
# max_upload_size: a /build/upload (és az admin file manager) fájlméret-plafonja bájtban.
# enforce_software_ownership: ha true, egy DB-token csak a saját ownerének
# szoftvereit uploadolhatja/publisholhatja (unrestricted token kivétel).
# Bekapcsolás CSAK backfill után: gazdátlan software-t bármely token elvihet.
# image_ids: -> { Array<Integer> } — image ids used by the owner
# usage_label: ->(image) { String or nil } label to display when in use
# application_token_source: auth source of the /build/* endpoints, exclusive.
# :env — the shared secret (update_secret) is accepted, DB tokens are not
# :database — only WarpEngine::ApplicationToken is accepted, the shared secret is not
# application_token_owner_class: class name of the mandatory token owner
# (e.g. "AdminUser"); nil makes :database mode reject every request.
# max_upload_size: file size cap in bytes for /build/upload (and the admin file manager).
# enforce_software_ownership: when true, a DB token may only upload/publish
# its own owner's softwares (unrestricted tokens are exempt).
# Enable ONLY after the backfill: any token can claim an ownerless software.
# ci_platforms: platforms served by /build/config:
# { "godot" => { builder: "<image>" }, "tic80" => { builder: ..., exporter: ... } }
# Empty map = the feature is inactive (POST → 204, GET → 404).
# ci_extension_public_key(_url): the Woodpecker httpsig ed25519 public key as
# PEM, or a URL to fetch it from (e.g. https://ci.../api/signature/public-key).
# With neither set, POST /build/config rejects every request.
# ci_update_server: server URL written into the upload/publish steps; nil → the request's base_url.
# woodpecker_url / woodpecker_api_token / woodpecker_repo_owner:
# Woodpecker CI management (repo sync, secret provisioning, pipeline control).
# All nil → the management features are inactive.
attr_accessor :file_container_path,
:image_container_path,
:update_secret,
@@ -20,6 +30,13 @@ module WarpEngine
:application_token_owner_class,
:max_upload_size,
:enforce_software_ownership,
:ci_platforms,
:ci_extension_public_key,
:ci_extension_public_key_url,
:ci_update_server,
:woodpecker_url,
:woodpecker_api_token,
:woodpecker_repo_owner,
:image_owners
def initialize
@@ -30,6 +47,13 @@ module WarpEngine
@application_token_owner_class = nil
@max_upload_size = 500 * 1024 * 1024
@enforce_software_ownership = false
@ci_platforms = {}
@ci_extension_public_key = nil
@ci_extension_public_key_url = nil
@ci_update_server = nil
@woodpecker_url = ENV["WOODPECKER_URL"]
@woodpecker_api_token = ENV["WOODPECKER_API_TOKEN"]
@woodpecker_repo_owner = ENV["WOODPECKER_REPO_OWNER"]
@image_owners = []
end
end
@@ -1,3 +1,3 @@
# Csak a dummy app tesztjeihez: az ApplicationToken owner szerepét tölti be.
# Test-only: plays the ApplicationToken owner role in the dummy app.
class TestOwner < ActiveRecord::Base
end
@@ -1,4 +1,4 @@
# Csak a tesztekhez: az ApplicationToken owner-e (a hostban ez pl. AdminUser).
# Test-only: plays the ApplicationToken owner role (AdminUser in the host).
class CreateTestOwners < ActiveRecord::Migration[8.1]
def change
create_table :test_owners, id: { type: :bigint, unsigned: true },
@@ -1,5 +1,5 @@
# A TestOwner csak a dummy appban létezik — host-oldali használatnál az owner-t
# felül kell írni (pl. owner: create(:admin_user)).
# TestOwner exists only in the dummy app — host-side usage must override the
# owner (e.g. owner: create(:admin_user)).
FactoryBot.define do
factory :test_owner, class: "TestOwner" do
name { "test owner" }
@@ -0,0 +1,17 @@
FactoryBot.define do
factory :ci_repository, class: "WarpEngine::CiRepository" do
sequence(:woodpecker_repo_id) { |n| n }
repo_owner { "testorg" }
sequence(:repo_name) { |n| "game-#{n}" }
platform { "tic80" }
active { true }
trait :with_software do
association :software
end
trait :inactive do
active { false }
end
end
end
@@ -0,0 +1,57 @@
require "rails_helper"
RSpec.describe WarpEngine::CiRepository do
describe "validations" do
subject { build(:ci_repository) }
it { is_expected.to validate_presence_of(:woodpecker_repo_id) }
it { is_expected.to validate_uniqueness_of(:woodpecker_repo_id) }
it { is_expected.to validate_presence_of(:repo_owner) }
it { is_expected.to validate_presence_of(:repo_name) }
it { is_expected.to validate_presence_of(:platform) }
it "rejects unsupported platforms" do
repo = build(:ci_repository, platform: "amiga")
expect(repo).not_to be_valid
expect(repo.errors[:platform]).to be_present
end
WarpEngine::PlatformLink::SUPPORTED_PLATFORMS.each do |p|
it "accepts #{p}" do
repo = build(:ci_repository, platform: p)
expect(repo).to be_valid
end
end
end
describe "#full_name" do
it "returns owner/name" do
repo = build(:ci_repository, repo_owner: "games", repo_name: "mygame")
expect(repo.full_name).to eq("games/mygame")
end
end
describe "default_scope" do
it "excludes soft-deleted records" do
repo = create(:ci_repository)
repo.update_column(:deleted_at, Time.current)
expect(described_class.all).not_to include(repo)
expect(described_class.unscoped).to include(repo)
end
end
describe ".active" do
it "returns only active repos" do
active = create(:ci_repository, active: true)
inactive = create(:ci_repository, active: false)
expect(described_class.active).to include(active)
expect(described_class.active).not_to include(inactive)
end
end
describe "associations" do
it { is_expected.to belong_to(:software).optional }
end
end
@@ -0,0 +1,210 @@
require "rails_helper"
RSpec.describe "Build configs endpoint", type: :request do
let(:signing_key) { OpenSSL::PKey.generate_key("ed25519") }
let(:ci_platforms) do
{
"godot" => { builder: "registry.example/godot-builder:4.6" },
"tic80" => { builder: "registry.example/tic80-builder:1.0",
exporter: "registry.example/tic80pro:1.0" }
}
end
before do
allow(WarpEngine.config).to receive(:ci_platforms).and_return(ci_platforms)
allow(WarpEngine.config).to receive(:ci_extension_public_key).and_return(signing_key.public_to_pem)
end
# Woodpecker 3.x-style RFC 9421 signature over @request-target + content-digest.
def signed_headers(body, path: "/build/config", digest_body: nil)
digest = "sha-256=:#{Digest::SHA256.base64digest(digest_body || body)}:"
inner = %{("@request-target" "content-digest");created=#{Time.now.to_i};alg="ed25519"}
base = [
%("@request-target": #{path}),
%("content-digest": #{digest}),
%("@signature-params": #{inner})
].join("\n")
signature = Base64.strict_encode64(signing_key.sign(nil, base))
{
"Content-Digest" => digest,
"Signature-Input" => "woodpecker-ci-extensions=#{inner}",
"Signature" => "woodpecker-ci-extensions=:#{signature}:",
"Content-Type" => "application/json"
}
end
# Legacy draft-cavage signature (single Signature header).
def cavage_signed_headers(method: "post", path: "/build/config")
date = Time.now.httpdate
signing_string = "(request-target): #{method} #{path}\ndate: #{date}"
signature = Base64.strict_encode64(signing_key.sign(nil, signing_string))
{
"Date" => date,
"Signature" => %(keyId="woodpecker-ci-plugins",algorithm="ed25519",headers="(request-target) date",signature="#{signature}"),
"Content-Type" => "application/json"
}
end
def extension_payload(marker_yaml, repo_name: "mygame")
{
repo: { name: repo_name },
pipeline: { branch: "master" },
configuration: [ { name: ".woodpecker.yaml", data: marker_yaml } ]
}.to_json
end
describe "GET /build/config" do
it "renders the pipeline for a configured platform" do
get "/build/config", params: { platform: "godot", name: "mygame" }
expect(response).to have_http_status(:ok)
pipeline = YAML.safe_load(response.body)
expect(pipeline["steps"]).to be_present
expect(response.body).to include("registry.example/godot-builder:4.6")
expect(response.body).to include("mygame")
end
it "returns 404 for an unknown platform" do
get "/build/config", params: { platform: "nope" }
expect(response).to have_http_status(:not_found)
end
it "returns 404 when the feature is not configured" do
allow(WarpEngine.config).to receive(:ci_platforms).and_return({})
get "/build/config", params: { platform: "godot" }
expect(response).to have_http_status(:not_found)
end
it "rejects path traversal in the platform param" do
get "/build/config", params: { platform: "../secrets" }
expect(response).to have_http_status(:not_found)
end
end
describe "POST /build/config" do
it "returns the rendered pipeline for a marker config" do
payload = extension_payload("platform: godot\n")
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:ok)
configs = response.parsed_body["configs"]
expect(configs.length).to eq(1)
expect(configs.first["name"]).to eq("godot")
pipeline = YAML.safe_load(configs.first["data"])
expect(pipeline["steps"].map { |s| s["name"] }).to include("version", "publish")
expect(configs.first["data"]).to include("mygame")
end
it "uses the marker's name override instead of the repo name" do
payload = extension_payload("platform: godot\nname: othername\n")
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response.parsed_body["configs"].first["data"]).to include("othername")
expect(response.parsed_body["configs"].first["data"]).not_to include("mygame")
end
it "accepts the configs key used by older Woodpecker payloads" do
payload = { repo: { name: "mygame" },
configs: [ { name: ".woodpecker.yaml", data: "platform: godot\n" } ] }.to_json
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:ok)
end
it "accepts a legacy draft-cavage signed request" do
payload = extension_payload("platform: godot\n")
post "/build/config", params: payload, headers: cavage_signed_headers
expect(response).to have_http_status(:ok)
end
it "returns 204 for a non-marker config" do
payload = extension_payload("steps:\n - name: build\n image: alpine\n")
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:no_content)
end
it "returns 204 when no configuration is sent" do
payload = { repo: { name: "mygame" } }.to_json
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:no_content)
end
it "returns 422 for a marker with an unknown platform" do
payload = extension_payload("platform: amiga\n")
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:unprocessable_entity)
end
it "rejects a request with an invalid signature" do
payload = extension_payload("platform: godot\n")
headers = signed_headers(payload)
other_key = OpenSSL::PKey.generate_key("ed25519")
allow(WarpEngine.config).to receive(:ci_extension_public_key).and_return(other_key.public_to_pem)
post "/build/config", params: payload, headers: headers
expect(response).to have_http_status(:forbidden)
end
it "rejects a request whose body does not match the signed content-digest" do
payload = extension_payload("platform: godot\n")
tampered = signed_headers(payload, digest_body: "something else")
post "/build/config", params: payload, headers: tampered
expect(response).to have_http_status(:forbidden)
end
it "rejects a request without a signature header" do
post "/build/config", params: extension_payload("platform: godot\n"),
headers: { "Content-Type" => "application/json" }
expect(response).to have_http_status(:forbidden)
end
it "rejects every request when no public key is configured" do
allow(WarpEngine.config).to receive(:ci_extension_public_key).and_return(nil)
allow(WarpEngine.config).to receive(:ci_extension_public_key_url).and_return(nil)
payload = extension_payload("platform: godot\n")
post "/build/config", params: payload, headers: signed_headers(payload)
expect(response).to have_http_status(:forbidden)
end
end
describe "shipped templates" do
it "renders every template to valid YAML with non-empty steps" do
templates = Dir[WarpEngine::Engine.root.join("app/services/warp_engine/platforms/*/pipeline.yaml.erb")]
expect(templates).not_to be_empty
templates.each do |path|
platform = File.basename(File.dirname(path))
allow(WarpEngine.config).to receive(:ci_platforms).and_return(
platform => { builder: "registry.example/builder:1", exporter: "registry.example/exporter:1" }
)
yaml = WarpEngine::CiConfigService.new.render(
platform: platform, name: "example", update_server: "https://games.example"
)
expect(yaml).to be_present, "#{platform}: no template rendered"
pipeline = YAML.safe_load(yaml)
expect(pipeline["steps"]).to be_present, "#{platform}: no steps"
pipeline["steps"].each do |step|
expect(step["image"]).to be_present, "#{platform}/#{step['name']}: missing image"
expect(step["commands"]).to be_present, "#{platform}/#{step['name']}: missing commands"
end
end
end
end
end
@@ -6,8 +6,8 @@ RSpec.describe "POST /build/publish", type: :request do
end
def stub_updater
updater = instance_double(WarpEngine::SoftwareUpdater::Tic80Service)
allow(WarpEngine::SoftwareUpdater::Tic80Service).to receive(:new).and_return(updater)
updater = instance_double(WarpEngine::Platforms::Tic80::Service)
allow(WarpEngine::Platforms::Tic80::Service).to receive(:new).and_return(updater)
allow(updater).to receive(:update)
updater
end
@@ -0,0 +1,71 @@
require "rails_helper"
RSpec.describe "CI API", type: :request do
before do
allow(WarpEngine.config).to receive(:woodpecker_url).and_return("https://ci.test")
allow(WarpEngine.config).to receive(:woodpecker_api_token).and_return("wp-token")
allow(WarpEngine.config).to receive(:update_secret).and_return("s3cret")
end
describe "GET /api/ci/repos" do
it "returns active repos" do
repo = create(:ci_repository, repo_name: "mygame", platform: "tic80")
get "/api/ci/repos"
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json.size).to eq(1)
expect(json.first["repo_name"]).to eq("mygame")
end
it "returns 503 when woodpecker not configured" do
allow(WarpEngine.config).to receive(:woodpecker_url).and_return(nil)
get "/api/ci/repos"
expect(response).to have_http_status(:service_unavailable)
end
end
describe "GET /api/ci/repos/:id/status" do
it "returns repo with pipeline status" do
repo = create(:ci_repository, repo_owner: "org", repo_name: "game")
client = instance_double(WarpEngine::WoodpeckerClient)
allow(WarpEngine::WoodpeckerClient).to receive(:new).and_return(client)
allow(client).to receive(:get_pipeline)
.and_return({ "number" => 1, "status" => "success" })
get "/api/ci/repos/#{repo.id}/status"
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json["repo"]["repo_name"]).to eq("game")
end
end
describe "POST /api/ci/repos/:id/trigger" do
it "requires authentication" do
repo = create(:ci_repository)
post "/api/ci/repos/#{repo.id}/trigger"
expect(response).to have_http_status(:unauthorized)
end
it "triggers a pipeline with valid secret" do
repo = create(:ci_repository, repo_owner: "org", repo_name: "game")
client = instance_double(WarpEngine::WoodpeckerClient)
allow(WarpEngine::WoodpeckerClient).to receive(:new).and_return(client)
allow(client).to receive(:trigger_pipeline)
.and_return({ "number" => 7, "status" => "pending" })
post "/api/ci/repos/#{repo.id}/trigger",
headers: { "X-Update-Secret" => "s3cret" }
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json["triggered"]).to be true
end
end
end
@@ -0,0 +1,53 @@
require "rails_helper"
RSpec.describe WarpEngine::CiPipelineService do
let(:client) { instance_double(WarpEngine::WoodpeckerClient) }
let(:service) { described_class.new(client: client) }
describe "#dashboard" do
it "returns latest pipeline for each active repo" do
repo = create(:ci_repository, repo_owner: "org", repo_name: "game")
pipeline = { "number" => 5, "status" => "success", "created_at" => "2026-08-06T12:00:00Z" }
allow(client).to receive(:latest_pipeline).with(repo.woodpecker_repo_id).and_return(pipeline)
entries = service.dashboard
expect(entries.size).to eq(1)
expect(entries.first[:pipeline]["status"]).to eq("success")
expect(repo.reload.last_pipeline_status).to eq("success")
end
it "handles API errors gracefully per repo" do
create(:ci_repository, repo_owner: "org", repo_name: "broken")
allow(client).to receive(:latest_pipeline)
.and_raise(WarpEngine::WoodpeckerClient::ApiError.new("fail", status: 500))
entries = service.dashboard
expect(entries.size).to eq(1)
expect(entries.first[:pipeline]).to be_nil
end
end
describe "#trigger" do
it "delegates to client" do
repo = build(:ci_repository, repo_owner: "org", repo_name: "game")
allow(client).to receive(:trigger_pipeline).and_return({ "number" => 6 })
result = service.trigger(repo, branch: "main")
expect(result["number"]).to eq(6)
expect(client).to have_received(:trigger_pipeline).with(repo.woodpecker_repo_id, branch: "main")
end
end
describe "#list_pipelines" do
it "returns paginated pipelines" do
repo = build(:ci_repository, repo_owner: "org", repo_name: "game")
pipelines = [{ "number" => 1 }, { "number" => 2 }]
allow(client).to receive(:list_pipelines).with(repo.woodpecker_repo_id, page: 1).and_return(pipelines)
expect(service.list_pipelines(repo)).to eq(pipelines)
end
end
end
@@ -0,0 +1,81 @@
require "rails_helper"
RSpec.describe WarpEngine::CiRepoSyncService do
let(:client) { instance_double(WarpEngine::WoodpeckerClient) }
let(:service) { described_class.new(client: client) }
describe "#sync_all" do
it "creates new CiRepository records from Woodpecker" do
allow(client).to receive(:list_repos).and_return([
{ "id" => 1, "name" => "mygame", "owner" => "org", "active" => true }
])
result = service.sync_all
expect(result[:created].size).to eq(1)
repo = result[:created].first
expect(repo.repo_name).to eq("mygame")
expect(repo.repo_owner).to eq("org")
expect(repo.active).to be true
end
it "updates existing records" do
existing = create(:ci_repository, woodpecker_repo_id: 1, repo_name: "old", platform: "tic80")
allow(client).to receive(:list_repos).and_return([
{ "id" => 1, "name" => "newname", "owner" => "org", "active" => true }
])
result = service.sync_all
expect(result[:updated].size).to eq(1)
expect(existing.reload.repo_name).to eq("newname")
end
it "deactivates repos missing from Woodpecker" do
orphan = create(:ci_repository, woodpecker_repo_id: 99, active: true)
allow(client).to receive(:list_repos).and_return([])
result = service.sync_all
expect(result[:deactivated]).to include(orphan)
expect(orphan.reload.active).to be false
end
it "auto-detects platform from matching Software" do
create(:software, name: "mygame", platform: "godot")
allow(client).to receive(:list_repos).and_return([
{ "id" => 1, "name" => "mygame", "owner" => "org", "active" => true }
])
result = service.sync_all
expect(result[:created].first.platform).to eq("godot")
expect(result[:created].first.software).to be_present
end
end
describe "#activate" do
it "calls client and syncs the repo" do
allow(client).to receive(:activate_repo).with(42)
allow(client).to receive(:get_repo).with(42).and_return(
{ "id" => 42, "name" => "game", "owner" => "org", "active" => true }
)
repo = service.activate(42)
expect(repo.woodpecker_repo_id).to eq(42)
expect(repo.active).to be true
end
end
describe "#deactivate" do
it "calls client and marks repo inactive" do
repo = create(:ci_repository, woodpecker_repo_id: 42, active: true)
allow(client).to receive(:deactivate_repo).with(42)
service.deactivate(42)
expect(repo.reload.active).to be false
end
end
end
@@ -0,0 +1,131 @@
require "rails_helper"
RSpec.describe WarpEngine::CiSecretSyncService do
let(:client) { instance_double(WarpEngine::WoodpeckerClient) }
let(:service) { described_class.new(client: client) }
before do
allow(WarpEngine.config).to receive(:application_token_source).and_return(:database)
allow(WarpEngine.config).to receive(:application_token_owner_class).and_return("TestOwner")
end
describe "#provision" do
it "creates secrets on repos that don't have one" do
repo = create(:ci_repository)
allow(client).to receive(:list_secrets).with(repo.woodpecker_repo_id).and_return([])
allow(client).to receive(:create_secret)
result = service.provision("plaintoken", repos: [ repo ])
expect(result[:synced]).to eq([ repo ])
expect(client).to have_received(:create_secret).with(
repo.woodpecker_repo_id, name: "application_token", value: "plaintoken"
)
end
it "updates secrets on repos that already have one" do
repo = create(:ci_repository)
allow(client).to receive(:list_secrets).with(repo.woodpecker_repo_id)
.and_return([ { "name" => "application_token" } ])
allow(client).to receive(:update_secret)
result = service.provision("newtoken", repos: [ repo ])
expect(result[:synced]).to eq([ repo ])
expect(client).to have_received(:update_secret).with(
repo.woodpecker_repo_id, "application_token", value: "newtoken"
)
end
it "records failed repos without raising" do
repo = create(:ci_repository)
allow(client).to receive(:list_secrets).and_raise(
WarpEngine::WoodpeckerClient::ConnectionError, "unreachable"
)
result = service.provision("tok", repos: [ repo ])
expect(result[:synced]).to be_empty
expect(result[:failed].size).to eq(1)
end
end
describe "#deprovision" do
it "deletes secrets from all relevant repos" do
token = create(:application_token)
sw = create(:software, name: "game1", owner: token.owner)
repo = create(:ci_repository, :with_software, software: sw)
allow(client).to receive(:delete_secret)
service.deprovision(token)
expect(client).to have_received(:delete_secret).with(repo.woodpecker_repo_id, "application_token")
end
end
describe "#rotate" do
it "creates new token, provisions, revokes old" do
token = create(:application_token)
sw = create(:software, name: "game1", owner: token.owner)
repo = create(:ci_repository, :with_software, software: sw)
allow(client).to receive(:list_secrets).and_return([])
allow(client).to receive(:create_secret)
result = service.rotate(token)
expect(result[:rotated]).to be true
expect(result[:new_token]).to be_a(WarpEngine::ApplicationToken)
expect(token.reload.deleted_at).to be_present
end
it "rolls back if all repos fail" do
token = create(:application_token)
sw = create(:software, name: "game1", owner: token.owner)
create(:ci_repository, :with_software, software: sw)
allow(client).to receive(:list_secrets).and_raise(
WarpEngine::WoodpeckerClient::ConnectionError, "down"
)
result = service.rotate(token)
expect(result[:rotated]).to be false
expect(token.reload.deleted_at).to be_nil
end
it "returns no-op when no repos exist" do
token = create(:application_token)
result = service.rotate(token)
expect(result[:rotated]).to be false
expect(result[:reason]).to eq("no repos")
end
end
describe "#repos_for_token" do
it "returns all active repos for unrestricted tokens" do
token = create(:application_token, :unrestricted)
repo1 = create(:ci_repository)
create(:ci_repository, :inactive)
repos = service.repos_for_token(token)
expect(repos).to eq([ repo1 ])
end
it "returns only owner's repos for scoped tokens" do
token = create(:application_token)
own_sw = create(:software, name: "mine", owner: token.owner)
other_sw = create(:software, name: "theirs", owner: create(:test_owner))
own_repo = create(:ci_repository, :with_software, software: own_sw)
create(:ci_repository, :with_software, software: other_sw)
repos = service.repos_for_token(token)
expect(repos).to eq([ own_repo ])
end
end
end
@@ -1,7 +1,7 @@
require "rails_helper"
require "zip"
RSpec.describe WarpEngine::SoftwareUpdater::Tic80Service do
RSpec.describe WarpEngine::Platforms::Tic80::Service do
let(:tmpdir) { Dir.mktmpdir }
let(:name) { "spectic" }
let(:version) { "9.9" }
@@ -0,0 +1,59 @@
require "rails_helper"
RSpec.describe WarpEngine::PublishService do
describe "#publish" do
it "raises ArgumentError for unsupported platform" do
input = WarpEngine::PublishInputDto.new(platform: "unknown", name: "game", version: "1.0")
expect { described_class.new.publish(input) }.to raise_error(ArgumentError, /Unsupported platform/)
end
it "routes to correct platform service" do
input = WarpEngine::PublishInputDto.new(platform: "tic80", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::Platforms::Tic80::Service)
allow(WarpEngine::Platforms::Tic80::Service).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.publish(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes godot platform to Godot::Service" do
input = WarpEngine::PublishInputDto.new(platform: "godot", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::Platforms::Godot::Service)
allow(WarpEngine::Platforms::Godot::Service).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.publish(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes bevy platform to Bevy::Service" do
input = WarpEngine::PublishInputDto.new(platform: "bevy", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::Platforms::Bevy::Service)
allow(WarpEngine::Platforms::Bevy::Service).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.publish(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes phaser platform to Phaser::Service" do
input = WarpEngine::PublishInputDto.new(platform: "phaser", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::Platforms::Phaser::Service)
allow(WarpEngine::Platforms::Phaser::Service).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.publish(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
end
end
@@ -1,59 +0,0 @@
require "rails_helper"
RSpec.describe WarpEngine::UpdateService do
describe "#update" do
it "raises ArgumentError for unsupported platform" do
input = WarpEngine::UpdateInputDto.new(platform: "unknown", name: "game", version: "1.0")
expect { described_class.new.update(input) }.to raise_error(ArgumentError, /Unsupported platform/)
end
it "routes to correct platform service" do
input = WarpEngine::UpdateInputDto.new(platform: "tic80", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::SoftwareUpdater::Tic80Service)
allow(WarpEngine::SoftwareUpdater::Tic80Service).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.update(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes godot platform to GodotService" do
input = WarpEngine::UpdateInputDto.new(platform: "godot", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::SoftwareUpdater::GodotService)
allow(WarpEngine::SoftwareUpdater::GodotService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.update(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes bevy platform to BevyService" do
input = WarpEngine::UpdateInputDto.new(platform: "bevy", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::SoftwareUpdater::BevyService)
allow(WarpEngine::SoftwareUpdater::BevyService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.update(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
it "routes phaser platform to PhaserService" do
input = WarpEngine::UpdateInputDto.new(platform: "phaser", name: "game", version: "1.0")
mock_service = instance_double(WarpEngine::SoftwareUpdater::PhaserService)
allow(WarpEngine::SoftwareUpdater::PhaserService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:update)
described_class.new.update(input)
expect(mock_service).to have_received(:update).with("game", "1.0")
end
end
end
@@ -0,0 +1,127 @@
require "rails_helper"
require "webmock/rspec"
RSpec.describe WarpEngine::WoodpeckerClient do
let(:base_url) { "https://ci.example.test" }
let(:token) { "wp-test-token" }
let(:client) { described_class.new(base_url: base_url, token: token) }
def stub_wp(method, path, status: 200, body: nil, request_body: nil)
stub = stub_request(method, "#{base_url}#{path}")
.with(headers: { "Authorization" => "Bearer #{token}", "Accept" => "application/json" })
stub = stub.with(body: request_body) if request_body
stub.to_return(status: status, body: body&.to_json, headers: { "Content-Type" => "application/json" })
end
describe "repos" do
it "lists repos" do
repos = [{ "id" => 1, "name" => "game1" }]
stub_wp(:get, "/api/repos", body: repos)
expect(client.list_repos).to eq(repos)
end
it "gets a repo" do
repo = { "id" => 42, "name" => "mygame" }
stub_wp(:get, "/api/repos/42", body: repo)
expect(client.get_repo(42)).to eq(repo)
end
it "deactivates a repo" do
stub_wp(:delete, "/api/repos/42", status: 204)
expect(client.deactivate_repo(42)).to be_nil
end
end
describe "secrets" do
it "lists secrets" do
secrets = [{ "name" => "application_token" }]
stub_wp(:get, "/api/repos/1/secrets", body: secrets)
expect(client.list_secrets(1)).to eq(secrets)
end
it "creates a secret" do
stub_wp(:post, "/api/repos/1/secrets", status: 200, body: { "name" => "application_token" })
result = client.create_secret(1, name: "application_token", value: "secret123")
expect(result["name"]).to eq("application_token")
end
it "updates a secret" do
stub_wp(:patch, "/api/repos/1/secrets/application_token", status: 200, body: { "name" => "application_token" })
result = client.update_secret(1, "application_token", value: "newsecret")
expect(result["name"]).to eq("application_token")
end
it "deletes a secret" do
stub_wp(:delete, "/api/repos/1/secrets/application_token", status: 204)
expect(client.delete_secret(1, "application_token")).to be_nil
end
end
describe "pipelines" do
it "lists pipelines" do
pipelines = [{ "number" => 1, "status" => "success" }]
stub_wp(:get, "/api/repos/42/pipelines?page=1&perPage=25", body: pipelines)
expect(client.list_pipelines(42)).to eq(pipelines)
end
it "gets latest pipeline" do
pipeline = { "number" => 5, "status" => "running" }
stub_wp(:get, "/api/repos/42/pipelines/latest", body: pipeline)
expect(client.latest_pipeline(42)).to eq(pipeline)
end
it "triggers a pipeline" do
pipeline = { "number" => 6, "status" => "pending" }
stub_wp(:post, "/api/repos/42/pipelines", body: pipeline)
expect(client.trigger_pipeline(42, branch: "main")).to eq(pipeline)
end
end
describe "error handling" do
it "raises ApiError on 404" do
stub_wp(:get, "/api/repos/999", status: 404, body: { "error" => "not found" })
expect { client.get_repo(999) }.to raise_error(WarpEngine::WoodpeckerClient::ApiError) { |e|
expect(e.status).to eq(404)
}
end
it "raises ApiError on 500" do
stub_wp(:get, "/api/repos", status: 500, body: { "error" => "internal" })
expect { client.list_repos }.to raise_error(WarpEngine::WoodpeckerClient::ApiError) { |e|
expect(e.status).to eq(500)
}
end
it "raises ConnectionError on connection refused" do
stub_request(:get, "#{base_url}/api/repos").to_raise(Errno::ECONNREFUSED)
expect { client.list_repos }.to raise_error(WarpEngine::WoodpeckerClient::ConnectionError)
end
it "raises ConnectionError on timeout" do
stub_request(:get, "#{base_url}/api/repos").to_timeout
expect { client.list_repos }.to raise_error(WarpEngine::WoodpeckerClient::ConnectionError)
end
it "raises ApiError when a 200 response is not JSON" do
stub_request(:get, "#{base_url}/api/repos")
.to_return(status: 200, body: "<!doctype html><html></html>",
headers: { "Content-Type" => "text/html" })
expect { client.list_repos }.to raise_error(WarpEngine::WoodpeckerClient::ApiError, /Expected JSON/)
end
end
end