Merge branch 'cursor/control-pm2-split-3038'

This commit is contained in:
2026-08-20 22:35:09 +07:00
65 changed files with 5390 additions and 1496 deletions
+43
View File
@@ -0,0 +1,43 @@
const fs = require("fs");
const path = require("path");
function loadEnv(file) {
const out = {};
if (!fs.existsSync(file)) return out;
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
const t = line.trim();
if (!t || t.startsWith("#")) continue;
const i = t.indexOf("=");
if (i === -1) continue;
const key = t.slice(0, i).trim();
let val = t.slice(i + 1).trim();
if (
(val.startsWith('"') && val.endsWith('"')) ||
(val.startsWith("'") && val.endsWith("'"))
) {
val = val.slice(1, -1);
}
out[key] = val;
}
return out;
}
const root = __dirname;
module.exports = {
apps: [
{
name: "jerapah-flow",
cwd: root,
script: "packages/server/runner.js",
interpreter: "node",
instances: 1,
autorestart: true,
max_restarts: 20,
env: {
NODE_ENV: "production",
...loadEnv(path.join(root, ".env")),
},
},
],
};
+1
View File
@@ -0,0 +1 @@
dump.rdb
+70 -2
View File
@@ -4,7 +4,7 @@ import cors from "@fastify/cors";
import jwt from "@fastify/jwt";
import { migrate, db } from "./db.js";
import { log, enableLogPersistence, flushLogs } from "./logger.js";
import { COOKIE } from "./src/api/auth.js";
import authPlugin, { addApiAuthGuard, COOKIE } from "./src/api/auth.js";
import {
clearRestartNeeded,
bumpGeneration,
@@ -35,6 +35,7 @@ import {
PM2_HTTP_NAME,
PM2_WORKER_NAME,
recreateChildren,
restartPm2Process,
stopPm2App,
} from "./pm2-bridge.js";
@@ -124,6 +125,14 @@ server.decorate("requireAdmin", async function requireAdmin(req, reply) {
}
});
await server.register(
async (api) => {
addApiAuthGuard(api, server);
await api.register(authPlugin);
},
{ prefix: "/api" },
);
/**
* @param {number} timeoutMs
* @param {string} lockToken
@@ -141,6 +150,43 @@ async function waitUntilIdle(timeoutMs, lockToken) {
return { ok: active === 0, active };
}
/** @param {unknown} raw */
function parsePmId(raw) {
if (raw == null || raw === "") return null;
const id = Math.floor(Number(raw));
if (!Number.isFinite(id) || id < 0) return Number.NaN;
return id;
}
async function handleProcessRestart(pmId, reply) {
const lock = tryAcquireOpsLock(`process-restart:${process.pid}`);
if (!lock.ok) {
return reply.code(409).send({ error: lock.error, holder: lock.holder });
}
try {
const restarted = await restartPm2Process(pmId);
return reply.send({ ok: true, ...restarted, status: await buildStatus() });
} catch (err) {
const code = err && typeof err === "object" ? err.code : undefined;
if (code === "BAD_REQUEST") {
return reply.code(400).send({ error: "pmId is required" });
}
if (code === "NOT_FOUND") {
return reply.code(404).send({ error: "process not found" });
}
if (code === "FORBIDDEN") {
return reply.code(403).send({ error: "process is not a JerapahFlow child" });
}
log.error({ err, pmId }, "process restart failed");
return reply.code(500).send({
error: err instanceof Error ? err.message : String(err),
});
} finally {
releaseOpsLock(lock.token);
}
}
async function buildStatus() {
const state = readControlState();
const children = await describeChildren();
@@ -250,9 +296,18 @@ server.post(
"/ops/restart",
{ onRequest: [server.authenticate, server.requireAdmin] },
async (req, reply) => {
const body = /** @type {{ force?: boolean, timeoutMs?: number }} */ (
const body = /** @type {{ force?: boolean, timeoutMs?: number, pmId?: number }} */ (
req.body ?? {}
);
const pmId = parsePmId(body.pmId);
if (pmId != null) {
if (Number.isNaN(pmId)) {
return reply.code(400).send({ error: "pmId is required" });
}
return handleProcessRestart(pmId, reply);
}
const force = Boolean(body.force);
const timeoutMs = Math.min(
Math.max(Number(body.timeoutMs) || DRAIN_DEFAULT_MS, 1_000),
@@ -334,6 +389,19 @@ server.post(
},
);
server.post(
"/ops/process/restart",
{ onRequest: [server.authenticate, server.requireAdmin] },
async (req, reply) => {
const body = /** @type {{ pmId?: number }} */ (req.body ?? {});
const pmId = parsePmId(body.pmId);
if (pmId == null || Number.isNaN(pmId)) {
return reply.code(400).send({ error: "pmId is required" });
}
return handleProcessRestart(pmId, reply);
},
);
server.post(
"/ops/scale",
{ onRequest: [server.authenticate, server.requireAdmin] },
+1 -1
View File
@@ -108,7 +108,7 @@ run(
["--filter", "@jerapah-flow/web", "dev"],
{
env: {
// vite.config reads nothing; port is set in vite.config.js
JFLOW_AUTH_PROXY: "http://127.0.0.1:8600",
},
},
);
+65 -23
View File
@@ -4,12 +4,27 @@ import { assertHttpStatus } from "./http-pages-store.js";
const MAX_NAME_LENGTH = 128;
const NAME_RE = /^[A-Za-z0-9._-]+$/;
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const ALLOWED_TYPES = new Set(["bearer", "basic", "header"]);
function nowIso() {
return new Date().toISOString();
}
/**
* @param {unknown} id
* @returns {string}
*/
export function assertAuthId(id) {
if (typeof id !== "string" || !UUID_RE.test(id)) {
const err = new Error("invalid auth id");
err.statusCode = 400;
throw err;
}
return id.toLowerCase();
}
/**
* @param {unknown} name
* @returns {string}
@@ -218,10 +233,11 @@ function publicAuth(row, { includeConfig = true } = {}) {
/**
* Internal: full config including literals (for runtime auth checks).
* @param {string} name
* @param {string} id
*/
export async function getHttpAuthInternal(name) {
const row = await db("http_auths").where({ name: assertAuthName(name) }).first();
export async function getHttpAuthInternal(id) {
const authId = assertAuthId(id);
const row = await db("http_auths").where({ id: authId }).first();
if (!row) return null;
return {
id: row.id,
@@ -235,11 +251,11 @@ export async function getHttpAuthInternal(name) {
/**
* Return only plaintext literal credential fields (not KV refs or encrypted secrets).
* @param {string} name
* @returns {Promise<{ name: string, type: string, literals: Record<string, string> } | null>}
* @param {string} id
* @returns {Promise<{ id: string, name: string, type: string, literals: Record<string, string> } | null>}
*/
export async function revealHttpAuthLiterals(name) {
const internal = await getHttpAuthInternal(name);
export async function revealHttpAuthLiterals(id) {
const internal = await getHttpAuthInternal(id);
if (!internal) return null;
/** @type {Record<string, string>} */
const literals = {};
@@ -248,7 +264,12 @@ export async function revealHttpAuthLiterals(name) {
const v = cfg[key];
if (typeof v === "string") literals[key] = v;
}
return { name: internal.name, type: internal.type, literals };
return {
id: internal.id,
name: internal.name,
type: internal.type,
literals,
};
}
export async function listHttpAuths() {
@@ -256,24 +277,23 @@ export async function listHttpAuths() {
return rows.map((r) => publicAuth(r));
}
/**
* @param {string} name
*/
export async function getHttpAuthByName(name) {
const row = await db("http_auths").where({ name: assertAuthName(name) }).first();
return row ? publicAuth(row) : null;
}
/**
* @param {string} id
*/
export async function getHttpAuthById(id) {
const row = await db("http_auths").where({ id }).first();
let authId;
try {
authId = assertAuthId(id);
} catch {
return null;
}
const row = await db("http_auths").where({ id: authId }).first();
return row ? publicAuth(row) : null;
}
/**
* @param {{
* id?: string | null,
* name: string,
* type: string,
* config?: unknown,
@@ -282,6 +302,7 @@ export async function getHttpAuthById(id) {
* }} opts
*/
export async function upsertHttpAuth({
id,
name,
type,
config,
@@ -290,7 +311,26 @@ export async function upsertHttpAuth({
}) {
const authName = assertAuthName(name);
const authType = assertAuthType(type);
const existing = await db("http_auths").where({ name: authName }).first();
/** @type {Record<string, unknown> | null} */
let existing = null;
if (id != null && String(id).length > 0) {
const authId = assertAuthId(id);
existing = await db("http_auths").where({ id: authId }).first();
if (!existing) {
const err = new Error("auth not found");
err.statusCode = 404;
throw err;
}
}
const nameClash = await db("http_auths").where({ name: authName }).first();
if (nameClash && (!existing || nameClash.id !== existing.id)) {
const err = new Error(`auth name "${authName}" already exists`);
err.statusCode = 409;
throw err;
}
const prevConfig = existing ? parseConfig(existing.config) : {};
const normalized = normalizeAuthConfig(authType, config, {
keepLiteralsFrom: prevConfig,
@@ -315,18 +355,19 @@ export async function upsertHttpAuth({
await db("http_auths")
.where({ id: existing.id })
.update({
name: authName,
type: authType,
config: configJson,
unauthorized_status: unauthStatus,
unauthorized_response: unauthResponse,
updated_at: now,
});
return getHttpAuthById(existing.id);
return getHttpAuthById(/** @type {string} */ (existing.id));
}
const id = randomUUID();
const newId = randomUUID();
await db("http_auths").insert({
id,
id: newId,
name: authName,
type: authType,
config: configJson,
@@ -335,7 +376,7 @@ export async function upsertHttpAuth({
created_at: now,
updated_at: now,
});
return getHttpAuthById(id);
return getHttpAuthById(newId);
}
/**
@@ -343,6 +384,7 @@ export async function upsertHttpAuth({
* @returns {Promise<boolean>}
*/
export async function deleteHttpAuth(id) {
const n = await db("http_auths").where({ id }).del();
const authId = assertAuthId(id);
const n = await db("http_auths").where({ id: authId }).del();
return n > 0;
}
+86 -30
View File
@@ -77,38 +77,47 @@ export async function resolveCredentialValue(field, ctx) {
}
/**
* Normalize trigger.auth into an inline auth mechanism object.
* @param {unknown} authField
* @returns {Promise<{
* @typedef {{
* type: string,
* config: Record<string, unknown>,
* unauthorized_status?: number | null,
* unauthorized_response?: string | null,
* label: string,
* } | null>}
* }} AuthMechanism
*/
export async function resolveAuthMechanism(authField) {
if (authField == null || authField === false) return null;
if (typeof authField === "string") {
const named = await getHttpAuthInternal(authField);
if (!named) {
log.warn({ name: authField }, "http auth: named profile not found");
/**
* Resolve one auth entry (auth profile id UUID, or inline object).
* @param {unknown} entry
* @returns {Promise<AuthMechanism | null>}
*/
export async function resolveAuthMechanism(entry) {
if (entry == null || entry === false) return null;
if (typeof entry === "string") {
try {
const named = await getHttpAuthInternal(entry);
if (!named) {
log.warn({ id: entry }, "http auth: profile id not found");
return null;
}
return {
type: named.type,
config: named.config,
unauthorized_status: named.unauthorized_status,
unauthorized_response: named.unauthorized_response,
label: named.name,
};
} catch (err) {
log.warn({ err, id: entry }, "http auth: invalid profile id");
return null;
}
return {
type: named.type,
config: named.config,
unauthorized_status: named.unauthorized_status,
unauthorized_response: named.unauthorized_response,
label: authField,
};
}
if (typeof authField === "object" && !Array.isArray(authField)) {
const obj = /** @type {Record<string, unknown>} */ (authField);
if (typeof obj.name === "string" && obj.name.length > 0 && !obj.type) {
return resolveAuthMechanism(obj.name);
if (typeof entry === "object" && !Array.isArray(entry)) {
const obj = /** @type {Record<string, unknown>} */ (entry);
if (typeof obj.id === "string" && obj.id.length > 0 && !obj.type) {
return resolveAuthMechanism(obj.id);
}
try {
const type = assertAuthType(obj.type);
@@ -116,6 +125,7 @@ export async function resolveAuthMechanism(authField) {
const config = { ...obj };
delete config.type;
delete config.name;
delete config.id;
return {
type,
config,
@@ -133,18 +143,64 @@ export async function resolveAuthMechanism(authField) {
}
/**
* Label for mermaid / summary (sync, no DB).
* Normalize trigger.auth (array of auth ids / inline objects) into mechanisms.
* Empty / null / false → no auth. Any entry that fails to resolve is skipped;
* if the field was non-empty but nothing resolves, returns [] (caller treats as unauthorized).
* @param {unknown} authField
* @returns {Promise<AuthMechanism[]>}
*/
export function authLabel(authField) {
if (authField == null) return null;
if (typeof authField === "string") return authField;
if (typeof authField === "object" && !Array.isArray(authField)) {
const o = /** @type {Record<string, unknown>} */ (authField);
if (typeof o.name === "string" && o.name) return o.name;
if (typeof o.type === "string" && o.type) return o.type;
export async function resolveAuthMechanisms(authField) {
if (authField == null || authField === false) return [];
if (!Array.isArray(authField) || authField.length === 0) return [];
/** @type {AuthMechanism[]} */
const out = [];
for (const entry of authField) {
const mech = await resolveAuthMechanism(entry);
if (mech) out.push(mech);
}
return "auth";
return out;
}
/**
* True if any mechanism accepts the request (OR).
* @param {import("fastify").FastifyRequest} req
* @param {AuthMechanism[]} mechanisms
* @param {{ owner: string, workflowKey: string }} ctx
*/
export async function checkAnyHttpAuth(req, mechanisms, ctx) {
for (const mechanism of mechanisms) {
if (await checkHttpAuth(req, mechanism, ctx)) return true;
}
return false;
}
/**
* Label for mermaid / summary (sync). Prefer resolved display names when provided.
* @param {unknown} authField
* @param {Map<string, string> | Record<string, string>} [nameById]
*/
export function authLabel(authField, nameById) {
if (authField == null || authField === false) return null;
if (!Array.isArray(authField) || authField.length === 0) return null;
const lookup =
nameById instanceof Map
? (id) => nameById.get(id)
: nameById
? (id) => nameById[id]
: () => undefined;
const parts = authField.map((entry) => {
if (typeof entry === "string") return lookup(entry) ?? entry;
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
const o = /** @type {Record<string, unknown>} */ (entry);
if (typeof o.id === "string" && o.id && !o.type) {
return lookup(o.id) ?? o.id;
}
if (typeof o.type === "string" && o.type) return o.type;
}
return "auth";
});
return parts.join("|");
}
/**
@@ -0,0 +1,49 @@
/**
* @param {import("knex").Knex} knex
*/
export async function up(knex) {
await knex.schema.createTable("workflow_revisions", (t) => {
t.text("id").primary();
t.text("workflow_id").notNullable();
t.text("owner").notNullable();
t.text("file").notNullable();
t.integer("revision").notNullable();
t.text("content_sha").notNullable();
t.text("content").notNullable();
t.text("reason");
t.text("meta");
t.text("created_at").notNullable();
});
await knex.schema.raw(
"CREATE UNIQUE INDEX workflow_revisions_workflow_id_revision_idx ON workflow_revisions (workflow_id, revision)",
);
await knex.schema.raw(
"CREATE INDEX workflow_revisions_workflow_id_created_at_idx ON workflow_revisions (workflow_id, created_at DESC)",
);
await knex.schema.createTable("workflow_trash", (t) => {
t.text("id").primary();
t.text("workflow_id").notNullable();
t.text("owner").notNullable();
t.text("file").notNullable();
t.text("name");
t.text("deleted_at").notNullable();
t.text("trash_path").notNullable();
});
await knex.schema.raw(
"CREATE INDEX workflow_trash_deleted_at_idx ON workflow_trash (deleted_at ASC)",
);
await knex.schema.raw(
"CREATE UNIQUE INDEX workflow_trash_owner_file_idx ON workflow_trash (owner, file)",
);
}
/**
* @param {import("knex").Knex} knex
*/
export async function down(knex) {
await knex.schema.dropTableIfExists("workflow_trash");
await knex.schema.dropTableIfExists("workflow_revisions");
}
@@ -0,0 +1,21 @@
/**
* @param {import("knex").Knex} knex
*/
export async function up(knex) {
await knex.schema.alterTable("workflow_runs", (t) => {
t.integer("workflow_revision");
});
await knex.schema.raw(
"CREATE INDEX workflow_runs_workflow_revision_idx ON workflow_runs (workflow, workflow_revision)",
);
}
/**
* @param {import("knex").Knex} knex
*/
export async function down(knex) {
await knex.schema.raw("DROP INDEX IF EXISTS workflow_runs_workflow_revision_idx");
await knex.schema.alterTable("workflow_runs", (t) => {
t.dropColumn("workflow_revision");
});
}
+2 -1
View File
@@ -12,7 +12,8 @@
"start:worker": "node worker.js",
"start:control": "node control.js",
"migrate": "node -e \"import('./db.js').then((m) => m.migrate().then(() => process.exit(0)))\"",
"test:plugins": "JFLOW_PLUGINS_DIR=./data/plugins-smoke-test JFLOW_DB_PATH=./data/plugins-smoke.db node test/plugins-smoke.js"
"test:plugins": "JFLOW_PLUGINS_DIR=./data/plugins-smoke-test JFLOW_DB_PATH=./data/plugins-smoke.db node test/plugins-smoke.js",
"test:workflow-history": "node test/workflow-history-smoke.js"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1111.0",
+47 -3
View File
@@ -130,6 +130,40 @@ export function restartPm2App(name) {
});
}
/**
* Restart a single PM2 process by id. Only jflow-http / jflow-worker.
* @param {number} pmId
* @returns {Promise<{ name: string, pmId: number }>}
*/
export async function restartPm2Process(pmId) {
const id = Math.floor(Number(pmId));
if (!Number.isFinite(id) || id < 0) {
const err = new Error("invalid pmId");
err.code = "BAD_REQUEST";
throw err;
}
const list = await listPm2();
const proc = list.find((p) => Number(p.pm_id) === id);
if (!proc) {
const err = new Error("process not found");
err.code = "NOT_FOUND";
throw err;
}
if (proc.name !== PM2_HTTP_NAME && proc.name !== PM2_WORKER_NAME) {
const err = new Error("process is not a JerapahFlow child");
err.code = "FORBIDDEN";
throw err;
}
await new Promise((resolve, reject) => {
pm2.restart(id, (err) => {
if (err) reject(err);
else resolve();
});
});
return { name: proc.name, pmId: id };
}
/**
* Shared env for child processes.
* @param {{ generation: number }} opts
@@ -251,19 +285,29 @@ export async function describeChildren() {
const mapOne = (p) => ({
name: p.name,
pmId: p.pm_id,
pmId: Number(p.pm_id),
status: p.pm2_env?.status ?? "unknown",
pid: p.pid ?? null,
restarts: p.pm2_env?.restart_time ?? 0,
uptime: p.pm2_env?.pm_uptime ?? null,
generation: Number(p.pm2_env?.JFLOW_CONFIG_GENERATION ?? 0) || null,
memory: Number(p.monit?.memory) || 0,
cpu: Number(p.monit?.cpu) || 0,
});
const httpMapped = http.map(mapOne);
const workersMapped = workers.map(mapOne);
const all = [...httpMapped, ...workersMapped];
return {
http: http.map(mapOne),
workers: workers.map(mapOne),
http: httpMapped,
workers: workersMapped,
httpOnline: http.some((p) => p.pm2_env?.status === "online"),
workerOnlineCount: workers.filter((p) => p.pm2_env?.status === "online").length,
totals: {
memory: all.reduce((sum, p) => sum + p.memory, 0),
cpu: all.reduce((sum, p) => sum + p.cpu, 0),
},
};
}
+35 -10
View File
@@ -24,8 +24,8 @@ import {
} from "./step-result.js";
import * as fsStore from "./fs-store.js";
import {
checkHttpAuth,
resolveAuthMechanism,
checkAnyHttpAuth,
resolveAuthMechanisms,
resolveUnauthorizedSpec,
sendHttpPageOrJson,
sendSuccessPage,
@@ -36,6 +36,7 @@ import {
resolveFailureTriggerConfig,
} from "./trigger-failure.js";
import { enqueueWorkflowJob } from "./workflow-queue.js";
import { ensureInitialRevision } from "./workflow-history.js";
/**
* @typedef {{ owner: string, file: string, workflow: any }} WorkflowEntry
@@ -57,10 +58,16 @@ function hasWorkflowTrigger(workflow) {
/**
* @param {import("fastify").FastifyInstance} server
* @param {{ queue?: import("bullmq").Queue | null }} [opts]
* @param {{
* queue?: import("bullmq").Queue | null,
* enableTriggers?: boolean,
* }} [opts]
* `enableTriggers` must be true only on the API (or all-in-one) process.
* Workers reload workflow defs but must not own cron/HTTP trigger registration.
*/
export function createRegistry(server, opts = {}) {
const queue = opts.queue ?? null;
const enableTriggers = opts.enableTriggers ?? true;
/** @type {Map<string, WorkflowEntry>} */
const workflows = new Map();
/** @type {Map<string, string>} */
@@ -241,22 +248,26 @@ export function createRegistry(server, opts = {}) {
return m === method && p === url;
}) ?? mapped.trigger;
if (liveTrigger.auth != null && liveTrigger.auth !== false) {
const mechanism = await resolveAuthMechanism(liveTrigger.auth);
if (!mechanism) {
if (
liveTrigger.auth != null &&
liveTrigger.auth !== false &&
!(Array.isArray(liveTrigger.auth) && liveTrigger.auth.length === 0)
) {
const mechanisms = await resolveAuthMechanisms(liveTrigger.auth);
if (mechanisms.length === 0) {
const { status, pageName } = resolveUnauthorizedSpec(liveTrigger, null);
return sendHttpPageOrJson(reply, status, pageName, {
error: "unauthorized",
});
}
const ok = await checkHttpAuth(req, mechanism, {
const ok = await checkAnyHttpAuth(req, mechanisms, {
owner: entry.owner,
workflowKey: mapped.key,
});
if (!ok) {
const { status, pageName } = resolveUnauthorizedSpec(
liveTrigger,
mechanism,
mechanisms[0],
);
return sendHttpPageOrJson(reply, status, pageName, {
error: "unauthorized",
@@ -736,13 +747,14 @@ export function createRegistry(server, opts = {}) {
return { runId: null, status: "failed", error: "workflow not found" };
}
const { owner, workflow } = entry;
const { owner, file, workflow } = entry;
if (workflow?.enabled === false && trigger.type !== "manual") {
log.debug({ workflow: key, trigger }, "skipping disabled workflow");
return { runId: null, status: "failed", error: "workflow disabled" };
}
const input = context.data ?? workflow.data ?? null;
const ensured = await ensureInitialRevision({ owner, file });
const run = await store.startRun({
owner,
workflow: key,
@@ -751,6 +763,7 @@ export function createRegistry(server, opts = {}) {
input,
parentRunId,
status: "queued",
workflowRevision: ensured?.revision ?? null,
});
const runLog = log.child({ runId: run.id, owner, workflow: key });
@@ -808,9 +821,17 @@ export function createRegistry(server, opts = {}) {
type: existing.trigger_type,
detail: existing.trigger_detail,
};
// jobId is BullMQ's id; enqueue uses runId as jobId, so they match today.
const jobId =
existing.job_id != null && String(existing.job_id).length > 0
? String(existing.job_id)
: runId;
const initialCtx = {
data: existing.input ?? workflow.data ?? null,
context: normalizeContext(null),
context: {
runId,
jobId,
},
};
try {
@@ -869,6 +890,10 @@ export function createRegistry(server, opts = {}) {
function reregister() {
registerWorkflows();
// Cron/HTTP triggers are API-owned. Workers also subscribe to reload and
// must only refresh the in-memory workflow map — otherwise N workers each
// schedule the same cron and enqueue N duplicate jobs.
if (!enableTriggers) return;
registerHttpTriggers();
registerCronTriggers();
}
+18
View File
@@ -18,6 +18,24 @@ export function cookieOpts() {
};
}
/**
* Require JWT for /api routes except bootstrap, login, and register.
* @param {import("fastify").FastifyInstance} api
* @param {import("fastify").FastifyInstance} root
*/
export function addApiAuthGuard(api, root) {
api.addHook("onRequest", async (req, reply) => {
const raw = (req.url || "").split("?")[0];
const stripped = raw.replace(/^\/api/, "") || "/";
const routeUrl = req.routeOptions?.url || stripped;
const open =
OPEN_API_ROUTES.has(`${req.method} ${routeUrl}`) ||
OPEN_API_ROUTES.has(`${req.method} ${stripped}`);
if (open) return;
await root.authenticate(req, reply);
});
}
export function validateCredentials(username, password) {
if (!/^[A-Za-z0-9_]{3,32}$/.test(username)) {
return "username must be 3-32 letters, numbers, or underscore";
+19 -9
View File
@@ -1,9 +1,9 @@
import {
assertAuthId,
assertAuthName,
assertAuthType,
listHttpAuths,
getHttpAuthById,
getHttpAuthByName,
upsertHttpAuth,
deleteHttpAuth,
revealHttpAuthLiterals,
@@ -18,28 +18,28 @@ export default async function httpAuthsPlugin(fastify) {
return { auths: await listHttpAuths() };
});
fastify.get("/http-auths/:name/reveal", async (req, reply) => {
const { name } = /** @type {{ name: string }} */ (req.params);
fastify.get("/http-auths/:id/reveal", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
try {
assertAuthName(name);
assertAuthId(id);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const revealed = await revealHttpAuthLiterals(name);
const revealed = await revealHttpAuthLiterals(id);
if (!revealed) {
return reply.code(404).send({ error: "auth not found" });
}
return revealed;
});
fastify.get("/http-auths/:name", async (req, reply) => {
const { name } = /** @type {{ name: string }} */ (req.params);
fastify.get("/http-auths/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
try {
assertAuthName(name);
assertAuthId(id);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const auth = await getHttpAuthByName(name);
const auth = await getHttpAuthById(id);
if (!auth) {
return reply.code(404).send({ error: "auth not found" });
}
@@ -48,6 +48,7 @@ export default async function httpAuthsPlugin(fastify) {
fastify.put("/http-auths", async (req, reply) => {
const body = /** @type {{
id?: string | null,
name?: string,
type?: string,
config?: unknown,
@@ -57,6 +58,9 @@ export default async function httpAuthsPlugin(fastify) {
try {
assertAuthName(String(body.name ?? ""));
assertAuthType(body.type);
if (body.id != null && String(body.id).length > 0) {
assertAuthId(String(body.id));
}
if (
body.unauthorized_response != null &&
String(body.unauthorized_response).length > 0
@@ -69,6 +73,7 @@ export default async function httpAuthsPlugin(fastify) {
);
}
const auth = await upsertHttpAuth({
id: body.id != null && String(body.id).length > 0 ? String(body.id) : null,
name: String(body.name),
type: String(body.type),
config: body.config,
@@ -83,6 +88,11 @@ export default async function httpAuthsPlugin(fastify) {
fastify.delete("/http-auths/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
try {
assertAuthId(id);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const existing = await getHttpAuthById(id);
if (!existing) {
return reply.code(404).send({ error: "auth not found" });
+1 -1
View File
@@ -14,10 +14,10 @@ import {
resolveScriptRef,
uninstallPlugin,
createBlankPlugin,
installPluginFromDirectory,
} from "../../plugin-store.js";
import {
installExamplePlugin,
installPluginFromDirectory,
installPluginFromGit,
installPluginFromZipBuffer,
} from "../../plugin-install.js";
+439 -89
View File
@@ -10,13 +10,39 @@ import {
authLabel,
validateWorkflowHttpTriggers,
} from "../../workflow-http-validate.js";
import { listHttpAuths } from "../../http-auths-store.js";
import { validateWorkflowFailureTriggers } from "../../trigger-failure.js";
import {
duplicateWorkflowYaml,
ensureWorkflowFilename,
suggestCopyFilename,
suggestDuplicateFilename,
} from "../../workflow-duplicate.js";
import { publishReload } from "../../control-bus.js";
import {
workflowIdFromFile,
newWorkflowFilename,
} from "../../workflow-normalize.js";
import {
collectWorkflowWarnings,
parseWorkflowDocument,
} from "../../workflow-validate-warnings.js";
import {
recordRevision,
listRevisions,
getRevision,
ensureInitialRevision,
} from "../../workflow-history.js";
import {
moveWorkflowToTrash,
listTrash,
restoreFromTrash,
purgeTrashItem,
isInTrash,
} from "../../workflow-trash.js";
import {
createWorkflowBackupBuffer,
restoreWorkflowBackup,
} from "../../workflow-backup.js";
/**
* Reload this process and notify other HTTP/worker processes via Redis.
@@ -31,7 +57,7 @@ async function reregisterAll(registry) {
}
}
function triggerSummary(owner, workflow) {
function triggerSummary(owner, workflow, nameById) {
if (!workflow || typeof workflow !== "object") return [];
return (workflow.triggers ?? []).map((t) => {
const type = t?.type ?? "unknown";
@@ -43,7 +69,7 @@ function triggerSummary(owner, workflow) {
schedule: t?.schedule ?? null,
onConsecutiveFailures: t?.onConsecutiveFailures ?? null,
onFailureWorkflow: t?.onFailureWorkflow ?? null,
auth: isHttp ? authLabel(t?.auth) : null,
auth: isHttp ? authLabel(t?.auth, nameById) : null,
};
});
}
@@ -62,6 +88,92 @@ function scriptNames(workflow) {
return names;
}
/**
* @param {unknown} parsed
*/
async function validateStrictWorkflow(parsed) {
compileWorkflowScripts(parsed?.scripts);
await validateWorkflowHttpTriggers(parsed);
await validateWorkflowFailureTriggers(parsed);
}
/**
* @param {{
* owner: string,
* file: string,
* content: string,
* saveAnyway?: boolean,
* reason?: string | null,
* meta?: Record<string, unknown> | null,
* forceRevision?: boolean,
* }} opts
*/
async function saveWorkflowContent(opts) {
const { warnings, parsed, parseError } = collectWorkflowWarnings(opts.content);
const saveAnyway = Boolean(opts.saveAnyway);
if (!saveAnyway) {
if (parseError) {
const err = new Error("workflow has validation warnings");
err.statusCode = 422;
err.warnings = warnings;
throw err;
}
try {
await validateStrictWorkflow(parsed);
} catch (validationErr) {
const err = new Error("workflow has validation warnings");
err.statusCode = 422;
err.warnings = [
...warnings,
{
code: "validation_error",
message:
validationErr instanceof Error
? validationErr.message
: String(validationErr),
},
];
throw err;
}
if (warnings.length) {
const err = new Error("workflow has validation warnings");
err.statusCode = 422;
err.warnings = warnings;
throw err;
}
}
const workflowId = workflowIdFromFile(opts.file);
const existed = fsStore.readWorkflowYaml(opts.owner, opts.file) != null;
fsStore.writeWorkflowYaml(opts.owner, opts.file, opts.content);
const registered = fsStore.readRegisters(opts.owner);
if (!registered.includes(opts.file)) {
registered.push(opts.file);
fsStore.writeRegisters(opts.owner, registered);
}
const revision = await recordRevision({
workflowId,
owner: opts.owner,
file: opts.file,
content: opts.content,
reason: opts.reason ?? "save",
meta: opts.meta ?? null,
force: opts.forceRevision,
});
return {
owner: opts.owner,
file: opts.file,
workflow_id: workflowId,
existed,
warnings,
revision,
};
}
/**
* @param {{ workflows: Map<string, any>, loadErrors: Map<string, string>, reregister: () => void }} registry
*/
@@ -74,12 +186,83 @@ export default function workflowsPluginFactory(registry) {
return { owners: fsStore.listOwners() };
});
fastify.get("/workflows/trash", async () => {
return { items: await listTrash() };
});
fastify.post("/workflows/trash/:id/restore", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
try {
const restored = await restoreFromTrash(id);
await recordRevision({
workflowId: restored.workflow_id,
owner: restored.owner,
file: restored.file,
content: restored.content,
reason: "restored-from-trash",
force: true,
});
await reregisterAll(registry);
return { owner: restored.owner, file: restored.file };
} catch (err) {
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.delete("/workflows/trash/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
try {
return await purgeTrashItem(id);
} catch (err) {
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.get("/workflows/backup", async (_req, reply) => {
const buffer = await createWorkflowBackupBuffer();
const stamp = new Date().toISOString().slice(0, 10);
return reply
.header("Content-Type", "application/zip")
.header(
"Content-Disposition",
`attachment; filename="jerapah-flow-backup-${stamp}.zip"`,
)
.send(buffer);
});
fastify.post("/workflows/backup/restore", async (req, reply) => {
const body = /** @type {{ zipBase64?: string, mode?: string }} */ (
req.body ?? {}
);
if (typeof body.zipBase64 !== "string" || !body.zipBase64.trim()) {
return reply.code(400).send({ error: "zipBase64 is required" });
}
const mode = body.mode === "replace" ? "replace" : "merge";
try {
const buffer = Buffer.from(body.zipBase64, "base64");
const result = await restoreWorkflowBackup(buffer, { mode });
await reregisterAll(registry);
return result;
} catch (err) {
return reply.code(400).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.get("/workflows", async (req) => {
const q = /** @type {{ owner?: string }} */ (req.query ?? {});
const stats = await store.workflowStats();
const owners = q.owner
? [fsStore.assertOwner(q.owner)]
: fsStore.listOwners();
const authNameById = Object.fromEntries(
(await listHttpAuths()).map((a) => [a.id, a.name]),
);
const items = [];
for (const owner of owners) {
@@ -93,6 +276,7 @@ export default function workflowsPluginFactory(registry) {
const files = [...new Set([...registered, ...onDisk])];
for (const file of files) {
if (await isInTrash(owner, file)) continue;
const key = `${owner}/${file}`;
const loaded = registry.workflows.get(key);
const loadError = registry.loadErrors.get(key) ?? null;
@@ -102,11 +286,8 @@ export default function workflowsPluginFactory(registry) {
if (raw != null) {
try {
parsed = yaml.parse(raw);
} catch (err) {
} catch {
// keep loadError
if (!loadError) {
// file on disk but unparseable and not in registers
}
}
}
}
@@ -118,18 +299,17 @@ export default function workflowsPluginFactory(registry) {
items.push({
owner,
file,
workflow_id: workflowIdFromFile(file),
key,
name: parsed?.name ?? file,
description: parsed?.description ?? null,
enabled: parsed ? parsed.enabled !== false : false,
registered: registered.includes(file),
loadError:
loadError ??
(parsed ? null : "unreadable"),
loadError: loadError ?? (parsed ? null : "unreadable"),
lastInvokedAt: st.lastInvokedAt,
lastStatus: st.lastStatus ?? null,
invocationCount: st.invocationCount,
triggers: triggerSummary(owner, parsed),
triggers: triggerSummary(owner, parsed, authNameById),
scripts: scriptNames(parsed),
});
}
@@ -137,6 +317,98 @@ export default function workflowsPluginFactory(registry) {
return { workflows: items };
});
fastify.get("/workflows/:owner/:file/revisions", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (fsStore.readWorkflowYaml(owner, file) == null) {
return reply.code(404).send({ error: "workflow not found" });
}
await ensureInitialRevision({ owner, file });
const workflowId = workflowIdFromFile(file);
return { workflow_id: workflowId, revisions: await listRevisions(workflowId) };
});
fastify.get(
"/workflows/:owner/:file/revisions/:revision",
async (req, reply) => {
const { owner, file, revision } = /** @type {{ owner: string, file: string, revision: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const workflowId = workflowIdFromFile(file);
const rev = await getRevision(workflowId, Number(revision));
if (!rev) {
return reply.code(404).send({ error: "revision not found" });
}
return {
workflow_id: workflowId,
revision: rev.revision,
content: rev.content,
reason: rev.reason,
meta: rev.meta,
created_at: rev.created_at,
};
},
);
fastify.post(
"/workflows/:owner/:file/revisions/:revision/revert",
async (req, reply) => {
const { owner, file, revision } = /** @type {{ owner: string, file: string, revision: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (fsStore.readWorkflowYaml(owner, file) == null) {
return reply.code(404).send({ error: "workflow not found" });
}
const workflowId = workflowIdFromFile(file);
const rev = await getRevision(workflowId, Number(revision));
if (!rev) {
return reply.code(404).send({ error: "revision not found" });
}
const body = /** @type {{ saveAnyway?: boolean }} */ (req.body ?? {});
try {
const saved = await saveWorkflowContent({
owner,
file,
content: rev.content,
saveAnyway: body.saveAnyway,
reason: "revert",
meta: { fromRevision: rev.revision },
});
await reregisterAll(registry);
return saved;
} catch (err) {
if (err.statusCode === 422) {
return reply.code(422).send({
error: err.message,
warnings: err.warnings ?? [],
});
}
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
},
);
fastify.get("/workflows/:owner/:file", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
@@ -167,6 +439,7 @@ export default function workflowsPluginFactory(registry) {
return {
owner,
file,
workflow_id: workflowIdFromFile(file),
key,
content,
parsed,
@@ -188,48 +461,95 @@ export default function workflowsPluginFactory(registry) {
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const body = /** @type {{ content?: string }} */ (req.body ?? {});
const body = /** @type {{ content?: string, saveAnyway?: boolean }} */ (
req.body ?? {}
);
if (typeof body.content !== "string") {
return reply.code(400).send({ error: "content is required" });
}
let parsed;
try {
parsed = yaml.parse(body.content);
} catch (err) {
return reply.code(400).send({
error: `invalid yaml: ${err instanceof Error ? err.message : String(err)}`,
const saved = await saveWorkflowContent({
owner,
file,
content: body.content,
saveAnyway: body.saveAnyway,
reason: "save",
});
await reregisterAll(registry);
return reply.code(saved.existed ? 200 : 201).send({
owner: saved.owner,
file: saved.file,
workflow_id: saved.workflow_id,
warnings: saved.warnings,
revision: saved.revision,
});
}
try {
compileWorkflowScripts(parsed?.scripts);
} catch (err) {
return reply.code(400).send({
if (err.statusCode === 422) {
return reply.code(422).send({
error: err.message,
warnings: err.warnings ?? [],
});
}
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.post("/workflows/:owner", async (req, reply) => {
const { owner } = /** @type {{ owner: string }} */ (req.params);
try {
await validateWorkflowHttpTriggers(parsed);
fsStore.assertOwner(owner);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const body = /** @type {{ content?: string, file?: string, saveAnyway?: boolean }} */ (
req.body ?? {}
);
if (typeof body.content !== "string") {
return reply.code(400).send({ error: "content is required" });
}
let file = body.file?.trim() ? ensureWorkflowFilename(body.file) : "";
if (!file) {
const existing = fsStore.listOwnerYamlFiles(owner);
file = suggestDuplicateFilename(existing);
}
try {
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (fsStore.readWorkflowYaml(owner, file) != null) {
return reply.code(409).send({ error: "workflow already exists" });
}
try {
const saved = await saveWorkflowContent({
owner,
file,
content: body.content,
saveAnyway: body.saveAnyway,
reason: "create",
forceRevision: true,
});
await reregisterAll(registry);
return reply.code(201).send({
owner: saved.owner,
file: saved.file,
workflow_id: saved.workflow_id,
warnings: saved.warnings,
revision: saved.revision,
});
} catch (err) {
if (err.statusCode === 422) {
return reply.code(422).send({
error: err.message,
warnings: err.warnings ?? [],
});
}
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
try {
await validateWorkflowFailureTriggers(parsed);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({
error: err instanceof Error ? err.message : String(err),
});
}
const existed = fsStore.readWorkflowYaml(owner, file) != null;
fsStore.writeWorkflowYaml(owner, file, body.content);
const registered = fsStore.readRegisters(owner);
if (!registered.includes(file)) {
registered.push(file);
fsStore.writeRegisters(owner, registered);
}
await reregisterAll(registry);
return reply.code(existed ? 200 : 201).send({ owner, file });
});
fastify.patch("/workflows/:owner/:file", async (req, reply) => {
@@ -250,23 +570,39 @@ export default function workflowsPluginFactory(registry) {
if (content == null) {
return reply.code(404).send({ error: "workflow not found" });
}
const doc = yaml.parseDocument(content);
if (doc.errors?.length) {
const msg = doc.errors[0]?.message ?? "invalid yaml";
return reply.code(400).send({ error: msg });
}
const parsed = doc.toJSON();
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
return reply.code(400).send({ error: "workflow yaml must be an object" });
let doc;
try {
({ doc } = parseWorkflowDocument(content));
} catch (err) {
return reply.code(err.statusCode ?? 400).send({
error: err instanceof Error ? err.message : String(err),
});
}
if (body.enabled) {
doc.delete("enabled");
} else {
doc.set("enabled", false);
}
fsStore.writeWorkflowYaml(owner, file, String(doc));
await reregisterAll(registry);
return { owner, file, enabled: body.enabled };
const nextContent = String(doc);
try {
const saved = await saveWorkflowContent({
owner,
file,
content: nextContent,
reason: body.enabled ? "enable" : "disable",
});
await reregisterAll(registry);
return {
owner,
file,
enabled: body.enabled,
revision: saved.revision,
};
} catch (err) {
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.delete("/workflows/:owner/:file", async (req, reply) => {
@@ -279,13 +615,31 @@ export default function workflowsPluginFactory(registry) {
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (!fsStore.deleteWorkflowYaml(owner, file)) {
const raw = fsStore.readWorkflowYaml(owner, file);
if (raw == null) {
return reply.code(404).send({ error: "workflow not found" });
}
const registered = fsStore.readRegisters(owner).filter((f) => f !== file);
fsStore.writeRegisters(owner, registered);
await reregisterAll(registry);
return { ok: true };
let name = null;
try {
const parsed = yaml.parse(raw);
name = parsed?.name ?? null;
} catch {
// ignore
}
try {
const item = await moveWorkflowToTrash({
workflowId: workflowIdFromFile(file),
owner,
file,
name,
});
await reregisterAll(registry);
return { ok: true, trash: item };
} catch (err) {
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
});
fastify.post("/workflows/:owner/:file/duplicate", async (req, reply) => {
@@ -303,7 +657,9 @@ export default function workflowsPluginFactory(registry) {
return reply.code(404).send({ error: "workflow not found" });
}
const body = /** @type {{ file?: unknown, owner?: unknown }} */ (req.body ?? {});
const body = /** @type {{ file?: unknown, owner?: unknown, saveAnyway?: boolean }} */ (
req.body ?? {}
);
let destOwner = owner;
if (body.owner != null && body.owner !== "") {
if (typeof body.owner !== "string") {
@@ -319,7 +675,9 @@ export default function workflowsPluginFactory(registry) {
let destFile;
try {
if (body.file == null || body.file === "") {
destFile = suggestCopyFilename(file, fsStore.listOwnerYamlFiles(destOwner));
destFile = suggestDuplicateFilename(
fsStore.listOwnerYamlFiles(destOwner),
);
} else if (typeof body.file !== "string") {
return reply.code(400).send({ error: "file must be a string" });
} else {
@@ -350,44 +708,34 @@ export default function workflowsPluginFactory(registry) {
});
}
let parsed;
try {
parsed = yaml.parse(content);
} catch (err) {
return reply.code(400).send({
error: `invalid yaml: ${err instanceof Error ? err.message : String(err)}`,
const saved = await saveWorkflowContent({
owner: destOwner,
file: destFile,
content,
saveAnyway: body.saveAnyway,
reason: "duplicated",
meta: { from: `${owner}/${file}` },
forceRevision: true,
});
await reregisterAll(registry);
return reply.code(201).send({
owner: destOwner,
file: destFile,
workflow_id: saved.workflow_id,
revision: saved.revision,
});
}
try {
compileWorkflowScripts(parsed?.scripts);
} catch (err) {
return reply.code(400).send({
if (err.statusCode === 422) {
return reply.code(422).send({
error: err.message,
warnings: err.warnings ?? [],
});
}
return reply.code(err.statusCode ?? 500).send({
error: err instanceof Error ? err.message : String(err),
});
}
try {
await validateWorkflowHttpTriggers(parsed);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({
error: err instanceof Error ? err.message : String(err),
});
}
try {
await validateWorkflowFailureTriggers(parsed);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({
error: err instanceof Error ? err.message : String(err),
});
}
fsStore.writeWorkflowYaml(destOwner, destFile, content);
const registered = fsStore.readRegisters(destOwner);
if (!registered.includes(destFile)) {
registered.push(destFile);
fsStore.writeRegisters(destOwner, registered);
}
await reregisterAll(registry);
return reply.code(201).send({ owner: destOwner, file: destFile });
});
fastify.post("/workflows/:owner/:file/run", async (req, reply) => {
@@ -443,3 +791,5 @@ export default function workflowsPluginFactory(registry) {
});
};
}
export { newWorkflowFilename };
+16 -12
View File
@@ -8,7 +8,7 @@ import { migrate, db } from "./db.js";
import { log, enableLogPersistence, flushLogs } from "./logger.js";
import * as store from "./store.js";
import { createRegistry } from "./registry.js";
import { COOKIE, OPEN_API_ROUTES } from "./src/api/auth.js";
import { addApiAuthGuard, COOKIE } from "./src/api/auth.js";
import authPlugin from "./src/api/auth.js";
import usersPlugin from "./src/api/users.js";
import scriptsPluginFactory from "./src/api/scripts.js";
@@ -28,6 +28,7 @@ import {
createWorkflowWorker,
getRedisUrlForLog,
} from "./workflow-queue.js";
import { purgeExpiredTrash } from "./workflow-trash.js";
import {
getConfigGeneration,
startHeartbeatLoop,
@@ -48,6 +49,14 @@ export async function startApp(opts = {}) {
if (shouldMigrate) {
await migrate();
try {
const purged = await purgeExpiredTrash();
if (purged > 0) {
log.info({ purged }, "purged expired workflow trash");
}
} catch (err) {
log.warn({ err }, "workflow trash purge failed");
}
}
enableLogPersistence();
@@ -117,7 +126,11 @@ export async function startApp(opts = {}) {
}
});
const registry = createRegistry(server, { queue: workflowQueue });
const registry = createRegistry(server, {
queue: workflowQueue,
// Cron + HTTP triggers enqueue jobs; only the API process may own them.
enableTriggers: runApi,
});
registry.registerWorkflows();
if (runApi) {
registry.registerHttpTriggers();
@@ -150,16 +163,7 @@ export async function startApp(opts = {}) {
if (runApi) {
await server.register(
async (api) => {
api.addHook("onRequest", async (req, reply) => {
const raw = (req.url || "").split("?")[0];
const stripped = raw.replace(/^\/api/, "") || "/";
const routeUrl = req.routeOptions?.url || stripped;
const open =
OPEN_API_ROUTES.has(`${req.method} ${routeUrl}`) ||
OPEN_API_ROUTES.has(`${req.method} ${stripped}`);
if (open) return;
await server.authenticate(req, reply);
});
addApiAuthGuard(api, server);
await api.register(authPlugin);
await api.register(usersPlugin);
await api.register(secretsPlugin);
+3
View File
@@ -65,6 +65,7 @@ function nowIso() {
* input?: unknown,
* parentRunId?: string | null,
* status?: "queued" | "running",
* workflowRevision?: number | null,
* }} opts
*/
export async function startRun({
@@ -75,6 +76,7 @@ export async function startRun({
input = null,
parentRunId = null,
status = "queued",
workflowRevision = null,
}) {
const id = randomUUID();
const now = nowIso();
@@ -91,6 +93,7 @@ export async function startRun({
queued_at: isQueued ? now : null,
input: serialize(input),
parent_run_id: parentRunId ?? null,
workflow_revision: workflowRevision ?? null,
});
return { id, started_at: now, queued_at: isQueued ? now : null };
}
@@ -12,9 +12,12 @@ import {
getHttpAuthInternal,
} from "../http-auths-store.js";
import {
authLabel,
checkAnyHttpAuth,
checkHttpAuth,
coerceCredentialString,
resolveAuthMechanism,
resolveAuthMechanisms,
resolveCredentialValue,
resolveUnauthorizedSpec,
sendHttpPageOrJson,
@@ -176,11 +179,11 @@ const secret = await upsertSecret({
config: { token: { secret: "does_not_exist_xyz" } },
},
ctx,
);
);
assert(!missingSec, "missing secret fails closed");
}
// --- named profile ---
// --- named profile (by id) ---
const profile = await upsertHttpAuth({
name: "webhook-smoke",
type: "bearer",
@@ -188,9 +191,10 @@ const profile = await upsertHttpAuth({
unauthorized_status: 403,
unauthorized_response: "deny-smoke",
});
assert(typeof profile.id === "string" && profile.id.length > 0, "profile has id");
{
const mech = await resolveAuthMechanism("webhook-smoke");
assert(mech?.label === "webhook-smoke", "named profile");
const mech = await resolveAuthMechanism(profile.id);
assert(mech?.label === "webhook-smoke", "profile by id");
const ok = await checkHttpAuth(
mockReq({ authorization: "Bearer named-token" }),
mech,
@@ -202,9 +206,68 @@ const profile = await upsertHttpAuth({
assert(pageName === "deny-smoke", "profile unauth page");
}
// --- rename keeps id ---
{
const renamed = await upsertHttpAuth({
id: profile.id,
name: "webhook-renamed",
type: "bearer",
config: { token: { keep: true } },
unauthorized_status: 403,
unauthorized_response: "deny-smoke",
});
assert(renamed.id === profile.id, "rename keeps id");
assert(renamed.name === "webhook-renamed", "rename updates name");
const mech = await resolveAuthMechanism(profile.id);
assert(mech?.label === "webhook-renamed", "resolve uses new name label");
const ok = await checkHttpAuth(
mockReq({ authorization: "Bearer named-token" }),
mech,
ctx,
);
assert(ok, "credentials survive rename");
}
// --- multi-auth OR ---
const basicProfile = await upsertHttpAuth({
name: "basic-smoke",
type: "basic",
config: { user: "bob", password: "p@ss" },
});
{
const mechs = await resolveAuthMechanisms([profile.id, basicProfile.id]);
assert(mechs.length === 2, "resolve two mechanisms");
assert(
authLabel([profile.id, basicProfile.id], {
[profile.id]: "webhook-renamed",
[basicProfile.id]: "basic-smoke",
}) === "webhook-renamed|basic-smoke",
"authLabel",
);
const viaBearer = await checkAnyHttpAuth(
mockReq({ authorization: "Bearer named-token" }),
mechs,
ctx,
);
assert(viaBearer, "OR accepts bearer");
const encoded = Buffer.from("bob:p@ss").toString("base64");
const viaBasic = await checkAnyHttpAuth(
mockReq({ authorization: `Basic ${encoded}` }),
mechs,
ctx,
);
assert(viaBasic, "OR accepts basic");
const neither = await checkAnyHttpAuth(
mockReq({ authorization: "Bearer wrong" }),
mechs,
ctx,
);
assert(!neither, "OR rejects when none match");
}
// trigger-level override
{
const mech = await getHttpAuthInternal("webhook-smoke");
const mech = await getHttpAuthInternal(profile.id);
const { status, pageName } = resolveUnauthorizedSpec(
{ unauthorized: { status: 401, response: "deny-smoke" } },
mech,
@@ -226,7 +289,7 @@ await validateWorkflowHttpTriggers({
type: "HTTP",
method: "POST",
path: "/x",
auth: "webhook-smoke",
auth: [profile.id, basicProfile.id],
response: "deny-smoke",
},
],
@@ -235,12 +298,38 @@ await validateWorkflowHttpTriggers({
let threw = false;
try {
await validateWorkflowHttpTriggers({
triggers: [{ type: "HTTP", path: "/x", auth: "no-such-profile" }],
triggers: [{ type: "HTTP", path: "/x", auth: profile.id }],
});
} catch {
threw = true;
}
assert(threw, "unknown auth fails validation");
assert(threw, "non-array auth fails validation");
threw = false;
try {
await validateWorkflowHttpTriggers({
triggers: [{ type: "HTTP", path: "/x", auth: ["webhook-renamed"] }],
});
} catch {
threw = true;
}
assert(threw, "name string fails validation");
threw = false;
try {
await validateWorkflowHttpTriggers({
triggers: [
{
type: "HTTP",
path: "/x",
auth: ["00000000-0000-4000-8000-000000000000"],
},
],
});
} catch {
threw = true;
}
assert(threw, "unknown auth id fails validation");
threw = false;
try {
@@ -280,6 +369,7 @@ assert(threw, "unknown page fails validation");
// cleanup
await deleteHttpAuth(profile.id);
await deleteHttpAuth(basicProfile.id);
await deleteHttpPage(page.id);
await deleteSecret(secret.id);
const leftover = (await listSecrets({ owner })).find(
@@ -0,0 +1,163 @@
/**
* Smoke: workflow revisions, SHA dedup, trash, restore, purge.
*
* Run: pnpm --dir packages/server test:workflow-history
*/
import assert from "node:assert/strict";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { db, migrate } from "../db.js";
import { WORKFLOWS_DIR } from "../paths.js";
import * as fsStore from "../fs-store.js";
import {
workflowContentSha,
workflowIdFromFile,
newWorkflowFilename,
} from "../workflow-normalize.js";
import {
recordRevision,
listRevisions,
getLatestRevision,
deleteRevisionHistory,
ensureInitialRevision,
} from "../workflow-history.js";
import {
moveWorkflowToTrash,
listTrash,
restoreFromTrash,
purgeTrashItem,
TRASH_WORKFLOWS_DIR,
} from "../workflow-trash.js";
import { collectWorkflowWarnings } from "../workflow-validate-warnings.js";
const owner = "__workflow_history_smoke__";
const file = newWorkflowFilename();
const workflowId = workflowIdFromFile(file);
const ownerDir = path.join(WORKFLOWS_DIR, owner);
const trashPath = path.join(TRASH_WORKFLOWS_DIR, owner, file);
function cleanup() {
if (fs.existsSync(trashPath)) fs.unlinkSync(trashPath);
if (fs.existsSync(ownerDir)) fs.rmSync(ownerDir, { recursive: true, force: true });
}
cleanup();
await migrate();
const yamlV1 = `name: smoke test
scripts:
- plugin/get-current-time
triggers:
- type: HTTP
method: POST
path: /smoke
`;
fsStore.writeWorkflowYaml(owner, file, yamlV1);
fsStore.writeRegisters(owner, [file]);
assert.equal(workflowContentSha(yamlV1), workflowContentSha(`${yamlV1}\n\n`));
const rev1 = await recordRevision({
workflowId,
owner,
file,
content: yamlV1,
reason: "create",
force: true,
});
assert.equal(rev1.skipped, false);
assert.equal(rev1.revision, 1);
const revDup = await recordRevision({
workflowId,
owner,
file,
content: `${yamlV1}\n\n`,
reason: "save",
});
assert.equal(revDup.skipped, true, "normalized SHA should dedupe blank lines");
const yamlV2 = yamlV1.replace("smoke test", "smoke test v2");
const rev2 = await recordRevision({
workflowId,
owner,
file,
content: yamlV2,
reason: "save",
});
assert.equal(rev2.revision, 2);
assert.equal((await listRevisions(workflowId)).length, 2);
const yamlDisabled = `${yamlV2}\nenabled: false\n`;
assert.equal(
workflowContentSha(yamlV2),
workflowContentSha(yamlDisabled),
"enabled-only change should not change content SHA",
);
const revDisable = await recordRevision({
workflowId,
owner,
file,
content: yamlDisabled,
reason: "disable",
});
assert.equal(revDisable.skipped, true, "enable/disable should not create a revision");
assert.equal((await listRevisions(workflowId)).length, 2);
const { startRun, getRun } = await import("../store.js");
const latest = await getLatestRevision(workflowId);
assert.equal(latest?.revision, 2);
const run = await startRun({
owner,
workflow: `${owner}/${file}`,
workflowName: "smoke test v2",
trigger: { type: "manual", detail: "smoke" },
input: null,
workflowRevision: latest?.revision ?? null,
});
const loaded = await getRun(run.id);
assert.equal(loaded.workflow_revision, 2);
await db("workflow_runs").where({ id: run.id }).del();
await deleteRevisionHistory(workflowId);
assert.equal(await getLatestRevision(workflowId), null);
const seeded = await ensureInitialRevision({ owner, file });
assert.ok(seeded);
assert.equal(seeded.revision, 1);
assert.equal(seeded.seeded, true);
const again = await ensureInitialRevision({ owner, file });
assert.equal(again?.revision, 1);
assert.equal(again?.seeded, false);
const warnings = collectWorkflowWarnings(
`name: bad\nscripts:\n - unknown-script-xyz\n`,
);
assert.ok(warnings.warnings.some((w) => w.code === "unknown_script"));
const trashed = await moveWorkflowToTrash({
workflowId,
owner,
file,
name: "smoke test v2",
});
assert.ok(trashed.id);
assert.equal(fsStore.readWorkflowYaml(owner, file), null);
assert.ok(fs.existsSync(trashPath));
const restored = await restoreFromTrash(trashed.id);
assert.equal(restored.file, file);
assert.ok(fsStore.readWorkflowYaml(owner, file));
await moveWorkflowToTrash({ workflowId, owner, file, name: "smoke test v2" });
const trashAgain = (await listTrash()).find((t) => t.file === file);
assert.ok(trashAgain);
await purgeTrashItem(trashAgain.id);
assert.ok(!(await listTrash()).some((t) => t.file === file));
await deleteRevisionHistory(workflowId);
cleanup();
console.log("workflow-history-smoke: ok");
await db.destroy();
+134
View File
@@ -0,0 +1,134 @@
import fs from "fs";
import os from "os";
import path from "path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { randomUUID } from "node:crypto";
import { DATA_DIR, PLUGINS_DIR, WORKFLOWS_DIR } from "./paths.js";
import { getAppVersion } from "./app-version.js";
import * as fsStore from "./fs-store.js";
import { listInstalledPlugins } from "./plugin-store.js";
const execFileAsync = promisify(execFile);
/**
* @param {string} dir
* @param {string} zipPath
*/
async function zipDirectory(dir, zipPath) {
await execFileAsync("zip", ["-r", zipPath, "."], { cwd: dir });
}
/**
* @param {string} zipPath
* @param {string} destDir
*/
async function unzipArchive(zipPath, destDir) {
fs.mkdirSync(destDir, { recursive: true });
await execFileAsync("unzip", ["-o", zipPath, "-d", destDir]);
}
/**
* Copy directory recursively.
* @param {string} src
* @param {string} dest
*/
function copyDir(src, dest) {
if (!fs.existsSync(src)) return;
fs.mkdirSync(dest, { recursive: true });
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const from = path.join(src, entry.name);
const to = path.join(dest, entry.name);
if (entry.isDirectory()) copyDir(from, to);
else fs.copyFileSync(from, to);
}
}
/**
* Build a backup zip buffer (workflows + installed plugins + manifest).
*/
export async function createWorkflowBackupBuffer() {
const staging = path.join(DATA_DIR, `.backup-staging-${randomUUID()}`);
fs.mkdirSync(staging, { recursive: true });
const zipPath = path.join(DATA_DIR, `.backup-${randomUUID()}.zip`);
try {
const wfDest = path.join(staging, "workflows");
copyDir(WORKFLOWS_DIR, wfDest);
const pluginsDest = path.join(staging, "plugins");
copyDir(PLUGINS_DIR, pluginsDest);
const manifest = {
version: getAppVersion(),
created_at: new Date().toISOString(),
plugins: listInstalledPlugins().map((p) => p.id),
owners: fsStore.listOwners(),
};
fs.writeFileSync(
path.join(staging, "manifest.json"),
JSON.stringify(manifest, null, 2),
"utf8",
);
await zipDirectory(staging, zipPath);
return fs.readFileSync(zipPath);
} finally {
fs.rmSync(staging, { recursive: true, force: true });
if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);
}
}
/**
* @param {Buffer} zipBuffer
* @param {{ mode?: "merge" | "replace" }} [opts]
*/
export async function restoreWorkflowBackup(zipBuffer, opts = {}) {
const mode = opts.mode === "replace" ? "replace" : "merge";
const extractDir = fs.mkdtempSync(path.join(os.tmpdir(), "jflow-restore-"));
const zipPath = path.join(extractDir, "backup.zip");
fs.writeFileSync(zipPath, zipBuffer);
/** @type {string[]} */
const warnings = [];
try {
const contentDir = path.join(extractDir, "content");
await unzipArchive(zipPath, contentDir);
const manifestPath = path.join(contentDir, "manifest.json");
if (fs.existsSync(manifestPath)) {
try {
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
for (const pluginId of manifest.plugins ?? []) {
const dir = path.join(PLUGINS_DIR, pluginId);
if (!fs.existsSync(dir)) {
warnings.push(`Plugin "${pluginId}" from backup is not installed`);
}
}
} catch {
warnings.push("Could not read backup manifest.json");
}
}
const wfSrc = path.join(contentDir, "workflows");
if (fs.existsSync(wfSrc)) {
if (mode === "replace" && fs.existsSync(WORKFLOWS_DIR)) {
fs.rmSync(WORKFLOWS_DIR, { recursive: true, force: true });
}
copyDir(wfSrc, WORKFLOWS_DIR);
}
const pluginsSrc = path.join(contentDir, "plugins");
if (fs.existsSync(pluginsSrc)) {
if (mode === "replace" && fs.existsSync(PLUGINS_DIR)) {
fs.rmSync(PLUGINS_DIR, { recursive: true, force: true });
}
copyDir(pluginsSrc, PLUGINS_DIR);
}
return { ok: true, mode, warnings };
} finally {
fs.rmSync(extractDir, { recursive: true, force: true });
}
}
+22 -7
View File
@@ -1,4 +1,8 @@
import yaml from "yaml";
import {
newWorkflowFilename,
workflowFileStem,
} from "./workflow-normalize.js";
export function ensureWorkflowFilename(file) {
const trimmed = String(file ?? "").trim();
@@ -6,13 +10,8 @@ export function ensureWorkflowFilename(file) {
return /\.ya?ml$/i.test(trimmed) ? trimmed : `${trimmed}.yaml`;
}
export function workflowFileStem(file) {
return String(file).replace(/\.ya?ml$/i, "");
}
/**
* Next unused copy filename: `track.yaml` → `track-copy.yaml`,
* `track-copy.yaml` → `track-copy-2.yaml`.
* Legacy human-readable copy name (kept for UI hints).
* @param {string} file
* @param {string[]} existingFiles
*/
@@ -33,6 +32,19 @@ export function suggestCopyFilename(file, existingFiles = []) {
return candidate(n);
}
/**
* UUID-based duplicate filename (default for new duplicates).
* @param {string[]} existingFiles
*/
export function suggestDuplicateFilename(existingFiles = []) {
const existing = new Set(existingFiles);
let file = newWorkflowFilename();
while (existing.has(file)) {
file = newWorkflowFilename();
}
return file;
}
export function nextCopyName(name) {
const trimmed = String(name ?? "").trim();
if (!trimmed) return "copy";
@@ -55,7 +67,10 @@ export function httpPathCopySuffix(sourceFile, destFile) {
function suffixHttpPath(path, suffix) {
const trimmed = String(path).replace(/\/+$/, "");
const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
const safe = String(suffix).replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "copy";
const safe =
String(suffix)
.replace(/[^A-Za-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "") || "copy";
return `${withSlash}-${safe}`;
}
+173
View File
@@ -0,0 +1,173 @@
import { randomUUID } from "node:crypto";
import { db } from "./db.js";
import * as fsStore from "./fs-store.js";
import { workflowContentSha, workflowIdFromFile } from "./workflow-normalize.js";
const MAX_REVISIONS = 50;
function nowIso() {
return new Date().toISOString();
}
/**
* @param {string | null} meta
*/
function parseMeta(meta) {
if (!meta) return null;
try {
return JSON.parse(meta);
} catch {
return null;
}
}
/**
* @param {string} workflowId
*/
export async function getLatestRevision(workflowId) {
const row = await db("workflow_revisions")
.where({ workflow_id: workflowId })
.orderBy("revision", "desc")
.first();
if (!row) return null;
return {
...row,
meta: parseMeta(row.meta),
};
}
/**
* @param {string} workflowId
*/
export async function listRevisions(workflowId) {
const rows = await db("workflow_revisions")
.where({ workflow_id: workflowId })
.orderBy("revision", "desc");
return rows.map((row) => ({
id: row.id,
workflow_id: row.workflow_id,
owner: row.owner,
file: row.file,
revision: row.revision,
content_sha: row.content_sha,
reason: row.reason ?? null,
meta: parseMeta(row.meta),
created_at: row.created_at,
}));
}
/**
* @param {string} workflowId
* @param {number} revision
*/
export async function getRevision(workflowId, revision) {
const row = await db("workflow_revisions")
.where({ workflow_id: workflowId, revision })
.first();
if (!row) return null;
return {
...row,
meta: parseMeta(row.meta),
};
}
/**
* Ensure a workflow has at least revision #1 (seed from disk when history is empty).
* @param {{ owner: string, file: string }} opts
* @returns {Promise<{ revision: number, id: string, content_sha: string, created_at: string, seeded: boolean } | null>}
*/
export async function ensureInitialRevision(opts) {
const workflowId = workflowIdFromFile(opts.file);
const latest = await getLatestRevision(workflowId);
if (latest) {
return {
revision: latest.revision,
id: latest.id,
content_sha: latest.content_sha,
created_at: latest.created_at,
seeded: false,
};
}
const content = fsStore.readWorkflowYaml(opts.owner, opts.file);
if (content == null) return null;
const recorded = await recordRevision({
workflowId,
owner: opts.owner,
file: opts.file,
content,
reason: "seed",
force: true,
});
if (recorded.revision == null || recorded.id == null) return null;
const row = await getLatestRevision(workflowId);
if (!row) return null;
return {
revision: row.revision,
id: row.id,
content_sha: row.content_sha,
created_at: row.created_at,
seeded: true,
};
}
/**
* Insert a revision when content changed (SHA dedup skips identical saves).
* @param {{
* workflowId: string,
* owner: string,
* file: string,
* content: string,
* reason?: string | null,
* meta?: Record<string, unknown> | null,
* force?: boolean,
* }} opts
* @returns {Promise<{ skipped: boolean, revision: number | null, id: string | null }>}
*/
export async function recordRevision(opts) {
const sha = workflowContentSha(opts.content);
const latest = await getLatestRevision(opts.workflowId);
if (!opts.force && latest && latest.content_sha === sha) {
return { skipped: true, revision: latest.revision, id: latest.id };
}
const nextRevision = latest ? latest.revision + 1 : 1;
const id = randomUUID();
const created_at = nowIso();
await db("workflow_revisions").insert({
id,
workflow_id: opts.workflowId,
owner: opts.owner,
file: opts.file,
revision: nextRevision,
content_sha: sha,
content: opts.content,
reason: opts.reason ?? null,
meta: opts.meta ? JSON.stringify(opts.meta) : null,
created_at,
});
const overflow = await db("workflow_revisions")
.where({ workflow_id: opts.workflowId })
.orderBy("revision", "desc")
.offset(MAX_REVISIONS)
.pluck("id");
if (overflow.length) {
await db("workflow_revisions").whereIn("id", overflow).del();
}
return { skipped: false, revision: nextRevision, id };
}
/**
* @param {string} workflowId
*/
export async function deleteRevisionHistory(workflowId) {
return db("workflow_revisions").where({ workflow_id: workflowId }).del();
}
+51 -18
View File
@@ -1,7 +1,11 @@
/**
* Validate HTTP trigger auth / response fields on workflow save.
*/
import { assertAuthType, getHttpAuthByName } from "./http-auths-store.js";
import {
assertAuthId,
assertAuthType,
getHttpAuthById,
} from "./http-auths-store.js";
import { getHttpPageByName, assertHttpResponsePage } from "./http-pages-store.js";
import { authLabel } from "./http-trigger-auth.js";
@@ -24,51 +28,80 @@ function assertCredentialFieldShape(field, label) {
}
/**
* @param {unknown} auth
* @param {unknown} entry
* @param {string} path
*/
async function validateAuthField(auth) {
if (auth == null || auth === false) return;
if (typeof auth === "string") {
const named = await getHttpAuthByName(auth);
async function validateAuthEntry(entry, path) {
if (typeof entry === "string") {
try {
assertAuthId(entry);
} catch {
const err = new Error(`${path} must be an auth profile UUID`);
err.statusCode = 400;
throw err;
}
const named = await getHttpAuthById(entry);
if (!named) {
const err = new Error(`unknown auth profile "${auth}"`);
const err = new Error(`unknown auth profile id "${entry}"`);
err.statusCode = 400;
throw err;
}
return;
}
if (typeof auth === "object" && !Array.isArray(auth)) {
const obj = /** @type {Record<string, unknown>} */ (auth);
if (typeof obj.name === "string" && obj.name.length > 0 && !obj.type) {
await validateAuthField(obj.name);
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
const obj = /** @type {Record<string, unknown>} */ (entry);
if (typeof obj.id === "string" && obj.id.length > 0 && !obj.type) {
await validateAuthEntry(obj.id, path);
return;
}
const type = assertAuthType(obj.type);
if (type === "bearer") {
assertCredentialFieldShape(obj.token, "auth.token");
assertCredentialFieldShape(obj.token, `${path}.token`);
} else if (type === "basic") {
assertCredentialFieldShape(obj.user, "auth.user");
assertCredentialFieldShape(obj.user, `${path}.user`);
if (obj.password != null && obj.password !== "") {
assertCredentialFieldShape(obj.password, "auth.password");
assertCredentialFieldShape(obj.password, `${path}.password`);
}
} else if (type === "header") {
if (typeof obj.header !== "string" || obj.header.length === 0) {
const err = new Error("auth.header must be a non-empty string");
const err = new Error(`${path}.header must be a non-empty string`);
err.statusCode = 400;
throw err;
}
assertCredentialFieldShape(obj.value, "auth.value");
assertCredentialFieldShape(obj.value, `${path}.value`);
}
return;
}
const err = new Error("auth must be a profile name or an auth object");
const err = new Error(
`${path} must be an auth profile UUID or an inline auth object`,
);
err.statusCode = 400;
throw err;
}
/**
* auth is an array of auth profile UUIDs and/or inline auth objects (OR).
* null / false / [] = no auth.
* @param {unknown} auth
*/
async function validateAuthField(auth) {
if (auth == null || auth === false) return;
if (!Array.isArray(auth)) {
const err = new Error(
"auth must be an array of auth profile UUIDs and/or inline auth objects",
);
err.statusCode = 400;
throw err;
}
for (let i = 0; i < auth.length; i++) {
await validateAuthEntry(auth[i], `auth[${i}]`);
}
}
/**
* @param {unknown} pageName
* @param {string} label
+77
View File
@@ -0,0 +1,77 @@
import { createHash, randomUUID } from "node:crypto";
import yaml from "yaml";
/**
* Stable key order for canonical JSON (dedup ignores YAML formatting).
* @param {unknown} value
*/
export function canonicalize(value) {
if (value == null || typeof value !== "object") return value;
if (Array.isArray(value)) return value.map(canonicalize);
const out = {};
for (const key of Object.keys(value).sort()) {
out[key] = canonicalize(value[key]);
}
return out;
}
/**
* Parse YAML to a JS object (null when empty/invalid for callers that handle errors).
* @param {string} content
*/
export function parseWorkflowObject(content) {
if (typeof content !== "string" || !content.trim()) return null;
return yaml.parse(content) ?? null;
}
/**
* Drop `enabled` before hashing so enable/disable does not create revision points.
* @param {unknown} parsed
*/
function stripEnabledForHash(parsed) {
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return parsed;
const { enabled, ...rest } = parsed;
return rest;
}
/**
* SHA256 of normalized workflow content (YAML → object → canonical JSON).
* @param {string} content
*/
export function workflowContentSha(content) {
const parsed = stripEnabledForHash(parseWorkflowObject(content));
const canonical = canonicalize(parsed);
const json = JSON.stringify(canonical);
return createHash("sha256").update(json, "utf8").digest("hex");
}
/**
* @param {string} file
*/
export function workflowIdFromFile(file) {
return String(file).replace(/\.ya?ml$/i, "");
}
/** @param {string} file */
export function workflowFileStem(file) {
return workflowIdFromFile(file);
}
/**
* New on-disk workflow filename: `{uuid}.yaml`.
* @param {string} [uuid]
*/
export function newWorkflowFilename(uuid) {
const id = uuid ?? randomUUID();
return `${id}.yaml`;
}
const UUID_FILE_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.ya?ml$/i;
/**
* @param {string} file
*/
export function isUuidWorkflowFile(file) {
return UUID_FILE_RE.test(String(file));
}
+183
View File
@@ -0,0 +1,183 @@
import fs from "fs";
import path from "path";
import { randomUUID } from "node:crypto";
import { db } from "./db.js";
import { deleteRevisionHistory } from "./workflow-history.js";
import { DATA_DIR, WORKFLOWS_DIR } from "./paths.js";
import * as fsStore from "./fs-store.js";
export const TRASH_WORKFLOWS_DIR = path.join(DATA_DIR, "trash", "workflows");
export const TRASH_RETENTION_DAYS = 7;
function nowIso() {
return new Date().toISOString();
}
function trashFilePath(owner, file) {
return path.join(TRASH_WORKFLOWS_DIR, owner, file);
}
/**
* @param {string} deletedAtIso
*/
export function trashAgeMs(deletedAtIso) {
return Date.now() - Date.parse(deletedAtIso);
}
/**
* @param {string} deletedAtIso
*/
export function trashDaysRemaining(deletedAtIso) {
const purgeAt =
Date.parse(deletedAtIso) + TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000;
return Math.max(0, Math.ceil((purgeAt - Date.now()) / (24 * 60 * 60 * 1000)));
}
function rowToItem(row) {
return {
id: row.id,
workflow_id: row.workflow_id,
owner: row.owner,
file: row.file,
name: row.name ?? null,
deleted_at: row.deleted_at,
trash_path: row.trash_path,
age_ms: trashAgeMs(row.deleted_at),
days_until_purge: trashDaysRemaining(row.deleted_at),
};
}
export async function listTrash() {
const rows = await db("workflow_trash").orderBy("deleted_at", "desc");
return rows.map(rowToItem);
}
export async function getTrashItem(id) {
const row = await db("workflow_trash").where({ id }).first();
return row ? rowToItem(row) : null;
}
export async function isInTrash(owner, file) {
const row = await db("workflow_trash").where({ owner, file }).first();
return Boolean(row);
}
/**
* Soft-delete: move YAML to trash dir, unregister, keep revision history.
* @param {{
* workflowId: string,
* owner: string,
* file: string,
* name?: string | null,
* }} opts
*/
export async function moveWorkflowToTrash(opts) {
const sourcePath = path.join(WORKFLOWS_DIR, opts.owner, opts.file);
if (!fs.existsSync(sourcePath)) {
const err = new Error("workflow not found");
err.statusCode = 404;
throw err;
}
const trashPath = trashFilePath(opts.owner, opts.file);
fs.mkdirSync(path.dirname(trashPath), { recursive: true });
fs.renameSync(sourcePath, trashPath);
const registered = fsStore.readRegisters(opts.owner).filter((f) => f !== opts.file);
fsStore.writeRegisters(opts.owner, registered);
const id = randomUUID();
const deleted_at = nowIso();
await db("workflow_trash").insert({
id,
workflow_id: opts.workflowId,
owner: opts.owner,
file: opts.file,
name: opts.name ?? null,
deleted_at,
trash_path: trashPath,
});
return rowToItem(await db("workflow_trash").where({ id }).first());
}
/**
* Restore workflow from trash.
* @param {string} trashId
*/
export async function restoreFromTrash(trashId) {
const row = await db("workflow_trash").where({ id: trashId }).first();
if (!row) {
const err = new Error("trash item not found");
err.statusCode = 404;
throw err;
}
const destPath = path.join(WORKFLOWS_DIR, row.owner, row.file);
if (fs.existsSync(destPath)) {
const err = new Error("workflow file already exists");
err.statusCode = 409;
throw err;
}
if (!fs.existsSync(row.trash_path)) {
const err = new Error("trash file missing on disk");
err.statusCode = 410;
throw err;
}
fs.mkdirSync(path.dirname(destPath), { recursive: true });
fs.renameSync(row.trash_path, destPath);
const registered = fsStore.readRegisters(row.owner);
if (!registered.includes(row.file)) {
registered.push(row.file);
fsStore.writeRegisters(row.owner, registered);
}
await db("workflow_trash").where({ id: trashId }).del();
return {
owner: row.owner,
file: row.file,
workflow_id: row.workflow_id,
content: fs.readFileSync(destPath, "utf8"),
};
}
/**
* Permanently delete a trash item and its revision history.
* @param {string} trashId
*/
export async function purgeTrashItem(trashId) {
const row = await db("workflow_trash").where({ id: trashId }).first();
if (!row) {
const err = new Error("trash item not found");
err.statusCode = 404;
throw err;
}
if (fs.existsSync(row.trash_path)) {
fs.unlinkSync(row.trash_path);
}
await deleteRevisionHistory(row.workflow_id);
await db("workflow_trash").where({ id: trashId }).del();
return { ok: true };
}
/**
* Auto-purge trash older than retention window.
* @returns {Promise<number>}
*/
export async function purgeExpiredTrash() {
const cutoff = new Date(
Date.now() - TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000,
).toISOString();
const rows = await db("workflow_trash")
.where("deleted_at", "<", cutoff)
.select("id");
for (const row of rows) {
await purgeTrashItem(row.id);
}
return rows.length;
}
@@ -0,0 +1,136 @@
import yaml from "yaml";
import { parseScriptStep } from "./workflow-parse.js";
import { resolveScriptRef } from "./plugin-store.js";
import { parseWorkflowObject } from "./workflow-normalize.js";
const SECRET_KEY_RE =
/(?:password|passwd|secret|token|api[_-]?key|auth(?:orization)?|credential|private[_-]?key)/i;
const BEARER_RE = /Bearer\s+[A-Za-z0-9._~+/=-]{8,}/;
/**
* Walk parsed YAML for suspicious secret-like string values.
* @param {unknown} value
* @param {string} pathKey
* @param {Array<{ code: string, message: string, path?: string }>} warnings
*/
function scanSecrets(value, pathKey, warnings) {
if (value == null) return;
if (typeof value === "string") {
if (BEARER_RE.test(value)) {
warnings.push({
code: "plaintext_secret",
message: "Possible Bearer token in workflow YAML",
path: pathKey,
});
}
return;
}
if (Array.isArray(value)) {
value.forEach((item, i) => scanSecrets(item, `${pathKey}[${i}]`, warnings));
return;
}
if (typeof value === "object") {
for (const [k, v] of Object.entries(value)) {
const childPath = pathKey ? `${pathKey}.${k}` : k;
if (typeof v === "string" && v.trim() && SECRET_KEY_RE.test(k)) {
warnings.push({
code: "plaintext_secret",
message: `Possible secret in field "${k}"`,
path: childPath,
});
}
scanSecrets(v, childPath, warnings);
}
}
}
/**
* Collect non-blocking save warnings for workflow YAML.
* @param {string} content
* @returns {{ warnings: Array<{ code: string, message: string, path?: string }>, parsed: unknown | null, parseError: string | null }}
*/
export function collectWorkflowWarnings(content) {
/** @type {Array<{ code: string, message: string, path?: string }>} */
const warnings = [];
let parsed = null;
let parseError = null;
try {
parsed = parseWorkflowObject(content);
if (parsed == null) {
warnings.push({
code: "invalid_yaml",
message: "Workflow YAML is empty or not an object",
});
} else if (typeof parsed !== "object" || Array.isArray(parsed)) {
warnings.push({
code: "invalid_yaml",
message: "Workflow YAML must be a mapping/object",
});
parsed = null;
}
} catch (err) {
parseError = err instanceof Error ? err.message : String(err);
warnings.push({
code: "invalid_yaml",
message: `Invalid YAML: ${parseError}`,
});
}
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
scanSecrets(parsed, "", warnings);
for (const [i, raw] of (parsed.scripts ?? []).entries()) {
try {
const step = parseScriptStep(raw);
if (step.kind === "set") continue;
const resolved = resolveScriptRef(step.script);
if (resolved.error) {
warnings.push({
code: "unknown_script",
message: resolved.error,
path: `scripts[${i}]`,
});
}
} catch (err) {
warnings.push({
code: "invalid_script_step",
message: err instanceof Error ? err.message : String(err),
path: `scripts[${i}]`,
});
}
}
}
return { warnings, parsed, parseError };
}
/**
* Strict validation used when saveAnyway is false.
* @param {unknown} parsed
*/
export function assertStrictWorkflow(parsed) {
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
const err = new Error("workflow yaml must be an object");
err.statusCode = 400;
throw err;
}
return parsed;
}
/**
* Parse for PATCH/enable toggles (must be valid YAML document).
* @param {string} content
*/
export function parseWorkflowDocument(content) {
const doc = yaml.parseDocument(content);
if (doc.errors?.length) {
const err = new Error(doc.errors[0]?.message ?? "invalid yaml");
err.statusCode = 400;
throw err;
}
const parsed = doc.toJSON();
assertStrictWorkflow(parsed);
return { doc, parsed };
}
@@ -13,4 +13,5 @@ triggers:
- type: HTTP
method: POST
path: /dev-zte-sms
auth: basic-auth
auth:
- 0f78d6d7-bd44-45d7-a826-f51c027b767f
@@ -36,4 +36,5 @@ triggers:
- type: HTTP
method: POST
path: /send-gmail
auth: basic-auth
auth:
- 0f78d6d7-bd44-45d7-a826-f51c027b767f
@@ -1,6 +1,7 @@
name: time to ntfy example
description: |
this workflow will send a message to ntfy with the current time
enabled: false
scripts:
- script: plugin/get-current-time
config:
@@ -12,3 +13,5 @@ triggers:
- type: HTTP
method: POST
path: /time-to-ntfy
auth:
- 0f78d6d7-bd44-45d7-a826-f51c027b767f
+18 -1
View File
@@ -10,6 +10,7 @@ import { ScriptDryRunPage } from "./pages/ScriptDryRunPage.jsx";
import { ScriptEditPage, ScriptNewPage } from "./pages/ScriptEditPage.jsx";
import { WorkflowsPage } from "./pages/WorkflowsPage.jsx";
import { WorkflowEditPage, WorkflowNewPage } from "./pages/WorkflowEditPage.jsx";
import { WorkflowTrashPage } from "./pages/WorkflowTrashPage.jsx";
import { EventsPage } from "./pages/EventsPage.jsx";
import { EventDetailPage } from "./pages/EventDetailPage.jsx";
import { FailuresPage } from "./pages/FailuresPage.jsx";
@@ -20,6 +21,7 @@ import { UsersPage } from "./pages/UsersPage.jsx";
import { SecretsPage } from "./pages/SecretsPage.jsx";
import { VariablesPage } from "./pages/VariablesPage.jsx";
import { OpsPage } from "./pages/OpsPage.jsx";
import { BackupPage } from "./pages/BackupPage.jsx";
export function App() {
const qc = useQueryClient();
@@ -59,6 +61,7 @@ export function App() {
<Route path="/scripts/:name/dry-run" element={<ScriptDryRunPage />} />
<Route path="/scripts/:name/edit" element={<ScriptEditPage />} />
<Route path="/workflows" element={<WorkflowsPage />} />
<Route path="/workflows/trash" element={<WorkflowTrashPage />} />
<Route path="/workflows/new" element={<WorkflowNewPage />} />
<Route path="/workflows/:owner/:file/edit" element={<WorkflowEditPage />} />
<Route path="/events" element={<EventsPage />} />
@@ -66,19 +69,33 @@ export function App() {
<Route path="/failures" element={<FailuresPage />} />
<Route path="/kv" element={<KvPage />} />
<Route path="/variables" element={<VariablesPage />} />
<Route path="/variables/new" element={<VariablesPage />} />
<Route path="/variables/:owner/:name/edit" element={<VariablesPage />} />
<Route path="/auth" element={<AuthProfilesPage />} />
<Route path="/auth/new" element={<AuthProfilesPage />} />
<Route path="/auth/:name/edit" element={<AuthProfilesPage />} />
<Route path="/responses" element={<ResponsesPage />} />
{user.role === "admin" ? (
<>
<Route path="/users" element={<UsersPage />} />
<Route path="/users/new" element={<UsersPage />} />
<Route path="/users/:username/edit" element={<UsersPage />} />
<Route path="/secrets" element={<SecretsPage />} />
<Route path="/ops" element={<OpsPage />} />
<Route path="/secrets/new" element={<SecretsPage />} />
<Route path="/secrets/:owner/:name/edit" element={<SecretsPage />} />
<Route path="/manage" element={<OpsPage />} />
<Route path="/ops" element={<Navigate to="/manage" replace />} />
<Route path="/backup" element={<BackupPage />} />
</>
) : (
<>
<Route path="/users" element={<Navigate to="/" replace />} />
<Route path="/users/*" element={<Navigate to="/" replace />} />
<Route path="/secrets" element={<Navigate to="/" replace />} />
<Route path="/secrets/*" element={<Navigate to="/" replace />} />
<Route path="/manage" element={<Navigate to="/" replace />} />
<Route path="/ops" element={<Navigate to="/" replace />} />
<Route path="/backup" element={<Navigate to="/" replace />} />
</>
)}
<Route path="*" element={<Navigate to="/" replace />} />
+155 -6
View File
@@ -191,17 +191,21 @@ export function useOwners() {
export function useSaveWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, content }) =>
mutationFn: async ({ owner, file, content, saveAnyway }) =>
(
await api.put(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`,
{ content },
{ content, ...(saveAnyway ? { saveAnyway: true } : {}) },
)
).data,
onSuccess: () => {
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
qc.invalidateQueries({
queryKey: ["workflows", vars.owner, vars.file, "revisions"],
});
qc.invalidateQueries({ queryKey: ["workflows", vars.owner, vars.file] });
},
});
}
@@ -235,6 +239,7 @@ export function useDeleteWorkflow() {
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["workflows", "trash"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
@@ -390,13 +395,14 @@ export function useDeleteSecret() {
});
}
export function useVariables(owner) {
export function useVariables(owner, options = {}) {
return useQuery({
queryKey: ["variables", owner ?? "all"],
queryFn: async () => {
const params = owner ? { owner } : {};
return (await api.get("/variables", { params })).data.variables;
},
...options,
});
}
@@ -488,8 +494,8 @@ export function useDeleteHttpAuth() {
}
/** Fetch plaintext literals only (not encrypted secrets). */
export async function fetchHttpAuthLiterals(name) {
return (await api.get(`/http-auths/${encodeURIComponent(name)}/reveal`)).data;
export async function fetchHttpAuthLiterals(id) {
return (await api.get(`/http-auths/${encodeURIComponent(id)}/reveal`)).data;
}
export function useOpsStatus(enabled = true) {
@@ -563,6 +569,15 @@ export function useOpsHttpStop() {
});
}
export function useOpsProcessRestart() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ pmId }) =>
(await opsApi.post("/restart", { pmId: Number(pmId) })).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["ops-status"] }),
});
}
export function useOpsBumpGeneration() {
const qc = useQueryClient();
return useMutation({
@@ -572,3 +587,137 @@ export function useOpsBumpGeneration() {
});
}
export function useWorkflowTrash() {
return useQuery({
queryKey: ["workflows", "trash"],
queryFn: async () => (await api.get("/workflows/trash")).data.items,
});
}
export function useRestoreWorkflowTrash() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id) =>
(await api.post(`/workflows/trash/${encodeURIComponent(id)}/restore`)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["workflows", "trash"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function usePurgeWorkflowTrash() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id) =>
(await api.delete(`/workflows/trash/${encodeURIComponent(id)}`)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows", "trash"] });
},
});
}
export function useWorkflowRevisions(owner, file, enabled = true) {
return useQuery({
queryKey: ["workflows", owner, file, "revisions"],
queryFn: async () =>
(
await api.get(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}/revisions`,
)
).data,
enabled: Boolean(owner && file) && enabled,
});
}
export function useWorkflowRevision(owner, file, revision) {
return useQuery({
queryKey: ["workflows", owner, file, "revisions", revision],
queryFn: async () =>
(
await api.get(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}/revisions/${revision}`,
)
).data,
enabled: Boolean(owner && file && revision != null),
});
}
export function useRevertWorkflowRevision() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, revision, saveAnyway }) =>
(
await api.post(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}/revisions/${revision}/revert`,
saveAnyway ? { saveAnyway: true } : {},
)
).data,
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["workflows", vars.owner, vars.file] });
qc.invalidateQueries({
queryKey: ["workflows", vars.owner, vars.file, "revisions"],
});
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useCreateWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, content, file, saveAnyway }) =>
(
await api.post(`/workflows/${encodeURIComponent(owner)}`, {
content,
...(file ? { file } : {}),
...(saveAnyway ? { saveAnyway: true } : {}),
})
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useDownloadWorkflowBackup() {
return useMutation({
mutationFn: async () => {
const res = await api.get("/workflows/backup", { responseType: "blob" });
const disposition = res.headers["content-disposition"] ?? "";
const match = disposition.match(/filename="([^"]+)"/);
const filename = match?.[1] ?? "jerapah-flow-backup.zip";
const url = URL.createObjectURL(res.data);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
return { ok: true };
},
});
}
export function useRestoreWorkflowBackup() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ file, mode }) => {
const buffer = await file.arrayBuffer();
const zipBase64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));
return (await api.post("/workflows/backup/restore", { zipBase64, mode })).data;
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
qc.invalidateQueries({ queryKey: ["ops-status"] });
},
});
}
@@ -0,0 +1,422 @@
import { useEffect, useState } from "react";
import { LuEye, LuEyeOff } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
fetchHttpAuthLiterals,
useHttpPages,
useUpsertHttpAuth,
} from "../api/hooks.js";
function emptyCred(source = "literal") {
return { source, value: "", kv: "", namespace: "", secret: "" };
}
function credFromPublic(field, literalValue) {
if (!field || field.source === "missing") return emptyCred("literal");
if (field.source === "kv") {
return {
source: "kv",
value: "",
kv: field.kv ?? "",
namespace: field.namespace ?? "",
secret: "",
};
}
if (field.source === "secret") {
return {
source: "secret",
value: "",
kv: "",
namespace: "",
secret: field.secret ?? "",
};
}
if (typeof literalValue === "string") {
return {
source: "literal",
value: literalValue,
kv: "",
namespace: "",
secret: "",
keep: true,
};
}
return {
source: "literal",
value: "",
kv: "",
namespace: "",
secret: "",
keep: field.set === true,
};
}
function toApiField(cred, { required = true } = {}) {
if (cred.source === "kv") {
const out = { kv: cred.kv };
if (cred.namespace) out.namespace = cred.namespace;
return out;
}
if (cred.source === "secret") {
return { secret: cred.secret };
}
if (cred.value) return cred.value;
if (cred.keep) return { keep: true };
if (!required) return "";
return null;
}
function emptyForm() {
return {
id: null,
name: "",
type: "bearer",
token: emptyCred(),
user: emptyCred(),
password: emptyCred(),
header: "",
value: emptyCred(),
unauthorized_status: "",
unauthorized_response: "",
};
}
function formFromAuth(auth, literals = {}) {
const cfg = auth.config ?? {};
return {
id: auth.id,
name: auth.name,
type: auth.type,
token: credFromPublic(cfg.token, literals.token),
user: credFromPublic(cfg.user, literals.user),
password: credFromPublic(cfg.password, literals.password),
header: cfg.header ?? "",
value: credFromPublic(cfg.value, literals.value),
unauthorized_status: auth.unauthorized_status ?? "",
unauthorized_response: auth.unauthorized_response ?? "",
};
}
function Field({ label, children, hint }) {
return (
<div className="form-control w-full">
<div className="label py-1">
<span className="label-text text-sm font-medium">{label}</span>
</div>
{children}
{hint ? (
<div className="label py-1">
<span className="label-text-alt opacity-60">{hint}</span>
</div>
) : null}
</div>
);
}
function CredentialFields({ label, cred, onChange, allowEmpty, masked }) {
const [show, setShow] = useState(false);
return (
<div className="space-y-3 rounded-box border border-base-300 p-3">
<p className="text-sm font-medium">{label}</p>
<Field label="Source">
<select
className="select select-bordered w-full"
value={cred.source}
onChange={(e) => onChange({ ...cred, source: e.target.value, keep: false })}
>
<option value="literal">Plain text</option>
<option value="kv">From KV</option>
<option value="secret">From secret</option>
</select>
</Field>
{cred.source === "literal" ? (
<Field
label="Value"
hint={
cred.keep && !cred.value
? "A value is already set. Enter a new one to replace it."
: null
}
>
<div className="flex w-full gap-1">
<input
type={masked && !show ? "password" : "text"}
className="input input-bordered w-full font-mono"
value={cred.value}
onChange={(e) => onChange({ ...cred, value: e.target.value, keep: false })}
placeholder={
cred.keep && !cred.value ? "(unchanged — leave blank to keep)" : ""
}
required={!allowEmpty && !cred.keep && !cred.value}
autoComplete="off"
/>
{masked ? (
<button
type="button"
className="btn btn-ghost btn-square shrink-0"
title={show ? "Hide" : "Reveal"}
aria-label={show ? "Hide value" : "Reveal value"}
onClick={() => setShow((v) => !v)}
>
{show ? <LuEyeOff className="size-4" /> : <LuEye className="size-4" />}
</button>
) : null}
</div>
</Field>
) : null}
{cred.source === "kv" ? (
<>
<Field label="Namespace (optional)">
<input
className="input input-bordered w-full font-mono"
placeholder="namespace"
value={cred.namespace}
onChange={(e) => onChange({ ...cred, namespace: e.target.value })}
/>
</Field>
<Field label="Key">
<input
className="input input-bordered w-full font-mono"
placeholder="key"
value={cred.kv}
onChange={(e) => onChange({ ...cred, kv: e.target.value })}
required
/>
</Field>
</>
) : null}
{cred.source === "secret" ? (
<Field
label="Secret name"
hint="Encrypted secret — value is never shown here. Manage it on the Secrets page."
>
<input
className="input input-bordered w-full font-mono"
placeholder="secret name"
value={cred.secret}
onChange={(e) => onChange({ ...cred, secret: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
/>
</Field>
) : null}
</div>
);
}
/**
* Add / edit an HTTP trigger auth profile.
* Reusable: mount when open; pass `auth` for edit (literals loaded inside).
*
* @param {"add" | "edit"} mode
* @param {object} [auth] Public auth row when mode is "edit"
* @param {() => void} onClose
* @param {(saved: unknown) => void} [onSaved]
*/
export function AuthEditorModal({ mode, auth, onClose, onSaved }) {
const { data: pages = [] } = useHttpPages();
const upsert = useUpsertHttpAuth();
const [form, setForm] = useState(emptyForm);
const [loading, setLoading] = useState(mode === "edit");
useEffect(() => {
if (mode !== "edit" || !auth?.id) {
setForm(emptyForm());
setLoading(false);
return;
}
let cancelled = false;
setLoading(true);
(async () => {
/** @type {Record<string, string>} */
let literals = {};
try {
const data = await fetchHttpAuthLiterals(auth.id);
literals = data.literals ?? {};
} catch {
// Form still works with keep markers
}
if (cancelled) return;
setForm(formFromAuth(auth, literals));
setLoading(false);
})();
return () => {
cancelled = true;
};
}, [mode, auth]);
function onSubmit(e) {
e.preventDefault();
/** @type {Record<string, unknown>} */
let config = {};
if (form.type === "bearer") {
const token = toApiField(form.token);
if (token == null) return;
config = { token };
} else if (form.type === "basic") {
const user = toApiField(form.user);
if (user == null) return;
const password = toApiField(form.password, { required: false });
config = { user, password: password ?? "" };
} else {
const value = toApiField(form.value);
if (value == null) return;
config = { header: form.header, value };
}
upsert.mutate(
{
id: form.id,
name: form.name,
type: form.type,
config,
unauthorized_status:
form.unauthorized_status === "" ? null : Number(form.unauthorized_status),
unauthorized_response: form.unauthorized_response || null,
},
{
onSuccess: (data) => {
onSaved?.(data?.auth ?? data);
onClose();
},
},
);
}
const title = mode === "add" ? "New auth profile" : `Edit ${form.name || auth?.name || ""}`;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-xl">
<h3 className="font-bold">{title}</h3>
{loading ? (
<div className="flex justify-center py-10">
<span className="loading loading-spinner" />
</div>
) : (
<form className="mt-3 space-y-4" onSubmit={onSubmit}>
<Field label="Name">
<input
className="input input-bordered w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
autoComplete="off"
/>
</Field>
<Field label="Type">
<select
className="select select-bordered w-full"
value={form.type}
onChange={(e) => setForm({ ...form, type: e.target.value })}
>
<option value="bearer">bearer</option>
<option value="basic">basic</option>
<option value="header">header</option>
</select>
</Field>
{form.type === "bearer" ? (
<CredentialFields
label="Token"
cred={form.token}
onChange={(token) => setForm({ ...form, token })}
/>
) : null}
{form.type === "basic" ? (
<>
<CredentialFields
label="User"
cred={form.user}
onChange={(user) => setForm({ ...form, user })}
/>
<CredentialFields
label="Password"
cred={form.password}
onChange={(password) => setForm({ ...form, password })}
allowEmpty
masked
/>
</>
) : null}
{form.type === "header" ? (
<>
<Field label="Header name">
<input
className="input input-bordered w-full font-mono"
value={form.header}
onChange={(e) => setForm({ ...form, header: e.target.value })}
required
placeholder="X-Webhook-Secret"
/>
</Field>
<CredentialFields
label="Header value"
cred={form.value}
onChange={(value) => setForm({ ...form, value })}
/>
</>
) : null}
<Field label="Unauthorized status (optional)">
<input
type="number"
className="input input-bordered w-full"
value={form.unauthorized_status}
onChange={(e) => setForm({ ...form, unauthorized_status: e.target.value })}
min={100}
max={599}
placeholder="401"
/>
</Field>
<Field label="Unauthorized response page (optional)">
<select
className="select select-bordered w-full"
value={form.unauthorized_response}
onChange={(e) => setForm({ ...form, unauthorized_response: e.target.value })}
>
<option value="">(default JSON)</option>
{pages.map((p) => (
<option key={p.id} value={p.name}>
{p.name}
</option>
))}
</select>
</Field>
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-primary" disabled={upsert.isPending}>
{upsert.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : null}
Save
</button>
</div>
</form>
)}
{loading ? (
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
</div>
) : null}
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onClose}>
close
</button>
</form>
</dialog>
);
}
@@ -1,44 +1,22 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useState } from "react";
import { errorMessage } from "../api/client.js";
import { useDuplicateWorkflow, useOwners, useWorkflows } from "../api/hooks.js";
import { ensureWorkflowFilename, suggestCopyFilename } from "../lib/workflow-doc.js";
import { useDuplicateWorkflow, useOwners } from "../api/hooks.js";
import { useNotifications } from "../notifications.jsx";
const EMPTY_WORKFLOWS = [];
export function DuplicateWorkflowDialog({ source, warnUnsaved, onClose, onDuplicated }) {
const { notify } = useNotifications();
const { data: owners = [] } = useOwners();
const { data: workflows = EMPTY_WORKFLOWS } = useWorkflows();
const duplicate = useDuplicateWorkflow();
const [destOwner, setDestOwner] = useState(source.owner);
const [destFile, setDestFile] = useState(() => suggestCopyFilename(source.file));
const fileTouched = useRef(false);
const existingFiles = useMemo(
() => workflows.filter((w) => w.owner === destOwner).map((w) => w.file),
[workflows, destOwner],
);
useEffect(() => {
if (fileTouched.current) return;
setDestFile(suggestCopyFilename(source.file, existingFiles));
}, [source.file, existingFiles]);
const yamlFile = ensureWorkflowFilename(destFile);
const sameAsSource = destOwner === source.owner && yamlFile === source.file;
const exists = existingFiles.includes(yamlFile);
const canSubmit = Boolean(destOwner && yamlFile) && !sameAsSource && !exists && !duplicate.isPending;
function onSubmit(e) {
e.preventDefault();
if (!canSubmit) return;
if (destOwner === source.owner && duplicate.isPending) return;
duplicate.mutate(
{
owner: source.owner,
file: source.file,
destOwner,
destFile: yamlFile,
},
{
onSuccess: (data) => {
@@ -54,11 +32,13 @@ export function DuplicateWorkflowDialog({ source, warnUnsaved, onClose, onDuplic
<div className="modal-box">
<h3 className="font-bold">Duplicate {source.key}?</h3>
<p className="mt-2 text-sm opacity-70">
The copy starts disabled. HTTP paths are rewritten when staying under the same owner so
triggers do not collide.
A new UUID filename is assigned automatically. The copy starts disabled. HTTP paths are
rewritten when staying under the same owner so triggers do not collide.
</p>
{warnUnsaved ? (
<p className="text-warning mt-2 text-sm">The copy uses the last saved YAML, not unsaved edits.</p>
<p className="text-warning mt-2 text-sm">
The copy uses the last saved YAML, not unsaved edits.
</p>
) : null}
<form className="mt-4 space-y-3" onSubmit={onSubmit}>
<label className="form-control w-full">
@@ -76,24 +56,6 @@ export function DuplicateWorkflowDialog({ source, warnUnsaved, onClose, onDuplic
))}
</datalist>
</label>
<label className="form-control w-full">
<span className="label py-0 text-sm">File</span>
<input
className="input input-sm w-full font-mono"
placeholder="file.yaml"
value={destFile}
onChange={(e) => {
fileTouched.current = true;
setDestFile(e.target.value);
}}
required
/>
</label>
{sameAsSource ? (
<p className="text-error text-sm">Choose a different owner or filename.</p>
) : exists ? (
<p className="text-error text-sm">{destOwner}/{yamlFile} already exists.</p>
) : null}
{duplicate.isError ? (
<p className="text-error text-sm">{errorMessage(duplicate.error)}</p>
) : null}
@@ -101,7 +63,7 @@ export function DuplicateWorkflowDialog({ source, warnUnsaved, onClose, onDuplic
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-primary" disabled={!canSubmit}>
<button type="submit" className="btn btn-primary" disabled={duplicate.isPending}>
{duplicate.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : null}
@@ -0,0 +1,165 @@
import { useState } from "react";
import { errorMessage } from "../api/client.js";
import { HeartbeatsToolbar } from "./HeartbeatsToolbar.jsx";
import { useNotifications } from "../notifications.jsx";
import { formatBytes, formatCpu, formatDuration } from "../lib/format.js";
const MAX_WORKERS = 32;
export function HeartbeatsAndPm2Card({
data,
children,
restart,
processRestart,
workerCount,
desiredWorkers,
onDecreaseWorkers,
onIncreaseWorkers,
onScale,
scalePending = false,
onReload,
reloadPending = false,
}) {
const { notify } = useNotifications();
const [forceRestart, setForceRestart] = useState(false);
const [pendingPmId, setPendingPmId] = useState(null);
async function onRestartAll() {
const label = forceRestart ? "Force restart" : "Restart";
if (
forceRestart &&
!window.confirm("Force restart will interrupt active jobs. Continue?")
) {
return;
}
try {
await restart.mutateAsync({ force: forceRestart });
notify.success(`${label} ok`);
} catch (e) {
notify.error(errorMessage(e, `${label} failed`));
}
}
async function onProcessRestart(pmId) {
const id = Number(pmId);
setPendingPmId(id);
try {
await processRestart.mutateAsync({ pmId: id });
notify.success("Process restart ok");
} catch (e) {
notify.error(errorMessage(e, "Process restart failed"));
} finally {
setPendingPmId(null);
}
}
const heartbeats = data?.heartbeats ?? [];
const httpChildren = children?.http ?? [];
const workerChildren = children?.workers ?? [];
const pm2Children = [...httpChildren, ...workerChildren];
const heartbeatByPid = new Map();
for (const h of heartbeats) {
if (!heartbeatByPid.has(h.pid)) heartbeatByPid.set(h.pid, h);
}
return (
<div className="card bg-base-100 border border-base-300 shadow-sm">
<div className="card-body gap-4">
<h2 className="card-title text-lg">Heartbeats</h2>
<HeartbeatsToolbar
forceRestart={forceRestart}
onForceRestartChange={setForceRestart}
onRestartAll={onRestartAll}
restartPending={restart.isPending}
workerCount={workerCount}
desiredWorkers={desiredWorkers}
onDecreaseWorkers={onDecreaseWorkers}
onIncreaseWorkers={onIncreaseWorkers}
onScale={onScale}
scalePending={scalePending}
onReload={onReload}
reloadPending={reloadPending}
maxWorkers={MAX_WORKERS}
/>
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Role</th>
<th>Name</th>
<th>PM ID</th>
<th>Status</th>
<th>PID</th>
<th>Generation</th>
<th>Uptime</th>
<th>Memory</th>
<th>CPU</th>
<th>Restarts</th>
<th />
</tr>
</thead>
<tbody>
{pm2Children.map((p) => {
const pid = p.pid ?? null;
const hb = pid != null ? heartbeatByPid.get(pid) : undefined;
const role =
hb?.role ??
(p.name === "jflow-http"
? "http"
: p.name === "jflow-worker"
? "worker"
: p.name ?? "unknown");
const generation = hb?.generation ?? p.generation ?? "—";
const uptimeMs =
p.uptime != null
? Math.max(0, Date.now() - Number(p.uptime))
: hb
? Math.max(0, Date.now() - hb.ts)
: null;
return (
<tr key={p.pmId}>
<td>{role}</td>
<td className="font-mono">{p.name}</td>
<td className="font-mono">{p.pmId}</td>
<td>{p.status}</td>
<td className="font-mono">{pid ?? "—"}</td>
<td className="font-mono">{generation}</td>
<td className="font-mono" title={uptimeMs != null ? `${uptimeMs}ms` : undefined}>
{formatDuration(uptimeMs)}
</td>
<td className="font-mono">{formatBytes(p.memory)}</td>
<td className="font-mono">{formatCpu(p.cpu)}</td>
<td className="font-mono">{p.restarts ?? 0}</td>
<td className="text-end">
<button
type="button"
className="btn btn-xs"
disabled={
processRestart.isPending && pendingPmId === p.pmId
}
onClick={() => onProcessRestart(p.pmId)}
>
Restart
</button>
</td>
</tr>
);
})}
{!pm2Children.length ? (
<tr>
<td colSpan={11} className="opacity-60">
No PM2 children
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
</div>
);
}
@@ -0,0 +1,87 @@
import { LuMinus, LuPlus } from "react-icons/lu";
export function HeartbeatsToolbar({
forceRestart,
onForceRestartChange,
onRestartAll,
restartPending = false,
workerCount,
desiredWorkers,
onDecreaseWorkers,
onIncreaseWorkers,
onScale,
scalePending = false,
onReload,
reloadPending = false,
minWorkers = 0,
maxWorkers = 32,
}) {
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<label className="label cursor-pointer gap-2 px-0">
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={forceRestart}
onChange={(e) => onForceRestartChange(e.target.checked)}
/>
<span className="label-text">Force</span>
</label>
<button
type="button"
className={`btn btn-sm ${forceRestart ? "btn-error" : "btn-primary"}`}
disabled={restartPending}
onClick={onRestartAll}
>
Restart all
</button>
<div className="divider divider-horizontal mx-1" />
<button
type="button"
className="btn btn-circle btn-sm"
aria-label="Decrease workers"
disabled={workerCount <= minWorkers}
onClick={onDecreaseWorkers}
>
<LuMinus className="size-4" />
</button>
<span className="min-w-20 text-center text-sm tabular-nums">
{workerCount} worker{workerCount === 1 ? "" : "s"}
</span>
<button
type="button"
className="btn btn-circle btn-sm"
aria-label="Increase workers"
disabled={workerCount >= maxWorkers}
onClick={onIncreaseWorkers}
>
<LuPlus className="size-4" />
</button>
<button
type="button"
className="btn btn-sm"
disabled={scalePending || workerCount === desiredWorkers}
onClick={onScale}
>
Scale
</button>
<div className="divider divider-horizontal mx-1" />
<button
type="button"
className="btn btn-sm"
disabled={reloadPending}
onClick={onReload}
>
Reload workflows
</button>
</div>
<div className="divider my-0" />
</div>
);
}
@@ -0,0 +1,46 @@
import { LuCircleCheck, LuCircleX } from "react-icons/lu";
export function HttpProcessCard({
httpOnline,
onStart,
onStop,
startPending = false,
stopPending = false,
}) {
return (
<div className="card bg-base-100 border border-base-300 shadow-sm">
<div className="card-body gap-4">
<h2 className="card-title text-lg">HTTP process</h2>
<div className="flex items-center gap-2">
{httpOnline ? (
<LuCircleCheck className="size-6 text-success" aria-hidden />
) : (
<LuCircleX className="size-6 text-error" aria-hidden />
)}
<span>{httpOnline ? "Running" : "Stopped"}</span>
</div>
<div className="card-actions justify-start px-0">
{httpOnline ? (
<button
type="button"
className="btn btn-sm btn-warning"
disabled={stopPending}
onClick={onStop}
>
Stop HTTP
</button>
) : (
<button
type="button"
className="btn btn-sm btn-primary"
disabled={startPending}
onClick={onStart}
>
Start HTTP
</button>
)}
</div>
</div>
</div>
);
}
+60 -29
View File
@@ -1,6 +1,8 @@
import { Fragment } from "react";
import { Link, NavLink, useNavigate } from "react-router-dom";
import {
LuActivity,
LuArchive,
LuCode,
LuDatabase,
LuFileText,
@@ -20,17 +22,50 @@ import { useLogout, useOpsStatus } from "../api/hooks.js";
import { brandMark } from "../theme/brand.js";
import { useTheme } from "../theme.jsx";
const links = [
{ to: "/", label: "Home", icon: LuHouse, end: true },
{ to: "/scripts", label: "Scripts", icon: LuCode },
{ to: "/workflows", label: "Workflows", icon: LuGitBranch },
{ to: "/events", label: "Events", icon: LuActivity },
{ to: "/kv", label: "KV", icon: LuDatabase },
{ to: "/variables", label: "Variables", icon: LuTags },
{ to: "/auth", label: "Auth", icon: LuShield },
{ to: "/responses", label: "Responses", icon: LuFileText },
const navSections = [
{
items: [{ to: "/", label: "Home", icon: LuHouse, end: true }],
},
{
title: "Automate",
items: [
{ to: "/workflows", label: "Workflows", icon: LuGitBranch },
{ to: "/scripts", label: "Scripts", icon: LuCode },
{ to: "/events", label: "Events", icon: LuActivity },
],
},
{
title: "Platform",
items: [
{ to: "/variables", label: "Variables", icon: LuTags },
{ to: "/kv", label: "KV", icon: LuDatabase },
{ to: "/auth", label: "Auth", icon: LuShield },
{ to: "/responses", label: "Responses", icon: LuFileText },
{ to: "/secrets", label: "Secrets", icon: LuKey, admin: true },
],
},
{
title: "Admin",
admin: true,
items: [
{ to: "/manage", label: "Manage", icon: LuServer },
{ to: "/backup", label: "Backup", icon: LuArchive },
{ to: "/users", label: "Users", icon: LuUsers },
],
},
];
function visibleSections(role) {
const isAdmin = role === "admin";
return navSections
.filter((s) => !s.admin || isAdmin)
.map((s) => ({
...s,
items: s.items.filter((item) => !item.admin || isAdmin),
}))
.filter((s) => s.items.length > 0);
}
export function Layout({ user, children }) {
const { theme, toggle } = useTheme();
const logout = useLogout();
@@ -38,17 +73,6 @@ export function Layout({ user, children }) {
const ops = useOpsStatus(user.role === "admin");
const restartNeeded = Boolean(ops.data?.desired?.restartNeeded);
const navItems = [
...links,
...(user.role === "admin"
? [
{ to: "/secrets", label: "Secrets", icon: LuKey },
{ to: "/users", label: "Users", icon: LuUsers },
{ to: "/ops", label: "Ops", icon: LuServer },
]
: []),
];
function closeDrawer() {
const el = document.getElementById("nav-drawer");
if (el) el.checked = false;
@@ -101,8 +125,8 @@ export function Layout({ user, children }) {
? ` (${ops.data.desired.restartReason})`
: ""}
.{" "}
<Link to="/ops" className="link font-medium">
Drain restart from Ops
<Link to="/manage" className="link font-medium">
Drain restart from Manage
</Link>{" "}
to apply on HTTP + workers.
</span>
@@ -120,13 +144,20 @@ export function Layout({ user, children }) {
<span className="text-base font-semibold text-base-content">JerapahFlow</span>
</div>
</li>
{navItems.map(({ to, label, icon: Icon, end }) => (
<li key={to}>
<NavLink to={to} end={end} onClick={closeDrawer}>
<Icon className="size-4" />
{label}
</NavLink>
</li>
{visibleSections(user.role).map((section) => (
<Fragment key={section.title ?? "overview"}>
{section.title ? (
<li className="menu-title">{section.title}</li>
) : null}
{section.items.map(({ to, label, icon: Icon, end }) => (
<li key={to}>
<NavLink to={to} end={end} onClick={closeDrawer}>
<Icon className="size-4" />
{label}
</NavLink>
</li>
))}
</Fragment>
))}
</ul>
</div>
@@ -0,0 +1,17 @@
import { formatBytes, formatCpu } from "../lib/format.js";
export function ProcessResourcesCard({ children }) {
const totals = children?.totals ?? { memory: 0, cpu: 0 };
return (
<div className="card bg-base-100 border border-base-300 shadow-sm">
<div className="card-body gap-4">
<h2 className="card-title text-lg">Resources</h2>
<div className="space-y-1 text-sm tabular-nums">
<p>{formatBytes(totals.memory)} memory total</p>
<p>{formatCpu(totals.cpu)} CPU total</p>
</div>
</div>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { LuCircleCheck, LuCirclePause } from "react-icons/lu";
export function QueueCard({
paused = false,
workersOnline = 0,
queuedJobs = 0,
activeJobs = 0,
onPause,
onResume,
pausePending = false,
resumePending = false,
}) {
return (
<div className="card bg-base-100 border border-base-300 shadow-sm">
<div className="card-body gap-4">
<h2 className="card-title text-lg">Queue</h2>
<div className="flex items-center gap-2">
{paused ? (
<LuCirclePause className="size-6 text-warning" aria-hidden />
) : (
<LuCircleCheck className="size-6 text-success" aria-hidden />
)}
<span>
{paused
? "Paused"
: `Running (${workersOnline} worker${workersOnline === 1 ? "" : "s"})`}
</span>
</div>
<div className="space-y-1 text-sm tabular-nums">
<p>
{activeJobs} running job{activeJobs === 1 ? "" : "s"}
</p>
<p>
{queuedJobs} queued job{queuedJobs === 1 ? "" : "s"}
</p>
</div>
<div className="card-actions justify-start px-0">
{paused ? (
<button
type="button"
className="btn btn-sm btn-primary"
disabled={resumePending}
onClick={onResume}
>
Resume workers
</button>
) : (
<button
type="button"
className="btn btn-sm btn-warning"
disabled={pausePending}
onClick={onPause}
>
Pause workers
</button>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,127 @@
import { useState } from "react";
import { errorMessage } from "../api/client.js";
import { useOwners, useUpsertSecret } from "../api/hooks.js";
/**
* Add / replace an encrypted secret.
* Reusable: mount when open; parent supplies mode + initial fields.
*
* @param {"add" | "replace"} mode
* @param {{ owner: string, name?: string }} initial
* @param {() => void} onClose
* @param {(saved: unknown) => void} [onSaved]
* @param {boolean} [lockOwner]
*/
export function SecretEditorModal({
mode,
initial,
onClose,
onSaved,
lockOwner = false,
}) {
const { data: owners = [] } = useOwners();
const upsert = useUpsertSecret();
const [form, setForm] = useState(() => ({
owner: initial.owner || owners[0] || "default",
name: initial.name || "",
value: "",
}));
function onSubmit(e) {
e.preventDefault();
upsert.mutate(
{ owner: form.owner, name: form.name, value: form.value },
{
onSuccess: (data) => {
onSaved?.(data?.secret ?? data);
onClose();
},
},
);
}
const title = mode === "add" ? "New secret" : `Replace ${form.owner}/${form.name}`;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-md">
<h3 className="font-bold">{title}</h3>
<form className="mt-3 space-y-2" onSubmit={onSubmit}>
{mode === "add" ? (
<>
<label className="form-control w-full">
<span className="label py-0 text-sm">Owner</span>
{owners.length > 0 ? (
<select
className="select w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
disabled={lockOwner}
>
{owners.map((o) => (
<option key={o} value={o}>
{o}
</option>
))}
</select>
) : (
<input
className="input w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
disabled={lockOwner}
/>
)}
</label>
<label className="form-control w-full">
<span className="label py-0 text-sm">Name</span>
<input
className="input w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
title="Letters, numbers, dots, underscores, hyphens"
/>
</label>
</>
) : null}
<label className="form-control w-full">
<span className="label py-0 text-sm">Value</span>
<input
type="password"
className="input w-full"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
required
autoComplete="new-password"
/>
</label>
<p className="text-xs opacity-60">
Values are encrypted at rest and never shown again after save. Values shorter than 8
characters are not redacted from logs.
</p>
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-primary" disabled={upsert.isPending}>
{upsert.isPending ? <span className="loading loading-spinner loading-xs" /> : null}
Save
</button>
</div>
</form>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onClose}>
close
</button>
</form>
</dialog>
);
}
@@ -0,0 +1,120 @@
import { useState } from "react";
import { errorMessage } from "../api/client.js";
import { useCreateUser, useUpdateUser } from "../api/hooks.js";
/**
* Add / edit a local user.
* Reusable: mount when open; pass `user` for edit.
*
* @param {"add" | "edit"} mode
* @param {{ id: string, username: string, role: string }} [user]
* @param {() => void} onClose
* @param {(saved: unknown) => void} [onSaved]
*/
export function UserEditorModal({ mode, user, onClose, onSaved }) {
const create = useCreateUser();
const update = useUpdateUser();
const [form, setForm] = useState(() => ({
username: user?.username || "",
password: "",
role: user?.role || "operator",
id: user?.id || null,
}));
const mutation = mode === "add" ? create : update;
function onSubmit(e) {
e.preventDefault();
if (mode === "add") {
create.mutate(
{
username: form.username,
password: form.password,
role: form.role,
},
{
onSuccess: (data) => {
onSaved?.(data?.user ?? data);
onClose();
},
},
);
return;
}
const body = { id: form.id, role: form.role };
if (form.password) body.password = form.password;
update.mutate(body, {
onSuccess: (data) => {
onSaved?.(data?.user ?? data);
onClose();
},
});
}
const title = mode === "add" ? "New user" : form.username;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-md">
<h3 className="font-bold">{title}</h3>
<form className="mt-3 space-y-2" onSubmit={onSubmit}>
{mode === "add" ? (
<label className="form-control w-full">
<span className="label py-0 text-sm">Username</span>
<input
className="input w-full"
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
required
/>
</label>
) : null}
<label className="form-control w-full">
<span className="label py-0 text-sm">
{mode === "add" ? "Password" : "New password"}
</span>
<input
type="password"
className="input w-full"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
required={mode === "add"}
minLength={mode === "add" ? 8 : undefined}
placeholder={mode === "edit" ? "leave blank to keep" : ""}
/>
</label>
<label className="form-control w-full">
<span className="label py-0 text-sm">Role</span>
<select
className="select w-full"
value={form.role}
onChange={(e) => setForm({ ...form, role: e.target.value })}
>
<option value="operator">operator</option>
<option value="admin">admin</option>
</select>
</label>
{mutation.isError ? (
<p className="text-error text-sm">{errorMessage(mutation.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-primary" disabled={mutation.isPending}>
{mutation.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : null}
Save
</button>
</div>
</form>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onClose}>
close
</button>
</form>
</dialog>
);
}
@@ -0,0 +1,191 @@
import { useState } from "react";
import { errorMessage } from "../api/client.js";
import { useOwners, useUpsertVariable } from "../api/hooks.js";
const TYPES = ["string", "number", "boolean"];
function defaultValue(type) {
if (type === "boolean") return false;
if (type === "number") return "";
return "";
}
/**
* Add / edit a plaintext workflow variable.
* Reusable: mount when open; parent supplies mode + initial fields.
*
* @param {"add" | "edit"} mode
* @param {{ owner: string, name?: string, type?: string, value?: string | number | boolean }} initial
* @param {() => void} onClose
* @param {(saved: unknown) => void} [onSaved]
* @param {boolean} [lockOwner] When true, owner cannot be changed (add mode).
*/
export function VariableEditorModal({
mode,
initial,
onClose,
onSaved,
lockOwner = false,
}) {
const { data: owners = [] } = useOwners();
const upsert = useUpsertVariable();
const [form, setForm] = useState(() => ({
owner: initial.owner || owners[0] || "default",
name: initial.name || "",
type: initial.type || "string",
value:
initial.type === "number"
? String(initial.value ?? "")
: initial.value !== undefined
? initial.value
: defaultValue(initial.type || "string"),
}));
const [formError, setFormError] = useState(null);
function onTypeChange(type) {
setForm({ ...form, type, value: defaultValue(type) });
}
function onSubmit(e) {
e.preventDefault();
let value = form.value;
if (form.type === "number") {
value = Number(form.value);
if (!Number.isFinite(value)) {
setFormError("value must be a finite number");
return;
}
}
if (form.type === "boolean") {
value = form.value === true;
}
setFormError(null);
upsert.mutate(
{ owner: form.owner, name: form.name, type: form.type, value },
{
onSuccess: (data) => {
onSaved?.(data?.variable ?? data);
onClose();
},
},
);
}
const title = mode === "add" ? "New variable" : `Edit ${form.owner}/${form.name}`;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-md">
<h3 className="font-bold">{title}</h3>
<form className="mt-3 space-y-2" onSubmit={onSubmit}>
{mode === "add" ? (
<>
<label className="form-control w-full">
<span className="label py-0 text-sm">Owner</span>
{owners.length > 0 ? (
<select
className="select w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
disabled={lockOwner}
>
{owners.map((o) => (
<option key={o} value={o}>
{o}
</option>
))}
</select>
) : (
<input
className="input w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
disabled={lockOwner}
/>
)}
</label>
<label className="form-control w-full">
<span className="label py-0 text-sm">Name</span>
<input
className="input w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
title="Letters, numbers, dots, underscores, hyphens"
/>
</label>
</>
) : null}
<label className="form-control w-full">
<span className="label py-0 text-sm">Type</span>
<select
className="select w-full"
value={form.type}
onChange={(e) => onTypeChange(e.target.value)}
>
{TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</label>
<label className="form-control w-full">
<span className="label py-0 text-sm">Value</span>
{form.type === "boolean" ? (
<select
className="select w-full"
value={form.value === true ? "true" : "false"}
onChange={(e) => setForm({ ...form, value: e.target.value === "true" })}
>
<option value="true">true</option>
<option value="false">false</option>
</select>
) : form.type === "number" ? (
<input
type="number"
className="input w-full font-mono"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
required
step="any"
/>
) : (
<textarea
className="textarea w-full font-mono min-h-24"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
spellCheck={false}
/>
)}
</label>
<p className="text-xs opacity-60">
Stored in plaintext. Use Secrets for credentials. In workflows use{" "}
<span className="font-mono">$VAR_name</span> as a whole field.
</p>
{formError ? <p className="text-error text-sm">{formError}</p> : null}
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-primary" disabled={upsert.isPending}>
{upsert.isPending ? <span className="loading loading-spinner loading-xs" /> : null}
Save
</button>
</div>
</form>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onClose}>
close
</button>
</form>
</dialog>
);
}
@@ -1,10 +1,13 @@
import { useEffect, useState } from "react";
import { LuPlus, LuTrash2 } from "react-icons/lu";
import { Link } from "react-router-dom";
import { LuEye, LuEyeOff, LuExternalLink, LuPlus, LuTrash2 } from "react-icons/lu";
import { useVariables } from "../../api/hooks.js";
import { triggerDestinations } from "../../lib/workflow-doc.js";
import { prettyJson } from "../../lib/script.js";
import { FieldLabel } from "./FieldHelp.jsx";
const MULTILINE_KEYS = new Set(["expression", "jsonata"]);
const VAR_PEEK_MAX = 48;
const CONFIG_REF_PREFIXES = [
{ prefix: "$SECRET_", label: "secret" },
@@ -17,19 +20,131 @@ function describeConfigRef(value) {
const trimmed = value.trim();
for (const { prefix, label } of CONFIG_REF_PREFIXES) {
if (trimmed.startsWith(prefix) && trimmed.length > prefix.length) {
return { label, name: trimmed.slice(prefix.length) };
return { label, name: trimmed.slice(prefix.length), kind: prefix };
}
}
return null;
}
function ConfigRefHint({ value }) {
function formatVarDisplay(value) {
if (typeof value === "string") return value === "" ? '""' : value;
return String(value);
}
function truncatePeek(text, maxLen = VAR_PEEK_MAX) {
if (!text) return "";
if (text.length <= maxLen) return text;
return `${text.slice(0, Math.max(0, maxLen - 1))}…`;
}
/** Edit-time lookup for `$VAR_` against workflow owner (not a runtime guarantee). */
function lookupVariable(variables, owner, name) {
const list = Array.isArray(variables) ? variables : [];
const match = list.find((v) => v.owner === owner && v.name === name);
if (match) {
return { status: "found", value: match.value, type: match.type };
}
const otherOwners = [
...new Set(list.filter((v) => v.name === name && v.owner !== owner).map((v) => v.owner)),
];
if (otherOwners.length > 0) {
return { status: "other_owner", otherOwners };
}
return { status: "missing" };
}
function variablesDeepLink({ owner, name, missing }) {
if (missing) {
const params = new URLSearchParams();
if (owner) params.set("owner", owner);
if (name) params.set("name", name);
const q = params.toString();
return q ? `/variables/new?${q}` : "/variables/new";
}
return `/variables/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/edit`;
}
function ConfigRefHint({ value, owner }) {
const ref = describeConfigRef(value);
const isVar = ref?.kind === "$VAR_";
const { data: variables = [], isPending } = useVariables(undefined, { enabled: isVar });
const [revealed, setRevealed] = useState(false);
useEffect(() => {
setRevealed(false);
}, [value, owner]);
if (!ref) return null;
if (!isVar) {
return (
<p className="text-xs opacity-60">
from {ref.label} <span className="font-mono">{ref.name}</span>
</p>
);
}
const lookup = !owner
? { status: "missing" }
: isPending
? { status: "loading" }
: lookupVariable(variables, owner, ref.name);
const linkTo = variablesDeepLink({
owner: owner || "",
name: ref.name,
missing: lookup.status !== "found",
});
let statusNote = null;
if (lookup.status === "missing") {
statusNote = <span className="text-warning">(missing)</span>;
} else if (lookup.status === "other_owner") {
statusNote = (
<span className="text-warning">
(missing · other owner: {lookup.otherOwners.join(", ")})
</span>
);
}
const fullText = lookup.status === "found" ? formatVarDisplay(lookup.value) : "";
const peek = truncatePeek(fullText);
const masked = lookup.status === "found" ? "******" : null;
return (
<p className="text-xs opacity-60">
from {ref.label} <span className="font-mono">{ref.name}</span>
</p>
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs opacity-60">
<span>
from variable <span className="font-mono">{ref.name}</span>
{lookup.status === "found" ? ":" : null}
</span>
{lookup.status === "found" ? (
<>
<span className="font-mono" title={revealed ? fullText : undefined}>
{revealed ? peek : masked}
</span>
<button
type="button"
className="btn btn-ghost btn-xs btn-square h-5 min-h-0 w-5"
aria-label={revealed ? "Hide value" : "Show value"}
title={revealed ? "Hide value" : "Show value"}
onClick={() => setRevealed((v) => !v)}
>
{revealed ? <LuEyeOff className="size-3" /> : <LuEye className="size-3" />}
</button>
</>
) : null}
{statusNote}
{lookup.status === "loading" ? null : (
<Link
to={linkTo}
target="_blank"
rel="noopener noreferrer"
className="link link-hover inline-flex items-center gap-0.5"
>
{lookup.status === "found" ? "Open Variables" : "Create on Variables"}
<LuExternalLink className="size-3" aria-hidden />
</Link>
)}
</div>
);
}
@@ -185,7 +300,7 @@ function ValueEditor({ value, onChange, spec, script, fieldKey, workflows, owner
if (type === "object" || (value != null && typeof value === "object" && !Array.isArray(value) && type !== "any")) {
const obj = value && typeof value === "object" && !Array.isArray(value) ? value : {};
return <ObjectFields value={obj} onChange={onChange} disabled={disabled} />;
return <ObjectFields value={obj} onChange={onChange} owner={owner} />;
}
if (type === "any") {
@@ -242,7 +357,7 @@ function JsonOrTextArea({ text, onCommit, disabled }) {
);
}
function ObjectFields({ value, onChange }) {
function ObjectFields({ value, onChange, owner }) {
const entries = Object.entries(value ?? {});
function setKey(oldKey, nextKey) {
@@ -286,6 +401,7 @@ function ObjectFields({ value, onChange }) {
<ObjectFields
value={v && !Array.isArray(v) ? v : {}}
onChange={(nv) => setVal(k, nv)}
owner={owner}
/>
) : (
<div className="space-y-0.5">
@@ -294,7 +410,7 @@ function ObjectFields({ value, onChange }) {
onCommit={(nv) => setVal(k, nv)}
className="font-mono text-xs"
/>
<ConfigRefHint value={v} />
<ConfigRefHint value={v} owner={owner} />
</div>
)}
</div>
@@ -425,7 +541,7 @@ export function ConfigFields({
excludeFile={excludeFile}
disabled={disabled}
/>
<ConfigRefHint value={cfg[key]} />
<ConfigRefHint value={cfg[key]} owner={owner} />
</div>
);
})}
@@ -461,7 +577,7 @@ export function ConfigFields({
excludeFile={excludeFile}
disabled={disabled}
/>
<ConfigRefHint value={cfg[key]} />
<ConfigRefHint value={cfg[key]} owner={owner} />
</div>
))}
<button type="button" className="btn btn-ghost btn-xs" disabled={disabled} onClick={addExtra}>
@@ -0,0 +1,67 @@
import { errorMessage } from "../../api/client.js";
export function SaveWorkflowWarningsDialog({ warnings, pending, onCancel, onSaveAnyway }) {
if (!warnings?.length) return null;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-lg">
<h3 className="font-bold">Save with warnings?</h3>
<p className="mt-2 text-sm opacity-70">
The workflow has issues that may prevent it from running correctly. You can fix them
first, or save anyway.
</p>
<ul className="mt-3 max-h-48 space-y-2 overflow-y-auto text-sm">
{warnings.map((w, i) => (
<li key={i} className="rounded-box bg-base-200 px-3 py-2">
<span className="badge badge-warning badge-xs mr-2">{w.code}</span>
{w.message}
{w.path ? (
<span className="mt-1 block font-mono text-xs opacity-60">{w.path}</span>
) : null}
</li>
))}
</ul>
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onCancel}>
Cancel
</button>
<button
type="button"
className="btn btn-warning"
disabled={pending}
onClick={onSaveAnyway}
>
{pending ? <span className="loading loading-spinner loading-xs" /> : null}
Save anyway
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onCancel}>
close
</button>
</form>
</dialog>
);
}
/**
* Extract validation warnings from a failed save mutation error.
* @param {unknown} error
*/
export function saveWarningsFromError(error) {
const warnings = error?.response?.data?.warnings;
return Array.isArray(warnings) ? warnings : null;
}
export function isSaveWarningsError(error) {
return error?.response?.status === 422 && saveWarningsFromError(error);
}
export function saveErrorMessage(error) {
if (isSaveWarningsError(error)) {
return "Workflow has validation warnings";
}
return errorMessage(error);
}
@@ -1,5 +1,5 @@
import { useState } from "react";
import { LuChevronDown, LuCopy, LuGripVertical, LuTrash2 } from "react-icons/lu";
import { useEffect, useMemo, useRef, useState } from "react";
import { LuChevronDown, LuCopy, LuGripVertical, LuTrash2, LuX } from "react-icons/lu";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import cronstrue from "cronstrue";
@@ -138,15 +138,27 @@ function typeLabel(type) {
return type || "Trigger";
}
function Field({ label, children, hint }) {
return (
<div className="flex w-full flex-col gap-1">
{label ? <span className="text-sm font-medium opacity-80">{label}</span> : null}
{children}
{hint ? <span className="text-xs opacity-60">{hint}</span> : null}
</div>
);
}
function HttpFields({ trigger, owner, disabled, onChange, auths, pages, alertDestinations }) {
const path = trigger.path || "/";
const url = namespacedPath(owner || "owner", path);
const authIsInline = trigger.auth != null && typeof trigger.auth === "object";
const authSelect = authIsInline
? "__inline__"
: typeof trigger.auth === "string" && trigger.auth
? trigger.auth
: "";
const authEntries = Array.isArray(trigger.auth) ? trigger.auth : [];
const selectedIds = authEntries.filter((e) => typeof e === "string" && e).map(String);
const inlineEntries = authEntries.filter((e) => e && typeof e === "object");
function setAuthIds(nextIds) {
const next = [...nextIds, ...inlineEntries];
onChange({ ...trigger, auth: next.length ? next : null });
}
function copyUrl() {
if (typeof navigator?.clipboard?.writeText === "function") {
@@ -155,11 +167,10 @@ function HttpFields({ trigger, owner, disabled, onChange, auths, pages, alertDes
}
return (
<div className="space-y-2">
<label className="form-control">
<span className="label py-0 text-sm">Method</span>
<div className="space-y-3">
<Field label="Method">
<select
className="select select-sm"
className="select select-bordered select-sm w-full"
value={trigger.method || "POST"}
disabled={disabled}
onChange={(e) => onChange({ ...trigger, method: e.target.value })}
@@ -173,51 +184,48 @@ function HttpFields({ trigger, owner, disabled, onChange, auths, pages, alertDes
<option value={trigger.method}>{trigger.method}</option>
)}
</select>
</label>
<label className="form-control">
<span className="label py-0 text-sm">Path</span>
</Field>
<Field label="Path">
<input
className="input input-sm font-mono"
className="input input-bordered input-sm w-full font-mono"
value={trigger.path ?? ""}
disabled={disabled}
onChange={(e) => onChange({ ...trigger, path: e.target.value })}
placeholder="/hook"
/>
</label>
<div className="flex items-center gap-2 text-xs font-mono opacity-80">
<span className="truncate">{url}</span>
<button type="button" className="btn btn-ghost btn-xs btn-square" title="Copy URL" onClick={copyUrl}>
<LuCopy className="size-3.5" />
</button>
</div>
<label className="form-control">
<span className="label py-0 text-sm">Auth</span>
</Field>
<Field label="URL">
<div className="flex w-full items-center gap-1">
<input
className="input input-bordered input-sm w-full font-mono opacity-80"
value={url}
readOnly
tabIndex={-1}
/>
<button
type="button"
className="btn btn-ghost btn-sm btn-square shrink-0"
title="Copy URL"
onClick={copyUrl}
>
<LuCopy className="size-3.5" />
</button>
</div>
</Field>
<AuthPicker
auths={auths}
selectedIds={selectedIds}
inlineCount={inlineEntries.length}
disabled={disabled}
onChange={setAuthIds}
/>
<Field label="Response page">
<select
className="select select-sm"
value={authSelect}
disabled={disabled}
onChange={(e) => {
const v = e.target.value;
if (v === "" || v === "__inline__") {
onChange({ ...trigger, auth: v === "__inline__" ? trigger.auth : null });
} else {
onChange({ ...trigger, auth: v });
}
}}
>
<option value="">None</option>
{auths.map((a) => (
<option key={a.name} value={a.name}>
{a.name}
</option>
))}
{authIsInline ? <option value="__inline__">Inline (edit in YAML)</option> : null}
</select>
</label>
<label className="form-control">
<span className="label py-0 text-sm">Response page</span>
<select
className="select select-sm"
className="select select-bordered select-sm w-full"
value={trigger.response ?? ""}
disabled={disabled}
onChange={(e) => onChange({ ...trigger, response: e.target.value })}
@@ -232,7 +240,8 @@ function HttpFields({ trigger, owner, disabled, onChange, auths, pages, alertDes
<option value={trigger.response}>{trigger.response}</option>
) : null}
</select>
</label>
</Field>
<FailureAlertFields
trigger={trigger}
disabled={disabled}
@@ -243,6 +252,165 @@ function HttpFields({ trigger, owner, disabled, onChange, auths, pages, alertDes
);
}
/**
* Searchable dropdown: pick an auth to add; chips with X to remove.
* YAML stores profile UUIDs; UI shows names.
*/
function AuthPicker({ auths, selectedIds, inlineCount, disabled, onChange }) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const rootRef = useRef(null);
const inputRef = useRef(null);
const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]);
const byId = useMemo(() => new Map(auths.map((a) => [a.id, a])), [auths]);
const available = useMemo(() => {
const q = query.trim().toLowerCase();
return auths
.filter((a) => !selectedSet.has(a.id))
.filter((a) => {
if (!q) return true;
return (
a.name.toLowerCase().includes(q) ||
String(a.type).toLowerCase().includes(q) ||
a.id.toLowerCase().includes(q)
);
});
}, [auths, selectedSet, query]);
useEffect(() => {
if (!open) return;
function onDoc(e) {
if (rootRef.current && !rootRef.current.contains(e.target)) {
setOpen(false);
setQuery("");
}
}
document.addEventListener("mousedown", onDoc);
return () => document.removeEventListener("mousedown", onDoc);
}, [open]);
function addAuth(id) {
if (selectedSet.has(id)) return;
onChange([...selectedIds, id]);
setQuery("");
setOpen(false);
}
function removeAuth(id) {
onChange(selectedIds.filter((x) => x !== id));
}
return (
<div className="flex w-full flex-col gap-1" ref={rootRef}>
<span className="text-sm font-medium opacity-80">Auth (any of)</span>
{selectedIds.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{selectedIds.map((id) => {
const auth = byId.get(id);
return (
<span
key={id}
className="badge badge-outline gap-1 h-7 px-2 font-normal"
title={id}
>
<span className="max-w-[10rem] truncate">
{auth ? (
<>
{auth.name}
<span className="opacity-60"> · {auth.type}</span>
</>
) : (
<span className="opacity-60">missing</span>
)}
</span>
<button
type="button"
className="btn btn-ghost btn-xs btn-square -mr-1"
title="Remove"
aria-label={`Remove ${auth?.name ?? id}`}
disabled={disabled}
onClick={() => removeAuth(id)}
>
<LuX className="size-3.5" />
</button>
</span>
);
})}
</div>
) : null}
<div className="relative w-full">
<div className="join w-full">
<input
ref={inputRef}
type="search"
className="input input-bordered input-sm join-item w-full min-w-0"
placeholder={auths.length === 0 ? "No auth profiles yet" : "Add auth…"}
value={query}
disabled={disabled || auths.length === 0}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
}}
onFocus={() => setOpen(true)}
onKeyDown={(e) => {
if (e.key === "Escape") {
setOpen(false);
setQuery("");
inputRef.current?.blur();
}
if (e.key === "Enter") {
e.preventDefault();
if (available[0]) addAuth(available[0].id);
}
}}
/>
<button
type="button"
className="btn btn-sm join-item btn-square"
disabled={disabled || auths.length === 0}
aria-label="Open auth list"
onClick={() => {
setOpen((v) => !v);
if (!open) inputRef.current?.focus();
}}
>
<LuChevronDown className={`size-4 transition-transform ${open ? "rotate-180" : ""}`} />
</button>
</div>
{open && !disabled && auths.length > 0 ? (
<ul className="menu menu-sm absolute z-50 mt-1 max-h-48 w-full overflow-y-auto rounded-box border border-base-300 bg-base-100 shadow-lg p-1">
{available.length === 0 ? (
<li className="disabled">
<span className="opacity-60">
{query.trim() ? "No matches" : "All profiles selected"}
</span>
</li>
) : (
available.map((a) => (
<li key={a.id}>
<button type="button" onClick={() => addAuth(a.id)}>
<span className="font-mono text-sm">{a.name}</span>
<span className="opacity-60 text-xs">{a.type}</span>
</button>
</li>
))
)}
</ul>
) : null}
</div>
{inlineCount > 0 ? (
<span className="text-xs opacity-60">
+ {inlineCount} inline auth{inlineCount === 1 ? "" : "s"} (edit in YAML)
</span>
) : null}
</div>
);
}
function CronFields({ trigger, disabled, onChange, alertDestinations }) {
const preset = matchCronPreset(trigger.schedule);
let human = "";
@@ -302,12 +470,11 @@ function CronFields({ trigger, disabled, onChange, alertDestinations }) {
function FailureAlertFields({ trigger, disabled, onChange, alertDestinations }) {
return (
<div className="space-y-2 border-t border-base-300 pt-3">
<p className="text-xs font-medium opacity-80">Failure alert</p>
<label className="form-control">
<span className="label py-0 text-sm">Consecutive failures</span>
<div className="space-y-3 border-t border-base-300 pt-3">
<p className="text-sm font-medium opacity-80">Failure alert</p>
<Field label="Consecutive failures">
<input
className="input input-sm"
className="input input-bordered input-sm w-full"
type="number"
min="1"
step="1"
@@ -318,11 +485,19 @@ function FailureAlertFields({ trigger, disabled, onChange, alertDestinations })
}
placeholder="e.g. 3"
/>
</label>
<label className="form-control">
<span className="label py-0 text-sm">On failure, start</span>
</Field>
<Field
label="On failure, start"
hint={
<>
After this many sequential failed runs for this trigger, JerapahFlow starts the
selected workflow (it must declare a <span className="font-mono">workflow</span>{" "}
trigger).
</>
}
>
<select
className="select select-sm"
className="select select-bordered select-sm w-full"
value={trigger.onFailureWorkflow ?? ""}
disabled={disabled}
onChange={(e) => onChange({ ...trigger, onFailureWorkflow: e.target.value })}
@@ -340,12 +515,7 @@ function FailureAlertFields({ trigger, disabled, onChange, alertDestinations })
<option value={trigger.onFailureWorkflow}>{trigger.onFailureWorkflow}</option>
) : null}
</select>
</label>
<p className="text-xs opacity-60">
After this many sequential failed runs for this trigger, JerapahFlow starts the
selected workflow (it must declare a <span className="font-mono">workflow</span>{" "}
trigger).
</p>
</Field>
</div>
);
}
@@ -0,0 +1,170 @@
import { useState } from "react";
import { LuHistory, LuRotateCcw } from "react-icons/lu";
import { errorMessage } from "../../api/client.js";
import {
useRevertWorkflowRevision,
useWorkflowRevisions,
} from "../../api/hooks.js";
import { formatTime } from "../../lib/format.jsx";
import { useNotifications } from "../../notifications.jsx";
import {
SaveWorkflowWarningsDialog,
isSaveWarningsError,
saveWarningsFromError,
} from "./SaveWorkflowWarningsDialog.jsx";
import { ConfirmDialog } from "./WorkflowRevisionBanner.jsx";
function reasonLabel(reason, meta) {
if (reason === "duplicated" && meta?.from) return `duplicated from ${meta.from}`;
if (reason === "revert" && meta?.fromRevision != null) {
return `reverted from #${meta.fromRevision}`;
}
if (reason === "restored-from-trash") return "restored from trash";
return reason ?? "save";
}
export function WorkflowHistoryPanel({
owner,
file,
previewRevision,
onSelectRevision,
onReverted,
}) {
const { notify } = useNotifications();
const revisions = useWorkflowRevisions(owner, file);
const revert = useRevertWorkflowRevision();
const [pendingRevision, setPendingRevision] = useState(null);
const [confirmRevision, setConfirmRevision] = useState(null);
const [warnings, setWarnings] = useState(null);
const items = revisions.data?.revisions ?? [];
const latestRevision = items[0]?.revision ?? null;
function doRevert(revision, saveAnyway = false) {
setPendingRevision(revision);
revert.mutate(
{ owner, file, revision, saveAnyway },
{
onSuccess: (data) => {
setWarnings(null);
setPendingRevision(null);
setConfirmRevision(null);
notify.success(`Restored revision #${revision}`);
onReverted?.(data);
},
onError: (err) => {
setPendingRevision(null);
if (isSaveWarningsError(err)) {
setWarnings({ revision, items: saveWarningsFromError(err) });
return;
}
notify.error(errorMessage(err));
},
},
);
}
function onRowClick(rev) {
if (rev.revision === latestRevision) {
onSelectRevision?.(null);
return;
}
onSelectRevision?.(rev.revision, rev);
}
const confirmRev = confirmRevision != null ? items.find((r) => r.revision === confirmRevision) : null;
return (
<div className="border-base-300 flex h-full min-h-0 flex-col rounded-box border bg-base-100">
<div className="border-base-300 flex items-center gap-2 border-b px-3 py-2">
<LuHistory className="size-4 opacity-70" />
<span className="text-sm font-medium">History</span>
<span className="text-xs opacity-50">({items.length} / 50)</span>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{revisions.isLoading ? (
<div className="flex justify-center p-4">
<span className="loading loading-spinner loading-sm" />
</div>
) : !items.length ? (
<p className="p-3 text-sm opacity-50">No revisions yet.</p>
) : (
<ul className="space-y-1">
{items.map((rev, index) => {
const isCurrent = index === 0;
const isSelected =
previewRevision === rev.revision || (previewRevision == null && isCurrent);
return (
<li
key={rev.id}
className={`hover:bg-base-200 flex cursor-pointer items-start justify-between gap-2 rounded-lg px-2 py-2 ${
isSelected ? "bg-base-200 ring-base-content/10 ring-1" : ""
}`}
onClick={() => onRowClick(rev)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onRowClick(rev);
}
}}
role="button"
tabIndex={0}
>
<div className="min-w-0">
<div className="flex items-center gap-1.5 text-sm font-medium">
<span>#{rev.revision}</span>
{isCurrent ? (
<span className="badge badge-primary badge-xs">Current</span>
) : null}
</div>
<div className="text-xs opacity-60">{formatTime(rev.created_at)}</div>
<div className="text-xs opacity-70">
{reasonLabel(rev.reason, rev.meta)}
</div>
</div>
{!isCurrent ? (
<button
type="button"
className="btn btn-ghost btn-xs shrink-0"
title="Revert to this revision"
disabled={revert.isPending}
onClick={(e) => {
e.stopPropagation();
setConfirmRevision(rev.revision);
}}
>
{pendingRevision === rev.revision && revert.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuRotateCcw className="size-3.5" />
)}
</button>
) : null}
</li>
);
})}
</ul>
)}
</div>
{confirmRev ? (
<ConfirmDialog
open
title={`Revert to revision #${confirmRev.revision}?`}
message={`This replaces the live workflow with revision #${confirmRev.revision} from ${formatTime(confirmRev.created_at)} and creates a new revision.`}
confirmLabel="Revert"
pending={revert.isPending}
onCancel={() => setConfirmRevision(null)}
onConfirm={() => doRevert(confirmRev.revision, false)}
/>
) : null}
{warnings ? (
<SaveWorkflowWarningsDialog
warnings={warnings.items}
pending={revert.isPending}
onCancel={() => setWarnings(null)}
onSaveAnyway={() => doRevert(warnings.revision, true)}
/>
) : null}
</div>
);
}
@@ -0,0 +1,129 @@
import { useState } from "react";
import { LuHistory } from "react-icons/lu";
import { errorMessage } from "../../api/client.js";
import { useRevertWorkflowRevision } from "../../api/hooks.js";
import { formatTime } from "../../lib/format.jsx";
import { useNotifications } from "../../notifications.jsx";
import {
SaveWorkflowWarningsDialog,
isSaveWarningsError,
saveWarningsFromError,
} from "./SaveWorkflowWarningsDialog.jsx";
function ConfirmDialog({
open,
title,
message,
confirmLabel,
confirmClass = "btn-warning",
pending,
onCancel,
onConfirm,
}) {
if (!open) return null;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-md">
<h3 className="font-bold">{title}</h3>
<p className="mt-2 text-sm opacity-70">{message}</p>
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={onCancel}>
Cancel
</button>
<button
type="button"
className={`btn ${confirmClass}`}
disabled={pending}
onClick={onConfirm}
>
{pending ? <span className="loading loading-spinner loading-xs" /> : null}
{confirmLabel}
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={onCancel}>
close
</button>
</form>
</dialog>
);
}
export function WorkflowRevisionBanner({
owner,
file,
revision,
createdAt,
onBackToCurrent,
onReverted,
}) {
const { notify } = useNotifications();
const revert = useRevertWorkflowRevision();
const [confirmOpen, setConfirmOpen] = useState(false);
const [warnings, setWarnings] = useState(null);
function doRevert(saveAnyway = false) {
revert.mutate(
{ owner, file, revision, saveAnyway },
{
onSuccess: (data) => {
setWarnings(null);
setConfirmOpen(false);
notify.success(`Restored revision #${revision}`);
onReverted?.(data);
},
onError: (err) => {
if (isSaveWarningsError(err)) {
setWarnings({ items: saveWarningsFromError(err) });
return;
}
notify.error(errorMessage(err));
},
},
);
}
return (
<>
<div className="alert alert-warning shrink-0 py-2">
<LuHistory className="size-4 shrink-0" />
<span className="text-sm">
Viewing revision <strong>#{revision}</strong> from {formatTime(createdAt)}
</span>
<div className="flex shrink-0 gap-2">
<button type="button" className="btn btn-ghost btn-xs" onClick={onBackToCurrent}>
Back to current
</button>
<button
type="button"
className="btn btn-warning btn-xs"
disabled={revert.isPending}
onClick={() => setConfirmOpen(true)}
>
Revert
</button>
</div>
</div>
<ConfirmDialog
open={confirmOpen}
title={`Revert to revision #${revision}?`}
message={`This replaces the live workflow with revision #${revision} from ${formatTime(createdAt)} and creates a new revision.`}
confirmLabel="Revert"
pending={revert.isPending}
onCancel={() => setConfirmOpen(false)}
onConfirm={() => doRevert(false)}
/>
{warnings ? (
<SaveWorkflowWarningsDialog
warnings={warnings.items}
pending={revert.isPending}
onCancel={() => setWarnings(null)}
onSaveAnyway={() => doRevert(true)}
/>
) : null}
</>
);
}
export { ConfirmDialog };
+16
View File
@@ -3,12 +3,28 @@
themes: light --default, dark --prefersdark;
}
@property --value {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
html,
body,
#root {
min-height: 100%;
}
.radial-progress {
transition:
--value 0.7s ease-out,
--radialprogress 0.7s ease-out;
}
.radial-progress::after {
transition: transform 0.7s ease-out;
}
.mermaid-clickable [id^="s"] {
cursor: pointer;
}
+31
View File
@@ -0,0 +1,31 @@
export function formatBytes(bytes) {
const n = Number(bytes);
if (!Number.isFinite(n)) return "—";
if (n === 0) return "0 KB";
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}
export function formatCpu(cpu) {
const n = Number(cpu);
if (!Number.isFinite(n)) return "—";
return `${n.toFixed(1)}%`;
}
/** Compact duration from milliseconds (e.g. `850ms`, `12s`, `5m 3s`, `2h 15m`, `3d 4h`). */
export function formatDuration(ms) {
const n = Number(ms);
if (!Number.isFinite(n) || n < 0) return "—";
if (n < 1000) return `${Math.round(n)}ms`;
const sec = Math.floor(n / 1000);
if (sec < 60) return `${sec}s`;
const min = Math.floor(sec / 60);
const s = sec % 60;
if (min < 60) return s ? `${min}m ${s}s` : `${min}m`;
const hr = Math.floor(min / 60);
const m = min % 60;
if (hr < 48) return m ? `${hr}h ${m}m` : `${hr}h`;
const days = Math.floor(hr / 24);
const h = hr % 24;
return h ? `${days}d ${h}h` : `${days}d`;
}
+2 -2
View File
@@ -291,7 +291,7 @@ function normalizeTrigger(raw) {
? ""
: String(raw.onConsecutiveFailures),
onFailureWorkflow: readOnFailureWorkflow(raw),
auth: raw.auth ?? null,
auth: Array.isArray(raw.auth) ? raw.auth : null,
response: typeof raw.response === "string" ? raw.response : "",
unauthorized: raw.unauthorized ?? null,
extra: Object.keys(extra).length ? extra : undefined,
@@ -345,7 +345,7 @@ function dumpTrigger(t) {
method: t.method || "POST",
path: t.path || "/",
};
if (t.auth != null && t.auth !== false && t.auth !== "") out.auth = t.auth;
if (Array.isArray(t.auth) && t.auth.length > 0) out.auth = t.auth;
if (t.response) out.response = t.response;
if (t.unauthorized != null && t.unauthorized !== "") out.unauthorized = t.unauthorized;
dumpFailureTriggerFields(t, out);
+70 -366
View File
@@ -1,163 +1,16 @@
import { useState } from "react";
import { LuEye, LuEyeOff, LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { LuEye, LuEyeOff, LuPencil, LuPlus, LuTrash2 } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
fetchHttpAuthLiterals,
useDeleteHttpAuth,
useHttpAuths,
useHttpPages,
useUpsertHttpAuth,
} from "../api/hooks.js";
import { AuthEditorModal } from "../components/AuthEditorModal.jsx";
import { formatTime } from "../lib/format.jsx";
function emptyCred(source = "literal") {
return { source, value: "", kv: "", namespace: "", secret: "" };
}
function credFromPublic(field, literalValue) {
if (!field || field.source === "missing") return emptyCred("literal");
if (field.source === "kv") {
return {
source: "kv",
value: "",
kv: field.kv ?? "",
namespace: field.namespace ?? "",
secret: "",
};
}
if (field.source === "secret") {
return {
source: "secret",
value: "",
kv: "",
namespace: "",
secret: field.secret ?? "",
};
}
// literal — prefer revealed value when available
if (typeof literalValue === "string") {
return {
source: "literal",
value: literalValue,
kv: "",
namespace: "",
secret: "",
keep: true,
};
}
return {
source: "literal",
value: "",
kv: "",
namespace: "",
secret: "",
keep: field.set === true,
};
}
function toApiField(cred, { required = true } = {}) {
if (cred.source === "kv") {
const out = { kv: cred.kv };
if (cred.namespace) out.namespace = cred.namespace;
return out;
}
if (cred.source === "secret") {
return { secret: cred.secret };
}
if (cred.value) return cred.value;
if (cred.keep) return { keep: true };
if (!required) return "";
return null;
}
function CredentialFields({ label, cred, onChange, allowEmpty, masked }) {
const [show, setShow] = useState(false);
return (
<div className="space-y-1 border-base-300 border rounded-box p-3">
<label className="label py-0">{label}</label>
<select
className="select select-sm w-full"
value={cred.source}
onChange={(e) => onChange({ ...cred, source: e.target.value, keep: false })}
>
<option value="literal">Plain text</option>
<option value="kv">From KV</option>
<option value="secret">From secret</option>
</select>
{cred.source === "literal" ? (
<>
<div className="flex gap-1 items-center">
<input
type={masked && !show ? "password" : "text"}
className="input input-sm w-full font-mono"
value={cred.value}
onChange={(e) => onChange({ ...cred, value: e.target.value, keep: false })}
placeholder={
cred.keep && !cred.value ? "(unchanged — leave blank to keep)" : ""
}
required={!allowEmpty && !cred.keep && !cred.value}
autoComplete="off"
/>
{masked ? (
<button
type="button"
className="btn btn-ghost btn-sm btn-square"
title={show ? "Hide" : "Reveal"}
aria-label={show ? "Hide value" : "Reveal value"}
onClick={() => setShow((v) => !v)}
>
{show ? <LuEyeOff className="size-4" /> : <LuEye className="size-4" />}
</button>
) : null}
</div>
{cred.keep && !cred.value ? (
<p className="text-xs opacity-60">
A value is already set. Enter a new one to replace it.
</p>
) : null}
</>
) : null}
{cred.source === "kv" ? (
<div className="flex flex-col sm:flex-row gap-2">
<input
className="input input-sm w-full font-mono"
placeholder="namespace (optional)"
value={cred.namespace}
onChange={(e) => onChange({ ...cred, namespace: e.target.value })}
/>
<input
className="input input-sm w-full font-mono"
placeholder="key"
value={cred.kv}
onChange={(e) => onChange({ ...cred, kv: e.target.value })}
required
/>
</div>
) : null}
{cred.source === "secret" ? (
<>
<input
className="input input-sm w-full font-mono"
placeholder="secret name"
value={cred.secret}
onChange={(e) => onChange({ ...cred, secret: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
/>
<p className="text-xs opacity-60">
Encrypted secret — value is never shown here. Manage it on the Secrets page.
</p>
</>
) : null}
</div>
);
}
/**
* List cell: literals show *** with reveal; secrets never reveal; kv shows ref only.
*/
function CredDisplay({ field, fieldKey, authName, cache, onRevealed }) {
function CredDisplay({ field, fieldKey, authId, cache, onRevealed }) {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
@@ -181,7 +34,6 @@ function CredDisplay({ field, fieldKey, authName, cache, onRevealed }) {
return <span className="font-mono text-xs">{ref}</span>;
}
// literal
const revealed = cache?.[fieldKey];
const shown = open && typeof revealed === "string";
@@ -197,7 +49,7 @@ function CredDisplay({ field, fieldKey, authName, cache, onRevealed }) {
setLoading(true);
setError(null);
try {
const data = await fetchHttpAuthLiterals(authName);
const data = await fetchHttpAuthLiterals(authId);
onRevealed?.(data.literals ?? {});
setOpen(true);
} catch (err) {
@@ -241,7 +93,7 @@ function CredentialsCell({ auth, cache, onRevealed }) {
<CredDisplay
field={cfg.token}
fieldKey="token"
authName={auth.name}
authId={auth.id}
cache={cache}
onRevealed={onRevealed}
/>
@@ -255,7 +107,7 @@ function CredentialsCell({ auth, cache, onRevealed }) {
<CredDisplay
field={cfg.user}
fieldKey="user"
authName={auth.name}
authId={auth.id}
cache={cache}
onRevealed={onRevealed}
/>
@@ -265,7 +117,7 @@ function CredentialsCell({ auth, cache, onRevealed }) {
<CredDisplay
field={cfg.password}
fieldKey="password"
authName={auth.name}
authId={auth.id}
cache={cache}
onRevealed={onRevealed}
/>
@@ -279,7 +131,7 @@ function CredentialsCell({ auth, cache, onRevealed }) {
<CredDisplay
field={cfg.value}
fieldKey="value"
authName={auth.name}
authId={auth.id}
cache={cache}
onRevealed={onRevealed}
/>
@@ -287,122 +139,70 @@ function CredentialsCell({ auth, cache, onRevealed }) {
);
}
const emptyForm = () => ({
name: "",
type: "bearer",
token: emptyCred(),
user: emptyCred(),
password: emptyCred(),
header: "",
value: emptyCred(),
unauthorized_status: "",
unauthorized_response: "",
});
export function AuthProfilesPage() {
const navigate = useNavigate();
const location = useLocation();
const { name: routeName } = useParams();
const isNewRoute = /\/auth\/new\/?$/.test(location.pathname);
const isEditRoute = Boolean(routeName) && !isNewRoute;
const { data: auths = [], isLoading } = useHttpAuths();
const { data: pages = [] } = useHttpPages();
const upsert = useUpsertHttpAuth();
const del = useDeleteHttpAuth();
const [mode, setMode] = useState(null);
const [form, setForm] = useState(emptyForm);
const [editor, setEditor] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
/** @type {[Record<string, Record<string, string>>, Function]} */
const [revealCache, setRevealCache] = useState({});
const [editLoading, setEditLoading] = useState(false);
const openedRouteKey = useRef(null);
function openAdd() {
setMode("add");
setForm(emptyForm());
}
async function openEdit(a) {
setEditLoading(true);
/** @type {Record<string, string>} */
let literals = {};
try {
const data = await fetchHttpAuthLiterals(a.name);
literals = data.literals ?? {};
setRevealCache((prev) => ({ ...prev, [a.name]: literals }));
} catch {
// keep empty; form still works with keep markers
} finally {
setEditLoading(false);
function closeEditor() {
setEditor(null);
openedRouteKey.current = null;
if (isNewRoute || isEditRoute) {
navigate("/auth", { replace: true });
}
const cfg = a.config ?? {};
setMode("edit");
setForm({
name: a.name,
type: a.type,
token: credFromPublic(cfg.token, literals.token),
user: credFromPublic(cfg.user, literals.user),
password: credFromPublic(cfg.password, literals.password),
header: cfg.header ?? "",
value: credFromPublic(cfg.value, literals.value),
unauthorized_status: a.unauthorized_status ?? "",
unauthorized_response: a.unauthorized_response ?? "",
});
}
function closeForm() {
setMode(null);
setForm(emptyForm());
}
useEffect(() => {
if (!isNewRoute) return;
if (openedRouteKey.current === "new") return;
openedRouteKey.current = "new";
setEditor({ mode: "add" });
}, [isNewRoute]);
function onSubmit(e) {
e.preventDefault();
/** @type {Record<string, unknown>} */
let config = {};
if (form.type === "bearer") {
const token = toApiField(form.token);
if (token == null) return;
config = { token };
} else if (form.type === "basic") {
const user = toApiField(form.user);
if (user == null) return;
const password = toApiField(form.password, { required: false });
config = { user, password: password ?? "" };
} else {
const value = toApiField(form.value);
if (value == null) return;
config = { header: form.header, value };
useEffect(() => {
if (!isEditRoute) {
if (!isNewRoute) openedRouteKey.current = null;
return;
}
upsert.mutate(
{
name: form.name,
type: form.type,
config,
unauthorized_status:
form.unauthorized_status === "" ? null : Number(form.unauthorized_status),
unauthorized_response: form.unauthorized_response || null,
},
{
onSuccess: () => {
setRevealCache((prev) => {
const next = { ...prev };
delete next[form.name];
return next;
});
closeForm();
},
},
);
}
if (isLoading) return;
const key = `edit:${routeName}`;
if (openedRouteKey.current === key) return;
openedRouteKey.current = key;
const auth = auths.find((a) => a.name === routeName);
if (!auth) {
setEditor({ mode: "add" });
return;
}
setEditor({ mode: "edit", auth });
}, [isEditRoute, isNewRoute, routeName, isLoading, auths]);
return (
<div className="space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Auth</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() => navigate("/auth/new")}
>
<LuPlus className="size-4" />
Add
</button>
</div>
<p className="text-sm opacity-70">
Named HTTP trigger auth profiles. Reference in YAML as{" "}
<code className="font-mono text-xs">auth: name</code>. Secrets are managed on the Secrets
page; KV values stay in KV.
HTTP trigger auth profiles. Rename freely — workflows keep working via a stable id.
Add them to a trigger from the workflow editor dropdown. Secrets are managed on the
Secrets page; KV values stay in KV.
</p>
{isLoading ? (
@@ -429,9 +229,9 @@ export function AuthProfilesPage() {
<td>
<CredentialsCell
auth={a}
cache={revealCache[a.name]}
cache={revealCache[a.id]}
onRevealed={(literals) =>
setRevealCache((prev) => ({ ...prev, [a.name]: literals }))
setRevealCache((prev) => ({ ...prev, [a.id]: literals }))
}
/>
</td>
@@ -441,8 +241,7 @@ export function AuthProfilesPage() {
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
disabled={editLoading}
onClick={() => openEdit(a)}
onClick={() => navigate(`/auth/${encodeURIComponent(a.name)}/edit`)}
>
<LuPencil className="size-4" />
</button>
@@ -462,116 +261,21 @@ export function AuthProfilesPage() {
</div>
)}
{mode ? (
<form
onSubmit={onSubmit}
className="fieldset bg-base-100 border-base-300 rounded-box max-w-xl border p-4 space-y-2"
>
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New auth profile" : `Edit ${form.name}`}
</legend>
<button
type="button"
className="btn btn-ghost btn-sm btn-square"
onClick={closeForm}
aria-label="Close"
>
<LuX className="size-4" />
</button>
</div>
<label className="label">Name</label>
<input
className="input w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
disabled={mode === "edit"}
/>
<label className="label">Type</label>
<select
className="select w-full"
value={form.type}
onChange={(e) => setForm({ ...form, type: e.target.value })}
>
<option value="bearer">bearer</option>
<option value="basic">basic</option>
<option value="header">header</option>
</select>
{form.type === "bearer" ? (
<CredentialFields
label="Token"
cred={form.token}
onChange={(token) => setForm({ ...form, token })}
/>
) : null}
{form.type === "basic" ? (
<>
<CredentialFields
label="User"
cred={form.user}
onChange={(user) => setForm({ ...form, user })}
/>
<CredentialFields
label="Password"
cred={form.password}
onChange={(password) => setForm({ ...form, password })}
allowEmpty
masked
/>
</>
) : null}
{form.type === "header" ? (
<>
<label className="label">Header name</label>
<input
className="input w-full font-mono"
value={form.header}
onChange={(e) => setForm({ ...form, header: e.target.value })}
required
placeholder="X-Webhook-Secret"
/>
<CredentialFields
label="Header value"
cred={form.value}
onChange={(value) => setForm({ ...form, value })}
/>
</>
) : null}
<label className="label">Unauthorized status (optional)</label>
<input
type="number"
className="input w-full"
value={form.unauthorized_status}
onChange={(e) => setForm({ ...form, unauthorized_status: e.target.value })}
min={100}
max={599}
placeholder="401"
/>
<label className="label">Unauthorized response page (optional)</label>
<select
className="select w-full"
value={form.unauthorized_response}
onChange={(e) => setForm({ ...form, unauthorized_response: e.target.value })}
>
<option value="">(default JSON)</option>
{pages.map((p) => (
<option key={p.id} value={p.name}>
{p.name}
</option>
))}
</select>
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={upsert.isPending}>
Save
</button>
</form>
{editor ? (
<AuthEditorModal
mode={editor.mode}
auth={editor.auth}
onClose={closeEditor}
onSaved={(saved) => {
const id = saved?.id || editor.auth?.id;
if (!id) return;
setRevealCache((prev) => {
const next = { ...prev };
delete next[id];
return next;
});
}}
/>
) : null}
{confirmDelete ? (
+159
View File
@@ -0,0 +1,159 @@
import { useState } from "react";
import { LuDownload, LuUpload } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDownloadWorkflowBackup,
useRestoreWorkflowBackup,
} from "../api/hooks.js";
import { useNotifications } from "../notifications.jsx";
export function BackupPage() {
const backup = useDownloadWorkflowBackup();
const restoreBackup = useRestoreWorkflowBackup();
const { notify } = useNotifications();
const [restoreMode, setRestoreMode] = useState("merge");
const [pendingFile, setPendingFile] = useState(null);
function download() {
backup.mutate(undefined, {
onSuccess: () => notify.success("Backup downloaded"),
onError: (err) => notify.error(errorMessage(err)),
});
}
function restore(file, mode) {
restoreBackup.mutate(
{ file, mode },
{
onSuccess: (data) => {
notify.success("Backup restored");
if (data.warnings?.length) {
notify.warning(data.warnings.join("; "));
}
},
onError: (err) => notify.error(errorMessage(err)),
onSettled: () => setPendingFile(null),
},
);
}
function onPickFile(e) {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
if (restoreMode === "replace") {
setPendingFile(file);
return;
}
restore(file, restoreMode);
}
return (
<div className="mx-auto max-w-3xl space-y-6">
<div>
<h1 className="text-xl font-semibold">Backup</h1>
<p className="text-sm opacity-70">
Download or restore workflows and installed plugins as a zip archive.
</p>
</div>
<section className="card bg-base-100 border border-base-300">
<div className="card-body gap-3">
<h2 className="card-title text-base">Download</h2>
<p className="text-sm opacity-70">
Includes workflow YAML and installed plugins. Use this to copy the
setup to another machine or keep a snapshot before a restore.
</p>
<div>
<button
type="button"
className="btn btn-primary btn-sm"
disabled={backup.isPending}
onClick={download}
>
{backup.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuDownload className="size-4" />
)}
Download backup
</button>
</div>
</div>
</section>
<section className="card bg-base-100 border border-base-300">
<div className="card-body gap-3">
<h2 className="card-title text-base">Restore</h2>
<p className="text-sm opacity-70">
Merge keeps existing files and overwrites matches from the zip.
Replace deletes current workflows and plugins first.
</p>
<div className="flex flex-wrap items-center gap-2">
<select
className="select select-bordered select-sm"
value={restoreMode}
onChange={(e) => setRestoreMode(e.target.value)}
aria-label="Restore mode"
>
<option value="merge">Merge</option>
<option value="replace">Replace</option>
</select>
<label
className={`btn btn-sm ${restoreBackup.isPending ? "btn-disabled" : ""}`}
>
{restoreBackup.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuUpload className="size-4" />
)}
Restore from zip
<input
type="file"
accept=".zip,application/zip"
className="hidden"
disabled={restoreBackup.isPending}
onChange={onPickFile}
/>
</label>
</div>
</div>
</section>
{pendingFile ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Replace with this backup?</h3>
<p className="mt-2 text-sm opacity-70">
Current workflows and plugins will be deleted, then{" "}
<span className="font-mono">{pendingFile.name}</span> will be
restored. This cannot be undone from this page.
</p>
<div className="modal-action">
<button
type="button"
className="btn btn-ghost"
onClick={() => setPendingFile(null)}
>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={restoreBackup.isPending}
onClick={() => restore(pendingFile, "replace")}
>
Replace
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setPendingFile(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+7 -1
View File
@@ -103,6 +103,12 @@ export function EventDetailPage() {
<dt className="opacity-60">Duration</dt>
<dd>{run.duration_ms != null ? `${run.duration_ms}ms` : "—"}</dd>
</div>
<div>
<dt className="opacity-60">Revision</dt>
<dd>
{run.workflow_revision != null ? `#${run.workflow_revision}` : "unknown version"}
</dd>
</div>
</dl>
{run.error ? (
@@ -111,7 +117,7 @@ export function EventDetailPage() {
</div>
) : null}
<div className="grid gap-2 sm:grid-cols-2">
<div className="grid gap-2 sm:grid-cols-3">
<JsonViewBlock title="Run input (data)" value={run.input} />
<JsonViewBlock title="Run output" value={runParts.output} />
<JsonViewBlock title="Run context" value={runParts.context} />
+4
View File
@@ -50,6 +50,7 @@ export function EventsPage() {
<tr>
<th>Status</th>
<th>Workflow</th>
<th>Revision</th>
<th>Trigger</th>
<th>Started</th>
<th>Duration</th>
@@ -66,6 +67,9 @@ export function EventsPage() {
{r.workflow_name || r.workflow}
</Link>
</td>
<td className="text-xs opacity-70">
{r.workflow_revision != null ? `#${r.workflow_revision}` : "unknown"}
</td>
<td className="text-xs">
{r.trigger_type}
{r.trigger_detail ? ` · ${r.trigger_detail}` : ""}
+82 -239
View File
@@ -1,9 +1,9 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import {
useOpsBumpGeneration,
useOpsHttpStart,
useOpsHttpStop,
useOpsPause,
useOpsProcessRestart,
useOpsReload,
useOpsRestart,
useOpsResume,
@@ -11,11 +11,20 @@ import {
useOpsStatus,
} from "../api/hooks.js";
import { errorMessage } from "../api/client.js";
import { HttpProcessCard } from "../components/HttpProcessCard.jsx";
import { QueueCard } from "../components/QueueCard.jsx";
import { ProcessResourcesCard } from "../components/ProcessResourcesCard.jsx";
import { HeartbeatsAndPm2Card } from "../components/HeartbeatsAndPm2Card.jsx";
import { useNotifications } from "../notifications.jsx";
const MAX_WORKERS = 32;
function Stat({ label, value }) {
return (
<div className="flex flex-col gap-0.5">
<span className="text-xs uppercase tracking-wide opacity-60">{label}</span>
<span className="text-xs uppercase tracking-wide opacity-60">
{label}
</span>
<span className="font-mono text-sm">{value}</span>
</div>
);
@@ -30,10 +39,10 @@ export function OpsPage() {
const scale = useOpsScale();
const httpStart = useOpsHttpStart();
const httpStop = useOpsHttpStop();
const bump = useOpsBumpGeneration();
const [workerCount, setWorkerCount] = useState("");
const [msg, setMsg] = useState(null);
const [err, setErr] = useState(null);
const processRestart = useOpsProcessRestart();
const { notify } = useNotifications();
const [workerCount, setWorkerCount] = useState(1);
const [workerInit, setWorkerInit] = useState(false);
const unavailable =
status.isError &&
@@ -41,21 +50,40 @@ export function OpsPage() {
status.error?.response?.status === 404 ||
status.error?.message?.includes("Network"));
const data = status.data;
const desired = data?.desired;
const queue = data?.queue;
const children = data?.children;
const httpOnline = Boolean(children?.httpOnline);
useEffect(() => {
if (!workerInit && desired?.workers != null) {
setWorkerCount(desired.workers);
setWorkerInit(true);
}
}, [desired?.workers, workerInit]);
function run(label, mutateAsync, args) {
setMsg(null);
setErr(null);
mutateAsync(args)
.then((data) => {
setMsg(`${label} ok`);
return data;
const call = args === undefined ? mutateAsync() : mutateAsync(args);
call
.then((result) => {
notify.success(`${label} ok`);
return result;
})
.catch((e) => setErr(errorMessage(e, `${label} failed`)));
.catch((e) => notify.error(errorMessage(e, `${label} failed`)));
}
function scaleWorkers() {
run("Scale", scale.mutateAsync, {
workers: workerCount,
force: false,
});
}
if (unavailable) {
return (
<div className="mx-auto max-w-3xl space-y-4">
<h1 className="text-2xl font-semibold">Ops</h1>
<h1 className="text-2xl font-semibold">Manage</h1>
<div className="alert alert-warning">
<span>
Control plane is not reachable on <code>/ops</code>. Use{" "}
@@ -68,20 +96,11 @@ export function OpsPage() {
);
}
const data = status.data;
const desired = data?.desired;
const queue = data?.queue;
const children = data?.children;
return (
<div className="mx-auto max-w-4xl space-y-6">
<div className="mx-auto space-y-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-2xl font-semibold">Ops</h1>
<p className="text-sm opacity-70">
Process control via PM2. Pause stops workers from opening jobs;
cron/HTTP can still enqueue. Restart drains active jobs unless forced.
</p>
<h1 className="text-2xl font-semibold">Manage</h1>
</div>
<button
type="button"
@@ -102,226 +121,50 @@ export function OpsPage() {
</div>
) : null}
{msg ? (
<div className="alert alert-success text-sm">
<span>{msg}</span>
</div>
) : null}
{err ? (
<div className="alert alert-error text-sm">
<span>{err}</span>
</div>
) : null}
{status.isLoading && !data ? (
<span className="loading loading-spinner" />
) : (
<>
<section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Stat label="HTTP desired" value={desired?.http ?? "—"} />
<Stat label="Workers desired" value={desired?.workers ?? "—"} />
<Stat label="Generation" value={desired?.generation ?? "—"} />
<Stat
label="Queue"
value={queue?.paused ? "paused" : "running"}
<div className="grid gap-6 md:grid-cols-3">
<HttpProcessCard
httpOnline={httpOnline}
startPending={httpStart.isPending}
stopPending={httpStop.isPending}
onStart={() => run("HTTP start", httpStart.mutateAsync)}
onStop={() => run("HTTP stop", httpStop.mutateAsync)}
/>
<Stat
label="Active jobs"
value={queue?.counts?.active ?? "—"}
<QueueCard
paused={Boolean(queue?.paused)}
workersOnline={Number(children?.workerOnlineCount) || 0}
activeJobs={Number(queue?.counts?.active) || 0}
queuedJobs={
(Number(queue?.counts?.waiting) || 0) +
(Number(queue?.counts?.delayed) || 0)
}
pausePending={pause.isPending}
resumePending={resume.isPending}
onPause={() => run("Pause", pause.mutateAsync)}
onResume={() => run("Resume", resume.mutateAsync)}
/>
<Stat
label="Waiting jobs"
value={queue?.counts?.waiting ?? "—"}
/>
<Stat
label="HTTP online"
value={children?.httpOnline ? "yes" : "no"}
/>
<Stat
label="Workers online"
value={children?.workerOnlineCount ?? "—"}
/>
</section>
<ProcessResourcesCard children={children} />
</div>
<section className="space-y-2">
<h2 className="text-lg font-medium">Queue</h2>
<div className="flex flex-wrap gap-2">
<button
type="button"
className={`btn btn-sm ${queue?.paused ? "btn-disabled" : ""}`}
disabled={pause.isPending || Boolean(queue?.paused)}
onClick={() => run("Pause", pause.mutateAsync)}
>
Pause workers
</button>
<button
type="button"
className={`btn btn-sm ${!queue?.paused ? "btn-disabled" : ""}`}
disabled={resume.isPending || !queue?.paused}
onClick={() => run("Resume", resume.mutateAsync)}
>
Resume workers
</button>
<button
type="button"
className="btn btn-sm"
disabled={reload.isPending}
onClick={() => run("Reload", reload.mutateAsync)}
>
Reload workflows
</button>
</div>
</section>
<section className="space-y-2">
<h2 className="text-lg font-medium">HTTP process</h2>
<div className="flex flex-wrap gap-2">
<button
type="button"
className="btn btn-sm btn-primary"
disabled={httpStart.isPending}
onClick={() => run("HTTP start", httpStart.mutateAsync)}
>
Start HTTP
</button>
<button
type="button"
className="btn btn-sm btn-warning"
disabled={httpStop.isPending}
onClick={() => run("HTTP stop", httpStop.mutateAsync)}
>
Stop HTTP
</button>
</div>
</section>
<section className="space-y-2">
<h2 className="text-lg font-medium">Workers</h2>
<div className="flex flex-wrap items-center gap-2">
<input
type="number"
min={0}
max={32}
className="input input-bordered input-sm w-24"
placeholder={String(desired?.workers ?? 1)}
value={workerCount}
onChange={(e) => setWorkerCount(e.target.value)}
/>
<button
type="button"
className="btn btn-sm"
disabled={scale.isPending || workerCount === ""}
onClick={() =>
run("Scale", scale.mutateAsync, {
workers: Number(workerCount),
force: false,
})
}
>
Scale (drain)
</button>
<button
type="button"
className="btn btn-sm btn-warning"
disabled={scale.isPending || workerCount === ""}
onClick={() =>
run("Scale force", scale.mutateAsync, {
workers: Number(workerCount),
force: true,
})
}
>
Scale (force)
</button>
</div>
</section>
<section className="space-y-2">
<h2 className="text-lg font-medium">Restart HTTP + workers</h2>
<p className="text-sm opacity-70">
Pauses the queue, waits until active jobs are 0, migrates DB, then
recreates PM2 processes. Force skips the wait (may interrupt runs).
</p>
<div className="flex flex-wrap gap-2">
<button
type="button"
className="btn btn-sm btn-primary"
disabled={restart.isPending}
onClick={() => run("Restart", restart.mutateAsync, { force: false })}
>
Drain restart
</button>
<button
type="button"
className="btn btn-sm btn-error"
disabled={restart.isPending}
onClick={() => {
if (
!window.confirm(
"Force restart will interrupt active jobs. Continue?",
)
) {
return;
}
run("Force restart", restart.mutateAsync, { force: true });
}}
>
Force restart
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={bump.isPending}
onClick={() =>
run("Bump generation", bump.mutateAsync, "manual test flag")
}
>
Flag restart-needed
</button>
</div>
</section>
<section className="space-y-2">
<h2 className="text-lg font-medium">Heartbeats</h2>
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Role</th>
<th>PID</th>
<th>Generation</th>
<th>Age (ms)</th>
</tr>
</thead>
<tbody>
{(data?.heartbeats ?? []).map((h) => (
<tr key={h.field}>
<td>{h.role}</td>
<td className="font-mono">{h.pid}</td>
<td className="font-mono">{h.generation}</td>
<td className="font-mono">
{Math.max(0, Date.now() - h.ts)}
</td>
</tr>
))}
{!data?.heartbeats?.length ? (
<tr>
<td colSpan={4} className="opacity-60">
No live heartbeats yet
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
<section className="space-y-2">
<h2 className="text-lg font-medium">PM2 children</h2>
<pre className="bg-base-200 max-h-64 overflow-auto rounded-lg p-3 text-xs">
{JSON.stringify(children ?? {}, null, 2)}
</pre>
</section>
<HeartbeatsAndPm2Card
data={data}
children={children}
restart={restart}
processRestart={processRestart}
workerCount={workerCount}
desiredWorkers={Number(desired?.workers) || 0}
onDecreaseWorkers={() => setWorkerCount((n) => Math.max(0, n - 1))}
onIncreaseWorkers={() =>
setWorkerCount((n) => Math.min(MAX_WORKERS, n + 1))
}
onScale={scaleWorkers}
scalePending={scale.isPending}
onReload={() => run("Reload", reload.mutateAsync)}
reloadPending={reload.isPending}
/>
</>
)}
</div>
+137 -140
View File
@@ -1,54 +1,80 @@
import { useState } from "react";
import { LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { LuPencil, LuPlus, LuTrash2 } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteSecret,
useOwners,
useSecrets,
useUpsertSecret,
} from "../api/hooks.js";
import { useDeleteSecret, useOwners, useSecrets } from "../api/hooks.js";
import { SecretEditorModal } from "../components/SecretEditorModal.jsx";
import { formatTime } from "../lib/format.jsx";
export function SecretsPage() {
const navigate = useNavigate();
const location = useLocation();
const { owner: routeOwner, name: routeName } = useParams();
const [params] = useSearchParams();
const isNewRoute = /\/secrets\/new\/?$/.test(location.pathname);
const isEditRoute = Boolean(routeOwner && routeName);
const { data: owners = [] } = useOwners();
const [ownerFilter, setOwnerFilter] = useState("");
const [ownerFilter, setOwnerFilter] = useState(
() => routeOwner || params.get("owner") || "",
);
const { data: secrets = [], isLoading } = useSecrets(ownerFilter || undefined);
const upsert = useUpsertSecret();
const del = useDeleteSecret();
const [mode, setMode] = useState(null);
const [form, setForm] = useState({
owner: "",
name: "",
value: "",
});
const [editor, setEditor] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
const [highlightName, setHighlightName] = useState(() => routeName || "");
const highlightRef = useRef(null);
const openedRouteKey = useRef(null);
function openAdd() {
setMode("add");
setForm({
owner: ownerFilter || owners[0] || "default",
name: "",
value: "",
const listPath = ownerFilter
? `/secrets?owner=${encodeURIComponent(ownerFilter)}`
: "/secrets";
function closeEditor() {
setEditor(null);
openedRouteKey.current = null;
if (isNewRoute || isEditRoute) {
navigate(listPath, { replace: true });
}
}
useEffect(() => {
if (!isNewRoute) return;
const key = `new:${params.get("owner") || ""}:${params.get("name") || ""}`;
if (openedRouteKey.current === key) return;
if (!params.get("owner") && !ownerFilter && owners.length === 0) return;
const owner = params.get("owner") || ownerFilter || owners[0] || "default";
if (params.get("owner")) setOwnerFilter(params.get("owner"));
openedRouteKey.current = key;
setEditor({
mode: "add",
initial: { owner, name: params.get("name") || "" },
});
}
}, [isNewRoute, params, owners, ownerFilter]);
function openReplace(s) {
setMode("replace");
setForm({ owner: s.owner, name: s.name, value: "" });
}
useEffect(() => {
if (!isEditRoute) {
if (!isNewRoute) openedRouteKey.current = null;
return;
}
if (ownerFilter !== routeOwner) {
setOwnerFilter(routeOwner);
return;
}
const key = `edit:${routeOwner}/${routeName}`;
if (openedRouteKey.current === key) return;
openedRouteKey.current = key;
setHighlightName(routeName);
setEditor({
mode: "replace",
initial: { owner: routeOwner, name: routeName },
});
}, [isEditRoute, isNewRoute, routeOwner, routeName, ownerFilter]);
function closeForm() {
setMode(null);
setForm({ owner: "", name: "", value: "" });
}
function onSubmit(e) {
e.preventDefault();
upsert.mutate(
{ owner: form.owner, name: form.name, value: form.value },
{ onSuccess: closeForm },
);
}
useEffect(() => {
if (!highlightName || isLoading) return;
highlightRef.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, [highlightName, isLoading, secrets]);
return (
<div className="space-y-4">
@@ -58,7 +84,16 @@ export function SecretsPage() {
<select
className="select select-sm"
value={ownerFilter}
onChange={(e) => setOwnerFilter(e.target.value)}
onChange={(e) => {
setOwnerFilter(e.target.value);
setHighlightName("");
navigate(
e.target.value
? `/secrets?owner=${encodeURIComponent(e.target.value)}`
: "/secrets",
{ replace: true },
);
}}
>
<option value="">all owners</option>
{owners.map((o) => (
@@ -67,7 +102,17 @@ export function SecretsPage() {
</option>
))}
</select>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() =>
navigate(
ownerFilter
? `/secrets/new?owner=${encodeURIComponent(ownerFilter)}`
: "/secrets/new",
)
}
>
<LuPlus className="size-4" />
Add
</button>
@@ -90,109 +135,59 @@ export function SecretsPage() {
</tr>
</thead>
<tbody>
{secrets.map((s) => (
<tr key={s.id} className="hover">
<td className="font-mono">{s.owner}</td>
<td className="font-mono">{s.name}</td>
<td className="whitespace-nowrap">{formatTime(s.updated_at)}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Replace value"
onClick={() => openReplace(s)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(s)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
{secrets.map((s) => {
const highlighted =
highlightName &&
s.name === highlightName &&
(!ownerFilter || s.owner === ownerFilter);
return (
<tr
key={s.id}
ref={highlighted ? highlightRef : undefined}
className={`hover ${highlighted ? "bg-primary/10 outline outline-1 outline-primary/40" : ""}`}
>
<td className="font-mono">{s.owner}</td>
<td className="font-mono">{s.name}</td>
<td className="whitespace-nowrap">{formatTime(s.updated_at)}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Replace value"
onClick={() =>
navigate(
`/secrets/${encodeURIComponent(s.owner)}/${encodeURIComponent(s.name)}/edit`,
)
}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(s)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{mode ? (
<form
onSubmit={onSubmit}
className="fieldset bg-base-100 border-base-300 rounded-box max-w-md border p-4"
>
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New secret" : `Replace ${form.owner}/${form.name}`}
</legend>
<button
type="button"
className="btn btn-ghost btn-sm btn-square"
onClick={closeForm}
aria-label="Close"
>
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<>
<label className="label">Owner</label>
{owners.length > 0 ? (
<select
className="select w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
>
{owners.map((o) => (
<option key={o} value={o}>
{o}
</option>
))}
</select>
) : (
<input
className="input w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
/>
)}
<label className="label">Name</label>
<input
className="input w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
title="Letters, numbers, dots, underscores, hyphens"
/>
</>
) : null}
<label className="label">Value</label>
<input
type="password"
className="input w-full"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
required
autoComplete="new-password"
/>
<p className="text-xs opacity-60 mt-1">
Values are encrypted at rest and never shown again after save.
Values shorter than 8 characters are not redacted from logs.
</p>
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={upsert.isPending}>
Save
</button>
</form>
{editor ? (
<SecretEditorModal
mode={editor.mode}
initial={editor.initial}
onClose={closeEditor}
onSaved={(saved) => {
setHighlightName(saved?.name || editor.initial.name);
}}
/>
) : null}
{confirmDelete ? (
@@ -201,7 +196,9 @@ export function SecretsPage() {
<h3 className="font-bold">
Delete {confirmDelete.owner}/{confirmDelete.name}?
</h3>
<p className="text-sm mt-2">This cannot be undone. Workflows that retrieve this name will fail.</p>
<p className="text-sm mt-2">
This cannot be undone. Workflows that retrieve this name will fail.
</p>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
+55 -96
View File
@@ -1,66 +1,64 @@
import { useState } from "react";
import { LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { LuPencil, LuPlus, LuTrash2 } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useCreateUser,
useDeleteUser,
useUpdateUser,
useUsers,
} from "../api/hooks.js";
import { useDeleteUser, useUsers } from "../api/hooks.js";
import { UserEditorModal } from "../components/UserEditorModal.jsx";
export function UsersPage() {
const navigate = useNavigate();
const location = useLocation();
const { username: routeUsername } = useParams();
const isNewRoute = /\/users\/new\/?$/.test(location.pathname);
const isEditRoute = Boolean(routeUsername) && !isNewRoute;
const { data: users = [], isLoading } = useUsers();
const create = useCreateUser();
const update = useUpdateUser();
const del = useDeleteUser();
const [mode, setMode] = useState(null);
const [form, setForm] = useState({
username: "",
password: "",
role: "operator",
id: null,
});
const [editor, setEditor] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
const openedRouteKey = useRef(null);
function openAdd() {
setMode("add");
setForm({ username: "", password: "", role: "operator", id: null });
}
function openEdit(u) {
setMode("edit");
setForm({ username: u.username, password: "", role: u.role, id: u.id });
}
function closeForm() {
setMode(null);
}
function onSubmit(e) {
e.preventDefault();
if (mode === "add") {
create.mutate(
{
username: form.username,
password: form.password,
role: form.role,
},
{ onSuccess: closeForm },
);
} else {
const body = { id: form.id, role: form.role };
if (form.password) body.password = form.password;
update.mutate(body, { onSuccess: closeForm });
function closeEditor() {
setEditor(null);
openedRouteKey.current = null;
if (isNewRoute || isEditRoute) {
navigate("/users", { replace: true });
}
}
const mutation = mode === "add" ? create : update;
useEffect(() => {
if (!isNewRoute) return;
if (openedRouteKey.current === "new") return;
openedRouteKey.current = "new";
setEditor({ mode: "add" });
}, [isNewRoute]);
useEffect(() => {
if (!isEditRoute) {
if (!isNewRoute) openedRouteKey.current = null;
return;
}
if (isLoading) return;
const key = `edit:${routeUsername}`;
if (openedRouteKey.current === key) return;
openedRouteKey.current = key;
const user = users.find((u) => u.username === routeUsername);
if (!user) {
setEditor({ mode: "add" });
return;
}
setEditor({ mode: "edit", user });
}, [isEditRoute, isNewRoute, routeUsername, isLoading, users]);
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Users</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() => navigate("/users/new")}
>
<LuPlus className="size-4" />
Add
</button>
@@ -90,7 +88,9 @@ export function UsersPage() {
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(u)}
onClick={() =>
navigate(`/users/${encodeURIComponent(u.username)}/edit`)
}
>
<LuPencil className="size-4" />
</button>
@@ -110,53 +110,12 @@ export function UsersPage() {
</div>
)}
{mode ? (
<form onSubmit={onSubmit} className="fieldset bg-base-100 border-base-300 rounded-box max-w-md border p-4">
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New user" : form.username}
</legend>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<>
<label className="label">Username</label>
<input
className="input w-full"
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
required
/>
</>
) : null}
<label className="label">{mode === "add" ? "Password" : "New password"}</label>
<input
type="password"
className="input w-full"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
required={mode === "add"}
minLength={mode === "add" ? 8 : undefined}
placeholder={mode === "edit" ? "leave blank to keep" : ""}
/>
<label className="label">Role</label>
<select
className="select w-full"
value={form.role}
onChange={(e) => setForm({ ...form, role: e.target.value })}
>
<option value="operator">operator</option>
<option value="admin">admin</option>
</select>
{mutation.isError ? (
<p className="text-error text-sm">{errorMessage(mutation.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={mutation.isPending}>
Save
</button>
</form>
{editor ? (
<UserEditorModal
mode={editor.mode}
user={editor.user}
onClose={closeEditor}
/>
) : null}
{confirmDelete ? (
+164 -208
View File
@@ -1,95 +1,110 @@
import { useState } from "react";
import { LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { LuPencil, LuPlus, LuTrash2 } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteVariable,
useOwners,
useUpsertVariable,
useVariables,
} from "../api/hooks.js";
import { useDeleteVariable, useOwners, useVariables } from "../api/hooks.js";
import { VariableEditorModal } from "../components/VariableEditorModal.jsx";
import { formatTime } from "../lib/format.jsx";
const TYPES = ["string", "number", "boolean"];
function defaultValue(type) {
if (type === "boolean") return false;
if (type === "number") return "";
return "";
}
function displayValue(value) {
if (typeof value === "string") return value === "" ? '""' : value;
return String(value);
}
export function VariablesPage() {
const navigate = useNavigate();
const location = useLocation();
const { owner: routeOwner, name: routeName } = useParams();
const [params] = useSearchParams();
const isNewRoute = /\/variables\/new\/?$/.test(location.pathname);
const isEditRoute = Boolean(routeOwner && routeName);
const { data: owners = [] } = useOwners();
const [ownerFilter, setOwnerFilter] = useState("");
const [ownerFilter, setOwnerFilter] = useState(
() => routeOwner || params.get("owner") || "",
);
const { data: variables = [], isLoading } = useVariables(ownerFilter || undefined);
const upsert = useUpsertVariable();
const del = useDeleteVariable();
const [mode, setMode] = useState(null);
const [form, setForm] = useState({
owner: "",
name: "",
type: "string",
value: "",
});
const [formError, setFormError] = useState(null);
const [editor, setEditor] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
const [highlightName, setHighlightName] = useState(() => routeName || "");
const highlightRef = useRef(null);
const openedRouteKey = useRef(null);
function openAdd() {
setMode("add");
setFormError(null);
setForm({
owner: ownerFilter || owners[0] || "default",
name: "",
type: "string",
value: "",
});
}
const listPath = ownerFilter
? `/variables?owner=${encodeURIComponent(ownerFilter)}`
: "/variables";
function openEdit(row) {
setMode("edit");
setFormError(null);
setForm({
owner: row.owner,
name: row.name,
type: row.type,
value: row.type === "number" ? String(row.value) : row.value,
});
}
function closeForm() {
setMode(null);
setFormError(null);
setForm({ owner: "", name: "", type: "string", value: "" });
}
function onTypeChange(type) {
setForm({ ...form, type, value: defaultValue(type) });
}
function onSubmit(e) {
e.preventDefault();
let value = form.value;
if (form.type === "number") {
value = Number(form.value);
if (!Number.isFinite(value)) {
setFormError("value must be a finite number");
return;
}
function closeEditor() {
setEditor(null);
openedRouteKey.current = null;
if (isNewRoute || isEditRoute) {
navigate(listPath, { replace: true });
}
if (form.type === "boolean") {
value = form.value === true;
}
setFormError(null);
upsert.mutate(
{ owner: form.owner, name: form.name, type: form.type, value },
{ onSuccess: closeForm },
);
}
useEffect(() => {
if (!isNewRoute) return;
const key = `new:${params.get("owner") || ""}:${params.get("name") || ""}`;
if (openedRouteKey.current === key) return;
if (!params.get("owner") && !ownerFilter && owners.length === 0) return;
const owner = params.get("owner") || ownerFilter || owners[0] || "default";
if (params.get("owner")) setOwnerFilter(params.get("owner"));
openedRouteKey.current = key;
setEditor({
mode: "add",
initial: {
owner,
name: params.get("name") || "",
type: "string",
value: "",
},
});
}, [isNewRoute, params, owners, ownerFilter]);
useEffect(() => {
if (!isEditRoute) {
if (!isNewRoute) openedRouteKey.current = null;
return;
}
if (ownerFilter !== routeOwner) {
setOwnerFilter(routeOwner);
return;
}
if (isLoading) return;
const key = `edit:${routeOwner}/${routeName}`;
if (openedRouteKey.current === key) return;
openedRouteKey.current = key;
setHighlightName(routeName);
const row = variables.find((v) => v.owner === routeOwner && v.name === routeName);
if (row) {
setEditor({
mode: "edit",
initial: {
owner: row.owner,
name: row.name,
type: row.type,
value: row.value,
},
});
return;
}
setEditor({
mode: "add",
initial: {
owner: routeOwner,
name: routeName,
type: "string",
value: "",
},
});
}, [isEditRoute, isNewRoute, routeOwner, routeName, ownerFilter, isLoading, variables]);
useEffect(() => {
if (!highlightName || isLoading) return;
highlightRef.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, [highlightName, isLoading, variables]);
return (
<div className="space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
@@ -98,7 +113,16 @@ export function VariablesPage() {
<select
className="select select-sm"
value={ownerFilter}
onChange={(e) => setOwnerFilter(e.target.value)}
onChange={(e) => {
setOwnerFilter(e.target.value);
setHighlightName("");
navigate(
e.target.value
? `/variables?owner=${encodeURIComponent(e.target.value)}`
: "/variables",
{ replace: true },
);
}}
>
<option value="">all owners</option>
{owners.map((o) => (
@@ -107,7 +131,17 @@ export function VariablesPage() {
</option>
))}
</select>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() =>
navigate(
ownerFilter
? `/variables/new?owner=${encodeURIComponent(ownerFilter)}`
: "/variables/new",
)
}
>
<LuPlus className="size-4" />
Add
</button>
@@ -132,144 +166,66 @@ export function VariablesPage() {
</tr>
</thead>
<tbody>
{variables.map((row) => (
<tr key={row.id} className="hover">
<td className="font-mono">{row.owner}</td>
<td className="font-mono">{row.name}</td>
<td className="font-mono text-xs">{row.type}</td>
<td className="font-mono text-xs max-w-xs truncate" title={displayValue(row.value)}>
{displayValue(row.value)}
</td>
<td className="whitespace-nowrap">{formatTime(row.updated_at)}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(row)}
{variables.map((row) => {
const highlighted =
highlightName &&
row.name === highlightName &&
(!ownerFilter || row.owner === ownerFilter);
return (
<tr
key={row.id}
ref={highlighted ? highlightRef : undefined}
className={`hover ${highlighted ? "bg-primary/10 outline outline-1 outline-primary/40" : ""}`}
>
<td className="font-mono">{row.owner}</td>
<td className="font-mono">{row.name}</td>
<td className="font-mono text-xs">{row.type}</td>
<td
className="font-mono text-xs max-w-xs truncate"
title={displayValue(row.value)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(row)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
{displayValue(row.value)}
</td>
<td className="whitespace-nowrap">{formatTime(row.updated_at)}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() =>
navigate(
`/variables/${encodeURIComponent(row.owner)}/${encodeURIComponent(row.name)}/edit`,
)
}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(row)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{mode ? (
<form
onSubmit={onSubmit}
className="fieldset bg-base-100 border-base-300 rounded-box max-w-md border p-4"
>
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New variable" : `Edit ${form.owner}/${form.name}`}
</legend>
<button
type="button"
className="btn btn-ghost btn-sm btn-square"
onClick={closeForm}
aria-label="Close"
>
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<>
<label className="label">Owner</label>
{owners.length > 0 ? (
<select
className="select w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
>
{owners.map((o) => (
<option key={o} value={o}>
{o}
</option>
))}
</select>
) : (
<input
className="input w-full"
value={form.owner}
onChange={(e) => setForm({ ...form, owner: e.target.value })}
required
/>
)}
<label className="label">Name</label>
<input
className="input w-full font-mono"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
pattern="[A-Za-z0-9._-]+"
title="Letters, numbers, dots, underscores, hyphens"
/>
</>
) : null}
<label className="label">Type</label>
<select
className="select w-full"
value={form.type}
onChange={(e) => onTypeChange(e.target.value)}
>
{TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
<label className="label">Value</label>
{form.type === "boolean" ? (
<select
className="select w-full"
value={form.value === true ? "true" : "false"}
onChange={(e) => setForm({ ...form, value: e.target.value === "true" })}
>
<option value="true">true</option>
<option value="false">false</option>
</select>
) : form.type === "number" ? (
<input
type="number"
className="input w-full font-mono"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
required
step="any"
/>
) : (
<textarea
className="textarea w-full font-mono min-h-24"
value={form.value}
onChange={(e) => setForm({ ...form, value: e.target.value })}
spellCheck={false}
/>
)}
<p className="text-xs opacity-60 mt-1">
Stored in plaintext. Use Secrets for credentials. In workflows use{" "}
<span className="font-mono">$VAR_name</span> as a whole field.
</p>
{formError ? <p className="text-error text-sm">{formError}</p> : null}
{upsert.isError ? (
<p className="text-error text-sm">{errorMessage(upsert.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={upsert.isPending}>
Save
</button>
</form>
{editor ? (
<VariableEditorModal
mode={editor.mode}
initial={editor.initial}
onClose={closeEditor}
onSaved={(saved) => {
setHighlightName(saved?.name || editor.initial.name);
}}
/>
) : null}
{confirmDelete ? (
+267 -64
View File
@@ -3,14 +3,27 @@ import { Link, useNavigate, useParams } from "react-router-dom";
import { LuArrowLeft, LuCopy, LuPause, LuPlay, LuSave } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useCreateWorkflow,
useOwners,
useSaveWorkflow,
useSetWorkflowEnabled,
useWorkflow,
useWorkflowRevision,
} from "../api/hooks.js";
import { DuplicateWorkflowDialog } from "../components/DuplicateWorkflowDialog.jsx";
import { WorkflowFileIcon } from "../components/WorkflowFileIcon.jsx";
import { WorkflowVisualEditor } from "../components/workflow/WorkflowVisualEditor.jsx";
import { WorkflowHistoryPanel } from "../components/workflow/WorkflowHistoryPanel.jsx";
import {
SaveWorkflowWarningsDialog,
isSaveWarningsError,
saveErrorMessage,
saveWarningsFromError,
} from "../components/workflow/SaveWorkflowWarningsDialog.jsx";
import {
ConfirmDialog,
WorkflowRevisionBanner,
} from "../components/workflow/WorkflowRevisionBanner.jsx";
import { NEW_WORKFLOW_YAML, parseWorkflowYaml } from "../lib/workflow-doc.js";
import { useNotifications } from "../notifications.jsx";
@@ -87,48 +100,63 @@ function WorkflowEditorLayout({
export function WorkflowNewPage() {
const navigate = useNavigate();
const { notify } = useNotifications();
const { data: owners = [] } = useOwners();
const [owner, setOwner] = useState("");
const [file, setFile] = useState("");
const [content, setContent] = useState(NEW_WORKFLOW_YAML);
const [savedYaml] = useState(NEW_WORKFLOW_YAML);
const save = useSaveWorkflow();
const [saveWarnings, setSaveWarnings] = useState(null);
const create = useCreateWorkflow();
useEffect(() => {
if (!owner && owners[0]) setOwner(owners[0]);
}, [owner, owners]);
function onSave() {
const yamlFile = file.endsWith(".yaml") || file.endsWith(".yml") ? file : `${file}.yaml`;
save.mutate(
{ owner, file: yamlFile, content },
function onSave(saveAnyway = false) {
create.mutate(
{ owner, content, saveAnyway },
{
onSuccess: () =>
onSuccess: (data) => {
setSaveWarnings(null);
notify.success(`Created ${data.file}`);
navigate(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(yamlFile)}/edit`,
),
`/workflows/${encodeURIComponent(data.owner)}/${encodeURIComponent(data.file)}/edit`,
);
},
onError: (err) => {
if (isSaveWarningsError(err)) {
setSaveWarnings(saveWarningsFromError(err));
return;
}
notify.error(errorMessage(err));
},
},
);
}
return (
<WorkflowEditorLayout
title="New workflow"
onSave={onSave}
savePending={save.isPending}
saveDisabled={!owner || !file}
saveError={save.isError ? errorMessage(save.error) : null}
>
<div className="flex min-h-0 flex-1 flex-col gap-3">
<WorkflowVisualEditor
yaml={content}
onYamlChange={setContent}
owner={owner}
file={file}
savedYaml={savedYaml}
showTest={false}
extraChrome={
<>
<>
<WorkflowEditorLayout
title="New workflow"
onSave={() => onSave(false)}
savePending={create.isPending}
saveDisabled={!owner}
saveError={create.isError && !saveWarnings ? errorMessage(create.error) : null}
>
<div className="flex min-h-0 flex-1 flex-col gap-3">
<p className="text-sm opacity-70 shrink-0">
A UUID filename is assigned on save (for example{" "}
<span className="font-mono">a1b2c3d4-….yaml</span>). Edit the{" "}
<span className="font-mono">name:</span> field for the display name.
</p>
<WorkflowVisualEditor
yaml={content}
onYamlChange={setContent}
owner={owner}
file=""
savedYaml={savedYaml}
showTest={false}
extraChrome={
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="owner"
@@ -136,18 +164,19 @@ export function WorkflowNewPage() {
onChange={(e) => setOwner(e.target.value)}
required
/>
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="file.yaml"
value={file}
onChange={(e) => setFile(e.target.value)}
required
/>
</>
}
}
/>
</div>
</WorkflowEditorLayout>
{saveWarnings ? (
<SaveWorkflowWarningsDialog
warnings={saveWarnings}
pending={create.isPending}
onCancel={() => setSaveWarnings(null)}
onSaveAnyway={() => onSave(true)}
/>
</div>
</WorkflowEditorLayout>
) : null}
</>
);
}
@@ -165,8 +194,15 @@ export function WorkflowEditPage() {
const [contentReady, setContentReady] = useState(false);
const [testOpen, setTestOpen] = useState(false);
const [duplicateOpen, setDuplicateOpen] = useState(false);
const [saveWarnings, setSaveWarnings] = useState(null);
const [previewRevision, setPreviewRevision] = useState(null);
const [previewMeta, setPreviewMeta] = useState(null);
const [previewBaseline, setPreviewBaseline] = useState(null);
const [discardConfirm, setDiscardConfirm] = useState(null);
const [savePreviewConfirm, setSavePreviewConfirm] = useState(false);
const routeKey = `${owner}/${file}`;
const [activeKey, setActiveKey] = useState(routeKey);
const previewQuery = useWorkflowRevision(owner, file, previewRevision);
if (activeKey !== routeKey) {
setActiveKey(routeKey);
@@ -175,29 +211,124 @@ export function WorkflowEditPage() {
setContentReady(false);
setTestOpen(false);
setDuplicateOpen(false);
setPreviewRevision(null);
setPreviewMeta(null);
setPreviewBaseline(null);
setDiscardConfirm(null);
setSavePreviewConfirm(false);
}
useEffect(() => {
if (existing.isLoading) return;
if (previewRevision != null) return;
if (!contentReady && existing.data?.content != null) {
setContent(existing.data.content);
setSavedYaml(existing.data.content);
setContentReady(true);
}
}, [existing.data, existing.isLoading, contentReady]);
}, [existing.data, existing.isLoading, contentReady, previewRevision]);
function onSave() {
useEffect(() => {
if (previewRevision == null || previewQuery.isLoading) return;
if (previewQuery.data?.content != null) {
setContent(previewQuery.data.content);
setPreviewBaseline(previewQuery.data.content);
setPreviewMeta({ created_at: previewQuery.data.created_at });
}
}, [previewRevision, previewQuery.data, previewQuery.isLoading]);
function isDirty() {
const baseline = previewRevision != null ? previewBaseline : savedYaml;
return contentReady && baseline != null && content !== baseline;
}
function exitPreview() {
setPreviewRevision(null);
setPreviewMeta(null);
setPreviewBaseline(null);
existing.refetch().then((result) => {
const next = result.data?.content;
if (next != null) {
setContent(next);
setSavedYaml(next);
}
});
}
function applySelectRevision(revision, meta) {
if (revision == null) {
exitPreview();
return;
}
setPreviewRevision(revision);
if (meta?.created_at) {
setPreviewMeta({ created_at: meta.created_at });
}
}
function onSelectRevision(revision, meta) {
if (isDirty()) {
setDiscardConfirm(() => () => applySelectRevision(revision, meta));
return;
}
applySelectRevision(revision, meta);
}
function onBackToCurrent() {
if (isDirty()) {
setDiscardConfirm(() => () => exitPreview());
return;
}
exitPreview();
}
function onReverted() {
setPreviewRevision(null);
setPreviewMeta(null);
setPreviewBaseline(null);
existing.refetch().then((result) => {
const next = result.data?.content;
if (next != null) {
setContent(next);
setSavedYaml(next);
}
});
}
function onSave(saveAnyway = false) {
save.mutate(
{ owner, file, content },
{ owner, file, content, saveAnyway },
{
onSuccess: () => {
setSavedYaml(content);
setSaveWarnings(null);
setSavePreviewConfirm(false);
notify.success("Workflow saved");
if (previewRevision != null) {
setPreviewRevision(null);
setPreviewMeta(null);
setPreviewBaseline(null);
}
},
onError: (err) => {
if (isSaveWarningsError(err)) {
setSaveWarnings(saveWarningsFromError(err));
return;
}
},
},
);
}
function onSaveRequest() {
const liveYaml = existing.data?.content;
if (previewRevision != null && content !== liveYaml) {
setSavePreviewConfirm(true);
return;
}
onSave(false);
}
if (existing.isLoading) {
return (
<div className="flex min-h-[12rem] items-center justify-center">
@@ -221,41 +352,78 @@ export function WorkflowEditPage() {
const parsedDoc = parseWorkflowYaml(content);
const yamlOk = !parsedDoc.parseError;
const workflowName = parsedDoc.doc?.name?.trim();
const pageTitle = workflowName ? `${workflowName} (${file})` : file;
const pageTitle = workflowName ? `${workflowName}` : file;
const isPreviewing = previewRevision != null;
const previewLoading = isPreviewing && previewQuery.isLoading;
return (
<>
<WorkflowEditorLayout
title={pageTitle}
title={
<span className="flex min-w-0 flex-col items-start gap-0.5">
<span className="truncate">{pageTitle}</span>
<span className="text-xs font-normal font-mono opacity-50">{file}</span>
</span>
}
savePending={save.isPending}
saveDisabled={!contentReady}
saveError={save.isError ? errorMessage(save.error) : null}
onSave={onSave}
onTest={() => setTestOpen(true)}
onDuplicate={() => setDuplicateOpen(true)}
onToggleEnabled={() =>
setEnabled.mutate({
owner,
file,
enabled: existing.data?.parsed?.enabled === false,
})
saveDisabled={!contentReady || previewLoading}
saveError={save.isError && !saveWarnings ? saveErrorMessage(save.error) : null}
onSave={() => onSaveRequest()}
onTest={isPreviewing ? undefined : () => setTestOpen(true)}
onDuplicate={isPreviewing ? undefined : () => setDuplicateOpen(true)}
onToggleEnabled={
isPreviewing
? undefined
: () =>
setEnabled.mutate({
owner,
file,
enabled: existing.data?.parsed?.enabled === false,
})
}
enabled={existing.data?.parsed?.enabled !== false}
enablePending={setEnabled.isPending}
enableDisabled={!contentReady || Boolean(existing.data?.parseError) || !yamlOk}
enableError={setEnabled.isError ? errorMessage(setEnabled.error) : null}
>
<div className="flex min-h-0 flex-1 flex-col gap-3">
<WorkflowVisualEditor
yaml={content}
onYamlChange={setContent}
owner={owner}
file={file}
savedYaml={savedYaml}
showTest
testOpen={testOpen}
onTestClose={() => setTestOpen(false)}
/>
<div className="flex min-h-0 flex-1 gap-3">
<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-3">
{isPreviewing && previewMeta ? (
<WorkflowRevisionBanner
owner={owner}
file={file}
revision={previewRevision}
createdAt={previewMeta.created_at}
onBackToCurrent={onBackToCurrent}
onReverted={onReverted}
/>
) : null}
{previewLoading ? (
<div className="flex min-h-[12rem] flex-1 items-center justify-center">
<span className="loading loading-spinner loading-lg" />
</div>
) : (
<WorkflowVisualEditor
yaml={content}
onYamlChange={setContent}
owner={owner}
file={file}
savedYaml={savedYaml}
showTest={!isPreviewing}
testOpen={testOpen}
onTestClose={() => setTestOpen(false)}
/>
)}
</div>
<div className="hidden w-64 shrink-0 xl:block">
<WorkflowHistoryPanel
owner={owner}
file={file}
previewRevision={previewRevision}
onSelectRevision={onSelectRevision}
onReverted={onReverted}
/>
</div>
</div>
</WorkflowEditorLayout>
{duplicateOpen ? (
@@ -271,6 +439,41 @@ export function WorkflowEditPage() {
}}
/>
) : null}
{saveWarnings ? (
<SaveWorkflowWarningsDialog
warnings={saveWarnings}
pending={save.isPending}
onCancel={() => setSaveWarnings(null)}
onSaveAnyway={() => onSave(true)}
/>
) : null}
{savePreviewConfirm ? (
<ConfirmDialog
open
title="Save over current workflow?"
message="This will replace the current live workflow with the content you are viewing."
confirmLabel="Save"
confirmClass="btn-primary"
pending={save.isPending}
onCancel={() => setSavePreviewConfirm(false)}
onConfirm={() => onSave(false)}
/>
) : null}
{discardConfirm ? (
<ConfirmDialog
open
title="Discard unsaved changes?"
message="You have unsaved edits. Switching versions will discard them."
confirmLabel="Discard"
pending={false}
onCancel={() => setDiscardConfirm(null)}
onConfirm={() => {
const action = discardConfirm;
setDiscardConfirm(null);
action?.();
}}
/>
) : null}
</>
);
}
@@ -0,0 +1,162 @@
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { LuArrowLeft, LuRotateCcw, LuTrash2 } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
usePurgeWorkflowTrash,
useRestoreWorkflowTrash,
useWorkflowTrash,
} from "../api/hooks.js";
import { formatTime } from "../lib/format.jsx";
import { useNotifications } from "../notifications.jsx";
function formatAge(ms) {
if (ms == null || ms < 0) return "—";
const mins = Math.floor(ms / 60_000);
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 48) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
export function WorkflowTrashPage() {
const navigate = useNavigate();
const { notify } = useNotifications();
const { data: items = [], isLoading } = useWorkflowTrash();
const restore = useRestoreWorkflowTrash();
const purge = usePurgeWorkflowTrash();
const [confirmPurge, setConfirmPurge] = useState(null);
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Link to="/workflows" className="btn btn-ghost btn-sm btn-square" aria-label="Back">
<LuArrowLeft className="size-4" />
</Link>
<h1 className="text-xl font-semibold">Workflow trash</h1>
</div>
<p className="text-sm opacity-70">
Deleted workflows are kept for 7 days. Restore to bring them back, or delete permanently
to remove the file and revision history.
</p>
{restore.isError ? (
<p className="text-error text-sm">{errorMessage(restore.error)}</p>
) : null}
{purge.isError ? (
<p className="text-error text-sm">{errorMessage(purge.error)}</p>
) : null}
{isLoading ? (
<span className="loading loading-spinner" />
) : !items.length ? (
<p className="opacity-50">Trash is empty.</p>
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Name</th>
<th>File</th>
<th>Owner</th>
<th>Deleted</th>
<th>Age</th>
<th>Purge in</th>
<th />
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id} className="hover">
<td>{item.name ?? "—"}</td>
<td className="font-mono text-xs">{item.file}</td>
<td className="font-mono text-xs">{item.owner}</td>
<td className="whitespace-nowrap">{formatTime(item.deleted_at)}</td>
<td>{formatAge(item.age_ms)}</td>
<td>
{item.days_until_purge <= 0 ? (
<span className="text-warning">soon</span>
) : (
`${item.days_until_purge}d`
)}
</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Restore"
disabled={restore.isPending}
onClick={() =>
restore.mutate(item.id, {
onSuccess: (data) => {
notify.success("Workflow restored");
navigate(
`/workflows/${encodeURIComponent(data.owner)}/${encodeURIComponent(data.file)}/edit`,
);
},
})
}
>
<LuRotateCcw className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete permanently"
onClick={() => setConfirmPurge(item)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{confirmPurge ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete permanently?</h3>
<p className="mt-2 text-sm">
{confirmPurge.name ?? confirmPurge.file} ({confirmPurge.owner}/{confirmPurge.file})
will be removed forever, including revision history.
</p>
<div className="modal-action">
<button
type="button"
className="btn btn-ghost"
onClick={() => setConfirmPurge(null)}
>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={purge.isPending}
onClick={() =>
purge.mutate(confirmPurge.id, {
onSuccess: () => {
notify.success("Permanently deleted");
setConfirmPurge(null);
},
})
}
>
Delete forever
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmPurge(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+13 -4
View File
@@ -72,6 +72,10 @@ export function WorkflowsPage() {
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Workflows</h1>
<div className="flex items-center gap-2">
<Link to="/workflows/trash" className="btn btn-ghost btn-sm">
<LuTrash2 className="size-4" />
Trash
</Link>
<button
type="button"
className="btn btn-ghost btn-sm"
@@ -128,6 +132,7 @@ export function WorkflowsPage() {
>
<WorkflowFileIcon className="size-7 shrink-0" />
{w.name}
<span className="block font-mono text-xs opacity-50">{w.file}</span>
</Link>
{!w.registered ? (
<span
@@ -151,7 +156,7 @@ export function WorkflowsPage() {
<label className="inline-flex items-center mr-1" title={w.enabled ? "Disable" : "Enable"}>
<input
type="checkbox"
className="toggle toggle-xs"
className="toggle toggle-success toggle-xs"
checked={Boolean(w.enabled)}
disabled={Boolean(w.loadError) || togglingKey === w.key}
onChange={() =>
@@ -202,7 +207,7 @@ export function WorkflowsPage() {
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
title="Move to trash"
onClick={() => setConfirmDelete(w)}
>
<LuTrash2 className="size-4" />
@@ -231,7 +236,11 @@ export function WorkflowsPage() {
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete.key}?</h3>
<h3 className="font-bold">Move {confirmDelete.key} to trash?</h3>
<p className="mt-2 text-sm opacity-70">
The workflow is removed from the list but kept in trash for 7 days. Revision history
is preserved.
</p>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
@@ -250,7 +259,7 @@ export function WorkflowsPage() {
)
}
>
Delete
Move to trash
</button>
</div>
</div>
+5
View File
@@ -2,11 +2,16 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
/** In dev:pm2, control (:8600) serves auth so login works when HTTP is stopped. */
const authProxyTarget =
process.env.JFLOW_AUTH_PROXY ?? "http://127.0.0.1:8700";
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 8500,
proxy: {
"/api/auth": { target: authProxyTarget, changeOrigin: true },
"/api": { target: "http://127.0.0.1:8700", changeOrigin: true },
"/admin": { target: "http://127.0.0.1:8700", changeOrigin: true },
"/u": { target: "http://127.0.0.1:8700", changeOrigin: true },
@@ -0,0 +1,8 @@
{
"id": "get-current-time",
"name": "Get current time",
"version": "0.1.0",
"jerapah": ">=0.1.0 <1.0.0",
"main": "script.js",
"description": "Example user plugin: return the current time as output.datetime"
}
+7
View File
@@ -0,0 +1,7 @@
{
"name": "jflow-plugin-get-current-time",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Example JerapahFlow plugin (no npm dependencies)"
}
+34
View File
@@ -0,0 +1,34 @@
function passContext(ctx) {
if (ctx?.context != null && typeof ctx.context === "object" && !Array.isArray(ctx.context)) {
return { ...ctx.context };
}
return {};
}
function getCurrentTime(ctx) {
const output = {
datetime: new Date().toISOString(),
processId: "1234",
};
return { output, context: { ...passContext(ctx), ...output } };
}
getCurrentTime.meta = {
description: "Return the current time as output.datetime",
config: {},
input: {},
output: {
datetime: { type: "string", description: "ISO timestamp" },
processId: { type: "string" },
},
context: {
datetime: { type: "string", description: "ISO timestamp" },
processId: { type: "string" },
},
example: {
data: {},
config: {},
},
};
export default getCurrentTime;