Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45b3aa7f1b | ||
|
|
4b147b0091 | ||
|
|
6950ff0d79 | ||
|
|
cc9ec25388 | ||
|
|
be2ff0719a | ||
|
|
9d93707848 | ||
|
|
aa99216c49 | ||
|
|
58d3794050 | ||
|
|
16f9610027 | ||
|
|
2023dd4e36 | ||
|
|
0bed6e0313 | ||
|
|
f29ba4ab8b | ||
|
|
56b6696ca3 | ||
|
|
0d0c67704c | ||
|
|
09e8a890e0 | ||
|
|
4b17a6fcc3 | ||
|
|
5507fbcb29 | ||
|
|
176cc08a6b | ||
|
|
5953c3cf75 | ||
|
|
0952a482fb | ||
|
|
c7f1d25e98 | ||
|
|
841eab0556 | ||
|
|
ac065fa911 | ||
|
|
70d8128bfb | ||
|
|
8c8ae66c7d | ||
|
|
c8a3f35b0a | ||
|
|
e5c83e87fe | ||
|
|
eb17c8e284 | ||
|
|
459f8b59fe | ||
|
|
e6c705cef7 | ||
|
|
19c4bb451d | ||
|
|
f71b79a17f | ||
|
|
e3eb7ca205 | ||
|
|
2e54163d9e | ||
|
|
344f79039f | ||
|
|
02fe634944 | ||
|
|
7b1f64d727 | ||
|
|
d53e38a48f | ||
|
|
740e738fca | ||
|
|
ee90284129 | ||
|
|
de42b3126b | ||
|
|
71dccbc590 | ||
|
|
4c6127786f | ||
|
|
bf082c59fe | ||
|
|
ee35c10454 | ||
|
|
1651fd00a2 | ||
|
|
d9e4447903 | ||
|
|
f59dd6ebec | ||
|
|
10413547c1 | ||
|
|
2f178db2c6 | ||
|
|
28485d51f7 | ||
|
|
24362b89d7 | ||
|
|
159e4a4cbf | ||
|
|
13a7919c91 | ||
|
|
d670690816 | ||
|
|
62c58c7c89 | ||
|
|
0b4d9a8463 | ||
|
|
51ca8c7e34 | ||
|
|
64047054b8 | ||
|
|
3f5258a76c | ||
|
|
3b93308b71 | ||
|
|
bf53f2e17c | ||
|
|
c2eca11a3b | ||
|
|
4c3f8de1fb | ||
|
|
b3e1869724 | ||
|
|
624f58c723 | ||
|
|
aedc0f6979 | ||
|
|
1e53ceeda6 | ||
|
|
f08ed0c22c | ||
|
|
ee0f877d97 | ||
|
|
b3d4e08914 | ||
|
|
ec9dd83e77 | ||
|
|
4930e2a870 | ||
|
|
5e21cc76fc | ||
|
|
529110a693 | ||
|
|
0b5f2a88cc | ||
|
|
ff6f04fe46 | ||
|
|
2e9a0e30c1 | ||
|
|
ad0acaccc2 | ||
|
|
30019a02d8 | ||
|
|
87999be3d2 | ||
|
|
4ce9f6000c | ||
|
|
0529962391 | ||
|
|
14c45e4f6c | ||
|
|
1c38b95fb0 | ||
|
|
dab66a2dce | ||
|
|
86eb0cfcae | ||
|
|
d3aa10c769 | ||
|
|
15524609fe | ||
|
|
aacb91ac70 | ||
|
|
f91502026b | ||
|
|
7f2f638f38 | ||
|
|
7879ead486 | ||
|
|
dda1caf3e0 | ||
|
|
bb483d3e68 | ||
|
|
73bc79b4bb | ||
|
|
9520426a66 | ||
|
|
b077423ab2 | ||
|
|
94867fbd5a | ||
|
|
6a37f2f4c7 | ||
|
|
b54338f91f | ||
|
|
c7b95b4d2b | ||
|
|
8e4388c325 | ||
|
|
305995cbe2 | ||
|
|
468170349d | ||
|
|
52446592e7 | ||
|
|
7bca0ef335 | ||
|
|
80717680a1 |
No files matched your search
+17
-20
@@ -10,28 +10,25 @@ jobs:
|
||||
deploy:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
- name: Authenticated host Stage deployment (Production blocked)
|
||||
shell: bash
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
export https_proxy=""
|
||||
export HTTP_PROXY=""
|
||||
export HTTPS_PROXY=""
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ "${BRANCH}" == develop ]] || { echo 'Production blocked' >&2; exit 2; }
|
||||
[[ "${DEPLOY_SHA}" =~ ^[0-9a-f]{40}$ ]] || exit 2
|
||||
# Provision DEPLOY_KNOWN_HOSTS from an independently verified host key.
|
||||
# Never use baked-in /opt/services, runner SSH keys or docker.sock.
|
||||
[[ -n "${DEPLOY_KEY}" && -n "${DEPLOY_KNOWN_HOSTS}" ]] || { echo 'Host boundary requires DEPLOY_KEY and verified DEPLOY_KNOWN_HOSTS' >&2; exit 2; }
|
||||
export http_proxy="" https_proxy="" HTTP_PROXY="" HTTPS_PROXY=""
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||
if [ "$BRANCH" = develop ]; then
|
||||
wget --no-proxy -qO scripts/release-corporate-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-corporate-stage.sh
|
||||
fi
|
||||
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh ${BRANCH}
|
||||
umask 077
|
||||
wrapper=$(mktemp)
|
||||
trap 'rm -f "$wrapper"' EXIT
|
||||
wget --no-proxy -qO "$wrapper" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/ci-host-deploy.sh"
|
||||
bash "$wrapper"
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Hermes runtime contract review (NO DEPLOY)
|
||||
on:
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
contract-review:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: backend/package-lock.json
|
||||
- run: npm ci --ignore-scripts --no-audit
|
||||
working-directory: backend
|
||||
- run: npm test -- --runInBand hermes-management
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json --noEmit
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json
|
||||
working-directory: backend
|
||||
# No SSH, Docker socket, secrets, deployments, dispatch or runtime mutation.
|
||||
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||
ENV DISABLE_OPENCOLLECTIVE=1
|
||||
@@ -33,6 +34,7 @@ USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Prisma migration history and Orchestration v4 rollout boundary
|
||||
|
||||
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
|
||||
|
||||
## Actual tracked history
|
||||
|
||||
| Migration | What its SQL actually does |
|
||||
| --- | --- |
|
||||
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
|
||||
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
|
||||
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
|
||||
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
|
||||
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
|
||||
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
|
||||
|
||||
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
|
||||
|
||||
## Required rollout safeguards (not authorization to deploy)
|
||||
|
||||
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
|
||||
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
|
||||
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
|
||||
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
|
||||
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
|
||||
|
||||
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
|
||||
|
||||
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
|
||||
@@ -1,35 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function cleanFaqs() {
|
||||
console.log('--- Cleaning Misplaced Content Tasks from FAQs ---');
|
||||
const countBefore = await prisma.fAQ.count();
|
||||
console.log(`Total FAQs before cleanup: ${countBefore}`);
|
||||
|
||||
const deleteResult = await prisma.fAQ.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ question: { contains: 'راهنمای' } },
|
||||
{ question: { contains: 'اینفوگرافیک' } },
|
||||
{ question: { contains: 'نگارش' } },
|
||||
{ question: { contains: 'تدوین' } },
|
||||
{ question: { contains: 'تولید' } },
|
||||
{ question: { contains: 'مقاله' } },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks.`);
|
||||
const countAfter = await prisma.fAQ.count();
|
||||
console.log(`Total real customer FAQs remaining: ${countAfter}`);
|
||||
}
|
||||
|
||||
cleanFaqs()
|
||||
.catch((err) => {
|
||||
console.error('Clean FAQs error:', err);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,211 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"key" VARCHAR(120) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
|
||||
"operation_mode" VARCHAR(30) NOT NULL,
|
||||
"model_tier" VARCHAR(2),
|
||||
"budget_limit_cents" INTEGER NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_runs" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"attempt" INTEGER NOT NULL DEFAULT 1,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"commit_sha" VARCHAR(64) NOT NULL,
|
||||
"environment" VARCHAR(50) NOT NULL,
|
||||
"retry_class" VARCHAR(30),
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"started_at" TIMESTAMPTZ,
|
||||
"finished_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_artifacts" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"uri" TEXT NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size_bytes" BIGINT,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"subject_hash" CHAR(64) NOT NULL,
|
||||
"predicate" JSONB NOT NULL,
|
||||
"signer" VARCHAR(150) NOT NULL,
|
||||
"signature" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_dependencies" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"depends_on_task_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_approval_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"gate" INTEGER NOT NULL,
|
||||
"decision" VARCHAR(20) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"notes" TEXT,
|
||||
"expires_at" TIMESTAMPTZ NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"run_id" UUID,
|
||||
"artifact_hash" CHAR(64),
|
||||
"commit_sha" VARCHAR(64),
|
||||
"environment" VARCHAR(50),
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID,
|
||||
"event_type" VARCHAR(60) NOT NULL,
|
||||
"from_state" VARCHAR(40),
|
||||
"to_state" VARCHAR(40),
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150),
|
||||
"payload" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_budget_ledger" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"amount_cents" INTEGER NOT NULL,
|
||||
"kind" VARCHAR(40) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_kill_switches" (
|
||||
"scope" VARCHAR(80) NOT NULL,
|
||||
"level" VARCHAR(30) NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Immutable evidence and accounting; corrections are new entries.
|
||||
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
|
||||
$$;
|
||||
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "advisor_contacts" (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"name" VARCHAR(150) NOT NULL,
|
||||
"phone" VARCHAR(20) NOT NULL,
|
||||
"title" VARCHAR(100),
|
||||
"is_default" BOOLEAN NOT NULL DEFAULT false,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "advisor_contacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "product_advisors" (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"product_id" UUID NOT NULL,
|
||||
"advisor_id" UUID NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "product_advisors_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "leads" (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"first_name" VARCHAR(100) NOT NULL,
|
||||
"last_name" VARCHAR(100) NOT NULL,
|
||||
"phone" VARCHAR(20) NOT NULL,
|
||||
"product_id" UUID,
|
||||
"advisor_id" UUID,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"notes" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "leads_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notification_queues" (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"channel" VARCHAR(20) NOT NULL,
|
||||
"recipient" VARCHAR(150) NOT NULL,
|
||||
"event" VARCHAR(50) NOT NULL,
|
||||
"subject" VARCHAR(255),
|
||||
"content" TEXT NOT NULL,
|
||||
"payload" JSONB,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'QUEUED',
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"max_attempts" INTEGER NOT NULL DEFAULT 3,
|
||||
"last_error" TEXT,
|
||||
"idempotency_key" VARCHAR(100),
|
||||
"sent_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "notification_queues_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notification_templates" (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"channel" VARCHAR(20) NOT NULL,
|
||||
"event" VARCHAR(50) NOT NULL,
|
||||
"name" VARCHAR(150) NOT NULL,
|
||||
"subject" VARCHAR(255),
|
||||
"body" TEXT NOT NULL,
|
||||
"pattern_code" VARCHAR(50),
|
||||
"variables" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"recipient_type" VARCHAR(30) NOT NULL DEFAULT 'customer',
|
||||
"custom_recipient" VARCHAR(150),
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "notification_templates_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "advisor_contacts_phone_key" ON "advisor_contacts"("phone");
|
||||
CREATE INDEX "advisor_contacts_phone_idx" ON "advisor_contacts"("phone");
|
||||
CREATE INDEX "advisor_contacts_is_default_idx" ON "advisor_contacts"("is_default");
|
||||
CREATE INDEX "advisor_contacts_is_active_idx" ON "advisor_contacts"("is_active");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_advisors_product_id_advisor_id_key" ON "product_advisors"("product_id", "advisor_id");
|
||||
CREATE INDEX "product_advisors_product_id_idx" ON "product_advisors"("product_id");
|
||||
CREATE INDEX "product_advisors_advisor_id_idx" ON "product_advisors"("advisor_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "leads_phone_idx" ON "leads"("phone");
|
||||
CREATE INDEX "leads_status_idx" ON "leads"("status");
|
||||
CREATE INDEX "leads_created_at_idx" ON "leads"("created_at");
|
||||
CREATE INDEX "leads_advisor_id_idx" ON "leads"("advisor_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notification_queues_idempotency_key_key" ON "notification_queues"("idempotency_key");
|
||||
CREATE INDEX "notification_queues_status_idx" ON "notification_queues"("status");
|
||||
CREATE INDEX "notification_queues_channel_idx" ON "notification_queues"("channel");
|
||||
CREATE INDEX "notification_queues_event_idx" ON "notification_queues"("event");
|
||||
CREATE INDEX "notification_queues_created_at_idx" ON "notification_queues"("created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notification_templates_channel_event_key" ON "notification_templates"("channel", "event");
|
||||
CREATE INDEX "notification_templates_channel_idx" ON "notification_templates"("channel");
|
||||
CREATE INDEX "notification_templates_event_idx" ON "notification_templates"("event");
|
||||
CREATE INDEX "notification_templates_is_active_idx" ON "notification_templates"("is_active");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leads" ADD CONSTRAINT "leads_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
ALTER TABLE "leads" ADD CONSTRAINT "leads_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
-- CreateTable approval_requests
|
||||
CREATE TABLE IF NOT EXISTS public.approval_requests (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"category" VARCHAR(50) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"payload" JSONB NOT NULL,
|
||||
"test_context" JSONB,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"ceo_notes" TEXT,
|
||||
"executed_at" TIMESTAMPTZ(6),
|
||||
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "approval_requests_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable audit_logs
|
||||
CREATE TABLE IF NOT EXISTS public.audit_logs (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"entity" VARCHAR(50) NOT NULL,
|
||||
"entity_id" VARCHAR(100),
|
||||
"action" VARCHAR(50) NOT NULL,
|
||||
"department" VARCHAR(50),
|
||||
"actor" VARCHAR(100) NOT NULL DEFAULT 'SYSTEM',
|
||||
"summary" VARCHAR(255) NOT NULL,
|
||||
"old_values" JSONB,
|
||||
"new_values" JSONB,
|
||||
"metadata" JSONB,
|
||||
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable department_tasks
|
||||
CREATE TABLE IF NOT EXISTS public.department_tasks (
|
||||
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
"code" VARCHAR(50) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"description" TEXT,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'BACKLOG',
|
||||
"priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM',
|
||||
"assignee" VARCHAR(100),
|
||||
"acceptance_criteria" JSONB,
|
||||
"execution_logs" JSONB,
|
||||
"deliverable_url" VARCHAR(255),
|
||||
"approval_id" UUID,
|
||||
"started_at" TIMESTAMPTZ(6),
|
||||
"completed_at" TIMESTAMPTZ(6),
|
||||
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "department_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "department_tasks_code_key" ON public.department_tasks("code");
|
||||
CREATE INDEX IF NOT EXISTS "approval_requests_department_idx" ON public.approval_requests("department");
|
||||
CREATE INDEX IF NOT EXISTS "approval_requests_category_idx" ON public.approval_requests("category");
|
||||
CREATE INDEX IF NOT EXISTS "approval_requests_status_idx" ON public.approval_requests("status");
|
||||
CREATE INDEX IF NOT EXISTS "approval_requests_created_at_idx" ON public.approval_requests("created_at");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "audit_logs_entity_idx" ON public.audit_logs("entity");
|
||||
CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON public.audit_logs("action");
|
||||
CREATE INDEX IF NOT EXISTS "audit_logs_department_idx" ON public.audit_logs("department");
|
||||
CREATE INDEX IF NOT EXISTS "audit_logs_created_at_idx" ON public.audit_logs("created_at");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "department_tasks_department_idx" ON public.department_tasks("department");
|
||||
CREATE INDEX IF NOT EXISTS "department_tasks_status_idx" ON public.department_tasks("status");
|
||||
CREATE INDEX IF NOT EXISTS "department_tasks_priority_idx" ON public.department_tasks("priority");
|
||||
CREATE INDEX IF NOT EXISTS "department_tasks_created_at_idx" ON public.department_tasks("created_at");
|
||||
+143
-301
@@ -178,7 +178,9 @@ model Blog {
|
||||
slug String @unique @db.VarChar(200)
|
||||
content String @db.Text
|
||||
excerpt String? @db.Text
|
||||
authorId String @map("author_id") @db.Uuid
|
||||
authorId String? @map("author_id") @db.Uuid
|
||||
authorTeam String? @map("author_team") @db.VarChar(200)
|
||||
authorRole String? @map("author_role") @db.VarChar(200)
|
||||
categoryId String? @map("category_id") @db.Uuid
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||
@@ -198,6 +200,7 @@ model Blog {
|
||||
isPublished Boolean @default(true) @map("is_published")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
||||
readingTime Int @default(3) @map("reading_time")
|
||||
featured Boolean @default(false)
|
||||
allowComments Boolean @default(true) @map("allow_comments")
|
||||
@@ -209,7 +212,7 @@ model Blog {
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
author User @relation(fields: [authorId], references: [id])
|
||||
author User? @relation(fields: [authorId], references: [id])
|
||||
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||
tags BlogTag[]
|
||||
comments BlogComment[]
|
||||
@@ -286,8 +289,6 @@ model Product {
|
||||
reviews ProductReview[]
|
||||
competitorPriceLogs CompetitorPriceLog[]
|
||||
priceSuggestions PriceSuggestion[]
|
||||
productAdvisors ProductAdvisor[]
|
||||
leads Lead[]
|
||||
|
||||
@@index([categorySlug])
|
||||
@@index([suitableFor])
|
||||
@@ -1091,319 +1092,160 @@ model DepartmentTask {
|
||||
@@map("department_tasks")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 8. AdvisorContact (مشاوران تخصصی و پاسخگویی)
|
||||
// ------------------------------------------------------------------------------
|
||||
model AdvisorContact {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
name String @db.VarChar(150)
|
||||
phone String @unique @db.VarChar(20)
|
||||
title String? @db.VarChar(100)
|
||||
isDefault Boolean @default(false) @map("is_default")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
productAdvisors ProductAdvisor[]
|
||||
leads Lead[]
|
||||
|
||||
@@index([phone])
|
||||
@@index([isDefault])
|
||||
@@index([isActive])
|
||||
@@map("advisor_contacts")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 9. ProductAdvisor (اتصال مشاور به محصول)
|
||||
// ------------------------------------------------------------------------------
|
||||
model ProductAdvisor {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
productId String @map("product_id") @db.Uuid
|
||||
advisorId String @map("advisor_id") @db.Uuid
|
||||
// Orchestration v4 additive models. Legacy governance tables remain untouched.
|
||||
model OrchestrationTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
key String @unique @db.VarChar(120)
|
||||
title String @db.VarChar(255)
|
||||
department String @db.VarChar(50)
|
||||
state String @default("DRAFT") @db.VarChar(40)
|
||||
operationMode String @map("operation_mode") @db.VarChar(30)
|
||||
modelTier String? @map("model_tier") @db.VarChar(2)
|
||||
budgetLimitCents Int @map("budget_limit_cents")
|
||||
version Int @default(1)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||
advisor AdvisorContact @relation(fields: [advisorId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([productId, advisorId])
|
||||
@@index([productId])
|
||||
@@index([advisorId])
|
||||
@@map("product_advisors")
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
runs OrchestrationRun[]
|
||||
dependencies OrchestrationDependency[] @relation("task_dependencies")
|
||||
dependedOnBy OrchestrationDependency[] @relation("task_dependents")
|
||||
decisions OrchestrationApprovalDecision[]
|
||||
events OrchestrationEvent[]
|
||||
budgetLedger OrchestrationBudgetLedger[]
|
||||
@@index([state, createdAt])
|
||||
@@index([department, state])
|
||||
@@map("orchestration_tasks")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 10. Lead (درخواستهای تماس و مشاوره کاربران)
|
||||
// ------------------------------------------------------------------------------
|
||||
model Lead {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
firstName String @map("first_name") @db.VarChar(100)
|
||||
lastName String @map("last_name") @db.VarChar(100)
|
||||
phone String @db.VarChar(20)
|
||||
productId String? @map("product_id") @db.Uuid
|
||||
advisorId String? @map("advisor_id") @db.Uuid
|
||||
status String @default("PENDING") @db.VarChar(30) // PENDING, CONTACTED, CANCELLED
|
||||
notes String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
|
||||
advisor AdvisorContact? @relation(fields: [advisorId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([phone])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@index([advisorId])
|
||||
@@map("leads")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 11. NotificationQueue (صف ناهمگام نوتیفیکیشنها با قابلیت Retry و Idempotency)
|
||||
// ------------------------------------------------------------------------------
|
||||
model NotificationQueue {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
channel String @db.VarChar(20) // SMS, EMAIL
|
||||
recipient String @db.VarChar(150)
|
||||
event String @db.VarChar(50)
|
||||
subject String? @db.VarChar(255)
|
||||
content String @db.Text
|
||||
payload Json? @db.JsonB
|
||||
status String @default("QUEUED") @db.VarChar(30) // QUEUED, PROCESSING, SENT, FAILED
|
||||
attempts Int @default(0)
|
||||
maxAttempts Int @default(3) @map("max_attempts")
|
||||
lastError String? @map("last_error") @db.Text
|
||||
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(100)
|
||||
sentAt DateTime? @map("sent_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([status])
|
||||
@@index([channel])
|
||||
@@index([event])
|
||||
@@index([createdAt])
|
||||
@@map("notification_queues")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 12. NotificationTemplate (قالبهای رویدادها برای ایمیل و پیامک)
|
||||
// ------------------------------------------------------------------------------
|
||||
model NotificationTemplate {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
channel String @db.VarChar(20) // SMS, EMAIL
|
||||
event String @db.VarChar(50) // ORDER_CREATED, PAYMENT_SUCCESS, NEW_LEAD, etc.
|
||||
name String @db.VarChar(150)
|
||||
subject String? @db.VarChar(255)
|
||||
body String @db.Text
|
||||
patternCode String? @map("pattern_code") @db.VarChar(50)
|
||||
variables String[] @default([])
|
||||
recipientType String @default("customer") @map("recipient_type") @db.VarChar(30)
|
||||
customRecipient String? @map("custom_recipient") @db.VarChar(150)
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@unique([channel, event])
|
||||
@@index([channel])
|
||||
@@index([event])
|
||||
@@index([isActive])
|
||||
@@map("notification_templates")
|
||||
}
|
||||
|
||||
|
||||
enum CorporateTaskStatus {
|
||||
TODO
|
||||
IN_PROGRESS
|
||||
TEST
|
||||
DONE
|
||||
BLOCKED
|
||||
REJECTED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum CorporatePriority {
|
||||
CEO_EXPEDITE
|
||||
CRITICAL
|
||||
HIGH
|
||||
MEDIUM
|
||||
LOW
|
||||
}
|
||||
|
||||
model CorporateTask {
|
||||
model OrchestrationRun {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskCode String @unique
|
||||
title String
|
||||
normalizedTitle String
|
||||
normalizedCode String
|
||||
description String
|
||||
department String
|
||||
priority CorporatePriority @default(CEO_EXPEDITE)
|
||||
status CorporateTaskStatus @default(TODO)
|
||||
actionType String @default("CEO_DIRECTIVE")
|
||||
dueCycle String?
|
||||
parentId String? @db.Uuid
|
||||
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
|
||||
children CorporateTask[] @relation("TaskChildren")
|
||||
goalId String? @db.Uuid
|
||||
goal CorporateGoal? @relation(fields: [goalId], references: [id])
|
||||
assignedAgent String?
|
||||
claimToken String? @db.Uuid
|
||||
leasedUntil DateTime? @db.Timestamptz()
|
||||
executionCount Int @default(0)
|
||||
qaCount Int @default(0)
|
||||
rejectionCount Int @default(0)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @db.Timestamptz()
|
||||
logs CorporateEvent[]
|
||||
evidence CorporateEvidence[]
|
||||
reviews CorporateReview[]
|
||||
effects CorporateEffect[]
|
||||
@@index([status, priority, updatedAt])
|
||||
@@index([parentId])
|
||||
@@index([goalId])
|
||||
@@map("corporate_tasks")
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
attempt Int @default(1)
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
commitSha String @map("commit_sha") @db.VarChar(64)
|
||||
environment String @db.VarChar(50)
|
||||
retryClass String? @map("retry_class") @db.VarChar(30)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
finishedAt DateTime? @map("finished_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
artifacts OrchestrationArtifact[]
|
||||
attestations OrchestrationAttestation[]
|
||||
approvals OrchestrationApprovalDecision[]
|
||||
@@unique([taskId, attempt])
|
||||
@@index([taskId, status])
|
||||
@@map("orchestration_runs")
|
||||
}
|
||||
|
||||
model CorporateEvent {
|
||||
model OrchestrationArtifact {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
speaker String
|
||||
speakerName String
|
||||
step String
|
||||
content String
|
||||
payload Json?
|
||||
timestamp DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId, timestamp])
|
||||
@@map("corporate_events")
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
uri String @db.Text
|
||||
sha256 String @db.Char(64)
|
||||
sizeBytes BigInt? @map("size_bytes")
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, sha256])
|
||||
@@map("orchestration_artifacts")
|
||||
}
|
||||
|
||||
model CorporateEvidence {
|
||||
model OrchestrationAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
claimToken String @db.Uuid
|
||||
executor String
|
||||
artifactUri String
|
||||
sha256 String
|
||||
summary String
|
||||
tool String
|
||||
result String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
reviews CorporateReview[]
|
||||
@@index([taskId])
|
||||
@@map("corporate_evidence")
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
subjectHash String @map("subject_hash") @db.Char(64)
|
||||
predicate Json @db.JsonB
|
||||
signer String @db.VarChar(150)
|
||||
signature String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, kind, subjectHash, signer])
|
||||
@@map("orchestration_attestations")
|
||||
}
|
||||
|
||||
model CorporateReview {
|
||||
model OrchestrationDependency {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
evidenceId String @db.Uuid
|
||||
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
|
||||
reviewer String
|
||||
passed Boolean
|
||||
findings String
|
||||
verification Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_reviews")
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
dependsOnTaskId String @map("depends_on_task_id") @db.Uuid
|
||||
kind String @default("BLOCKS") @db.VarChar(30)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation("task_dependencies",fields:[taskId],references:[id],onDelete:Restrict)
|
||||
dependsOnTask OrchestrationTask @relation("task_dependents",fields:[dependsOnTaskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, dependsOnTaskId])
|
||||
@@map("orchestration_dependencies")
|
||||
}
|
||||
|
||||
model CorporateResearch {
|
||||
model OrchestrationApprovalDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String
|
||||
category String
|
||||
source String
|
||||
opportunity String
|
||||
impact String
|
||||
recommendedAction String
|
||||
status String @default("DISCOVERED")
|
||||
cadence String
|
||||
provenance Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
sources CorporateSource[]
|
||||
roadmaps CorporateRoadmap[]
|
||||
@@map("corporate_research")
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
gate Int
|
||||
decision String @db.VarChar(20)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
notes String? @db.Text
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
runId String? @map("run_id") @db.Uuid
|
||||
artifactHash String? @map("artifact_hash") @db.Char(64)
|
||||
commitSha String? @map("commit_sha") @db.VarChar(64)
|
||||
environment String? @db.VarChar(50)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
run OrchestrationRun? @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, gate, createdAt])
|
||||
@@map("orchestration_approval_decisions")
|
||||
}
|
||||
|
||||
model CorporateSource {
|
||||
model OrchestrationEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
url String
|
||||
title String
|
||||
excerpt String
|
||||
retrievedAt DateTime @db.Timestamptz()
|
||||
sha256 String
|
||||
@@index([researchId])
|
||||
@@map("corporate_sources")
|
||||
taskId String? @map("task_id") @db.Uuid
|
||||
eventType String @map("event_type") @db.VarChar(60)
|
||||
fromState String? @map("from_state") @db.VarChar(40)
|
||||
toState String? @map("to_state") @db.VarChar(40)
|
||||
sequence Int
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(150)
|
||||
payload Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask? @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, sequence])
|
||||
@@index([eventType, createdAt])
|
||||
@@map("orchestration_events")
|
||||
}
|
||||
|
||||
model CorporateRoadmap {
|
||||
model OrchestrationBudgetLedger {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
cycleName String
|
||||
month String
|
||||
seasonalTheme String
|
||||
strategicGoals String[]
|
||||
plannedArticlesCount Int
|
||||
plannedRefreshesCount Int
|
||||
plannedCatalogEnrichments Int
|
||||
isActive Boolean @default(false)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
goals CorporateGoal[]
|
||||
@@index([month])
|
||||
@@map("corporate_roadmaps")
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
amountCents Int @map("amount_cents")
|
||||
kind String @db.VarChar(40)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, createdAt])
|
||||
@@map("orchestration_budget_ledger")
|
||||
}
|
||||
model OrchestrationKillSwitch {
|
||||
scope String @id @db.VarChar(80)
|
||||
level String @db.VarChar(30)
|
||||
active Boolean @default(true)
|
||||
reason String @db.Text
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
version Int @default(1)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@map("orchestration_kill_switches")
|
||||
}
|
||||
|
||||
model CorporateGoal {
|
||||
// Transactional dispatch intent. Lease tokens are server-only fencing credentials.
|
||||
model PrepareWorkflowOutbox {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roadmapId String @db.Uuid
|
||||
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
|
||||
title String
|
||||
department String
|
||||
acceptanceCriteria String
|
||||
metric String
|
||||
target Float?
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
tasks CorporateTask[]
|
||||
@@index([roadmapId])
|
||||
@@map("corporate_goals")
|
||||
}
|
||||
|
||||
model CorporateEffect {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
metric String
|
||||
availability String
|
||||
baseline Float?
|
||||
observed Float?
|
||||
source String
|
||||
observedAt DateTime @db.Timestamptz()
|
||||
recordedBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_effects")
|
||||
}
|
||||
|
||||
model CorporateReport {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
day String @unique
|
||||
summary String
|
||||
snapshot Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_reports")
|
||||
}
|
||||
|
||||
model CorporateOperation {
|
||||
key String @id
|
||||
payloadHash String
|
||||
response Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_operations")
|
||||
taskId String @unique @map("task_id") @db.Uuid
|
||||
status String @default("PENDING") @db.VarChar(20)
|
||||
attempts Int @default(0)
|
||||
leaseOwner String? @map("lease_owner") @db.VarChar(100)
|
||||
leaseToken String? @map("lease_token") @db.Uuid
|
||||
leaseUntil DateTime? @map("lease_until") @db.Timestamptz()
|
||||
heartbeatAt DateTime? @map("heartbeat_at") @db.Timestamptz()
|
||||
runId String? @map("run_id") @db.Uuid
|
||||
reservationId String? @map("reservation_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@index([status, leaseUntil])
|
||||
@@map("prepare_workflow_outbox")
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const defaultFaqs = [
|
||||
{
|
||||
order: 1,
|
||||
question: 'آیا برای خرید مکملهای تخصصی کنینا به نسخه دامپزشک نیاز است؟',
|
||||
answer: 'خیر، مکملهای غذایی و درمانی کنینا بدون نسخه قابل سفارش هستند. با این وجود جهت تعیین دقیقترین دوز مصرفی متناسب با سن، وزن و شرایط بالینی پت دلبندتان، میتوانید از خدمات مشاوره تخصصی و رایگان دامپزشکان کنینا استفاده نمایید.',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
order: 2,
|
||||
question: 'چگونه میتوانم از اصالت مکملهای آلمانی کنینا اطمینان حاصل کنم؟',
|
||||
answer: 'تمامی محصولات کنینا در ایران به صورت ۱۰۰٪ اورجینال و با هولوگرام اصالت، بارکد رسمی کارخانه Canina pharma GmbH آلمان و بچنامبر معتبر عرضه میگردند و اصالت آنها تضمین بالینی و قانونی دارد.',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
order: 3,
|
||||
question: 'ارسال سفارشها به چه صورت است و چقدر زمان میبرد؟',
|
||||
answer: 'سفارشهای تهران از طریق پیک اختصاصی و اکسپرس در همان روز یا روز بعد و سفارشهای سراسر کشور از طریق پست پیشتاز و تیپاکس ظرف ۲ الی ۴ روز کاری با بستهبندی ایمن و استاندارد تحویل داده میشوند.',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
order: 4,
|
||||
question: 'شرایط ارسال رایگان سفارشها چیست؟',
|
||||
answer: 'سفارشهای بالای ۲,۰۰۰,۰۰۰ تومان در سراسر کشور مشمول ارسال کاملاً رایگان کنینا خواهند شد.',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
order: 5,
|
||||
question: 'آیا امکان دریافت مشاوره قبل از خرید مکمل مفاصل یا کلسیم وجود دارد؟',
|
||||
answer: 'بله، شما میتوانید از طریق کلید شناور «درخواست مشاوره تلفنی» در سایت یا شماره تماس پشتیبانی با کارشناسان و کادر دامپزشکی ما گفتگوی مستقیم و رایگان داشته باشید.',
|
||||
isActive: true,
|
||||
},
|
||||
];
|
||||
|
||||
async function seedRealFaqs() {
|
||||
console.log('--- Seeding Real Customer FAQs ---');
|
||||
for (const item of defaultFaqs) {
|
||||
await prisma.fAQ.create({
|
||||
data: item,
|
||||
});
|
||||
}
|
||||
const count = await prisma.fAQ.count();
|
||||
console.log(`Successfully seeded real customer FAQs. Total count: ${count}`);
|
||||
}
|
||||
|
||||
seedRealFaqs()
|
||||
.catch((err) => {
|
||||
console.error('Seed error:', err);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('--- Inspecting and Cleaning FAQs ---');
|
||||
|
||||
const totalBefore = await prisma.fAQ.count();
|
||||
console.log(`Total FAQs before: ${totalBefore}`);
|
||||
|
||||
const activeCount = await prisma.fAQ.count({ where: { isActive: true } });
|
||||
const inactiveCount = await prisma.fAQ.count({ where: { isActive: false } });
|
||||
console.log(`Active FAQs: ${activeCount}, Inactive FAQs: ${inactiveCount}`);
|
||||
|
||||
// Fetch sample of active and inactive
|
||||
const sampleActive = await prisma.fAQ.findMany({
|
||||
where: { isActive: true },
|
||||
select: { id: true, question: true, order: true },
|
||||
take: 5,
|
||||
});
|
||||
console.log('Sample Active FAQs:', JSON.stringify(sampleActive, null, 2));
|
||||
|
||||
// Find tasks that contain content development phrases
|
||||
const tasksToDelete = await prisma.fAQ.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ question: { contains: 'راهنمای' } },
|
||||
{ question: { contains: 'اینفوگرافیک' } },
|
||||
{ question: { contains: 'نگارش' } },
|
||||
{ question: { contains: 'تدوین' } },
|
||||
{ question: { contains: 'تولید' } },
|
||||
{ question: { contains: 'مقاله' } },
|
||||
],
|
||||
},
|
||||
select: { id: true, question: true, isActive: true },
|
||||
});
|
||||
|
||||
console.log(`Found ${tasksToDelete.length} content tasks inside FAQs table.`);
|
||||
|
||||
if (tasksToDelete.length > 0) {
|
||||
const ids = tasksToDelete.map(t => t.id);
|
||||
const deleteResult = await prisma.fAQ.deleteMany({
|
||||
where: { id: { in: ids } },
|
||||
});
|
||||
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks from faqs.`);
|
||||
}
|
||||
|
||||
const totalAfter = await prisma.fAQ.count();
|
||||
console.log(`Total FAQs remaining: ${totalAfter}`);
|
||||
|
||||
const remaining = await prisma.fAQ.findMany({
|
||||
select: { id: true, question: true, isActive: true, order: true },
|
||||
take: 10,
|
||||
});
|
||||
console.log('Remaining FAQs:', JSON.stringify(remaining, null, 2));
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -57,7 +57,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getUsers(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getUsers(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("users")
|
||||
@@ -145,7 +145,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getProducts(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getProducts(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("products")
|
||||
@@ -206,7 +206,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
||||
async getOrders(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getOrders(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get("orders/:id")
|
||||
@@ -354,4 +354,34 @@ export class AdminController {
|
||||
await this.settingsService.updateBulkUiTexts(body);
|
||||
return { success: true, data: body };
|
||||
}
|
||||
|
||||
|
||||
@Get("symptoms")
|
||||
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحهبندی، جستجو و متادیتا" })
|
||||
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
|
||||
const res = await this.adminService.getSymptoms(query);
|
||||
return res;
|
||||
}
|
||||
|
||||
@Post("symptoms")
|
||||
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
|
||||
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
const res = await this.adminService.createSymptom(body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Put("symptoms/:id")
|
||||
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
|
||||
async updateSymptom(@Param("id") id: string, @Body() body: any) {
|
||||
const res = await this.adminService.updateSymptom(id, body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Delete("symptoms/:id")
|
||||
@ApiOperation({ summary: "حذف علامت درمانی" })
|
||||
async deleteSymptom(@Param("id") id: string) {
|
||||
const res = await this.adminService.deleteSymptom(id);
|
||||
return res;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CorporateController } from "./hermes/corporate.controller";
|
||||
import { CorporateService } from "./hermes/corporate.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { ReportsController } from "./reports.controller";
|
||||
@@ -35,7 +33,6 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
@Module({
|
||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||
controllers: [
|
||||
CorporateController,
|
||||
AdminController,
|
||||
ReportsController,
|
||||
MediaController,
|
||||
@@ -55,7 +52,6 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
CorporateService,
|
||||
AdminService,
|
||||
ReportsService,
|
||||
MediaService,
|
||||
|
||||
@@ -1869,4 +1869,164 @@ export class AdminService {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
|
||||
const page = Math.max(1, Number(params?.page) || 1);
|
||||
const limit = Math.max(1, Number(params?.limit) || 20);
|
||||
const offset = (page - 1) * limit;
|
||||
const search = params?.search?.trim() || '';
|
||||
|
||||
let items: any[] = [];
|
||||
let total = 0;
|
||||
|
||||
if (search) {
|
||||
const searchPattern = `%${search}%`;
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
} else {
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s;
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
}
|
||||
|
||||
const lastPage = Math.ceil(total / limit) || 1;
|
||||
|
||||
return {
|
||||
data: items,
|
||||
meta: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
lastPage,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
|
||||
const name = dto.name.trim();
|
||||
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
|
||||
|
||||
return await this.prisma.$queryRawUnsafe(`
|
||||
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
|
||||
}
|
||||
|
||||
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
// 1. Get existing symptom
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const oldName = existing[0].name;
|
||||
const newName = dto.name?.trim() || oldName;
|
||||
const newSlug = dto.slug?.trim() || existing[0].slug;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Update symptoms table
|
||||
const updated = await tx.$queryRawUnsafe(`
|
||||
UPDATE symptoms
|
||||
SET
|
||||
name = $2,
|
||||
slug = $3,
|
||||
description = $4,
|
||||
meta_title = $5,
|
||||
meta_description = $6,
|
||||
keywords = $7,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1::uuid
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
|
||||
|
||||
// If name changed, cascade update across product_symptoms & products JSON
|
||||
if (oldName !== newName) {
|
||||
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
|
||||
await tx.$executeRaw`
|
||||
UPDATE products
|
||||
SET dosage_config = jsonb_set(
|
||||
dosage_config,
|
||||
'{symptoms}',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
|
||||
ELSE elem
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
|
||||
)
|
||||
)
|
||||
WHERE dosage_config ? 'symptoms'
|
||||
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
|
||||
`;
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async deleteSymptom(id: string) {
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const name = existing[0].name;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Delete join links
|
||||
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
|
||||
// Delete symptom row
|
||||
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
|
||||
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('ApprovalsController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new ApprovalsController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,category:SEO,title:Legacy,payload:{}} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:APPROVED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:REJECTED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,12 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
@@ -83,17 +82,7 @@ export class ApprovalsController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
const item = await (this.prisma as any).approvalRequest.create({
|
||||
data: {
|
||||
department: dto.department,
|
||||
category: dto.category,
|
||||
title: dto.title,
|
||||
payload: dto.payload,
|
||||
testContext: dto.testContext || {},
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@@ -106,7 +95,6 @@ export class ApprovalsController {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
// شبیهسازی بسته به دستهبندی
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
@@ -140,80 +128,7 @@ export class ApprovalsController {
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
|
||||
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
|
||||
}
|
||||
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
if (dto.decision === "REJECTED") {
|
||||
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل میشوند
|
||||
await (this.prisma as any).departmentTask.deleteMany({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
await (this.prisma as any).approvalRequest.delete({
|
||||
where: { id },
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
|
||||
};
|
||||
}
|
||||
|
||||
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر مییابد
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
executedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
||||
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
|
||||
if (existingTask) {
|
||||
await (this.prisma as any).departmentTask.update({
|
||||
where: { id: existingTask.id },
|
||||
data: {
|
||||
status: "TODO",
|
||||
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code: "TSK-" + Date.now().toString().slice(-6),
|
||||
department: item.department,
|
||||
title: item.title,
|
||||
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
|
||||
data: updated,
|
||||
};
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).approvalRequest.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: createdBlog });
|
||||
});
|
||||
|
||||
it("propagates create validation failures", async () => {
|
||||
const req = { user: { id: "admin-user-id" } };
|
||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
||||
});
|
||||
|
||||
it("updateBlog should update blog details and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
const body = {
|
||||
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||
});
|
||||
|
||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
||||
});
|
||||
|
||||
it("deleteBlog should delete blog and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||
|
||||
@@ -203,6 +203,50 @@ describe("Admin BlogsService", () => {
|
||||
expect(result).toEqual(createdBlog);
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
|
||||
|
||||
await service.createBlog(
|
||||
{
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
id: "client-id",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
updatedAt: "2000-01-01T00:00:00.000Z",
|
||||
viewCount: 999999,
|
||||
serverOwned: "must-not-pass",
|
||||
},
|
||||
"user-admin-1",
|
||||
);
|
||||
|
||||
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
|
||||
expect(payload).toEqual(expect.objectContaining({
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
}));
|
||||
expect(payload).not.toHaveProperty("id");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("updatedAt");
|
||||
expect(payload).not.toHaveProperty("viewCount");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
|
||||
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
|
||||
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
|
||||
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
|
||||
await expect(
|
||||
service.createBlog(
|
||||
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
|
||||
"user-admin-1",
|
||||
),
|
||||
).rejects.toThrow(message);
|
||||
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
||||
const futureDate = new Date(Date.now() + 86400000).toISOString();
|
||||
const blogData = {
|
||||
@@ -274,6 +318,81 @@ describe("Admin BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("material freshness and scheduled publishing", () => {
|
||||
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
expect(payload).not.toHaveProperty("markContentUpdated");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
});
|
||||
it("automatically marks freshness when material article content changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { content: "Meaningfully revised content" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
it("does not mark freshness for attribution-only changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
|
||||
});
|
||||
it("allows explicitly clearing contentUpdatedAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
});
|
||||
it("publishes due posts without rewriting createdAt", async () => {
|
||||
const scheduledAt = new Date("2025-02-01T10:00:00Z");
|
||||
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
|
||||
mockPrisma.blog.update.mockResolvedValue({});
|
||||
await service.publishDueScheduledBlogs();
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog security and freshness validation", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
});
|
||||
|
||||
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
|
||||
await service.updateBlog("blog-1", {
|
||||
title: "Allowed title",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
serverOwned: "must-not-pass",
|
||||
});
|
||||
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.title).toBe("Allowed title");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it("rejects an invalid explicit contentUpdatedAt", async () => {
|
||||
await expect(
|
||||
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
|
||||
).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
|
||||
await service.updateBlog("blog-1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
|
||||
await service.updateBlog("blog-1", {
|
||||
contentUpdatedAt: "not-a-date",
|
||||
markContentUpdated: true,
|
||||
});
|
||||
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteBlog", () => {
|
||||
it("should throw NotFoundException if blog not found", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(null);
|
||||
@@ -468,7 +587,6 @@ describe("Admin BlogsService", () => {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: scheduledDate,
|
||||
createdAt: scheduledDate,
|
||||
},
|
||||
});
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -141,16 +142,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async createBlog(data: any, currentUserId: string) {
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const parsed = new Date(value as string | number | Date);
|
||||
if (!Number.isFinite(parsed.getTime())) {
|
||||
throw new BadRequestException(`Invalid ${field}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
||||
const parsedContentUpdatedAt = markContentUpdated
|
||||
? new Date()
|
||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
||||
|
||||
// Connect or create tags
|
||||
const tagConnectOrCreate = [];
|
||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||
@@ -171,13 +187,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || "PUBLISHED";
|
||||
let finalStatus = data.status || "PUBLISHED";
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
data.isPublished !== undefined ? data.isPublished : true;
|
||||
let finalPublishedAt = parsedPublishedAt;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = "SCHEDULED";
|
||||
@@ -191,19 +206,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
const createPayload = {
|
||||
title: data.title,
|
||||
slug: data.slug,
|
||||
content: data.content,
|
||||
excerpt: data.excerpt,
|
||||
authorTeam: data.authorTeam,
|
||||
authorRole: data.authorRole,
|
||||
imageUrl: data.imageUrl,
|
||||
imageAlt: data.imageAlt,
|
||||
imageCaption: data.imageCaption,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
focusKeywords: data.focusKeywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
noIndex: data.noIndex,
|
||||
noFollow: data.noFollow,
|
||||
schemaType: data.schemaType,
|
||||
ogTitle: data.ogTitle,
|
||||
ogDescription: data.ogDescription,
|
||||
ogImage: data.ogImage,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
featured: data.featured,
|
||||
allowComments: data.allowComments,
|
||||
showOnHome: data.showOnHome,
|
||||
homeDisplayMode: data.homeDisplayMode,
|
||||
relatedProductIds: data.relatedProductIds,
|
||||
relatedBlogIds: data.relatedBlogIds,
|
||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
contentUpdatedAt: parsedContentUpdatedAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||
: {}),
|
||||
};
|
||||
} satisfies Prisma.BlogCreateInput;
|
||||
|
||||
const created = await this.prisma.blog.create({
|
||||
data: createPayload,
|
||||
@@ -223,19 +264,83 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
"content",
|
||||
"excerpt",
|
||||
"authorTeam",
|
||||
"authorRole",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
"metaTitle",
|
||||
"metaDescription",
|
||||
"keywords",
|
||||
"focusKeywords",
|
||||
"canonicalUrl",
|
||||
"noIndex",
|
||||
"noFollow",
|
||||
"schemaType",
|
||||
"ogTitle",
|
||||
"ogDescription",
|
||||
"ogImage",
|
||||
"status",
|
||||
"isPublished",
|
||||
"featured",
|
||||
"allowComments",
|
||||
"showOnHome",
|
||||
"homeDisplayMode",
|
||||
"relatedProductIds",
|
||||
"relatedBlogIds",
|
||||
] as const;
|
||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
||||
for (const field of mutableScalarFields) {
|
||||
if (data[field] !== undefined) {
|
||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
const materialContentFields = [
|
||||
"title",
|
||||
"content",
|
||||
"excerpt",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
] as const;
|
||||
const hasMaterialContentChange = materialContentFields.some(
|
||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
||||
);
|
||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(updatePayload, {
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
@@ -245,7 +350,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
? { category: { connect: { id: categoryId } } }
|
||||
: { category: { disconnect: true } }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
@@ -259,7 +364,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
updatePayload.status = "PUBLISHED";
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
@@ -472,7 +576,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
|
||||
describe("department task completion policy", () => {
|
||||
it("rejects model-only output without a live deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: null,
|
||||
acceptanceCriteria: { criteria: ["live URL responds 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without acceptance criteria", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: null,
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("allows completion with URL, criteria and QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "canina://blog/sample-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "git://stage/canina-repo#commit123",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects missing or placeholder post-tsk article deliverables", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion when QA evidence reports missing article or 404 error", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export interface CompletableTask {
|
||||
code?: string | null;
|
||||
title?: string | null;
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
if (!criteria) return false;
|
||||
if (typeof criteria === "string") return criteria.trim().length > 0;
|
||||
if (Array.isArray(criteria)) return criteria.length > 0;
|
||||
if (typeof criteria === "object") {
|
||||
const value = criteria as Record<string, unknown>;
|
||||
const items = value.criteria;
|
||||
return Array.isArray(items) ? items.length > 0 : Object.keys(value).length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasValidQaEvidence(logs: unknown): boolean {
|
||||
if (!Array.isArray(logs)) return false;
|
||||
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
|
||||
|
||||
let foundValidPass = false;
|
||||
for (const log of logs) {
|
||||
if (!log || typeof log !== "object") continue;
|
||||
const entry = log as Record<string, unknown>;
|
||||
const status = String(entry.status || "").toUpperCase();
|
||||
const note = String(entry.note || "").toLowerCase();
|
||||
|
||||
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
|
||||
if (
|
||||
note.includes("404") ||
|
||||
note.includes("مقاله یافت نشد") ||
|
||||
note.includes("not found") ||
|
||||
note.includes("missing article") ||
|
||||
note.includes("post-tsk")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (validPassStatuses.includes(status)) {
|
||||
foundValidPass = true;
|
||||
}
|
||||
}
|
||||
return foundValidPass;
|
||||
}
|
||||
|
||||
export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
const rawUrl = task.deliverableUrl?.trim();
|
||||
if (!rawUrl) {
|
||||
throw new BadRequestException("DONE requires a verifiable deliverable URL");
|
||||
}
|
||||
|
||||
const lowerUrl = rawUrl.toLowerCase();
|
||||
|
||||
// Reject internal pseudo-protocols
|
||||
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
|
||||
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Reject git repository pointers or staging branches as production deliverables
|
||||
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
|
||||
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Must be an HTTP or HTTPS URL
|
||||
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
|
||||
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
|
||||
}
|
||||
|
||||
// Reject deleted or placeholder post-tsk articles
|
||||
if (/post[-_]?tsk/i.test(rawUrl)) {
|
||||
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
|
||||
}
|
||||
if (task.title && /post[-_]?tsk/i.test(task.title)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
|
||||
}
|
||||
if (task.code && /post[-_]?tsk/i.test(task.code)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
|
||||
}
|
||||
|
||||
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
|
||||
throw new BadRequestException("DONE requires explicit acceptance criteria");
|
||||
}
|
||||
|
||||
if (!hasValidQaEvidence(task.executionLogs)) {
|
||||
throw new BadRequestException("DONE requires QA/production verification evidence");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('DepartmentTasksController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new DepartmentTasksController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,title:Legacy} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:DONE} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:TODO} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,12 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
@@ -112,37 +112,7 @@ export class DepartmentTasksController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code,
|
||||
department: body.department,
|
||||
title: body.title,
|
||||
description: body.description || null,
|
||||
status: body.status || "TODO",
|
||||
priority: body.priority || "MEDIUM",
|
||||
assignee: body.assignee || "AI_AGENT",
|
||||
acceptanceCriteria: body.acceptanceCriteria || null,
|
||||
executionLogs: body.executionLogs || [],
|
||||
deliverableUrl: body.deliverableUrl || null,
|
||||
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه لاگها
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: task.id,
|
||||
action: "CREATE",
|
||||
department: task.department,
|
||||
actor: task.assignee || "SYSTEM",
|
||||
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
|
||||
newValues: task,
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: task };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@@ -151,58 +121,7 @@ export class DepartmentTasksController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
const existing = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
logs.push({
|
||||
timestamp: new Date().toISOString(),
|
||||
status: body.status,
|
||||
note: body.logNote,
|
||||
});
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
status: body.status,
|
||||
executionLogs: logs,
|
||||
};
|
||||
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
||||
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
||||
if (body.status === "DONE") updateData.completedAt = new Date();
|
||||
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه میشود
|
||||
if (body.status === "TODO" && body.logNote) {
|
||||
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).departmentTask.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: updated.id,
|
||||
action: "UPDATE",
|
||||
department: updated.department,
|
||||
actor: "SYSTEM",
|
||||
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
|
||||
oldValues: { status: existing.status },
|
||||
newValues: { status: updated.status, note: body.logNote },
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: updated };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف تسک" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).departmentTask.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,16 @@ export class DecideApprovalDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
outcome?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
evidence?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import {
|
||||
normalizeSearch,
|
||||
pagination,
|
||||
taskInput,
|
||||
monthlyPlanInput,
|
||||
} from './corporate-policy';
|
||||
describe('corporate contract policy', () => {
|
||||
it.each([
|
||||
['2027-02', 28],
|
||||
['2028-02', 29],
|
||||
['2028-04', 30],
|
||||
['2028-01', 31],
|
||||
])('enforces real calendar coverage for %s', (month, count) => {
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
const body = {
|
||||
roadmapId: id,
|
||||
month,
|
||||
needs: [],
|
||||
dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({
|
||||
title: 'new article',
|
||||
description: 'instruction',
|
||||
actionType: 'BLOG_NEW',
|
||||
department: 'CONTENT_SEO',
|
||||
goalId: id,
|
||||
sourceIds: [id],
|
||||
dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`,
|
||||
})),
|
||||
};
|
||||
expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count));
|
||||
expect(() =>
|
||||
monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
monthlyPlanInput({
|
||||
...body,
|
||||
dailyArticles: [...body.dailyArticles, body.dailyArticles[0]],
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
it('normalizes Persian letters, digits and separators', () => {
|
||||
expect(normalizeSearch('كيك ۱۲۳ (ة)')).toBe('کیک 123 ه');
|
||||
});
|
||||
it('bounds pagination and sort keys', () => {
|
||||
expect(pagination({ limit: '100' }).limit).toBe(100);
|
||||
expect(() => pagination({ limit: '101' })).toThrow();
|
||||
expect(() => pagination({ page: '-1' })).toThrow();
|
||||
expect(() => pagination({ sortBy: 'password' })).toThrow();
|
||||
});
|
||||
it('defaults CEO priority and rejects status/command injection', () => {
|
||||
expect(
|
||||
taskInput({
|
||||
title: 'عنوان',
|
||||
description: 'کار',
|
||||
department: 'CONTENT_SEO',
|
||||
}).priority,
|
||||
).toBe('CEO_EXPEDITE');
|
||||
expect(() =>
|
||||
taskInput({
|
||||
title: 'x',
|
||||
description: 'x',
|
||||
department: 'CONTENT_SEO',
|
||||
status: 'DONE',
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,317 +0,0 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
export const departments = [
|
||||
'CONTENT_SEO',
|
||||
'CATALOG_COMMERCE',
|
||||
'WIKI_SCIENTIFIC',
|
||||
'TECH_DEVOPS',
|
||||
'MARKET_INTELLIGENCE',
|
||||
];
|
||||
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||
export const statuses = [
|
||||
'TODO',
|
||||
'IN_PROGRESS',
|
||||
'TEST',
|
||||
'DONE',
|
||||
'BLOCKED',
|
||||
'REJECTED',
|
||||
'CANCELLED',
|
||||
];
|
||||
export function object(value: unknown, keys: string[]): Record<string, any> {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
Object.keys(value).some((k) => !keys.includes(k))
|
||||
)
|
||||
throw new BadRequestException('Invalid fields');
|
||||
return value as Record<string, any>;
|
||||
}
|
||||
export function text(value: unknown, max = 10000): string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
||||
throw new BadRequestException('Invalid text');
|
||||
return value.trim();
|
||||
}
|
||||
export function uuid(value: unknown): string {
|
||||
const id = text(value, 36);
|
||||
if (
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
id,
|
||||
)
|
||||
)
|
||||
throw new BadRequestException('Invalid UUID');
|
||||
return id.toLowerCase();
|
||||
}
|
||||
export function choice(value: unknown, values: string[]): string {
|
||||
if (typeof value !== 'string' || !values.includes(value))
|
||||
throw new BadRequestException('Invalid enum');
|
||||
return value;
|
||||
}
|
||||
export function normalizeSearch(value: string): string {
|
||||
return value
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/[يى]/g, 'ی')
|
||||
.replace(/ك/g, 'ک')
|
||||
.replace(/ة/g, 'ه')
|
||||
.replace(/[۰-۹٠-٩]/g, (c) =>
|
||||
String(
|
||||
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
|
||||
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
|
||||
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
|
||||
),
|
||||
)
|
||||
.replace(/[\u200c\u200d()()]/g, ' ')
|
||||
.replace(/[\u064b-\u065f]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
export function pagination(q: Record<string, any>) {
|
||||
const page = Number(q.page ?? 1),
|
||||
limit = Number(q.limit ?? 20);
|
||||
if (
|
||||
!Number.isSafeInteger(page) ||
|
||||
page < 1 ||
|
||||
page > 1000000 ||
|
||||
!Number.isInteger(limit) ||
|
||||
limit < 1 ||
|
||||
limit > 100
|
||||
)
|
||||
throw new BadRequestException('Invalid pagination');
|
||||
const sortBy = choice(q.sortBy ?? 'createdAt', [
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'title',
|
||||
'taskCode',
|
||||
'priority',
|
||||
'status',
|
||||
]);
|
||||
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
|
||||
| 'asc'
|
||||
| 'desc';
|
||||
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
|
||||
}
|
||||
export function meta(total: number, page: number, limit: number) {
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
return {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
hasNextPage: page < totalPages,
|
||||
hasPrevPage: page > 1,
|
||||
};
|
||||
}
|
||||
export function taskInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'department',
|
||||
'description',
|
||||
'priority',
|
||||
'parentId',
|
||||
'goalId',
|
||||
'actionType',
|
||||
'dueCycle',
|
||||
]);
|
||||
return {
|
||||
title: text(b.title, 300),
|
||||
description: text(b.description),
|
||||
department: choice(b.department, departments),
|
||||
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
|
||||
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
|
||||
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
|
||||
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
|
||||
'CEO_DIRECTIVE',
|
||||
'BLOG_NEW',
|
||||
'BLOG_UPDATE',
|
||||
'CATALOG_ENRICH',
|
||||
'WIKI_ENRICH',
|
||||
'RESEARCH',
|
||||
'ENGINEERING',
|
||||
]),
|
||||
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
|
||||
};
|
||||
}
|
||||
export function planMonth(value: unknown): string {
|
||||
const month = text(value, 7);
|
||||
if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month))
|
||||
throw new BadRequestException('Invalid YYYY-MM month');
|
||||
return month;
|
||||
}
|
||||
export function monthlyPlanInput(input: unknown) {
|
||||
const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']);
|
||||
const month = planMonth(b.month);
|
||||
const days = new Date(
|
||||
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0),
|
||||
).getUTCDate();
|
||||
if (
|
||||
!Array.isArray(b.dailyArticles) ||
|
||||
b.dailyArticles.length !== days ||
|
||||
!Array.isArray(b.needs) ||
|
||||
b.needs.length > 200
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Full daily article coverage and bounded needs required',
|
||||
);
|
||||
const mapping: Record<string, string> = {
|
||||
BLOG_NEW: 'CONTENT_SEO',
|
||||
BLOG_UPDATE: 'CONTENT_SEO',
|
||||
CATALOG_ENRICH: 'CATALOG_COMMERCE',
|
||||
WIKI_ENRICH: 'WIKI_SCIENTIFIC',
|
||||
ENGINEERING: 'TECH_DEVOPS',
|
||||
};
|
||||
const parse = (raw: unknown, daily: boolean) => {
|
||||
const t = object(raw, [
|
||||
'title',
|
||||
'description',
|
||||
'department',
|
||||
'priority',
|
||||
'goalId',
|
||||
'actionType',
|
||||
'dueCycle',
|
||||
'sourceIds',
|
||||
'target',
|
||||
'reason',
|
||||
]);
|
||||
const actionType = choice(
|
||||
t.actionType,
|
||||
daily
|
||||
? ['BLOG_NEW']
|
||||
: ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'],
|
||||
);
|
||||
const department = choice(t.department, [mapping[actionType]]);
|
||||
const dueCycle = text(t.dueCycle, 10);
|
||||
const date = new Date(dueCycle + 'T00:00:00Z');
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) ||
|
||||
!dueCycle.startsWith(month + '-') ||
|
||||
!Number.isFinite(date.getTime()) ||
|
||||
date.toISOString().slice(0, 10) !== dueCycle
|
||||
)
|
||||
throw new BadRequestException('Invalid plan day');
|
||||
if (
|
||||
!Array.isArray(t.sourceIds) ||
|
||||
!t.sourceIds.length ||
|
||||
t.sourceIds.length > 30
|
||||
)
|
||||
throw new BadRequestException('Stored sources required');
|
||||
const sourceIds = t.sourceIds.map(uuid);
|
||||
if (new Set(sourceIds).size !== sourceIds.length)
|
||||
throw new BadRequestException('Duplicate source');
|
||||
if (daily && (t.target !== undefined || t.reason !== undefined))
|
||||
throw new BadRequestException('Daily new articles cannot be needs');
|
||||
return {
|
||||
title: text(t.title, 300),
|
||||
description: text(t.description),
|
||||
department,
|
||||
actionType,
|
||||
dueCycle,
|
||||
priority: choice(t.priority ?? 'MEDIUM', priorities),
|
||||
goalId: uuid(t.goalId),
|
||||
sourceIds,
|
||||
...(daily
|
||||
? {}
|
||||
: { target: text(t.target, 2000), reason: text(t.reason) }),
|
||||
};
|
||||
};
|
||||
const dailyArticles = b.dailyArticles.map((t) => parse(t, true));
|
||||
if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days)
|
||||
throw new BadRequestException(
|
||||
'Exactly one new article per calendar day required',
|
||||
);
|
||||
const needs = b.needs.map((t) => parse(t, false));
|
||||
if (
|
||||
new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle])))
|
||||
.size !== needs.length
|
||||
)
|
||||
throw new BadRequestException('Duplicate need');
|
||||
return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs };
|
||||
}
|
||||
export function canonical(value: any): string {
|
||||
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
||||
if (value && typeof value === 'object')
|
||||
return (
|
||||
'{' +
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
|
||||
.join(',') +
|
||||
'}'
|
||||
);
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
/** Public projection must also cover nested evidence and child records. */
|
||||
export function publicData(value: any): any {
|
||||
if (value instanceof Date) return value;
|
||||
if (Array.isArray(value)) return value.map(publicData);
|
||||
if (value && typeof value === 'object')
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => key !== 'claimToken')
|
||||
.map(([key, item]) => [key, publicData(item)]),
|
||||
);
|
||||
return value;
|
||||
}
|
||||
export function httpsUrl(value: unknown): string {
|
||||
const raw = text(value, 2000);
|
||||
try {
|
||||
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw))
|
||||
throw new Error();
|
||||
const u = new URL(raw);
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (
|
||||
u.protocol !== 'https:' ||
|
||||
u.username ||
|
||||
u.password ||
|
||||
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
|
||||
host === 'localhost' ||
|
||||
host.endsWith('.localhost') ||
|
||||
/(^|\.)example\.(com|org|net)$/.test(host)
|
||||
)
|
||||
throw new Error();
|
||||
return raw;
|
||||
} catch {
|
||||
throw new BadRequestException('Valid HTTPS host URL required');
|
||||
}
|
||||
}
|
||||
export function timestamp(value: unknown, message: string): Date {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
const date = new Date(value);
|
||||
if (
|
||||
!Number.isFinite(date.getTime()) ||
|
||||
date.getTime() > Date.now() ||
|
||||
date.toISOString().slice(0, 19) !== value.slice(0, 19)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
return date;
|
||||
}
|
||||
export function evidenceInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'claimToken',
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'summary',
|
||||
'tool',
|
||||
'result',
|
||||
]);
|
||||
const uri = text(b.artifactUri, 2000);
|
||||
|
||||
const sha = text(b.sha256, 64);
|
||||
if (!/^[a-f0-9]{64}$/.test(sha))
|
||||
throw new BadRequestException('Invalid digest');
|
||||
if (uri.startsWith('urn:')) {
|
||||
if (uri !== 'urn:sha256:' + sha)
|
||||
throw new BadRequestException('Digest locator mismatch');
|
||||
} else httpsUrl(uri);
|
||||
return {
|
||||
claimToken: uuid(b.claimToken),
|
||||
artifactUri: uri,
|
||||
sha256: sha,
|
||||
summary: text(b.summary),
|
||||
tool: text(b.tool, 100),
|
||||
result: text(b.result),
|
||||
};
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../common/guards/roles.guard';
|
||||
import { Roles } from '../../common/decorators/roles.decorator';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { text } from './corporate-policy';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/hermes')
|
||||
export class CorporateController {
|
||||
constructor(private readonly service: CorporateService) {}
|
||||
private actor(req: any) {
|
||||
// API keys must use their authenticated key identity, not an editable worker label.
|
||||
const user = req.user;
|
||||
const id = user?.id ?? user?.sub;
|
||||
if (!id) throw new UnauthorizedException('Authenticated subject required');
|
||||
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
|
||||
}
|
||||
private key(key?: string) {
|
||||
return text(key, 200);
|
||||
}
|
||||
@Get('runtime') runtime() {
|
||||
return {
|
||||
mode: 'MANUAL_DORMANT',
|
||||
schedulesEnabled: false,
|
||||
externalExecutionEnabled: false,
|
||||
};
|
||||
}
|
||||
@Get('tasks') tasks(@Query() query: Record<string, any>) {
|
||||
return this.service.tasks(query);
|
||||
}
|
||||
@Get('tasks/:id') detail(@Param('id') id: string) {
|
||||
return this.service.detail(id);
|
||||
}
|
||||
@Post('tasks') create(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.create(this.actor(req), key ?? randomUUID(), body);
|
||||
}
|
||||
@Post('claims') claim(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.claim(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Post('tasks/:id/evidence') evidence(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.submitEvidence(
|
||||
this.actor(req),
|
||||
this.key(key),
|
||||
id,
|
||||
body,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/reviews') review(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.review(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Post('tasks/:id/effects') effect(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.effect(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Get('market-insights') insights(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('market-insights', q);
|
||||
}
|
||||
@Post('market-insights') research(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.research(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('monthly-roadmap', q);
|
||||
}
|
||||
@Post('monthly-roadmap') roadmap(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.roadmap(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Post('monthly-plans') persistMonthlyPlan(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.persistMonthlyPlan(
|
||||
this.actor(req),
|
||||
this.key(key),
|
||||
body,
|
||||
);
|
||||
}
|
||||
@Get('monthly-plans/:roadmapId') monthlyPlan(
|
||||
@Param('roadmapId') roadmapId: string,
|
||||
@Query('month') month: string,
|
||||
) {
|
||||
return this.service.monthlyPlan(roadmapId, month);
|
||||
}
|
||||
@Get('reports') reports(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('reports', q);
|
||||
}
|
||||
@Post('reports') report(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.report(this.actor(req), this.key(key), body);
|
||||
}
|
||||
}
|
||||
@@ -1,840 +0,0 @@
|
||||
import passport from 'passport';
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CorporateController } from './corporate.controller';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { ApiKeysService } from '../api-keys.service';
|
||||
|
||||
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||
? describe
|
||||
: describe.skip;
|
||||
integration('corporate API / disposable PostgreSQL', () => {
|
||||
let app: INestApplication, db: PrismaService;
|
||||
const key = () => randomUUID();
|
||||
const post = (path: string, body: any, actor = 'executor', op = key()) =>
|
||||
request(app.getHttpServer())
|
||||
.post('/admin/hermes/' + path)
|
||||
.set('x-api-key', actor)
|
||||
.set('Idempotency-Key', op)
|
||||
.send(body);
|
||||
const input = {
|
||||
title: 'كيك ۱۲۳',
|
||||
description: 'integration fixture',
|
||||
department: 'CONTENT_SEO',
|
||||
};
|
||||
beforeAll(async () => {
|
||||
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
|
||||
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||
throw new Error('Disposable loopback corporate_test DB required');
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'test-only-not-runtime',
|
||||
},
|
||||
(_payload, done) => done(null, false),
|
||||
),
|
||||
);
|
||||
db = new PrismaClient({
|
||||
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
|
||||
}) as PrismaService;
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [CorporateController],
|
||||
providers: [
|
||||
CorporateService,
|
||||
{ provide: PrismaService, useValue: db },
|
||||
{
|
||||
provide: ApiKeysService,
|
||||
useValue: {
|
||||
validateKey: async (id: string) => ({
|
||||
id,
|
||||
isApiKey: true,
|
||||
role: 'Admin',
|
||||
scopes: id === 'unscoped' ? [] : ['admin'],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication();
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (db)
|
||||
await db.$executeRawUnsafe(
|
||||
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||
);
|
||||
await app?.close();
|
||||
await db?.$disconnect();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.$executeRawUnsafe(
|
||||
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||
);
|
||||
});
|
||||
async function planFixture(month = '2996-02') {
|
||||
const research = (
|
||||
await post('market-insights', {
|
||||
title: 'monthly fixture',
|
||||
category: 'TREND',
|
||||
source: 'disposable receipt',
|
||||
opportunity: 'test planning',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'plan',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: {
|
||||
method: 'fixture',
|
||||
collector: 'jest',
|
||||
context: 'disposable',
|
||||
},
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'fixture',
|
||||
excerpt: 'test only',
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
const roadmap = (
|
||||
await post('monthly-roadmap', {
|
||||
researchId: research.id,
|
||||
month,
|
||||
cycleName: 'monthly fixture',
|
||||
seasonalTheme: 'test',
|
||||
strategicGoals: ['coverage'],
|
||||
plannedArticlesCount: 29,
|
||||
plannedRefreshesCount: 0,
|
||||
plannedCatalogEnrichments: 0,
|
||||
goals: [
|
||||
'CONTENT_SEO',
|
||||
'CATALOG_COMMERCE',
|
||||
'WIKI_SCIENTIFIC',
|
||||
'TECH_DEVOPS',
|
||||
].map((department) => ({
|
||||
title: department,
|
||||
department,
|
||||
acceptanceCriteria: 'independent QA',
|
||||
metric: 'coverage',
|
||||
})),
|
||||
}).expect(201)
|
||||
).body;
|
||||
const task = (
|
||||
actionType: string,
|
||||
department: string,
|
||||
dueCycle: string,
|
||||
) => ({
|
||||
title: actionType + ' ' + dueCycle,
|
||||
description: 'Evidence-backed instruction requiring QA',
|
||||
actionType,
|
||||
department,
|
||||
dueCycle,
|
||||
goalId: roadmap.goals.find((g: any) => g.department === department).id,
|
||||
sourceIds: [research.sources[0].id],
|
||||
...(actionType === 'BLOG_NEW'
|
||||
? {}
|
||||
: {
|
||||
target: 'https://canina.ir/identified-gap',
|
||||
reason: 'Documented coverage gap',
|
||||
}),
|
||||
});
|
||||
return {
|
||||
research,
|
||||
roadmap,
|
||||
body: {
|
||||
roadmapId: roadmap.id,
|
||||
month,
|
||||
dailyArticles: Array.from({ length: 29 }, (_, i) =>
|
||||
task(
|
||||
'BLOG_NEW',
|
||||
'CONTENT_SEO',
|
||||
`${month}-${String(i + 1).padStart(2, '0')}`,
|
||||
),
|
||||
),
|
||||
needs: [
|
||||
task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'),
|
||||
task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'),
|
||||
task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'),
|
||||
task('ENGINEERING', 'TECH_DEVOPS', month + '-04'),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => {
|
||||
const { body, research, roadmap } = await planFixture();
|
||||
body.roadmapId = body.roadmapId.toUpperCase();
|
||||
for (const entry of [...body.dailyArticles, ...body.needs]) {
|
||||
entry.goalId = entry.goalId.toUpperCase();
|
||||
entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase());
|
||||
}
|
||||
const op = key();
|
||||
const created = (
|
||||
await post('monthly-plans', body, 'planner', op).expect(201)
|
||||
).body;
|
||||
expect(created.tasks).toHaveLength(33);
|
||||
const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH');
|
||||
expect(need.logs[0].payload).toMatchObject({
|
||||
target: body.needs[2].target,
|
||||
reason: body.needs[2].reason,
|
||||
});
|
||||
expect(
|
||||
created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'),
|
||||
).toHaveLength(29);
|
||||
expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true);
|
||||
expect(
|
||||
(await post('monthly-plans', body, 'planner', op).expect(201)).body,
|
||||
).toEqual(created);
|
||||
const read = await request(app.getHttpServer())
|
||||
.get(`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(read.body).toEqual(created);
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + created.tasks[0].id)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(detail.body.logs[0].step).toBe('PLANNED');
|
||||
expect(detail.body.logs[0].payload).toMatchObject({
|
||||
researchId: research.id,
|
||||
roadmapId: roadmap.id,
|
||||
month: body.month,
|
||||
dueCycle: body.month + '-01',
|
||||
sourceIds: [research.sources[0].id],
|
||||
});
|
||||
expect(await db.corporateOperation.count()).toBe(3);
|
||||
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||
});
|
||||
it('validates calendar, action separation, needs and stored lineage without partial writes', async () => {
|
||||
const { body } = await planFixture();
|
||||
const mutations: Array<[number, (b: any) => void]> = [
|
||||
[400, (b) => b.dailyArticles.pop()],
|
||||
[400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)],
|
||||
[400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')],
|
||||
[400, (b) => (b.month = '2028-13')],
|
||||
[400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')],
|
||||
[400, (b) => (b.needs[0].actionType = 'BLOG_NEW')],
|
||||
[400, (b) => (b.needs[0].reason = ' ')],
|
||||
[400, (b) => delete b.needs[0].target],
|
||||
[400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')],
|
||||
[400, (b) => (b.dailyArticles[0].sourceIds = [])],
|
||||
[409, (b) => (b.dailyArticles[0].sourceIds = [key()])],
|
||||
[409, (b) => (b.dailyArticles[0].goalId = key())],
|
||||
[409, (b) => (b.needs[0].goalId = b.needs[1].goalId)],
|
||||
[409, (b) => (b.roadmapId = key())],
|
||||
];
|
||||
for (const [status, mutate] of mutations) {
|
||||
const invalid = JSON.parse(JSON.stringify(body));
|
||||
mutate(invalid);
|
||||
await post('monthly-plans', invalid).expect(status);
|
||||
expect(await db.corporateTask.count()).toBe(0);
|
||||
expect(await db.corporateEvent.count()).toBe(0);
|
||||
expect(await db.corporateOperation.count()).toBe(2);
|
||||
}
|
||||
});
|
||||
it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => {
|
||||
const { body } = await planFixture();
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/hermes/monthly-plans')
|
||||
.send(body)
|
||||
.expect(401);
|
||||
await post('monthly-plans', body, 'unscoped').expect(403);
|
||||
const op = key();
|
||||
const otherOp = key();
|
||||
let release!: () => void;
|
||||
let ready!: () => void;
|
||||
const locked = new Promise<void>((r) => (ready = r));
|
||||
const hold = new Promise<void>((r) => (release = r));
|
||||
const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]);
|
||||
const blocker = db.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||
ready();
|
||||
await hold;
|
||||
});
|
||||
await locked;
|
||||
const pending = [
|
||||
post('monthly-plans', body, 'planner', op).then((r) => r),
|
||||
post('monthly-plans', body, 'other', otherOp).then((r) => r),
|
||||
];
|
||||
try {
|
||||
let waiters = 0;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity
|
||||
WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`;
|
||||
waiters = rows.length;
|
||||
if (waiters >= 2) break;
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
expect(waiters).toBeGreaterThanOrEqual(2);
|
||||
} finally {
|
||||
release();
|
||||
await blocker;
|
||||
}
|
||||
const results = await Promise.all(pending);
|
||||
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
|
||||
expect(await db.corporateTask.count()).toBe(33);
|
||||
expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe(
|
||||
33,
|
||||
);
|
||||
const winner = results[0].status === 201 ? 'planner' : 'other';
|
||||
const winningOp = winner === 'planner' ? op : otherOp;
|
||||
await post(
|
||||
'monthly-plans',
|
||||
{ ...body, needs: [] },
|
||||
winner,
|
||||
winningOp,
|
||||
).expect(409);
|
||||
expect(
|
||||
(await post('monthly-plans', body, winner, winningOp).expect(201)).body,
|
||||
).toEqual(results[winner === 'planner' ? 0 : 1].body);
|
||||
const runtime = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/runtime')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(runtime.body).toEqual({
|
||||
mode: 'MANUAL_DORMANT',
|
||||
schedulesEnabled: false,
|
||||
externalExecutionEnabled: false,
|
||||
});
|
||||
});
|
||||
it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => {
|
||||
const { body } = await planFixture();
|
||||
// Disposable-only trigger fails after the first task/event have been written.
|
||||
await db.$executeRawUnsafe(
|
||||
`CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`,
|
||||
);
|
||||
await db.$executeRawUnsafe(
|
||||
'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()',
|
||||
);
|
||||
const op = key();
|
||||
try {
|
||||
await post('monthly-plans', body, 'planner', op).expect(500);
|
||||
expect(await db.corporateTask.count()).toBe(0);
|
||||
expect(await db.corporateEvent.count()).toBe(0);
|
||||
expect(await db.corporateOperation.count()).toBe(2);
|
||||
} finally {
|
||||
await db.$executeRawUnsafe(
|
||||
'DROP TRIGGER reject_plan_event ON corporate_events',
|
||||
);
|
||||
await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()');
|
||||
}
|
||||
await post('monthly-plans', body, 'planner', op).expect(201);
|
||||
});
|
||||
it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => {
|
||||
const { body } = await planFixture();
|
||||
await post('monthly-plans', body).expect(201);
|
||||
const legacy = (
|
||||
await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201)
|
||||
).body;
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id);
|
||||
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||
// Model the persisted event's due-day boundary in the disposable DB without changing system time.
|
||||
const planned = await db.corporateTask.findFirstOrThrow({
|
||||
where: { actionType: 'BLOG_NEW' },
|
||||
});
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
await db.corporateTask.update({
|
||||
where: { id: planned.id },
|
||||
data: { dueCycle: day },
|
||||
});
|
||||
expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed
|
||||
const event = await db.corporateEvent.findFirstOrThrow({
|
||||
where: { taskId: planned.id, step: 'PLANNED' },
|
||||
});
|
||||
await db.corporateEvent.update({
|
||||
where: { id: event.id },
|
||||
data: { payload: { ...(event.payload as object), dueCycle: day } },
|
||||
});
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||
planned.id,
|
||||
);
|
||||
});
|
||||
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
let release!: () => void, locked!: () => void;
|
||||
const ready = new Promise<void>((r) => (locked = r));
|
||||
const hold = new Promise<void>((r) => (release = r));
|
||||
const claiming = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
|
||||
await tx.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: {
|
||||
status: 'IN_PROGRESS',
|
||||
claimToken: key(),
|
||||
assignedAgent: 'executor',
|
||||
leasedUntil: new Date(Date.now() + 60000),
|
||||
},
|
||||
});
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
const pending = post('tasks', { ...input, parentId: parent.id }).then(
|
||||
(r) => r,
|
||||
);
|
||||
try {
|
||||
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
|
||||
let waiting = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const rows = await db.$queryRaw<
|
||||
any[]
|
||||
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
} finally {
|
||||
release();
|
||||
await claiming;
|
||||
}
|
||||
expect((await pending).status).toBe(409);
|
||||
expect(
|
||||
await db.corporateTask.count({ where: { parentId: parent.id } }),
|
||||
).toBe(0);
|
||||
});
|
||||
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||
for (const status of ['TODO', 'BLOCKED'] as const) {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: { status },
|
||||
});
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||
child.id,
|
||||
);
|
||||
}
|
||||
});
|
||||
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
const body = {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
for (const artifactUri of [
|
||||
'https://',
|
||||
'https://?x',
|
||||
'https:///pubmed.ncbi.nlm.nih.gov/x',
|
||||
'https://pubmed.ncbi.nlm.nih.gov./x',
|
||||
'https://bad host/x',
|
||||
'https://user:pass@host.org/a',
|
||||
'https://localhost/a',
|
||||
'https://127.1/a',
|
||||
'https://[::1]/a',
|
||||
'urn:sha256:',
|
||||
'urn:sha256:' + 'b'.repeat(64),
|
||||
]) {
|
||||
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||
400,
|
||||
);
|
||||
}
|
||||
expect(await db.corporateEvidence.count()).toBe(0);
|
||||
await post(`tasks/${task.id}/evidence`, {
|
||||
...body,
|
||||
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
|
||||
}).expect(201);
|
||||
});
|
||||
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
|
||||
const service = app.get(CorporateService);
|
||||
const research = {
|
||||
title: 'research',
|
||||
category: 'TREND',
|
||||
source: 'receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'source',
|
||||
excerpt: 'receipt',
|
||||
retrievedAt: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
};
|
||||
for (const time of [
|
||||
null,
|
||||
0,
|
||||
false,
|
||||
[],
|
||||
'2026-01-01',
|
||||
'2026-02-30T00:00:00Z',
|
||||
]) {
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [{ ...research.sources[0], retrievedAt: time }],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.effect('fixture', key(), key(), {
|
||||
metric: 'views',
|
||||
availability: 'UNAVAILABLE',
|
||||
source: 'none',
|
||||
observedAt: time,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow('Invalid observation time');
|
||||
}
|
||||
for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [
|
||||
{
|
||||
...research.sources[0],
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
url,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(await db.corporateResearch.count()).toBe(0);
|
||||
});
|
||||
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const op = key();
|
||||
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
|
||||
.task;
|
||||
expect(claim.claimToken).toBeTruthy();
|
||||
expect(
|
||||
(await post('claims', {}, 'executor', op).expect(201)).body.task
|
||||
.claimToken,
|
||||
).toBe(claim.claimToken);
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
}).expect(201);
|
||||
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'competitor')
|
||||
.expect(200);
|
||||
expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||
}
|
||||
});
|
||||
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateEvent.createMany({
|
||||
data: Array.from({ length: 105 }, () => ({
|
||||
taskId: task.id,
|
||||
speaker: 'SYSTEM',
|
||||
speakerName: 'fixture',
|
||||
step: 'FIXTURE',
|
||||
content: 'x'.repeat(10000),
|
||||
payload: { nested: ['x'.repeat(10000)] },
|
||||
})),
|
||||
});
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(detail.body.logs).toHaveLength(100);
|
||||
expect(detail.body.relationsMeta.logs).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
const op = key(),
|
||||
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||
const report = (await post('reports', body, 'executor', op).expect(201))
|
||||
.body;
|
||||
expect(report.snapshot.events).toHaveLength(100);
|
||||
expect(report.snapshot.meta.events).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
|
||||
expect(
|
||||
Buffer.byteLength(JSON.stringify(report.body ?? report)),
|
||||
).toBeLessThan(1000000);
|
||||
await db.corporateEvent.deleteMany();
|
||||
expect(
|
||||
(await post('reports', body, 'executor', op).expect(201)).body,
|
||||
).toEqual(report);
|
||||
});
|
||||
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
|
||||
const service = app.get(CorporateService) as any;
|
||||
const before = await db.corporateTask.count();
|
||||
await expect(
|
||||
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||
await tx.corporateTask.create({
|
||||
data: {
|
||||
title: 'rollback',
|
||||
description: 'fixture',
|
||||
taskCode: key(),
|
||||
normalizedTitle: 'rollback',
|
||||
normalizedCode: key(),
|
||||
department: 'CONTENT_SEO',
|
||||
createdBy: 'fixture',
|
||||
},
|
||||
});
|
||||
return { value: 'x'.repeat(1100000) };
|
||||
}),
|
||||
).rejects.toThrow('Operation response exceeds limit');
|
||||
expect(await db.corporateTask.count()).toBe(before);
|
||||
expect(await db.corporateOperation.count()).toBe(0);
|
||||
});
|
||||
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
|
||||
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
|
||||
await post('tasks', input, 'unscoped').expect(403);
|
||||
const op = key(),
|
||||
a = await post('tasks', input, 'executor', op).expect(201);
|
||||
const b = await post('tasks', input, 'executor', op).expect(201);
|
||||
expect(b.body.id).toBe(a.body.id);
|
||||
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
|
||||
409,
|
||||
);
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(list.body.meta).toEqual({
|
||||
total: 1,
|
||||
page: 1,
|
||||
limit: 1,
|
||||
totalPages: 1,
|
||||
hasNextPage: false,
|
||||
hasPrevPage: false,
|
||||
});
|
||||
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?limit=101')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?sortBy=password')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
});
|
||||
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claims = await Promise.all([
|
||||
post('claims', {}, 'executor'),
|
||||
post('claims', {}, 'competitor'),
|
||||
]);
|
||||
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
|
||||
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
|
||||
const oldActor = claimed.assignedAgent.replace('apikey:', '');
|
||||
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
|
||||
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
|
||||
.task;
|
||||
expect(renewed.claimToken).not.toBe(claimed.claimToken);
|
||||
const evidence = {
|
||||
claimToken: claimed.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
|
||||
const e = (
|
||||
await post(
|
||||
`tasks/${task.id}/evidence`,
|
||||
{ ...evidence, claimToken: renewed.claimToken },
|
||||
'new-executor',
|
||||
).expect(201)
|
||||
).body;
|
||||
const review = {
|
||||
evidenceId: e.id,
|
||||
passed: true,
|
||||
findings: 'verified',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'digest readback',
|
||||
result: 'match',
|
||||
},
|
||||
};
|
||||
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
|
||||
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'reviewer')
|
||||
.expect(200);
|
||||
expect(detail.body.status).toBe('DONE');
|
||||
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
|
||||
await post(`tasks/${task.id}/effects`, {
|
||||
metric: 'engagement',
|
||||
availability: 'UNAVAILABLE',
|
||||
observed: 0,
|
||||
source: 'provider unavailable',
|
||||
observedAt: new Date().toISOString(),
|
||||
}).expect(400);
|
||||
});
|
||||
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
|
||||
const urgent = (await post('tasks', input).expect(201)).body;
|
||||
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
|
||||
.body;
|
||||
let release!: () => void, locked!: () => void;
|
||||
const ready = new Promise<void>((r) => (locked = r)),
|
||||
hold = new Promise<void>((r) => (release = r));
|
||||
const locking = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
try {
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(low.id);
|
||||
} finally {
|
||||
release();
|
||||
await locking;
|
||||
}
|
||||
const next = (await post('claims', {}, 'other').expect(201)).body.task;
|
||||
expect(next.id).toBe(urgent.id);
|
||||
});
|
||||
it('serializes simultaneous duplicate mutations into one durable record', async () => {
|
||||
const op = key();
|
||||
const responses = await Promise.all([
|
||||
post('tasks', input, 'executor', op),
|
||||
post('tasks', input, 'executor', op),
|
||||
]);
|
||||
expect(responses.map((r) => r.status)).toEqual([201, 201]);
|
||||
expect(responses[0].body.id).toBe(responses[1].body.id);
|
||||
expect(await db.corporateTask.count()).toBe(1);
|
||||
});
|
||||
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(child.id);
|
||||
const e = (
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
|
||||
sha256: 'b'.repeat(64),
|
||||
summary: 'child artifact',
|
||||
tool: 'jest',
|
||||
result: 'receipt',
|
||||
}).expect(201)
|
||||
).body;
|
||||
await post(
|
||||
`tasks/${child.id}/reviews`,
|
||||
{
|
||||
evidenceId: e.id,
|
||||
passed: false,
|
||||
findings: 'needs correction',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'readback',
|
||||
result: 'failed',
|
||||
},
|
||||
},
|
||||
'reviewer',
|
||||
).expect(201);
|
||||
expect(
|
||||
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
|
||||
.status,
|
||||
).toBe('BLOCKED');
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
|
||||
const research = (
|
||||
await post('market-insights', {
|
||||
title: 'fixture research',
|
||||
category: 'TREND',
|
||||
source: 'study receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: {
|
||||
method: 'test fixture',
|
||||
collector: 'integration',
|
||||
context: 'disposable',
|
||||
},
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'fixture',
|
||||
excerpt: 'test-only',
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
const roadmap = (
|
||||
await post('monthly-roadmap', {
|
||||
researchId: research.id,
|
||||
cycleName: 'test',
|
||||
month: '2026-10',
|
||||
seasonalTheme: 'evidence pending seasonal analysis',
|
||||
strategicGoals: ['measure'],
|
||||
plannedArticlesCount: 31,
|
||||
plannedRefreshesCount: 0,
|
||||
plannedCatalogEnrichments: 0,
|
||||
goals: [
|
||||
{
|
||||
title: 'goal',
|
||||
department: 'CONTENT_SEO',
|
||||
acceptanceCriteria: 'QA',
|
||||
metric: 'engagement',
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(roadmap.goals).toHaveLength(1);
|
||||
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
|
||||
for (const path of ['market-insights', 'monthly-roadmap']) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(r.body.meta.total).toBe(1);
|
||||
}
|
||||
const report = (
|
||||
await post('reports', {
|
||||
day: new Date().toISOString().slice(0, 10),
|
||||
summary: 'test fixture daily report',
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(report.snapshot.tasks).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -1,828 +0,0 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma, CorporatePriority } from '@prisma/client';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import {
|
||||
canonical,
|
||||
monthlyPlanInput,
|
||||
planMonth,
|
||||
publicData,
|
||||
choice,
|
||||
departments,
|
||||
evidenceInput,
|
||||
httpsUrl,
|
||||
timestamp,
|
||||
meta,
|
||||
normalizeSearch,
|
||||
object,
|
||||
pagination,
|
||||
priorities,
|
||||
statuses,
|
||||
taskInput,
|
||||
text,
|
||||
uuid,
|
||||
} from './corporate-policy';
|
||||
type Tx = Prisma.TransactionClient;
|
||||
@Injectable()
|
||||
export class CorporateService {
|
||||
constructor(private readonly db: PrismaService) {}
|
||||
private async operation(
|
||||
actor: string,
|
||||
op: string,
|
||||
key: string,
|
||||
body: unknown,
|
||||
fn: (tx: Tx) => Promise<any>,
|
||||
) {
|
||||
text(key, 200);
|
||||
const scoped = createHash('sha256')
|
||||
.update(canonical([actor, op, key]))
|
||||
.digest('hex');
|
||||
const hash = createHash('sha256').update(canonical(body)).digest('hex');
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
|
||||
const prior = await tx.corporateOperation.findUnique({
|
||||
where: { key: scoped },
|
||||
});
|
||||
if (prior) {
|
||||
if (prior.payloadHash !== hash)
|
||||
throw new ConflictException('Idempotency key payload mismatch');
|
||||
return prior.response;
|
||||
}
|
||||
const result = await fn(tx);
|
||||
const serialized = JSON.stringify(result);
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
|
||||
throw new BadRequestException('Operation response exceeds limit');
|
||||
const response = JSON.parse(serialized);
|
||||
await tx.corporateOperation.create({
|
||||
data: { key: scoped, payloadHash: hash, response },
|
||||
});
|
||||
return response;
|
||||
},
|
||||
{ maxWait: 10000, timeout: 20000 },
|
||||
);
|
||||
}
|
||||
private event(
|
||||
tx: Tx,
|
||||
taskId: string,
|
||||
actor: string,
|
||||
step: string,
|
||||
content: string,
|
||||
speaker = 'SYSTEM',
|
||||
payload?: any,
|
||||
) {
|
||||
return tx.corporateEvent.create({
|
||||
data: { taskId, speaker, speakerName: actor, step, content, payload },
|
||||
});
|
||||
}
|
||||
private async lock(tx: Tx, id: string) {
|
||||
uuid(id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
|
||||
if (!rows.length) throw new NotFoundException('Task not found');
|
||||
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
|
||||
}
|
||||
private async fenced(tx: Tx, id: string, token: string, actor: string) {
|
||||
const t = await this.lock(tx, id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
|
||||
if (!rows.length) throw new ConflictException('Stale lease or owner');
|
||||
return t;
|
||||
}
|
||||
async tasks(q: Record<string, any>) {
|
||||
const p = pagination(q),
|
||||
where: Prisma.CorporateTaskWhereInput = {};
|
||||
if (q.department) where.department = choice(q.department, departments);
|
||||
if (q.priority)
|
||||
where.priority = choice(q.priority, priorities) as CorporatePriority;
|
||||
if (q.status) where.status = choice(q.status, statuses) as any;
|
||||
if (q.search) {
|
||||
const search = normalizeSearch(text(q.search, 300));
|
||||
where.OR = [
|
||||
{ normalizedTitle: { contains: search } },
|
||||
{ normalizedCode: { contains: search } },
|
||||
];
|
||||
}
|
||||
if (q.goalId) where.goalId = uuid(q.goalId);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const total = await tx.corporateTask.count({ where });
|
||||
const data = await tx.corporateTask.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
|
||||
});
|
||||
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
async detail(id: string) {
|
||||
uuid(id);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const order = { id: 'asc' as const };
|
||||
const task = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
|
||||
evidence: { take: 100, orderBy: order },
|
||||
reviews: { take: 100, orderBy: order },
|
||||
effects: { take: 100, orderBy: order },
|
||||
children: { take: 100, orderBy: order },
|
||||
_count: {
|
||||
select: {
|
||||
logs: true,
|
||||
evidence: true,
|
||||
reviews: true,
|
||||
effects: true,
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!task) throw new NotFoundException('Task not found');
|
||||
const { _count, ...data } = task;
|
||||
const relationsMeta = Object.fromEntries(
|
||||
Object.entries(_count).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
return publicData({ ...data, relationsMeta });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
create(actor: string, key: string, input: unknown) {
|
||||
const b = taskInput(input);
|
||||
return this.operation(actor, 'create-task', key, b, async (tx) => {
|
||||
if (b.parentId) {
|
||||
const parent = await this.lock(tx, b.parentId);
|
||||
if (!['TODO', 'BLOCKED'].includes(parent.status))
|
||||
throw new ConflictException('Parent no longer accepts children');
|
||||
}
|
||||
const code = 'TSK-' + randomUUID();
|
||||
const task = await tx.corporateTask.create({
|
||||
data: {
|
||||
...b,
|
||||
priority: b.priority as CorporatePriority,
|
||||
taskCode: code,
|
||||
normalizedCode: normalizeSearch(code),
|
||||
normalizedTitle: normalizeSearch(b.title),
|
||||
createdBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
|
||||
return task;
|
||||
});
|
||||
}
|
||||
private plannedWhere(
|
||||
roadmapId: string,
|
||||
month: string,
|
||||
): Prisma.CorporateEventWhereInput {
|
||||
return {
|
||||
step: 'PLANNED',
|
||||
AND: [
|
||||
{ payload: { path: ['roadmapId'], equals: roadmapId } },
|
||||
{ payload: { path: ['month'], equals: month } },
|
||||
],
|
||||
};
|
||||
}
|
||||
private async readPlan(tx: Tx, roadmapId: string, month: string) {
|
||||
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||
where: { id: roadmapId },
|
||||
});
|
||||
const tasks = await tx.corporateTask.findMany({
|
||||
where: { logs: { some: this.plannedWhere(roadmapId, month) } },
|
||||
include: {
|
||||
logs: {
|
||||
where: this.plannedWhere(roadmapId, month),
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
},
|
||||
orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
if (!roadmap || !tasks.length)
|
||||
throw new NotFoundException('Monthly plan not found');
|
||||
return publicData({
|
||||
roadmapId,
|
||||
month,
|
||||
researchId: roadmap.researchId,
|
||||
tasks,
|
||||
});
|
||||
}
|
||||
monthlyPlan(roadmapId: string, month: unknown) {
|
||||
roadmapId = uuid(roadmapId);
|
||||
const cycle = planMonth(month);
|
||||
return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), {
|
||||
isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
|
||||
});
|
||||
}
|
||||
persistMonthlyPlan(actor: string, key: string, input: unknown) {
|
||||
const b = monthlyPlanInput(input);
|
||||
return this.operation(actor, 'monthly-plan', key, b, async (tx) => {
|
||||
// Separate actor/key-independent fence: one complete plan per roadmap/month.
|
||||
const scope = canonical(['monthly-plan', b.roadmapId, b.month]);
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||
if (
|
||||
await tx.corporateEvent.count({
|
||||
where: this.plannedWhere(b.roadmapId, b.month),
|
||||
})
|
||||
)
|
||||
throw new ConflictException('Monthly plan already persisted');
|
||||
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||
where: { id: b.roadmapId },
|
||||
include: { goals: true, research: { include: { sources: true } } },
|
||||
});
|
||||
if (
|
||||
!roadmap ||
|
||||
roadmap.month !== b.month ||
|
||||
!roadmap.research.sources.length
|
||||
)
|
||||
throw new ConflictException(
|
||||
'Matching evidence-backed roadmap required',
|
||||
);
|
||||
const entries = [...b.dailyArticles, ...b.needs];
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
!roadmap.goals.some(
|
||||
(g) => g.id === entry.goalId && g.department === entry.department,
|
||||
) ||
|
||||
!entry.sourceIds.every((id) =>
|
||||
roadmap.research.sources.some((s) => s.id === id),
|
||||
)
|
||||
)
|
||||
throw new ConflictException(
|
||||
'Goal/department and source lineage must match roadmap research',
|
||||
);
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const { sourceIds, target, reason, ...data } = entry;
|
||||
const taskCode = 'TSK-' + randomUUID();
|
||||
const task = await tx.corporateTask.create({
|
||||
data: {
|
||||
...data,
|
||||
priority: data.priority as CorporatePriority,
|
||||
status: 'TODO',
|
||||
taskCode,
|
||||
normalizedCode: normalizeSearch(taskCode),
|
||||
normalizedTitle: normalizeSearch(data.title),
|
||||
createdBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
task.id,
|
||||
actor,
|
||||
'PLANNED',
|
||||
entry.description,
|
||||
'SYSTEM',
|
||||
{
|
||||
version: 1,
|
||||
roadmapId: roadmap.id,
|
||||
researchId: roadmap.researchId,
|
||||
month: b.month,
|
||||
goalId: entry.goalId,
|
||||
department: entry.department,
|
||||
actionType: entry.actionType,
|
||||
dueCycle: entry.dueCycle,
|
||||
sourceIds,
|
||||
...(target ? { target, reason } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
return this.readPlan(tx, b.roadmapId, b.month);
|
||||
});
|
||||
}
|
||||
claim(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, ['department', 'leaseSeconds']);
|
||||
const department =
|
||||
b.department === undefined ? null : choice(b.department, departments);
|
||||
const seconds = Number(b.leaseSeconds ?? 300);
|
||||
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
|
||||
throw new BadRequestException('Lease must be 30..900 seconds');
|
||||
return this.operation(
|
||||
actor,
|
||||
'claim',
|
||||
key,
|
||||
{ department, seconds },
|
||||
async (tx) => {
|
||||
const candidates = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT t.id FROM corporate_tasks t
|
||||
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
|
||||
AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED'
|
||||
AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
|
||||
OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle"
|
||||
OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD')))
|
||||
AND (${department}::text IS NULL OR t.department=${department})
|
||||
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
|
||||
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
|
||||
if (!candidates.length) return { task: null };
|
||||
const id = candidates[0].id,
|
||||
token = randomUUID();
|
||||
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
|
||||
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
|
||||
return {
|
||||
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
submitEvidence(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = evidenceInput(input);
|
||||
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
|
||||
await this.fenced(tx, id, b.claimToken, actor);
|
||||
const e = await tx.corporateEvidence.create({
|
||||
data: { ...b, taskId: id, executor: actor },
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: { status: 'TEST', leasedUntil: null },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
'EVIDENCE_SUBMITTED',
|
||||
b.summary,
|
||||
'AGENT',
|
||||
{ evidenceId: e.id },
|
||||
);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
review(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'evidenceId',
|
||||
'passed',
|
||||
'findings',
|
||||
'verification',
|
||||
]);
|
||||
const evidenceId = uuid(b.evidenceId),
|
||||
findings = text(b.findings);
|
||||
if (typeof b.passed !== 'boolean')
|
||||
throw new BadRequestException('passed must be boolean');
|
||||
const v = object(b.verification, [
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'method',
|
||||
'result',
|
||||
]);
|
||||
const verification = {
|
||||
artifactUri: text(v.artifactUri, 2000),
|
||||
sha256: text(v.sha256, 64),
|
||||
method: text(v.method, 1000),
|
||||
result: text(v.result),
|
||||
};
|
||||
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
|
||||
uuid(id);
|
||||
const relation = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
select: { parentId: true },
|
||||
});
|
||||
if (relation?.parentId) await this.lock(tx, relation.parentId);
|
||||
const task = await this.lock(tx, id);
|
||||
const evidence = await tx.corporateEvidence.findUnique({
|
||||
where: { id: evidenceId },
|
||||
});
|
||||
if (
|
||||
task.status !== 'TEST' ||
|
||||
!evidence ||
|
||||
evidence.taskId !== id ||
|
||||
evidence.claimToken !== task.claimToken
|
||||
)
|
||||
throw new ConflictException('Current execution evidence required');
|
||||
if (evidence.executor === actor)
|
||||
throw new ConflictException('Independent reviewer required');
|
||||
if (
|
||||
verification.sha256 !== evidence.sha256 ||
|
||||
verification.artifactUri !== evidence.artifactUri
|
||||
)
|
||||
throw new ConflictException('QA must verify exact artifact');
|
||||
if (
|
||||
b.passed &&
|
||||
(await tx.corporateTask.count({
|
||||
where: { parentId: id, status: { not: 'DONE' } },
|
||||
}))
|
||||
)
|
||||
throw new ConflictException('Unfinished children');
|
||||
const r = await tx.corporateReview.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
evidenceId,
|
||||
reviewer: actor,
|
||||
passed: b.passed,
|
||||
findings,
|
||||
verification,
|
||||
},
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: b.passed ? 'DONE' : 'TODO',
|
||||
claimToken: null,
|
||||
leasedUntil: null,
|
||||
qaCount: { increment: 1 },
|
||||
rejectionCount: { increment: b.passed ? 0 : 1 },
|
||||
},
|
||||
});
|
||||
if (!b.passed && task.parentId) {
|
||||
await tx.corporateTask.update({
|
||||
where: { id: task.parentId },
|
||||
data: { status: 'BLOCKED' },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
task.parentId,
|
||||
actor,
|
||||
'CHILD_QA_REJECTED',
|
||||
'Parent blocked pending child correction',
|
||||
'QA',
|
||||
{ childId: id },
|
||||
);
|
||||
}
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
|
||||
findings,
|
||||
'QA',
|
||||
{ reviewId: r.id },
|
||||
);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
async collection(
|
||||
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
|
||||
q: Record<string, any>,
|
||||
) {
|
||||
const p = pagination(q);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const model =
|
||||
kind === 'market-insights'
|
||||
? tx.corporateResearch
|
||||
: kind === 'monthly-roadmap'
|
||||
? tx.corporateRoadmap
|
||||
: tx.corporateReport;
|
||||
const where: any = {};
|
||||
if (kind === 'market-insights' && q.category)
|
||||
where.category = choice(q.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]);
|
||||
if (kind === 'monthly-roadmap' && q.month)
|
||||
where.month = text(q.month, 40);
|
||||
const delegate = model as any;
|
||||
const total = await delegate.count({ where });
|
||||
const data = await delegate.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||
...(kind === 'market-insights'
|
||||
? { include: { sources: true } }
|
||||
: kind === 'monthly-roadmap'
|
||||
? { include: { goals: true } }
|
||||
: {}),
|
||||
});
|
||||
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
research(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'category',
|
||||
'source',
|
||||
'opportunity',
|
||||
'impact',
|
||||
'recommendedAction',
|
||||
'cadence',
|
||||
'provenance',
|
||||
'sources',
|
||||
]);
|
||||
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
|
||||
throw new BadRequestException('1..30 sources required');
|
||||
const sources = b.sources.map((raw) => {
|
||||
const s = object(raw, [
|
||||
'url',
|
||||
'title',
|
||||
'excerpt',
|
||||
'retrievedAt',
|
||||
'sha256',
|
||||
]);
|
||||
const url = httpsUrl(s.url),
|
||||
sha256 = text(s.sha256, 64),
|
||||
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
|
||||
if (
|
||||
!url.startsWith('https://') ||
|
||||
!/^[a-f0-9]{64}$/.test(sha256) ||
|
||||
!Number.isFinite(retrievedAt.getTime()) ||
|
||||
retrievedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid source');
|
||||
return {
|
||||
url,
|
||||
sha256,
|
||||
retrievedAt,
|
||||
title: text(s.title, 300),
|
||||
excerpt: text(s.excerpt),
|
||||
};
|
||||
});
|
||||
const provenance = object(b.provenance, ['method', 'collector', 'context']);
|
||||
const data = {
|
||||
title: text(b.title, 300),
|
||||
category: choice(b.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]),
|
||||
source: text(b.source, 2000),
|
||||
opportunity: text(b.opportunity),
|
||||
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
|
||||
recommendedAction: text(b.recommendedAction),
|
||||
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
|
||||
provenance: {
|
||||
method: text(provenance.method),
|
||||
collector: text(provenance.collector, 300),
|
||||
context: text(provenance.context),
|
||||
},
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'research', key, b, (tx) =>
|
||||
tx.corporateResearch.create({
|
||||
data: { ...data, sources: { create: sources } },
|
||||
include: { sources: true },
|
||||
}),
|
||||
);
|
||||
}
|
||||
roadmap(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'researchId',
|
||||
'cycleName',
|
||||
'month',
|
||||
'seasonalTheme',
|
||||
'strategicGoals',
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
'isActive',
|
||||
'goals',
|
||||
]);
|
||||
if (
|
||||
!Array.isArray(b.strategicGoals) ||
|
||||
!b.strategicGoals.length ||
|
||||
b.strategicGoals.length > 30 ||
|
||||
!Array.isArray(b.goals) ||
|
||||
!b.goals.length ||
|
||||
b.goals.length > 100
|
||||
)
|
||||
throw new BadRequestException('Goals required');
|
||||
for (const k of [
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
])
|
||||
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
|
||||
throw new BadRequestException('Invalid counts');
|
||||
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
|
||||
throw new BadRequestException('Invalid active flag');
|
||||
const goals = b.goals.map((raw) => {
|
||||
const g = object(raw, [
|
||||
'title',
|
||||
'department',
|
||||
'acceptanceCriteria',
|
||||
'metric',
|
||||
'target',
|
||||
]);
|
||||
if (
|
||||
g.target !== undefined &&
|
||||
(typeof g.target !== 'number' || !Number.isFinite(g.target))
|
||||
)
|
||||
throw new BadRequestException('Invalid target');
|
||||
return {
|
||||
title: text(g.title, 300),
|
||||
department: choice(g.department, departments),
|
||||
acceptanceCriteria: text(g.acceptanceCriteria),
|
||||
metric: text(g.metric, 300),
|
||||
target: g.target,
|
||||
};
|
||||
});
|
||||
const data = {
|
||||
researchId: uuid(b.researchId),
|
||||
cycleName: text(b.cycleName, 300),
|
||||
month: text(b.month, 40),
|
||||
seasonalTheme: text(b.seasonalTheme),
|
||||
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
|
||||
plannedArticlesCount: b.plannedArticlesCount,
|
||||
plannedRefreshesCount: b.plannedRefreshesCount,
|
||||
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
|
||||
isActive: b.isActive ?? false,
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'roadmap', key, b, async (tx) => {
|
||||
const research = await tx.corporateResearch.findUnique({
|
||||
where: { id: data.researchId },
|
||||
include: { sources: true },
|
||||
});
|
||||
if (!research || !research.sources.length)
|
||||
throw new ConflictException('Evidence-backed research required');
|
||||
const result = await tx.corporateRoadmap.create({
|
||||
data: { ...data, goals: { create: goals } },
|
||||
include: { goals: true },
|
||||
});
|
||||
await tx.corporateResearch.update({
|
||||
where: { id: research.id },
|
||||
data: { status: 'IN_BACKLOG' },
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
effect(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'metric',
|
||||
'availability',
|
||||
'baseline',
|
||||
'observed',
|
||||
'source',
|
||||
'observedAt',
|
||||
]);
|
||||
const availability = choice(b.availability, [
|
||||
'MEASURED',
|
||||
'UNAVAILABLE',
|
||||
'UNINSTRUMENTED',
|
||||
'BUSINESS_DISABLED',
|
||||
]);
|
||||
for (const k of ['baseline', 'observed'])
|
||||
if (
|
||||
b[k] !== undefined &&
|
||||
b[k] !== null &&
|
||||
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
|
||||
)
|
||||
throw new BadRequestException('Invalid metric');
|
||||
if (availability === 'MEASURED' && typeof b.observed !== 'number')
|
||||
throw new BadRequestException('Measured value required');
|
||||
if (
|
||||
availability !== 'MEASURED' &&
|
||||
(b.observed != null || b.baseline != null)
|
||||
)
|
||||
throw new BadRequestException('Unavailable is not zero');
|
||||
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
|
||||
if (
|
||||
!Number.isFinite(observedAt.getTime()) ||
|
||||
observedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid observation time');
|
||||
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
|
||||
const task = await this.lock(tx, id);
|
||||
if (task.status !== 'DONE')
|
||||
throw new ConflictException('Effects require completed QA');
|
||||
const e = await tx.corporateEffect.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
metric: text(b.metric, 300),
|
||||
availability,
|
||||
baseline: b.baseline,
|
||||
observed: b.observed,
|
||||
source: text(b.source, 2000),
|
||||
observedAt,
|
||||
recordedBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
|
||||
effectId: e.id,
|
||||
});
|
||||
return e;
|
||||
});
|
||||
}
|
||||
report(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, ['day', 'summary']);
|
||||
const day = text(b.day, 10),
|
||||
summary = text(b.summary);
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
||||
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
|
||||
)
|
||||
throw new BadRequestException('ISO day required');
|
||||
return this.operation(actor, 'report', key, b, async (tx) => {
|
||||
const start = new Date(day + 'T00:00:00Z'),
|
||||
end = new Date(start.getTime() + 86400000);
|
||||
const taskWhere = { updatedAt: { gte: start, lt: end } };
|
||||
const eventWhere = { timestamp: { gte: start, lt: end } };
|
||||
const effectWhere = { createdAt: { gte: start, lt: end } };
|
||||
const totals = {
|
||||
tasks: await tx.corporateTask.count({ where: taskWhere }),
|
||||
events: await tx.corporateEvent.count({ where: eventWhere }),
|
||||
effects: await tx.corporateEffect.count({ where: effectWhere }),
|
||||
};
|
||||
const tasks = await tx.corporateTask.findMany({
|
||||
where: taskWhere,
|
||||
take: 100,
|
||||
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskCode: true,
|
||||
title: true,
|
||||
status: true,
|
||||
department: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
const events = await tx.corporateEvent.findMany({
|
||||
where: eventWhere,
|
||||
take: 100,
|
||||
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
timestamp: true,
|
||||
speaker: true,
|
||||
speakerName: true,
|
||||
step: true,
|
||||
content: true,
|
||||
},
|
||||
});
|
||||
const effects = await tx.corporateEffect.findMany({
|
||||
where: effectWhere,
|
||||
take: 100,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
metric: true,
|
||||
availability: true,
|
||||
baseline: true,
|
||||
observed: true,
|
||||
source: true,
|
||||
observedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
let fieldsTruncated = false;
|
||||
const project = (rows: any[]) =>
|
||||
rows.map((row) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(row).map(([name, value]) => {
|
||||
if (typeof value === 'string' && value.length > 1000) {
|
||||
fieldsTruncated = true;
|
||||
return [name, value.slice(0, 1000)];
|
||||
}
|
||||
return [name, value];
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bounded = {
|
||||
tasks: project(tasks),
|
||||
events: project(events),
|
||||
effects: project(effects),
|
||||
};
|
||||
const counts = Object.fromEntries(
|
||||
Object.entries(totals).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const snapshot = JSON.parse(
|
||||
JSON.stringify({
|
||||
timezone: 'UTC',
|
||||
...bounded,
|
||||
meta: {
|
||||
...counts,
|
||||
fieldsTruncated,
|
||||
stringLimit: 1000,
|
||||
eventPayloadsOmitted: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return tx.corporateReport.create({
|
||||
data: { day, summary, snapshot, createdBy: actor },
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('retired legacy orchestration HTTP boundary', () => {
|
||||
let app: INestApplication;
|
||||
const dbAccess = jest.fn();
|
||||
const prisma = new Proxy({}, {get: (_target, key) => {
|
||||
// Nest inspects provider thenables and lifecycle hooks during setup.
|
||||
if (["then", "onModuleInit", "onApplicationBootstrap", "onModuleDestroy", "beforeApplicationShutdown", "onApplicationShutdown"].includes(String(key))) return undefined;
|
||||
dbAccess(key);
|
||||
throw new Error('Persistence must not be accessed');
|
||||
}});
|
||||
const routes = [
|
||||
['post', '/admin/approvals'],
|
||||
['put', '/admin/approvals/missing/decide'],
|
||||
['post', '/admin/department-tasks'],
|
||||
['put', '/admin/department-tasks/missing/status'],
|
||||
] as const;
|
||||
beforeAll(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [ApprovalsController, DepartmentTasksController],
|
||||
providers: [{provide: PrismaService, useValue: prisma}, RolesGuard],
|
||||
}).overrideGuard(JwtAuthGuard).useValue({canActivate(context: any) {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = {id: 'test-admin', role: req.headers.authorization};
|
||||
return true;
|
||||
}}).compile();
|
||||
app = module.createNestApplication();
|
||||
await app.init();
|
||||
dbAccess.mockClear();
|
||||
});
|
||||
beforeEach(() => dbAccess.mockClear());
|
||||
afterAll(async () => { if (app) await app.close(); });
|
||||
it.each(routes)('%s %s returns explicit 410 for authorized callers before database access', async (method, path) => {
|
||||
const response = await request(app.getHttpServer())[method](path)
|
||||
.set('Authorization', 'Admin').send({decision:'APPROVED',status:'DONE'}).expect(410);
|
||||
expect(response.body.message).toContain('retired');
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(routes)('%s %s retains anonymous and customer authorization guards', async (method, path) => {
|
||||
await request(app.getHttpServer())[method](path).send({}).expect(403);
|
||||
await request(app.getHttpServer())[method](path).set('Authorization','CUSTOMER').send({}).expect(403);
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -76,7 +76,7 @@ describe("MediaService", () => {
|
||||
|
||||
const validFile = {
|
||||
originalname: "product-cover.webp",
|
||||
buffer: Buffer.from("dummy-image-bytes"),
|
||||
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
|
||||
mimetype: "image/webp",
|
||||
size: 5000,
|
||||
} as any;
|
||||
|
||||
@@ -79,6 +79,28 @@ export class MediaService {
|
||||
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
||||
);
|
||||
}
|
||||
|
||||
// SEC-01: Magic number verification for uploaded binary content
|
||||
const buf = file.buffer;
|
||||
if (!buf || buf.length < 4) {
|
||||
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
||||
}
|
||||
|
||||
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
||||
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
||||
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
||||
const isWebp =
|
||||
buf.length >= 12 &&
|
||||
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
||||
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
||||
|
||||
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
||||
throw new BadRequestException(
|
||||
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
||||
);
|
||||
}
|
||||
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Patch,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { AdvisorsService, CreateAdvisorDto } from './advisors.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Controller('admin')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class AdvisorsController {
|
||||
constructor(
|
||||
private readonly advisorsService: AdvisorsService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Advisors Management
|
||||
*/
|
||||
@Get('advisors')
|
||||
async listAdvisors() {
|
||||
const data = await this.advisorsService.listAdvisors();
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Post('advisors')
|
||||
async createAdvisor(@Body() dto: CreateAdvisorDto) {
|
||||
const data = await this.advisorsService.createAdvisor(dto);
|
||||
return { success: true, message: 'مشاور جدید با موفقیت اضافه شد.', data };
|
||||
}
|
||||
|
||||
@Put('advisors/:id')
|
||||
async updateAdvisor(@Param('id') id: string, @Body() dto: Partial<CreateAdvisorDto>) {
|
||||
const data = await this.advisorsService.updateAdvisor(id, dto);
|
||||
return { success: true, message: 'اطلاعات مشاور بهروزرسانی شد.', data };
|
||||
}
|
||||
|
||||
@Patch('advisors/:id/set-default')
|
||||
async setDefaultAdvisor(@Param('id') id: string) {
|
||||
const data = await this.advisorsService.setDefaultAdvisor(id);
|
||||
return { success: true, message: 'مشاور با موفقیت به عنوان پیشفرض سیستم انتخاب شد.', data };
|
||||
}
|
||||
|
||||
@Delete('advisors/:id')
|
||||
async deleteAdvisor(@Param('id') id: string) {
|
||||
return this.advisorsService.deleteAdvisor(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leads (Contact Requests) Management
|
||||
*/
|
||||
@Get('leads')
|
||||
async listLeads(
|
||||
@Query('page') page?: number,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('search') search?: string,
|
||||
) {
|
||||
const data = await this.advisorsService.listLeads({ page, limit, status, search });
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Patch('leads/:id/status')
|
||||
async updateLeadStatus(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { status: string; notes?: string },
|
||||
) {
|
||||
const data = await this.advisorsService.updateLeadStatus(id, body.status, body.notes);
|
||||
return { success: true, message: 'وضعیت درخواست تماس بهروزرسانی شد.', data };
|
||||
}
|
||||
|
||||
@Delete('leads/:id')
|
||||
async deleteLead(@Param('id') id: string) {
|
||||
return this.advisorsService.deleteLead(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Product Advisor Linking
|
||||
*/
|
||||
@Get('products/:productId/advisor')
|
||||
async getProductAdvisor(@Param('productId') productId: string) {
|
||||
const pa = await this.prisma.productAdvisor.findFirst({
|
||||
where: { productId },
|
||||
include: { advisor: true },
|
||||
});
|
||||
return { success: true, data: pa?.advisor || null };
|
||||
}
|
||||
|
||||
@Post('products/:productId/advisor')
|
||||
async assignProductAdvisor(
|
||||
@Param('productId') productId: string,
|
||||
@Body() body: { advisorId: string | null },
|
||||
) {
|
||||
if (!body.advisorId) {
|
||||
// Remove product advisor assignment
|
||||
await this.prisma.productAdvisor.deleteMany({ where: { productId } });
|
||||
return { success: true, message: 'مشاور اختصاصی محصول حذف و به حالت پیشفرض بازگشت.' };
|
||||
}
|
||||
|
||||
// Upsert assignment
|
||||
await this.prisma.productAdvisor.upsert({
|
||||
where: {
|
||||
productId_advisorId: {
|
||||
productId,
|
||||
advisorId: body.advisorId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
productId,
|
||||
advisorId: body.advisorId,
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
|
||||
return { success: true, message: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' };
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { AdvisorsService } from './advisors.service';
|
||||
import { AdvisorsController } from './advisors.controller';
|
||||
import { PublicLeadController } from './public-lead.controller';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, NotificationsModule],
|
||||
controllers: [AdvisorsController, PublicLeadController],
|
||||
providers: [AdvisorsService],
|
||||
exports: [AdvisorsService],
|
||||
})
|
||||
export class AdvisorsModule {}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AdvisorsService } from './advisors.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
describe('AdvisorsService', () => {
|
||||
let service: AdvisorsService;
|
||||
let prisma: any;
|
||||
let queueService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
advisorContact: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
lead: {
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
product: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
productAdvisor: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
queueService = {
|
||||
enqueue: jest.fn().mockResolvedValue({ id: 'q-1' }),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdvisorsService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: NotificationsQueueService, useValue: queueService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AdvisorsService>(AdvisorsService);
|
||||
});
|
||||
|
||||
it('should list advisors with counts', async () => {
|
||||
prisma.advisorContact.findMany.mockResolvedValueOnce([
|
||||
{
|
||||
id: 'adv-1',
|
||||
name: 'دکتر علوی',
|
||||
phone: '09123456789',
|
||||
isDefault: true,
|
||||
isActive: true,
|
||||
_count: { productAdvisors: 2, leads: 5 },
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.listAdvisors();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('دکتر علوی');
|
||||
expect(result[0].productsCount).toBe(2);
|
||||
expect(result[0].leadsCount).toBe(5);
|
||||
});
|
||||
|
||||
it('should create lead and enqueue notifications for default advisor and client', async () => {
|
||||
prisma.lead.count.mockResolvedValueOnce(0); // rate limit
|
||||
prisma.advisorContact.findFirst.mockResolvedValueOnce({
|
||||
id: 'adv-def',
|
||||
name: 'مشاور پیشفرض',
|
||||
phone: '09120000000',
|
||||
isDefault: true,
|
||||
isActive: true,
|
||||
});
|
||||
prisma.lead.create.mockResolvedValueOnce({
|
||||
id: 'lead-1',
|
||||
firstName: 'علی',
|
||||
lastName: 'رضایی',
|
||||
phone: '09129876543',
|
||||
advisorId: 'adv-def',
|
||||
status: 'PENDING',
|
||||
});
|
||||
|
||||
const res = await service.handlePublicLead({
|
||||
firstName: 'علی',
|
||||
lastName: 'رضایی',
|
||||
phone: '09129876543',
|
||||
});
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.leadId).toBe('lead-1');
|
||||
expect(queueService.enqueue).toHaveBeenCalledTimes(2); // 1 for advisor, 1 for client
|
||||
});
|
||||
|
||||
it('should reject invalid phone format', async () => {
|
||||
await expect(
|
||||
service.handlePublicLead({
|
||||
firstName: 'تست',
|
||||
lastName: 'تستی',
|
||||
phone: '1234',
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -1,379 +0,0 @@
|
||||
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
|
||||
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||
|
||||
export class CreateAdvisorDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
phone!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
title?: string;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
isDefault?: boolean;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export class CreateLeadDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
firstName!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
lastName!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
phone!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
productId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdvisorsService {
|
||||
private readonly logger = new Logger(AdvisorsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly queueService: NotificationsQueueService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* List all advisors with attached product count and leads count
|
||||
*/
|
||||
async listAdvisors() {
|
||||
const advisors = await this.prisma.advisorContact.findMany({
|
||||
orderBy: [{ isDefault: 'desc' }, { createdAt: 'desc' }],
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
productAdvisors: true,
|
||||
leads: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return advisors.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
phone: a.phone,
|
||||
title: a.title,
|
||||
isDefault: a.isDefault,
|
||||
isActive: a.isActive,
|
||||
productsCount: a._count.productAdvisors,
|
||||
leadsCount: a._count.leads,
|
||||
createdAt: a.createdAt,
|
||||
updatedAt: a.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new advisor
|
||||
*/
|
||||
async createAdvisor(dto: CreateAdvisorDto) {
|
||||
if (!dto.name || !dto.phone) {
|
||||
throw new BadRequestException('نام و شماره موبایل مشاور الزامی است.');
|
||||
}
|
||||
|
||||
const cleanPhone = dto.phone.trim();
|
||||
const existing = await this.prisma.advisorContact.findUnique({
|
||||
where: { phone: cleanPhone },
|
||||
});
|
||||
if (existing) {
|
||||
throw new BadRequestException('مشاوری با این شماره تلفن قبلاً ثبت شده است.');
|
||||
}
|
||||
|
||||
// If marked default, unset others first
|
||||
if (dto.isDefault) {
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
|
||||
const advisor = await this.prisma.advisorContact.create({
|
||||
data: {
|
||||
name: dto.name.trim(),
|
||||
phone: cleanPhone,
|
||||
title: dto.title?.trim() || null,
|
||||
isDefault: Boolean(dto.isDefault),
|
||||
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : true,
|
||||
},
|
||||
});
|
||||
|
||||
return advisor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update advisor
|
||||
*/
|
||||
async updateAdvisor(id: string, dto: Partial<CreateAdvisorDto>) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور مورد نظر یافت نشد.');
|
||||
|
||||
if (dto.phone && dto.phone !== existing.phone) {
|
||||
const phoneExists = await this.prisma.advisorContact.findUnique({
|
||||
where: { phone: dto.phone.trim() },
|
||||
});
|
||||
if (phoneExists && phoneExists.id !== id) {
|
||||
throw new BadRequestException('شماره تلفن وارد شده برای مشاور دیگری ثبت شده است.');
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.isDefault) {
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true, id: { not: id } },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
|
||||
return this.prisma.advisorContact.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: dto.name ? dto.name.trim() : undefined,
|
||||
phone: dto.phone ? dto.phone.trim() : undefined,
|
||||
title: dto.title !== undefined ? dto.title?.trim() || null : undefined,
|
||||
isDefault: dto.isDefault !== undefined ? Boolean(dto.isDefault) : undefined,
|
||||
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set advisor as default
|
||||
*/
|
||||
async setDefaultAdvisor(id: string) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
|
||||
return this.prisma.advisorContact.update({
|
||||
where: { id },
|
||||
data: { isDefault: true, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete advisor
|
||||
*/
|
||||
async deleteAdvisor(id: string) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||
|
||||
await this.prisma.advisorContact.delete({ where: { id } });
|
||||
return { success: true, message: 'مشاور با موفقیت حذف شد.' };
|
||||
}
|
||||
|
||||
/**
|
||||
* List customer leads (contact requests)
|
||||
*/
|
||||
async listLeads(query: { page?: number; limit?: number; status?: string; search?: string }) {
|
||||
const page = Math.max(1, Number(query.page || 1));
|
||||
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
where.status = query.status;
|
||||
}
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ firstName: { contains: query.search, mode: 'insensitive' } },
|
||||
{ lastName: { contains: query.search, mode: 'insensitive' } },
|
||||
{ phone: { contains: query.search, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.lead.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
include: {
|
||||
advisor: {
|
||||
select: { id: true, name: true, phone: true, title: true },
|
||||
},
|
||||
product: {
|
||||
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.lead.count({ where }),
|
||||
]);
|
||||
|
||||
const [pendingCount, contactedCount, cancelledCount] = await Promise.all([
|
||||
this.prisma.lead.count({ where: { status: 'PENDING' } }),
|
||||
this.prisma.lead.count({ where: { status: 'CONTACTED' } }),
|
||||
this.prisma.lead.count({ where: { status: 'CANCELLED' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit) || 1,
|
||||
stats: {
|
||||
total,
|
||||
pending: pendingCount,
|
||||
contacted: contactedCount,
|
||||
cancelled: cancelledCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update lead status or notes
|
||||
*/
|
||||
async updateLeadStatus(id: string, status: string, notes?: string) {
|
||||
const lead = await this.prisma.lead.findUnique({ where: { id } });
|
||||
if (!lead) throw new NotFoundException('درخواست تماس یافت نشد.');
|
||||
|
||||
return this.prisma.lead.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status,
|
||||
notes: notes !== undefined ? notes : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete lead
|
||||
*/
|
||||
async deleteLead(id: string) {
|
||||
await this.prisma.lead.delete({ where: { id } });
|
||||
return { success: true, message: 'درخواست تماس با موفقیت حذف شد.' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Public Lead Creation from Website
|
||||
*/
|
||||
async handlePublicLead(dto: CreateLeadDto) {
|
||||
if (!dto.firstName || !dto.lastName || !dto.phone) {
|
||||
throw new BadRequestException('نام، نام خانوادگی و شماره موبایل الزامی است.');
|
||||
}
|
||||
|
||||
const cleanPhone = dto.phone.replace(/\s+/g, '').replace(/^(\+98|0098)/, '0');
|
||||
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||
throw new BadRequestException('شماره موبایل وارد شده نامعتبر است (مثال: ۰۹۱۲۳۴۵۶۷۸۹).');
|
||||
}
|
||||
|
||||
// Rate limit: max 3 requests per 24 hours per phone
|
||||
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const countToday = await this.prisma.lead.count({
|
||||
where: {
|
||||
phone: cleanPhone,
|
||||
createdAt: { gte: oneDayAgo },
|
||||
},
|
||||
});
|
||||
|
||||
if (countToday >= 3) {
|
||||
throw new BadRequestException('حداکثر تعداد درخواست روزانه برای این شماره تکمیل شده است. همکاران ما به زودی با شما تماس خواهند گرفت.');
|
||||
}
|
||||
|
||||
// Resolve advisor: Product-specific -> Default advisor -> First active advisor
|
||||
let advisor = null;
|
||||
let product = null;
|
||||
|
||||
if (dto.productId) {
|
||||
product = await this.prisma.product.findUnique({
|
||||
where: { id: dto.productId },
|
||||
select: { id: true, nameFa: true },
|
||||
});
|
||||
|
||||
const pa = await this.prisma.productAdvisor.findFirst({
|
||||
where: { productId: dto.productId },
|
||||
include: { advisor: true },
|
||||
});
|
||||
if (pa?.advisor?.isActive) {
|
||||
advisor = pa.advisor;
|
||||
}
|
||||
}
|
||||
|
||||
if (!advisor) {
|
||||
advisor = await this.prisma.advisorContact.findFirst({
|
||||
where: { isDefault: true, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
if (!advisor) {
|
||||
advisor = await this.prisma.advisorContact.findFirst({
|
||||
where: { isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Create lead record in DB
|
||||
const lead = await this.prisma.lead.create({
|
||||
data: {
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
phone: cleanPhone,
|
||||
productId: dto.productId || null,
|
||||
advisorId: advisor?.id || null,
|
||||
status: 'PENDING',
|
||||
},
|
||||
});
|
||||
|
||||
// Enqueue SMS notification to Advisor
|
||||
// Pattern 580260: "مشاور گرامی، درخواست تماس جدیدی از {0} با شماره {1} برای {2} ثبت شد. canina.ir"
|
||||
if (advisor) {
|
||||
const productName = product ? product.nameFa : 'مشاوره عمومی';
|
||||
const advisorMsg = `مشاور گرامی، درخواست تماس جدیدی از ${dto.firstName} ${dto.lastName} (${cleanPhone}) برای «${productName}» ثبت شد. لطفاً در اسرع وقت تماس حاصل فرمایید.`;
|
||||
const clientName = `${dto.firstName} ${dto.lastName}`.trim();
|
||||
|
||||
await this.queueService.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: advisor.phone,
|
||||
event: 'NEW_LEAD',
|
||||
content: advisorMsg,
|
||||
payload: {
|
||||
patternId: 580260, // Registered official advisor pattern
|
||||
args: [clientName, cleanPhone, productName],
|
||||
},
|
||||
idempotencyKey: `lead_advisor_${lead.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Enqueue confirmation SMS to Client
|
||||
// Pattern 580259: "{0} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران ما به زودی با شما تماس خواهند گرفت. canina.ir"
|
||||
const clientMsg = `${dto.firstName} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.`;
|
||||
await this.queueService.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: cleanPhone,
|
||||
event: 'LEAD_CONFIRMATION',
|
||||
content: clientMsg,
|
||||
payload: {
|
||||
patternId: 580259, // Registered official client pattern
|
||||
args: [dto.firstName.trim()],
|
||||
},
|
||||
idempotencyKey: `lead_client_${lead.id}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'درخواست مشاوره شما با موفقیت ثبت شد. مشاور ما به زودی با شما تماس خواهد گرفت.',
|
||||
leadId: lead.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Body,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { AdvisorsService, CreateLeadDto } from './advisors.service';
|
||||
|
||||
@Controller('public')
|
||||
export class PublicLeadController {
|
||||
constructor(private readonly advisorsService: AdvisorsService) {}
|
||||
|
||||
@Post('lead')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async createLead(@Body() dto: CreateLeadDto) {
|
||||
const result = await this.advisorsService.handlePublicLead(dto);
|
||||
return {
|
||||
ok: true,
|
||||
success: true,
|
||||
message: result.message,
|
||||
leadId: result.leadId,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
import { registerPrepareWorker } from './orchestration-worker/worker-registration';
|
||||
import { RouterUsageModule } from './router-usage/router-usage.module';
|
||||
import { runtimeReadRegistration } from './hermes-management/runtime-read.registration';
|
||||
import { TasksModule } from './common/services/tasks.module';
|
||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||
import { PrismaModule } from "./prisma/prisma.module";
|
||||
import { SupportChatModule } from './support-chat/support-chat.module';
|
||||
@@ -36,13 +40,17 @@ import { DoctorsModule } from "./doctors/doctors.module";
|
||||
import { FaqModule } from "./faq/faq.module";
|
||||
import { MenuModule } from "./menu/menu.module";
|
||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||
import { NotificationsModule } from "./notifications/notifications.module";
|
||||
import { AdvisorsModule } from "./advisors/advisors.module";
|
||||
import { OrchestrationModule } from "./orchestration/orchestration.module";
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
...registerPrepareWorker(),
|
||||
RouterUsageModule,
|
||||
// Deny-all registration: no request identity or runtime credentials are accepted yet.
|
||||
runtimeReadRegistration(),
|
||||
OrchestrationModule,
|
||||
SupportChatModule,
|
||||
RevalidationModule,
|
||||
SmsModule,
|
||||
@@ -81,8 +89,7 @@ import { Request, Response, NextFunction } from "express";
|
||||
B2BModule,
|
||||
FaqModule,
|
||||
MenuModule,
|
||||
NotificationsModule,
|
||||
AdvisorsModule,
|
||||
TasksModule,
|
||||
],
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
|
||||
@@ -9,7 +9,6 @@ import { AdminModule } from "../admin/admin.module";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { NotificationsModule } from "../notifications/notifications.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -17,7 +16,6 @@ import { NotificationsModule } from "../notifications/notifications.module";
|
||||
forwardRef(() => AdminModule),
|
||||
PassportModule,
|
||||
RedisModule,
|
||||
NotificationsModule,
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
secret: getJwtSecret(),
|
||||
|
||||
@@ -4,7 +4,6 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
describe("AuthService", () => {
|
||||
@@ -44,7 +43,6 @@ describe("AuthService", () => {
|
||||
{ provide: JwtService, useValue: mockJwt },
|
||||
{ provide: RedisService, useValue: mockRedis },
|
||||
{ provide: SmsService, useValue: mockSms },
|
||||
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import { RedisService } from "../redis/redis.service";
|
||||
import { SendOtpDto } from "./dto/send-otp.dto";
|
||||
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
@@ -43,7 +42,6 @@ export class AuthService {
|
||||
private jwtService: JwtService,
|
||||
private redisService: RedisService,
|
||||
private smsService: SmsService,
|
||||
private transactionalEmails: TransactionalEmailsService,
|
||||
) {}
|
||||
|
||||
private async generateTokens(payload: Record<string, any>) {
|
||||
@@ -259,13 +257,6 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
// Fire-and-forget welcome email when register provided an address
|
||||
if (user.email) {
|
||||
this.transactionalEmails
|
||||
.sendWelcome(user.email, user.firstName)
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
|
||||
describe("findAll", () => {
|
||||
it("should query published blogs with pagination", async () => {
|
||||
const blogs = [
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null },
|
||||
];
|
||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||
mockPrisma.blog.count.mockResolvedValue(1);
|
||||
@@ -49,6 +49,9 @@ describe("BlogsService", () => {
|
||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||
expect(result.data).toEqual(blogs);
|
||||
expect(result.meta.total).toBe(1);
|
||||
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
||||
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
|
||||
});
|
||||
|
||||
it("should filter by categorySlug and search term", async () => {
|
||||
@@ -67,7 +70,19 @@ describe("BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the minimal public author identity for list results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
||||
await service.findAll({});
|
||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("selects the minimal public author identity for homepage results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
await service.findHomepage();
|
||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
@@ -90,6 +105,12 @@ describe("BlogsService", () => {
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("selects the minimal public author identity for detail results", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
|
||||
@@ -64,12 +64,15 @@ export class BlogsService {
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: {
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
{ id: "asc" },
|
||||
],
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
@@ -108,9 +111,11 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -125,9 +130,11 @@ export class BlogsService {
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -163,9 +170,7 @@ export class BlogsService {
|
||||
],
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
},
|
||||
author: { select: { id: true, firstName: true, lastName: true } },
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -110,4 +110,22 @@ describe("RevalidationService", () => {
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidate batch", () => {
|
||||
it("should send deduplicated tags and paths in one request", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
|
||||
|
||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
|
||||
@@ -38,8 +38,6 @@ export interface SmsConfig {
|
||||
shippingBodyId: number;
|
||||
b2bBodyId: number;
|
||||
petCareBodyId: number;
|
||||
leadAdvisorBodyId?: number;
|
||||
leadConfirmationBodyId?: number;
|
||||
rules?: SmsRule[];
|
||||
}
|
||||
|
||||
@@ -124,16 +122,6 @@ export class SmsService {
|
||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||
"0",
|
||||
),
|
||||
leadAdvisorBodyId: Number(
|
||||
dbConfig.leadAdvisorBodyId ||
|
||||
process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID ||
|
||||
"580260",
|
||||
),
|
||||
leadConfirmationBodyId: Number(
|
||||
dbConfig.leadConfirmationBodyId ||
|
||||
process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID ||
|
||||
"580259",
|
||||
),
|
||||
rules: Array.isArray(dbConfig.rules)
|
||||
? (dbConfig.rules as SmsRule[])
|
||||
: DEFAULT_SMS_RULES,
|
||||
@@ -152,8 +140,6 @@ export class SmsService {
|
||||
),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
||||
leadAdvisorBodyId: Number(process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID || "580260"),
|
||||
leadConfirmationBodyId: Number(process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID || "580259"),
|
||||
rules: DEFAULT_SMS_RULES,
|
||||
};
|
||||
}
|
||||
@@ -1391,88 +1377,13 @@ export class SmsService {
|
||||
});
|
||||
return false;
|
||||
}
|
||||
// 2. Dispatch generic direct SMS via MeliPayamak SendSMS endpoint if fromNumber configured, else fall back to local log
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
to: phone,
|
||||
from: config.fromNumber || "50004001100228",
|
||||
text: message,
|
||||
isFlash: false,
|
||||
});
|
||||
|
||||
const req = https.request(
|
||||
"https://rest.payamak-panel.com/api/SendSMS/SendSMS",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as { Value?: number | string; RetStatus?: number; StrRetStatus?: string };
|
||||
const val = Number(json.Value ?? 0);
|
||||
if (val > 15 || json.RetStatus === 1) {
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, RecId: ${val}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: "SUCCESS",
|
||||
recId: String(val),
|
||||
});
|
||||
resolve(true);
|
||||
} else {
|
||||
const errMsg = `خطای ارسال پیامک متنی با کد: ${val} (${json.StrRetStatus || ''})`;
|
||||
this.logger.error(`[SMS Text Error] To: ${phone}, Code: ${val}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: "FAILED",
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve(false);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: "FAILED",
|
||||
errorMessage: `خطای پارس پاسخ ملی پیامک: ${data || msg}`,
|
||||
});
|
||||
resolve(false);
|
||||
}
|
||||
})();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on("error", (err: Error) => {
|
||||
void (async () => {
|
||||
this.logger.error(`[SMS Text Network Error] To: ${phone}: ${err.message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: "FAILED",
|
||||
errorMessage: err.message,
|
||||
});
|
||||
resolve(false);
|
||||
})();
|
||||
});
|
||||
|
||||
req.write(payload);
|
||||
req.end();
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: "SUCCESS",
|
||||
});
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TasksService } from './tasks.service';
|
||||
import { OrdersModule } from '../../orders/orders.module';
|
||||
import { PaymentModule } from '../../payment/payment.module';
|
||||
import { RedisModule } from '../../redis/redis.module';
|
||||
|
||||
@Module({
|
||||
imports: [OrdersModule, PaymentModule, RedisModule],
|
||||
providers: [TasksService],
|
||||
exports: [TasksService],
|
||||
})
|
||||
export class TasksModule {}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
||||
import { OrdersService } from '../../orders/orders.service';
|
||||
import { RedisService } from '../../redis/redis.service';
|
||||
import { PaymentService } from '../../payment/payment.service';
|
||||
|
||||
@Injectable()
|
||||
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(TasksService.name);
|
||||
private reservationTimer: NodeJS.Timeout | null = null;
|
||||
private reconciliationTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly ordersService: OrdersService,
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly redisService: RedisService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap() {
|
||||
this.logger.log('Starting background maintenance tasks...');
|
||||
|
||||
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
|
||||
this.reservationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.ordersService.releaseExpiredInventoryReservations();
|
||||
if (result.releasedCount > 0) {
|
||||
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:inventory_release');
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
|
||||
this.reconciliationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.paymentService.reconcilePendingTransactions();
|
||||
if (result.total > 0) {
|
||||
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:payment_reconciliation');
|
||||
}
|
||||
}, 10 * 60 * 1000);
|
||||
|
||||
// Initial check on startup after 30 seconds
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.ordersService.releaseExpiredInventoryReservations();
|
||||
} catch (err) {
|
||||
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
|
||||
}
|
||||
}, 30 * 1000);
|
||||
}
|
||||
|
||||
onApplicationShutdown() {
|
||||
this.logger.log('Stopping background maintenance tasks...');
|
||||
if (this.reservationTimer) {
|
||||
clearInterval(this.reservationTimer);
|
||||
this.reservationTimer = null;
|
||||
}
|
||||
if (this.reconciliationTimer) {
|
||||
clearInterval(this.reconciliationTimer);
|
||||
this.reconciliationTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,9 @@ import { Module } from "@nestjs/common";
|
||||
import { ContactController } from "./contact.controller";
|
||||
import { ContactService } from "./contact.service";
|
||||
import { SmsModule } from "../common/sms.module";
|
||||
import { NotificationsModule } from "../notifications/notifications.module";
|
||||
|
||||
@Module({
|
||||
imports: [SmsModule, NotificationsModule],
|
||||
imports: [SmsModule],
|
||||
controllers: [ContactController],
|
||||
providers: [ContactService],
|
||||
exports: [ContactService],
|
||||
|
||||
@@ -2,7 +2,6 @@ import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||
|
||||
describe("ContactService", () => {
|
||||
let service: ContactService;
|
||||
@@ -35,17 +34,6 @@ describe("ContactService", () => {
|
||||
provide: SmsService,
|
||||
useValue: mockSmsService,
|
||||
},
|
||||
{
|
||||
provide: TransactionalEmailsService,
|
||||
useValue: {
|
||||
sendWelcome: jest.fn().mockResolvedValue(undefined),
|
||||
sendOrderCreated: jest.fn().mockResolvedValue(undefined),
|
||||
sendOrderPaid: jest.fn().mockResolvedValue(undefined),
|
||||
sendOrderShipped: jest.fn().mockResolvedValue(undefined),
|
||||
sendContactConfirmation: jest.fn().mockResolvedValue(undefined),
|
||||
notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||
|
||||
export interface CreateContactSubmissionDto {
|
||||
name: string;
|
||||
@@ -26,7 +25,6 @@ export class ContactService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly transactionalEmails: TransactionalEmailsService,
|
||||
) {}
|
||||
|
||||
async submitContactForm(dto: CreateContactSubmissionDto) {
|
||||
@@ -58,28 +56,6 @@ export class ContactService {
|
||||
);
|
||||
}
|
||||
|
||||
// Email confirmation to submitter + admin notify (non-blocking)
|
||||
void Promise.resolve(
|
||||
this.transactionalEmails.notifyAdminsAboutContact({
|
||||
name: dto.name,
|
||||
phone: dto.phone,
|
||||
email: dto.email,
|
||||
subject: dto.subject,
|
||||
message: dto.message,
|
||||
submissionId: submission.id,
|
||||
}),
|
||||
).catch(() => {});
|
||||
if (dto.email) {
|
||||
void Promise.resolve(
|
||||
this.transactionalEmails.sendContactConfirmation(
|
||||
dto.email,
|
||||
dto.name,
|
||||
dto.message,
|
||||
submission.id,
|
||||
),
|
||||
).catch(() => {});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
describe('backend-owned runtime authorization', () => {
|
||||
const ctx = { subject: 'admin', profiles: ['seo'] };
|
||||
const make = (allow = true, enabled = false) => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ id: 'j', profile: 'seo', enabled: false }),
|
||||
),
|
||||
);
|
||||
const authorize = jest.fn().mockResolvedValue(allow);
|
||||
return {
|
||||
fetcher,
|
||||
authorize,
|
||||
s: new HermesIntegrationService(
|
||||
new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
{ authorize },
|
||||
enabled,
|
||||
),
|
||||
};
|
||||
};
|
||||
it('denies missing principal, missing profile, denied policy before upstream IO', async () => {
|
||||
const { s, fetcher } = make(false);
|
||||
await expect(s.pauseCron(ctx, 'seo', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
await expect(
|
||||
s.pauseCron({ ...ctx, subject: '' }, 'seo', 'j'),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
await expect(s.pauseCron(ctx, 'dev', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('allows authorized pause but leaves resume disabled by default', async () => {
|
||||
const { s, fetcher, authorize } = make();
|
||||
await s.pauseCron(ctx, 'seo', 'j');
|
||||
expect(authorize).toHaveBeenCalledWith(ctx, 'cron.pause', 'seo');
|
||||
await expect(s.resumeCron(ctx, 'seo', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('fails closed on all execution and never forwards arbitrary events or RPC', async () => {
|
||||
const { s, fetcher } = make();
|
||||
expect(s.capabilities()).toMatchObject({
|
||||
chat: false,
|
||||
control: false,
|
||||
eventDispatch: false,
|
||||
cronResume: false,
|
||||
});
|
||||
await expect(s.chat(ctx, 'seo', 'hello')).rejects.toMatchObject({
|
||||
code: 'UNSUPPORTED',
|
||||
});
|
||||
await expect(s.control(ctx, 'seo', 'interrupt')).rejects.toMatchObject({
|
||||
code: 'UNSUPPORTED',
|
||||
});
|
||||
await expect(
|
||||
s.dispatchEvent(ctx, 'seo', { type: 'order.created' }),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('fails closed when authorization provider throws', async () => {
|
||||
const a = new HermesAdapter({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
});
|
||||
const s = new HermesIntegrationService(a, {
|
||||
authorize: () => Promise.reject(new Error('private')),
|
||||
});
|
||||
await expect(s.health(ctx)).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
});
|
||||
});
|
||||
|
||||
it('checks every read capability and filters the global profile roster', async () => {
|
||||
const fetcher = jest.fn().mockImplementation((input: URL) => {
|
||||
const payloads: Record<string, unknown> = {
|
||||
'/api/health': {
|
||||
ok: true,
|
||||
version: 'x',
|
||||
commit: 'x',
|
||||
auth_required: true,
|
||||
},
|
||||
'/api/status': {
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
},
|
||||
'/api/profiles': {
|
||||
profiles: [
|
||||
{ name: 'seo', is_default: false, gateway_running: false },
|
||||
{ name: 'dev', is_default: false, gateway_running: false },
|
||||
],
|
||||
},
|
||||
'/api/model/info': {
|
||||
model: 'm',
|
||||
provider: 'p',
|
||||
effective_context_length: 1,
|
||||
},
|
||||
'/api/model/options': { providers: [] },
|
||||
'/api/analytics/usage': {
|
||||
period_days: 30,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 0,
|
||||
total_sessions: 0,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
},
|
||||
'/api/sessions': { sessions: [], total: 0 },
|
||||
'/api/cron/jobs': [],
|
||||
};
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify(payloads[input.pathname])),
|
||||
);
|
||||
});
|
||||
const authorize = jest.fn().mockResolvedValue(true);
|
||||
const s = new HermesIntegrationService(
|
||||
new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
{ authorize },
|
||||
);
|
||||
const p = { subject: 'verified', profiles: ['seo'] };
|
||||
await s.health(p);
|
||||
await s.status(p, 'seo');
|
||||
expect(await s.profiles(p)).toHaveLength(1);
|
||||
await s.modelInfo(p, 'seo');
|
||||
await s.modelOptions(p, 'seo');
|
||||
await s.usage(p, 'seo');
|
||||
await s.sessions(p, 'seo');
|
||||
await s.crons(p, 'seo');
|
||||
expect(authorize).toHaveBeenCalledTimes(8);
|
||||
expect(authorize.mock.calls.every((c) => c[1] === 'runtime.read')).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { HermesAdapter, HermesError, Json } from './hermes.adapter';
|
||||
/** Context MUST be constructed from verified backend identity, never request bodies. */
|
||||
export interface RuntimePrincipal {
|
||||
subject: string;
|
||||
profiles: readonly string[];
|
||||
}
|
||||
export type RuntimePermission =
|
||||
| 'runtime.read'
|
||||
| 'cron.pause'
|
||||
| 'cron.resume'
|
||||
| 'chat'
|
||||
| 'control'
|
||||
| 'event.dispatch';
|
||||
export interface RuntimeAuthorizer {
|
||||
authorize(
|
||||
principal: RuntimePrincipal,
|
||||
permission: RuntimePermission,
|
||||
profile?: string,
|
||||
): Promise<boolean>;
|
||||
}
|
||||
/** No controller or socket is registered: only the backend gatekeeper can call this seam. */
|
||||
export class HermesIntegrationService {
|
||||
constructor(
|
||||
private readonly adapter: HermesAdapter,
|
||||
private readonly policy: RuntimeAuthorizer,
|
||||
private readonly resumeEnabled = false,
|
||||
) {}
|
||||
capabilities() {
|
||||
return {
|
||||
inventory: true,
|
||||
cronPause: true,
|
||||
cronResume: this.resumeEnabled,
|
||||
chat: false,
|
||||
control: false,
|
||||
eventDispatch: false,
|
||||
} as const;
|
||||
}
|
||||
private async check(
|
||||
principal: RuntimePrincipal,
|
||||
permission: RuntimePermission,
|
||||
profile?: string,
|
||||
): Promise<void> {
|
||||
if (
|
||||
!principal?.subject ||
|
||||
!Array.isArray(principal.profiles) ||
|
||||
(profile && !principal.profiles.includes(profile))
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
try {
|
||||
if (
|
||||
(await this.policy.authorize(principal, permission, profile)) !== true
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
} catch {
|
||||
throw new HermesError('FORBIDDEN');
|
||||
}
|
||||
}
|
||||
async health(p: RuntimePrincipal) {
|
||||
await this.check(p, 'runtime.read');
|
||||
return this.adapter.health();
|
||||
}
|
||||
async status(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.status(profile);
|
||||
}
|
||||
async profiles(p: RuntimePrincipal) {
|
||||
await this.check(p, 'runtime.read');
|
||||
return (await this.adapter.profiles()).filter(
|
||||
(r) => typeof r.name === 'string' && p.profiles.includes(r.name),
|
||||
);
|
||||
}
|
||||
async modelInfo(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.modelInfo(profile);
|
||||
}
|
||||
async modelOptions(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.modelOptions(profile);
|
||||
}
|
||||
async usage(p: RuntimePrincipal, profile: string, days = 30) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.usage(profile, days);
|
||||
}
|
||||
async sessions(p: RuntimePrincipal, profile: string, limit = 20, offset = 0) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.sessions(profile, limit, offset);
|
||||
}
|
||||
async crons(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.crons(profile);
|
||||
}
|
||||
async pauseCron(p: RuntimePrincipal, profile: string, id: string) {
|
||||
await this.check(p, 'cron.pause', profile);
|
||||
return this.adapter.pauseCron(profile, id);
|
||||
}
|
||||
async resumeCron(p: RuntimePrincipal, profile: string, id: string) {
|
||||
await this.check(p, 'cron.resume', profile);
|
||||
if (!this.resumeEnabled) throw new HermesError('FORBIDDEN');
|
||||
return this.adapter.resumeCron(profile, id);
|
||||
}
|
||||
async chat(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_text: string,
|
||||
): Promise<never> {
|
||||
await this.check(p, 'chat', profile);
|
||||
throw new HermesError('UNSUPPORTED');
|
||||
}
|
||||
async control(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_command: 'interrupt',
|
||||
): Promise<never> {
|
||||
await this.check(p, 'control', profile);
|
||||
throw new HermesError('UNSUPPORTED');
|
||||
}
|
||||
/** Disabled independently of policy: no unreviewed event may become an agent prompt. */
|
||||
async dispatchEvent(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_event: Json,
|
||||
): Promise<never> {
|
||||
await this.check(p, 'event.dispatch', profile);
|
||||
throw new HermesError('FORBIDDEN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { HermesManagementModule } from './hermes-management.module';
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
it('requires explicit registration and denies by default without publishing controllers', async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [
|
||||
HermesManagementModule.register({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
}),
|
||||
],
|
||||
}).compile();
|
||||
const service = module.get(HermesIntegrationService);
|
||||
await expect(
|
||||
service.health({ subject: 'admin', profiles: [] }),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
await module.close();
|
||||
});
|
||||
|
||||
it('registers backend credential broker without acquiring credentials before policy authorization', async () => {
|
||||
const credentials=jest.fn().mockResolvedValue({username:'backend',password:'test-only'});
|
||||
const module=await Test.createTestingModule({imports:[HermesManagementModule.registerAuthenticated(credentials)]}).compile();
|
||||
await expect(module.get(HermesIntegrationService).health({subject:'admin',profiles:[]})).rejects.toMatchObject({code:'FORBIDDEN'});
|
||||
expect(credentials).not.toHaveBeenCalled();
|
||||
await module.close();
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { DynamicModule, Module } from '@nestjs/common';
|
||||
import { HermesSessionBroker } from './hermes-session-broker';
|
||||
import { HermesAdapter, HermesConfig } from './hermes.adapter';
|
||||
import {
|
||||
HermesIntegrationService,
|
||||
RuntimeAuthorizer,
|
||||
} from './hermes-integration.service';
|
||||
@Module({})
|
||||
export class HermesManagementModule {
|
||||
static registerAuthenticated(
|
||||
credentials: () => Promise<{username:string;password:string}>,
|
||||
policy: RuntimeAuthorizer = {authorize: async () => false},
|
||||
): DynamicModule {
|
||||
const broker = new HermesSessionBroker(credentials);
|
||||
return this.register({origin:'http://canina-hermes-inventory:9119',token:()=>broker.token()},policy);
|
||||
}
|
||||
|
||||
static register(
|
||||
config: HermesConfig,
|
||||
policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) },
|
||||
): DynamicModule {
|
||||
return {
|
||||
module: HermesManagementModule,
|
||||
providers: [
|
||||
{ provide: HermesAdapter, useFactory: () => new HermesAdapter(config) },
|
||||
{
|
||||
provide: HermesIntegrationService,
|
||||
useFactory: (adapter: HermesAdapter) =>
|
||||
new HermesIntegrationService(adapter, policy, false),
|
||||
inject: [HermesAdapter],
|
||||
},
|
||||
],
|
||||
exports: [HermesIntegrationService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach } from '@jest/globals';
|
||||
import { HermesSessionBroker } from './hermes-session-broker';
|
||||
const credentials = async () => ({username:'backend',password:'test-only'});
|
||||
const response = () => new Response('{"ok":true}', {headers:{'set-cookie':'hermes_session_at=verified-test-token; Max-Age=60; Path=/; HttpOnly'}});
|
||||
describe('server-only Hermes session broker',()=>{
|
||||
afterEach(()=>{jest.useRealTimers();});
|
||||
it('renews expired cached access without retaining the refresh cookie',async()=>{
|
||||
jest.useFakeTimers();
|
||||
const fetcher=jest.fn().mockImplementation(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
await broker.token();
|
||||
await jest.advanceTimersByTimeAsync(51000);
|
||||
await broker.token();
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it('bounds credential waits and releases the pending login after timeout',async()=>{
|
||||
jest.useFakeTimers();
|
||||
const load=jest.fn().mockImplementationOnce(()=>new Promise(()=>{})).mockImplementation(credentials);
|
||||
const broker=new HermesSessionBroker(load,jest.fn().mockImplementation(async()=>response()));
|
||||
const result=expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'});
|
||||
await jest.advanceTimersByTimeAsync(5001);await result;
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
});
|
||||
it('rejects oversized response bodies and short cookie lifetimes',async()=>{
|
||||
for(const res of [new Response('x'.repeat(4097)),new Response('{"ok":true}',{headers:{'set-cookie':'hermes_session_at=token; Max-Age=1; Path=/'}})]){
|
||||
await expect(new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(res)).token()).rejects.toMatchObject({message:'Hermes auth_required'});
|
||||
}
|
||||
});
|
||||
|
||||
it('coalesces login, caches only access token and uses installed password-login contract',async()=>{
|
||||
const fetcher=jest.fn().mockImplementation(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
expect(await Promise.all([broker.token(),broker.token()])).toEqual(['verified-test-token','verified-test-token']);
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const [url,options]=fetcher.mock.calls[0];
|
||||
expect(url).toBe('http://canina-hermes-inventory:9119/auth/password-login');
|
||||
expect(JSON.parse(options.body)).toEqual({provider:'basic',username:'backend',password:'test-only'});
|
||||
expect(options.redirect).toBe('error');
|
||||
});
|
||||
it('fails closed without echoing credentials, response bodies or provider errors',async()=>{
|
||||
for(const result of [new Response('private secret',{status:401}),new Response('{"ok":true}'),new Response('{"ok":false}',{headers:{'set-cookie':'hermes_session_at=bad; Max-Age=60'}})]){
|
||||
const broker=new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(result));
|
||||
await expect(broker.token()).rejects.toMatchObject({message:'Hermes auth_required'});
|
||||
}
|
||||
});
|
||||
it('does not cache failures and permits a later successful login',async()=>{
|
||||
const fetcher=jest.fn().mockRejectedValueOnce(new Error('sensitive upstream')).mockImplementationOnce(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
await expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'});
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { HermesError } from './hermes.adapter';
|
||||
export class HermesSessionBroker {
|
||||
private cached: {token:string;until:number}|undefined;
|
||||
private pending: Promise<string>|undefined;
|
||||
constructor(private readonly credentials:()=>Promise<{username:string;password:string}>,private readonly fetcher:typeof fetch=fetch) {}
|
||||
token():Promise<string>{
|
||||
if(this.cached && this.cached.until>Date.now()) return Promise.resolve(this.cached.token);
|
||||
if(this.pending) return this.pending;
|
||||
this.pending=this.login().finally(()=>{this.pending=undefined;});
|
||||
return this.pending;
|
||||
}
|
||||
private async login():Promise<string>{
|
||||
const controller=new AbortController();
|
||||
const timer=setTimeout(()=>controller.abort(),5000);
|
||||
try{
|
||||
const creds=await Promise.race([this.credentials(),new Promise<never>((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new HermesError('UNAVAILABLE')),{once:true}))]);
|
||||
if(!creds.username || !creds.password) throw new HermesError('AUTH_REQUIRED');
|
||||
const response=await this.fetcher('http://canina-hermes-inventory:9119/auth/password-login',{method:'POST',redirect:'error',signal:controller.signal,headers:{'Content-Type':'application/json'},body:JSON.stringify({provider:'basic',...creds})});
|
||||
if(!response.ok) throw new HermesError('AUTH_REQUIRED');
|
||||
const reader=response.body?.getReader();
|
||||
if(!reader) throw new HermesError('AUTH_REQUIRED');
|
||||
const chunks:Uint8Array[]=[];let size=0;
|
||||
try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096)throw new HermesError('AUTH_REQUIRED');chunks.push(value);}}finally{await reader.cancel().catch(()=>undefined);}
|
||||
const body=JSON.parse(Buffer.concat(chunks).toString('utf8')) as {ok?:unknown};
|
||||
const cookies=response.headers.getSetCookie();
|
||||
const cookie=cookies.find(c=>c.startsWith('hermes_session_at='));
|
||||
const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1];
|
||||
const age=Number(cookie?.match(/(?:^|;)\s*Max-Age=(\d+)/i)?.[1]);
|
||||
if(body.ok!==true || !token || !Number.isSafeInteger(age) || age<30)throw new HermesError('AUTH_REQUIRED');
|
||||
this.cached={token,until:Date.now()+Math.min(age-10,300)*1000};
|
||||
return token;
|
||||
}catch(error){if(error instanceof HermesError)throw error;throw new HermesError('UNAVAILABLE');}
|
||||
finally{clearTimeout(timer);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { HermesAdapter, HermesError } from './hermes.adapter';
|
||||
const health = {
|
||||
ok: true,
|
||||
version: '0.13',
|
||||
commit: 'abc',
|
||||
auth_required: true,
|
||||
};
|
||||
describe('installed Hermes health contract', () => {
|
||||
it('uses pinned internal origin, bearer only server side and strips extra fields', async () => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ ...health, token: 'never', home: '/secret' }),
|
||||
),
|
||||
);
|
||||
const adapter = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('private'),
|
||||
},
|
||||
fetcher,
|
||||
);
|
||||
expect(await adapter.health()).toEqual(health);
|
||||
expect(fetcher.mock.calls[0][0].toString()).toBe(
|
||||
'http://canina-hermes:9119/api/health',
|
||||
);
|
||||
expect(fetcher.mock.calls[0][1].headers.Authorization).toBe(
|
||||
'Bearer private',
|
||||
);
|
||||
expect(fetcher.mock.calls[0][1].redirect).toBe('error');
|
||||
});
|
||||
it('refuses a runtime reporting that authentication is disabled', async () => {
|
||||
const adapter = new HermesAdapter({origin:'http://canina-hermes:9119',token:async()=> 'private'},
|
||||
jest.fn().mockResolvedValue(new Response(JSON.stringify({...health,auth_required:false}))));
|
||||
await expect(adapter.health()).rejects.toMatchObject({code:'AUTH_REQUIRED'});
|
||||
});
|
||||
|
||||
it('fails closed for bad origin, auth errors, malformed contract and oversized bodies', async () => {
|
||||
expect(
|
||||
() =>
|
||||
new HermesAdapter({
|
||||
origin: 'https://evil.test',
|
||||
token: () => Promise.resolve(''),
|
||||
}),
|
||||
).toThrow(HermesError);
|
||||
for (const response of [
|
||||
new Response('private', { status: 401 }),
|
||||
new Response('{}'),
|
||||
new Response('x'.repeat(262145)),
|
||||
]) {
|
||||
const a = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
jest.fn().mockResolvedValue(response),
|
||||
);
|
||||
await expect(a.health()).rejects.toBeInstanceOf(HermesError);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('bounded profile-scoped REST inventory', () => {
|
||||
const create = (payload: unknown) => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify(payload)));
|
||||
return {
|
||||
a: new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
fetcher,
|
||||
};
|
||||
};
|
||||
it('projects status, profiles, models and usage without raw paths, prompts or credentials', async () => {
|
||||
expect(
|
||||
await create({
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
}).a.status('seo'),
|
||||
).toEqual({
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
});
|
||||
expect(
|
||||
await create({
|
||||
profiles: [
|
||||
{
|
||||
name: 'seo',
|
||||
is_default: false,
|
||||
gateway_running: false,
|
||||
path: '/private',
|
||||
description: 'token=secret',
|
||||
},
|
||||
],
|
||||
}).a.profiles(),
|
||||
).toEqual([{ name: 'seo', is_default: false, gateway_running: false }]);
|
||||
expect(
|
||||
await create({
|
||||
model: 'm',
|
||||
provider: 'p',
|
||||
effective_context_length: 0,
|
||||
api_key: 'secret',
|
||||
}).a.modelInfo('seo'),
|
||||
).toEqual({ model: 'm', provider: 'p', effective_context_length: 0 });
|
||||
expect(
|
||||
await create({
|
||||
providers: [
|
||||
{ slug: 'p', name: 'Provider', models: ['m'], api_key: 'secret' },
|
||||
],
|
||||
current: { api_key: 'secret' },
|
||||
}).a.modelOptions('seo'),
|
||||
).toEqual([{ slug: 'p', name: 'Provider', models: ['m'] }]);
|
||||
expect(
|
||||
await create({
|
||||
period_days: 7,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 2,
|
||||
total_sessions: 1,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
tools: { secret: 1 },
|
||||
}).a.usage('seo', 7),
|
||||
).toEqual({
|
||||
period_days: 7,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 2,
|
||||
total_sessions: 1,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
it('uses scoped list contract and rejects unbounded queries or profile escape', async () => {
|
||||
const { a, fetcher } = create({
|
||||
sessions: [
|
||||
{
|
||||
id: 's',
|
||||
profile: 'seo',
|
||||
is_active: false,
|
||||
source: 'cron',
|
||||
title: 'secret',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
storage: {},
|
||||
});
|
||||
expect(await a.sessions('seo', 20, 0)).toEqual({
|
||||
sessions: [{ id: 's', profile: 'seo', is_active: false, source: 'cron' }],
|
||||
total: 1,
|
||||
});
|
||||
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/sessions');
|
||||
expect(fetcher.mock.calls[0][0].searchParams.get('full')).toBe('false');
|
||||
await expect(a.sessions('../escape', 20, 0)).rejects.toThrow();
|
||||
await expect(a.sessions('seo', 101, 0)).rejects.toThrow();
|
||||
await expect(a.usage('seo', 366)).rejects.toThrow();
|
||||
await expect(
|
||||
create({
|
||||
sessions: [],
|
||||
total: 0,
|
||||
storage: { seo: 'corrupt' },
|
||||
}).a.sessions('seo'),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
create({
|
||||
sessions: [
|
||||
{ id: 's', profile: 'dev', source: 'cli', is_active: false },
|
||||
],
|
||||
total: 1,
|
||||
}).a.sessions('seo'),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it('lists scoped cron array; pause/resume use exact POST routes without triggers', async () => {
|
||||
expect(
|
||||
await create([
|
||||
{ id: 'j', profile: 'seo', enabled: false, prompt: 'secret' },
|
||||
]).a.crons('seo'),
|
||||
).toEqual([{ id: 'j', profile: 'seo', enabled: false }]);
|
||||
const { a, fetcher } = create({ id: 'j', profile: 'seo', enabled: false });
|
||||
expect(await a.pauseCron('seo', 'j')).toEqual({
|
||||
id: 'j',
|
||||
profile: 'seo',
|
||||
enabled: false,
|
||||
});
|
||||
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/cron/jobs/j/pause');
|
||||
expect(fetcher.mock.calls[0][1].method).toBe('POST');
|
||||
const resume = create({ id: 'j', profile: 'seo', enabled: true });
|
||||
await resume.a.resumeCron('seo', 'j');
|
||||
expect(resume.fetcher.mock.calls[0][0].pathname).toBe(
|
||||
'/api/cron/jobs/j/resume',
|
||||
);
|
||||
await expect(a.pauseCron('seo', '../trigger')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resource budgets and safe errors', () => {
|
||||
it('does not leak upstream errors or tokens and limits credential waits', async () => {
|
||||
jest.useFakeTimers();
|
||||
const a = new HermesAdapter({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => new Promise(() => {}),
|
||||
});
|
||||
const result = expect(a.health()).rejects.toMatchObject({
|
||||
code: 'UNAVAILABLE',
|
||||
message: 'Hermes unavailable',
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(5001);
|
||||
await result;
|
||||
jest.useRealTimers();
|
||||
});
|
||||
it('caps concurrency before upstream IO', async () => {
|
||||
const resolvers: ((r: Response) => void)[] = [];
|
||||
const fetcher = jest.fn(
|
||||
() =>
|
||||
new Promise<Response>((r) => {
|
||||
resolvers.push(r);
|
||||
}),
|
||||
);
|
||||
const a = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
);
|
||||
const calls = Array.from({ length: 4 }, () => a.health());
|
||||
const denied = expect(a.health()).rejects.toMatchObject({ code: 'LIMIT' });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
resolvers.forEach((r) => r(new Response(JSON.stringify(health))));
|
||||
await denied;
|
||||
await Promise.all(calls);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
export type Json =
|
||||
| null
|
||||
| boolean
|
||||
| number
|
||||
| string
|
||||
| Json[]
|
||||
| { [key: string]: Json };
|
||||
export type Row = Record<string, Json>;
|
||||
export type HermesErrorCode =
|
||||
| 'CONFIGURATION'
|
||||
| 'AUTH_REQUIRED'
|
||||
| 'UNAVAILABLE'
|
||||
| 'CONTRACT'
|
||||
| 'LIMIT'
|
||||
| 'FORBIDDEN'
|
||||
| 'UNSUPPORTED';
|
||||
export class HermesError extends Error {
|
||||
constructor(readonly code: HermesErrorCode) {
|
||||
super(`Hermes ${code.toLowerCase()}`);
|
||||
}
|
||||
}
|
||||
export interface HermesConfig {
|
||||
origin: string;
|
||||
token: () => Promise<string>;
|
||||
}
|
||||
export interface Health {
|
||||
ok: boolean;
|
||||
version: string;
|
||||
commit: string;
|
||||
auth_required: boolean;
|
||||
provenance?: Row;
|
||||
}
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
throw new HermesError('CONTRACT');
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
function fields(
|
||||
value: unknown,
|
||||
schema: Record<string, 'string' | 'boolean' | 'number'>,
|
||||
): Row {
|
||||
const source = object(value);
|
||||
const result: Row = {};
|
||||
for (const [key, type] of Object.entries(schema)) {
|
||||
if (
|
||||
typeof source[key] !== type ||
|
||||
(type === 'number' && !Number.isFinite(source[key]))
|
||||
)
|
||||
throw new HermesError('CONTRACT');
|
||||
result[key] = source[key] as Json;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export class HermesAdapter {
|
||||
private readonly origin: string;
|
||||
private inflight = 0;
|
||||
constructor(
|
||||
private readonly config: HermesConfig,
|
||||
private readonly fetcher: typeof fetch = fetch,
|
||||
) {
|
||||
if (
|
||||
![
|
||||
'http://canina-hermes:9119',
|
||||
'http://canina-hermes-inventory:9119',
|
||||
].includes(config.origin)
|
||||
)
|
||||
throw new HermesError('CONFIGURATION');
|
||||
this.origin = config.origin;
|
||||
}
|
||||
private async request(
|
||||
path: string,
|
||||
profile?: string,
|
||||
method = 'GET',
|
||||
params: Record<string, string> = {},
|
||||
): Promise<unknown> {
|
||||
if (
|
||||
profile !== undefined &&
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(profile)
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
const url = new URL(path, this.origin);
|
||||
if (profile) url.searchParams.set('profile', profile);
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
if (this.inflight >= 4) throw new HermesError('LIMIT');
|
||||
this.inflight++;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const token = await Promise.race([
|
||||
this.config.token(),
|
||||
new Promise<never>((_, reject) =>
|
||||
controller.signal.addEventListener(
|
||||
'abort',
|
||||
() => reject(new HermesError('UNAVAILABLE')),
|
||||
{ once: true },
|
||||
),
|
||||
),
|
||||
]);
|
||||
if (!token || /[\r\n]/.test(token))
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
const response = await this.fetcher(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
signal: controller.signal,
|
||||
redirect: 'error',
|
||||
});
|
||||
if ([401, 403].includes(response.status))
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
if (response.status === 404) throw new HermesError('UNSUPPORTED');
|
||||
if (!response.ok) throw new HermesError('UNAVAILABLE');
|
||||
if (Number(response.headers.get('content-length')) > 262144)
|
||||
throw new HermesError('LIMIT');
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new HermesError('CONTRACT');
|
||||
let bytes = 0;
|
||||
const chunks: Uint8Array[] = [];
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
if (bytes > 262144) throw new HermesError('LIMIT');
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
}
|
||||
const data: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if (this.origin === 'http://canina-hermes-inventory:9119') {
|
||||
const rows = Array.isArray(data) ? data : [data];
|
||||
for (const row of rows) provenance(row, true);
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (error instanceof HermesError) throw error;
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this.inflight--;
|
||||
}
|
||||
}
|
||||
async health(): Promise<Health> {
|
||||
const raw = await this.request('/api/health');
|
||||
const health = {
|
||||
...fields(raw, {
|
||||
ok: 'boolean',
|
||||
version: 'string',
|
||||
commit: 'string',
|
||||
auth_required: 'boolean',
|
||||
}),
|
||||
...provenance(raw),
|
||||
} as unknown as Health;
|
||||
if (!health.auth_required) throw new HermesError('AUTH_REQUIRED');
|
||||
return health;
|
||||
}
|
||||
async status(profile: string): Promise<Row> {
|
||||
const raw = object(await this.request('/api/status', profile));
|
||||
const row = fields(raw, {
|
||||
version: 'string',
|
||||
gateway_running: 'boolean',
|
||||
overall: 'string',
|
||||
active_agents: 'number',
|
||||
});
|
||||
if (raw.gateway_state !== null && typeof raw.gateway_state !== 'string')
|
||||
throw new HermesError('CONTRACT');
|
||||
return {
|
||||
...row,
|
||||
gateway_state: raw.gateway_state as Json,
|
||||
...provenance(raw),
|
||||
...(raw.provenance
|
||||
? {
|
||||
gateway_running: false,
|
||||
active_agents: 0,
|
||||
gateway_state: null,
|
||||
overall: 'unknown',
|
||||
liveGatewayState: 'unknown',
|
||||
liveActiveAgents: null,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
async profiles(): Promise<Row[]> {
|
||||
return list(object(await this.request('/api/profiles')).profiles).map(
|
||||
(r) => ({
|
||||
...fields(r, {
|
||||
name: 'string',
|
||||
is_default: 'boolean',
|
||||
gateway_running: 'boolean',
|
||||
}),
|
||||
...provenance(r),
|
||||
...(object(r).provenance
|
||||
? { gateway_running: false, liveGatewayState: 'unknown' }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
async modelInfo(profile: string): Promise<Row> {
|
||||
const raw = await this.request('/api/model/info', profile);
|
||||
return {
|
||||
...fields(raw, {
|
||||
model: 'string',
|
||||
provider: 'string',
|
||||
effective_context_length: 'number',
|
||||
}),
|
||||
...provenance(raw),
|
||||
};
|
||||
}
|
||||
async modelOptions(profile: string): Promise<Row[]> {
|
||||
return list(
|
||||
object(await this.request('/api/model/options', profile)).providers,
|
||||
).map((r) => {
|
||||
const row = fields(r, { slug: 'string', name: 'string' });
|
||||
const models = list(object(r).models);
|
||||
if (models.some((m) => typeof m !== 'string'))
|
||||
throw new HermesError('CONTRACT');
|
||||
return { ...row, models: models as string[] };
|
||||
});
|
||||
}
|
||||
async usage(profile: string, days = 30): Promise<Row> {
|
||||
bound(days, 1, 365);
|
||||
const raw = object(
|
||||
await this.request('/api/analytics/usage', profile, 'GET', {
|
||||
days: String(days),
|
||||
}),
|
||||
);
|
||||
return {
|
||||
...fields(raw, { period_days: 'number' }),
|
||||
...provenance(raw),
|
||||
totals: fields(raw.totals, {
|
||||
total_input: 'number',
|
||||
total_output: 'number',
|
||||
total_sessions: 'number',
|
||||
total_estimated_cost: 'number',
|
||||
}),
|
||||
};
|
||||
}
|
||||
async sessions(profile: string, limit = 20, offset = 0): Promise<Row> {
|
||||
bound(limit, 1, 100);
|
||||
bound(offset, 0, 10000);
|
||||
const raw = object(
|
||||
await this.request('/api/sessions', profile, 'GET', {
|
||||
limit: String(limit),
|
||||
offset: String(offset),
|
||||
full: 'false',
|
||||
order: 'recent',
|
||||
}),
|
||||
);
|
||||
if (raw.storage && Object.keys(object(raw.storage)).length)
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
const rows = list(raw.sessions).map((r) =>
|
||||
scoped(r, profile, {
|
||||
id: 'string',
|
||||
profile: 'string',
|
||||
source: 'string',
|
||||
is_active: 'boolean',
|
||||
}),
|
||||
);
|
||||
return {
|
||||
...fields(raw, { total: 'number' }),
|
||||
sessions: rows,
|
||||
...provenance(raw),
|
||||
};
|
||||
}
|
||||
async crons(profile: string): Promise<Row[]> {
|
||||
return list(await this.request('/api/cron/jobs', profile)).map((r) =>
|
||||
scoped(r, profile, {
|
||||
id: 'string',
|
||||
profile: 'string',
|
||||
enabled: 'boolean',
|
||||
}),
|
||||
);
|
||||
}
|
||||
private async cron(
|
||||
profile: string,
|
||||
id: string,
|
||||
action: 'pause' | 'resume',
|
||||
): Promise<Row> {
|
||||
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new HermesError('FORBIDDEN');
|
||||
return scoped(
|
||||
await this.request(`/api/cron/jobs/${id}/${action}`, profile, 'POST'),
|
||||
profile,
|
||||
{ id: 'string', profile: 'string', enabled: 'boolean' },
|
||||
);
|
||||
}
|
||||
pauseCron(profile: string, id: string): Promise<Row> {
|
||||
return this.cron(profile, id, 'pause');
|
||||
}
|
||||
resumeCron(profile: string, id: string): Promise<Row> {
|
||||
return this.cron(profile, id, 'resume');
|
||||
}
|
||||
}
|
||||
|
||||
function list(value: unknown): unknown[] {
|
||||
if (!Array.isArray(value) || value.length > 1000)
|
||||
throw new HermesError('CONTRACT');
|
||||
return value;
|
||||
}
|
||||
function bound(value: number, min: number, max: number): void {
|
||||
if (!Number.isInteger(value) || value < min || value > max)
|
||||
throw new HermesError('LIMIT');
|
||||
}
|
||||
function scoped(
|
||||
value: unknown,
|
||||
profile: string,
|
||||
schema: Record<string, 'string' | 'boolean' | 'number'>,
|
||||
): Row {
|
||||
const row = fields(value, schema);
|
||||
if (row.profile !== profile) throw new HermesError('FORBIDDEN');
|
||||
return { ...row, ...provenance(value) };
|
||||
}
|
||||
|
||||
/** Snapshot provenance is mandatory on inventory origin; never synthesize a capture time. */
|
||||
function provenance(value: unknown, required = false): Row {
|
||||
const raw = object(value);
|
||||
if (!raw.provenance && !required) return {};
|
||||
const p = object(raw.provenance);
|
||||
if (
|
||||
p.source !== 'snapshot' ||
|
||||
p.liveProcess !== 'unknown' ||
|
||||
typeof p.capturedAt !== 'string' ||
|
||||
!p.capturedAt.endsWith('Z') ||
|
||||
!Number.isFinite(Date.parse(p.capturedAt)) ||
|
||||
Date.parse(p.capturedAt) > Date.now() ||
|
||||
typeof p.ageSeconds !== 'number' ||
|
||||
!Number.isInteger(p.ageSeconds) ||
|
||||
p.ageSeconds < 0 ||
|
||||
!['fresh', 'stale'].includes(String(p.freshness))
|
||||
)
|
||||
throw new HermesError('CONTRACT');
|
||||
return {
|
||||
provenance: {
|
||||
source: 'snapshot',
|
||||
capturedAt: p.capturedAt,
|
||||
ageSeconds: p.ageSeconds,
|
||||
freshness: p.freshness as string,
|
||||
liveProcess: 'unknown',
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createServer } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
it('exercises bounded HTTP transport against an isolated server', async () => {
|
||||
const seen: string[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
seen.push(`${req.method} ${req.url}`);
|
||||
if (req.headers.authorization !== 'Bearer local-test') {
|
||||
res.writeHead(401).end();
|
||||
return;
|
||||
}
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
ok: true,
|
||||
version: 'test',
|
||||
commit: 'test',
|
||||
auth_required: true,
|
||||
api_key: 'redacted',
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
const transport: typeof fetch = (input, init) =>
|
||||
fetch(
|
||||
`http://127.0.0.1:${port}${new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url).pathname}`,
|
||||
init,
|
||||
);
|
||||
const adapter = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('local-test'),
|
||||
},
|
||||
transport,
|
||||
);
|
||||
expect(await adapter.health()).toEqual({
|
||||
ok: true,
|
||||
version: 'test',
|
||||
commit: 'test',
|
||||
auth_required: true,
|
||||
});
|
||||
expect(seen).toEqual(['GET /api/health']);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((e) => (e ? reject(e) : resolve())),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { loadRuntimeGrants } from './runtime-read.module';
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
describe('reviewed runtime grants file', () => {
|
||||
it('loads an exact reviewed file and fails closed for malformed grants', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'runtime-grants-'));
|
||||
const file = join(dir, 'grants.json');
|
||||
try {
|
||||
await writeFile(file, JSON.stringify({ 'subject-1': ['default'] }));
|
||||
expect(await loadRuntimeGrants(file, dir)).toEqual({
|
||||
'subject-1': ['default'],
|
||||
});
|
||||
for (const invalid of [
|
||||
null,
|
||||
[],
|
||||
{ 'subject-1': [] },
|
||||
{ 'subject-1': ['default', 'default'] },
|
||||
{ 'subject-1': ['../x'] },
|
||||
{ 'subject-1': [3] },
|
||||
{ 'subject-1': ['default'], extra: true },
|
||||
]) {
|
||||
await writeFile(file, JSON.stringify(invalid));
|
||||
await expect(loadRuntimeGrants(file, dir)).rejects.toThrow();
|
||||
}
|
||||
await expect(loadRuntimeGrants('/etc/passwd')).rejects.toThrow();
|
||||
} finally {
|
||||
await rm(dir, { recursive: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import passport from 'passport';
|
||||
import { sign } from 'jsonwebtoken';
|
||||
import request from 'supertest';
|
||||
import { RuntimeReadModule } from './runtime-read.module';
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
describe('runtime HTTP authentication and read contract', () => {
|
||||
let app: INestApplication;
|
||||
const health = jest.fn().mockResolvedValue({ ok: true, auth_required: true });
|
||||
beforeAll(async () => {
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'test-only-http-key',
|
||||
},
|
||||
(payload, done) => done(null, { id: payload.sub, role: payload.role }),
|
||||
),
|
||||
);
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [
|
||||
PassportModule,
|
||||
RuntimeReadModule.register({ 'admin-1': ['default'] }),
|
||||
],
|
||||
})
|
||||
.overrideProvider(HermesIntegrationService)
|
||||
.useValue({ health })
|
||||
.compile();
|
||||
app = module.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
it('rejects missing and forged credentials before upstream', async () => {
|
||||
health.mockClear();
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/runtime/health')
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/runtime/health')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' + sign({ sub: 'admin-1', role: 'Admin' }, 'forged'),
|
||||
)
|
||||
.expect(401);
|
||||
expect(health).not.toHaveBeenCalled();
|
||||
});
|
||||
it('accepts verified allowlisted admin but rejects signed ungranted subject', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/runtime/health')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' + sign({ sub: 'other', role: 'Admin' }, 'test-only-http-key'),
|
||||
)
|
||||
.expect(403);
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/runtime/health')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' +
|
||||
sign({ sub: 'admin-1', role: 'Admin' }, 'test-only-http-key'),
|
||||
)
|
||||
.expect(200);
|
||||
expect(r.body).toEqual({ ok: true, auth_required: true });
|
||||
expect(r.headers['set-cookie']).toBeUndefined();
|
||||
});
|
||||
it('does not register mutation handlers', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/runtime/schedules')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' +
|
||||
sign({ sub: 'admin-1', role: 'Admin' }, 'test-only-http-key'),
|
||||
)
|
||||
.expect(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Req,
|
||||
Query,
|
||||
UseGuards,
|
||||
Injectable,
|
||||
ForbiddenException,
|
||||
ServiceUnavailableException,
|
||||
HttpException,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import {
|
||||
HermesIntegrationService,
|
||||
RuntimePrincipal,
|
||||
} from './hermes-integration.service';
|
||||
import { HermesError } from './hermes.adapter';
|
||||
export interface VerifiedRuntimeRequest {
|
||||
user?: {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
profiles?: string[];
|
||||
};
|
||||
}
|
||||
@Injectable()
|
||||
export class RuntimeReadAccess {
|
||||
private readonly grants: Readonly<Record<string, readonly string[]>>;
|
||||
constructor(grants: Readonly<Record<string, readonly string[]>>) {
|
||||
if (
|
||||
!grants ||
|
||||
typeof grants !== 'object' ||
|
||||
Array.isArray(grants) ||
|
||||
Object.keys(grants).length > 1000
|
||||
)
|
||||
throw new Error('Invalid runtime access configuration');
|
||||
const copy: Record<string, readonly string[]> = Object.create(null);
|
||||
for (const [subject, profiles] of Object.entries(grants)) {
|
||||
if (
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9@._:-]{0,127}$/.test(subject) ||
|
||||
['__proto__', 'constructor', 'prototype'].includes(subject) ||
|
||||
!Array.isArray(profiles) ||
|
||||
profiles.length === 0 ||
|
||||
profiles.length > 100 ||
|
||||
new Set(profiles).size !== profiles.length ||
|
||||
profiles.some(
|
||||
(p) =>
|
||||
typeof p !== 'string' ||
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(p),
|
||||
)
|
||||
)
|
||||
throw new Error('Invalid runtime access configuration');
|
||||
copy[subject] = Object.freeze([...profiles]);
|
||||
}
|
||||
this.grants = Object.freeze(copy);
|
||||
}
|
||||
principal(req: VerifiedRuntimeRequest): RuntimePrincipal {
|
||||
const u = req.user;
|
||||
if (
|
||||
!u?.id ||
|
||||
u.isApiKey ||
|
||||
!['admin', 'superadmin'].includes(
|
||||
(u.role ?? '').toLowerCase().replace(/[_-]/g, ''),
|
||||
) ||
|
||||
!Object.hasOwn(this.grants, u.id)
|
||||
)
|
||||
throw new ForbiddenException('Runtime access denied');
|
||||
return { subject: u.id, profiles: this.grants[u.id] };
|
||||
}
|
||||
authorize(
|
||||
p: RuntimePrincipal,
|
||||
permission: string,
|
||||
profile?: string,
|
||||
): Promise<boolean> {
|
||||
return Promise.resolve(
|
||||
permission === 'runtime.read' &&
|
||||
Object.hasOwn(this.grants, p.subject) &&
|
||||
(!profile || this.grants[p.subject].includes(profile)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@Controller('admin/orchestration/runtime')
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
export class RuntimeReadController {
|
||||
constructor(
|
||||
private readonly runtime: HermesIntegrationService,
|
||||
private readonly access: RuntimeReadAccess,
|
||||
) {}
|
||||
private async read(
|
||||
req: VerifiedRuntimeRequest,
|
||||
call: (p: RuntimePrincipal) => Promise<unknown>,
|
||||
) {
|
||||
const p = this.access.principal(req);
|
||||
try {
|
||||
return await call(p);
|
||||
} catch (e) {
|
||||
if (e instanceof HermesError) {
|
||||
if (e.code === 'FORBIDDEN')
|
||||
throw new ForbiddenException('Runtime access denied');
|
||||
if (e.code === 'LIMIT')
|
||||
throw new HttpException('Runtime request limit', 429);
|
||||
}
|
||||
throw new ServiceUnavailableException('Runtime unavailable');
|
||||
}
|
||||
}
|
||||
private profile(
|
||||
q: Record<string, unknown>,
|
||||
p: RuntimePrincipal,
|
||||
extras: string[] = [],
|
||||
): string {
|
||||
if (
|
||||
Object.keys(q).some((k) => !['profile', ...extras].includes(k)) ||
|
||||
typeof q.profile !== 'string' ||
|
||||
!p.profiles.includes(q.profile)
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
return q.profile;
|
||||
}
|
||||
private number(
|
||||
q: Record<string, unknown>,
|
||||
key: string,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
): number {
|
||||
if (q[key] === undefined) return fallback;
|
||||
if (typeof q[key] !== 'string' || !/^\d+$/.test(q[key]))
|
||||
throw new HermesError('LIMIT');
|
||||
const n = Number(q[key]);
|
||||
if (!Number.isSafeInteger(n) || n < min || n > max)
|
||||
throw new HermesError('LIMIT');
|
||||
return n;
|
||||
}
|
||||
@Get('health') health(@Req() req: VerifiedRuntimeRequest) {
|
||||
return this.read(req, (p) => this.runtime.health(p));
|
||||
}
|
||||
@Get('profiles') profiles(@Req() req: VerifiedRuntimeRequest) {
|
||||
return this.read(req, (p) => this.runtime.profiles(p));
|
||||
}
|
||||
@Get('status') status(
|
||||
@Req() req: VerifiedRuntimeRequest,
|
||||
@Query() q: Record<string, unknown>,
|
||||
) {
|
||||
return this.read(req, (p) => this.runtime.status(p, this.profile(q, p)));
|
||||
}
|
||||
@Get('usage') usage(
|
||||
@Req() req: VerifiedRuntimeRequest,
|
||||
@Query() q: Record<string, unknown>,
|
||||
) {
|
||||
return this.read(req, (p) =>
|
||||
this.runtime.usage(
|
||||
p,
|
||||
this.profile(q, p, ['days']),
|
||||
this.number(q, 'days', 30, 1, 365),
|
||||
),
|
||||
);
|
||||
}
|
||||
@Get('sessions') sessions(
|
||||
@Req() req: VerifiedRuntimeRequest,
|
||||
@Query() q: Record<string, unknown>,
|
||||
) {
|
||||
return this.read(req, (p) =>
|
||||
this.runtime.sessions(
|
||||
p,
|
||||
this.profile(q, p, ['limit', 'offset']),
|
||||
this.number(q, 'limit', 20, 1, 100),
|
||||
this.number(q, 'offset', 0, 0, 10000),
|
||||
),
|
||||
);
|
||||
}
|
||||
@Get('schedules') schedules(
|
||||
@Req() req: VerifiedRuntimeRequest,
|
||||
@Query() q: Record<string, unknown>,
|
||||
) {
|
||||
return this.read(req, (p) => this.runtime.crons(p, this.profile(q, p)));
|
||||
}
|
||||
@Get('model-info') modelInfo(
|
||||
@Req() req: VerifiedRuntimeRequest,
|
||||
@Query() q: Record<string, unknown>,
|
||||
) {
|
||||
return this.read(req, (p) => this.runtime.modelInfo(p, this.profile(q, p)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { DynamicModule, Module } from '@nestjs/common';
|
||||
import { open, lstat } from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { HermesManagementModule } from './hermes-management.module';
|
||||
import {
|
||||
RuntimeReadAccess,
|
||||
RuntimeReadController,
|
||||
} from './runtime-read.controller';
|
||||
import { HermesError } from './hermes.adapter';
|
||||
export async function runtimeSecret(path: string): Promise<string> {
|
||||
if (!/^\/run\/secrets\/[a-zA-Z0-9_-]+$/.test(path))
|
||||
throw new HermesError('CONFIGURATION');
|
||||
try {
|
||||
const file = await open(path, 'r');
|
||||
try {
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.size > 4096) throw new Error();
|
||||
const value = (await file.readFile('utf8')).trim();
|
||||
if (!value || /[\r\n]/.test(value)) throw new Error();
|
||||
return value;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
} catch {
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
/** Exact fixed mount roots only; startup fails closed, never browser/JWT grants. */
|
||||
export async function loadRuntimeGrants(
|
||||
path = '/run/secrets/hermes_runtime_grants',
|
||||
reviewedRoot?: string,
|
||||
): Promise<Readonly<Record<string, readonly string[]>>> {
|
||||
const roots = reviewedRoot
|
||||
? [resolve(reviewedRoot)]
|
||||
: ['/run/secrets', '/etc/canina'];
|
||||
if (!roots.includes(dirname(path)) || resolve(path) !== path)
|
||||
throw new HermesError('CONFIGURATION');
|
||||
try {
|
||||
const stat = await lstat(path);
|
||||
if (
|
||||
!stat.isFile() ||
|
||||
stat.isSymbolicLink() ||
|
||||
stat.size > 65536 ||
|
||||
stat.mode & 0o022
|
||||
)
|
||||
throw new Error();
|
||||
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const data: unknown = JSON.parse(await file.readFile('utf8'));
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data))
|
||||
throw new Error();
|
||||
new RuntimeReadAccess(data as Record<string, readonly string[]>);
|
||||
return data as Record<string, readonly string[]>;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
} catch {
|
||||
throw new HermesError('CONFIGURATION');
|
||||
}
|
||||
}
|
||||
@Module({})
|
||||
export class RuntimeReadModule {
|
||||
static async registerFromFile(
|
||||
path = '/run/secrets/hermes_runtime_grants',
|
||||
): Promise<DynamicModule> {
|
||||
return this.register(await loadRuntimeGrants(path));
|
||||
}
|
||||
static register(
|
||||
grants: Readonly<Record<string, readonly string[]>>,
|
||||
): DynamicModule {
|
||||
const access = new RuntimeReadAccess(grants);
|
||||
return {
|
||||
module: RuntimeReadModule,
|
||||
imports: [
|
||||
HermesManagementModule.registerAuthenticated(
|
||||
async () => ({
|
||||
username: await runtimeSecret('/run/secrets/hermes_username'),
|
||||
password: await runtimeSecret('/run/secrets/hermes_password'),
|
||||
}),
|
||||
access,
|
||||
),
|
||||
],
|
||||
controllers: [RuntimeReadController],
|
||||
providers: [{ provide: RuntimeReadAccess, useValue: access }],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { runtimeReadRegistration } from './runtime-read.registration';
|
||||
import { RuntimeReadModule } from './runtime-read.module';
|
||||
describe('application runtime registration',()=>{
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
it('registers denied routes without reading files when not explicitly enabled',async()=>{
|
||||
const file=jest.spyOn(RuntimeReadModule,'registerFromFile');
|
||||
const register=jest.spyOn(RuntimeReadModule,'register');
|
||||
await runtimeReadRegistration({});
|
||||
expect(file).not.toHaveBeenCalled();expect(register).toHaveBeenCalledWith({});
|
||||
});
|
||||
it('uses only the fixed reviewed grants mount when enabled',async()=>{
|
||||
const file=jest.spyOn(RuntimeReadModule,'registerFromFile').mockResolvedValue({module:RuntimeReadModule});
|
||||
await runtimeReadRegistration({CANINA_RUNTIME_READ_ENABLED:'true'});
|
||||
expect(file).toHaveBeenCalledWith('/run/secrets/hermes_runtime_grants');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { RuntimeReadModule } from './runtime-read.module';
|
||||
export function runtimeReadRegistration(env:Record<string,string|undefined>=process.env) {
|
||||
return env.CANINA_RUNTIME_READ_ENABLED === 'true'
|
||||
? RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
: RuntimeReadModule.register({});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import {
|
||||
RuntimeReadController,
|
||||
RuntimeReadAccess,
|
||||
} from './runtime-read.controller';
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
import { HermesError } from './hermes.adapter';
|
||||
import {
|
||||
ForbiddenException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
describe('runtime read boundary', () => {
|
||||
const health = jest.fn();
|
||||
const profiles = jest.fn();
|
||||
const status = jest.fn();
|
||||
const service = {
|
||||
health,
|
||||
profiles,
|
||||
status,
|
||||
} as unknown as HermesIntegrationService;
|
||||
const access = new RuntimeReadAccess({ 'admin-1': ['default'] });
|
||||
const controller = new RuntimeReadController(service, access);
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
it('denies unconfigured identity without IO', async () => {
|
||||
await expect(
|
||||
controller.health({ user: { id: 'other', role: 'Admin' } }),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(health).not.toHaveBeenCalled();
|
||||
});
|
||||
it('uses server scope not body or user supplied profiles', async () => {
|
||||
status.mockResolvedValue({ overall: 'ok' });
|
||||
await expect(
|
||||
controller.status(
|
||||
{ user: { id: 'admin-1', role: 'Admin', profiles: ['other'] } },
|
||||
{ profile: 'other' },
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(status).not.toHaveBeenCalled();
|
||||
await controller.status(
|
||||
{ user: { id: 'admin-1', role: 'Admin' } },
|
||||
{ profile: 'default' },
|
||||
);
|
||||
expect(status).toHaveBeenCalledWith(
|
||||
{ subject: 'admin-1', profiles: ['default'] },
|
||||
'default',
|
||||
);
|
||||
});
|
||||
it('rejects duplicate/missing/unknown query parameters before IO', async () => {
|
||||
for (const q of [
|
||||
{},
|
||||
{ profile: ['default', 'other'] },
|
||||
{ profile: 'default', token: 'leak' },
|
||||
])
|
||||
await expect(
|
||||
controller.status({ user: { id: 'admin-1', role: 'Admin' } }, q),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(status).not.toHaveBeenCalled();
|
||||
});
|
||||
it('maps credential failure without leaking upstream errors', async () => {
|
||||
health.mockRejectedValue(new HermesError('AUTH_REQUIRED'));
|
||||
await expect(
|
||||
controller.health({ user: { id: 'admin-1', role: 'Admin' } }),
|
||||
).rejects.toThrow('Runtime unavailable');
|
||||
});
|
||||
it('rejects API keys and non-admins even when subject is configured', async () => {
|
||||
for (const user of [
|
||||
{ id: 'admin-1', role: 'User' },
|
||||
{ id: 'admin-1', role: 'Admin', isApiKey: true },
|
||||
])
|
||||
await expect(controller.health({ user })).rejects.toBeInstanceOf(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(health).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
const provenance = {
|
||||
source: 'snapshot',
|
||||
capturedAt: '2020-01-01T00:00:00Z',
|
||||
ageSeconds: 100,
|
||||
freshness: 'stale',
|
||||
liveProcess: 'unknown',
|
||||
};
|
||||
function adapter(data: unknown) {
|
||||
return new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes-inventory:9119',
|
||||
token: () => Promise.resolve('test'),
|
||||
},
|
||||
jest.fn(() =>
|
||||
Promise.resolve(new Response(JSON.stringify(data), { status: 200 })),
|
||||
) as typeof fetch,
|
||||
);
|
||||
}
|
||||
describe('snapshot provenance boundary', () => {
|
||||
it('rejects missing provenance from dedicated inventory origin', async () => {
|
||||
await expect(
|
||||
adapter({
|
||||
ok: true,
|
||||
version: '1',
|
||||
commit: 'x',
|
||||
auth_required: true,
|
||||
}).health(),
|
||||
).rejects.toMatchObject({ code: 'CONTRACT' });
|
||||
});
|
||||
it('cannot present copied gateway scalars as live telemetry', async () => {
|
||||
const row = await adapter({
|
||||
version: '1',
|
||||
gateway_running: true,
|
||||
active_agents: 12,
|
||||
gateway_state: 'running',
|
||||
overall: 'ok',
|
||||
provenance,
|
||||
}).status('default');
|
||||
expect(row).toMatchObject({
|
||||
gateway_running: false,
|
||||
active_agents: 0,
|
||||
gateway_state: null,
|
||||
overall: 'unknown',
|
||||
liveGatewayState: 'unknown',
|
||||
liveActiveAgents: null,
|
||||
provenance,
|
||||
});
|
||||
});
|
||||
it('profile readiness cannot be inferred from copied PID state', async () => {
|
||||
const rows = await adapter({
|
||||
profiles: [
|
||||
{
|
||||
name: 'default',
|
||||
is_default: true,
|
||||
gateway_running: true,
|
||||
provenance,
|
||||
},
|
||||
],
|
||||
provenance,
|
||||
}).profiles();
|
||||
expect(rows[0]).toMatchObject({
|
||||
gateway_running: false,
|
||||
liveGatewayState: 'unknown',
|
||||
provenance,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "../../../.hermes-contract-build",
|
||||
"incremental": false,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["./*.ts"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* Branded HTML wrappers for Canina transactional emails.
|
||||
* Colors match the storefront tokens in frontend/application/app/globals.css.
|
||||
*/
|
||||
|
||||
const BRAND = {
|
||||
blue: '#1E4053',
|
||||
gold: '#F1B646',
|
||||
teal: '#9BC8CC',
|
||||
dark: '#060709',
|
||||
soft: '#F4F7F6',
|
||||
border: '#E5ECE9',
|
||||
muted: '#445D60',
|
||||
} as const;
|
||||
|
||||
export function escapeHtml(value: string): string {
|
||||
return String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
export function textToHtmlParagraphs(text: string): string {
|
||||
return escapeHtml(text)
|
||||
.split(/\r?\n/)
|
||||
.map((line) => (line.trim().length === 0 ? ' ' : line))
|
||||
.join('<br/>');
|
||||
}
|
||||
|
||||
export interface CaninaEmailLayoutOptions {
|
||||
title: string;
|
||||
bodyHtml: string;
|
||||
eyebrow?: string;
|
||||
footerNote?: string;
|
||||
}
|
||||
|
||||
export function renderCaninaEmailLayout(options: CaninaEmailLayoutOptions): string {
|
||||
const title = escapeHtml(options.title);
|
||||
const eyebrow = escapeHtml(options.eyebrow || 'CANINA');
|
||||
const footerNote = escapeHtml(
|
||||
options.footerNote || 'این پیام از طرف فروشگاه کنینا ارسال شده است.',
|
||||
);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${title}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:${BRAND.soft};color:${BRAND.dark};font-family:Tahoma,Arial,sans-serif;line-height:1.9;font-size:15px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;background:${BRAND.soft};">
|
||||
<tr>
|
||||
<td align="center" style="padding:28px 14px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;max-width:600px;background:#ffffff;text-align:right;border:1px solid ${BRAND.border};">
|
||||
<tr>
|
||||
<td style="padding:0;height:4px;background:${BRAND.gold};font-size:0;line-height:0;"> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding:24px 28px 8px;background:${BRAND.blue};">
|
||||
<p style="margin:0;font-size:11px;letter-spacing:0.18em;color:${BRAND.teal};">${eyebrow}</p>
|
||||
<p style="margin:8px 0 0;font-size:22px;font-weight:700;color:#ffffff;">کنینا</p>
|
||||
<p style="margin:4px 0 0;font-size:13px;color:${BRAND.gold};">مکمل تخصصی حیوانات خانگی</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding:28px;">
|
||||
<h1 style="margin:0 0 16px;font-size:20px;font-weight:700;color:${BRAND.blue};">${title}</h1>
|
||||
<div style="color:${BRAND.muted};">${options.bodyHtml}</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding:18px 28px;background:${BRAND.dark};color:#d5dde0;font-size:12px;">
|
||||
<p style="margin:0;color:#ffffff;font-weight:700;">کنینا ایران</p>
|
||||
<p style="margin:8px 0 0;">
|
||||
<a href="mailto:support@canina.ir" style="color:${BRAND.gold};text-decoration:none;" dir="ltr">support@canina.ir</a>
|
||||
·
|
||||
<a href="https://canina.ir" style="color:${BRAND.teal};text-decoration:none;" dir="ltr">canina.ir</a>
|
||||
</p>
|
||||
<p style="margin:10px 0 0;color:#9aa8ad;">${footerNote}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export function renderCaninaNotificationEmail(subject: string, content: string): string {
|
||||
return renderCaninaEmailLayout({
|
||||
title: subject || 'اطلاعیه کنینا',
|
||||
bodyHtml: `<p style="margin:0;">${textToHtmlParagraphs(content || '')}</p>`,
|
||||
});
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as net from 'net';
|
||||
import * as tls from 'tls';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface SmtpConfig {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
secure?: boolean; // true for 465 (TLS), false for 587/25 (STARTTLS)
|
||||
user: string;
|
||||
password: string;
|
||||
fromName: string;
|
||||
fromEmail: string;
|
||||
}
|
||||
|
||||
export interface SendMailOptions {
|
||||
to: string;
|
||||
subject: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class EmailService {
|
||||
private readonly logger = new Logger(EmailService.name);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Read SMTP configuration from DB Setting table with fallback to env variables
|
||||
*/
|
||||
async getConfig(): Promise<SmtpConfig> {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'email' },
|
||||
});
|
||||
const dbConfig = (setting?.value as Record<string, any>) || {};
|
||||
|
||||
return {
|
||||
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||
host: dbConfig.host || process.env.SMTP_HOST || 'mail.canina.ir',
|
||||
port: Number(dbConfig.port || process.env.SMTP_PORT || 587),
|
||||
secure: dbConfig.secure !== undefined ? Boolean(dbConfig.secure) : Number(dbConfig.port || 587) === 465,
|
||||
user: dbConfig.user || process.env.SMTP_USER || '',
|
||||
password: dbConfig.password || process.env.SMTP_PASSWORD || '',
|
||||
fromName: dbConfig.fromName || process.env.SMTP_FROM_NAME || 'کنینا ایران',
|
||||
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'support@canina.ir',
|
||||
};
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error loading email config: ${err?.message}`);
|
||||
return {
|
||||
enabled: true,
|
||||
host: process.env.SMTP_HOST || 'mail.canina.ir',
|
||||
port: Number(process.env.SMTP_PORT || 587),
|
||||
secure: Number(process.env.SMTP_PORT || 587) === 465,
|
||||
user: process.env.SMTP_USER || '',
|
||||
password: process.env.SMTP_PASSWORD || '',
|
||||
fromName: 'کنینا ایران',
|
||||
fromEmail: 'support@canina.ir',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save SMTP configuration to database
|
||||
*/
|
||||
async saveConfig(dto: Partial<SmtpConfig>): Promise<SmtpConfig> {
|
||||
const current = await this.getConfig();
|
||||
const port = Number(dto.port ?? current.port);
|
||||
const secure = dto.secure !== undefined ? Boolean(dto.secure) : (port === 465);
|
||||
|
||||
const updated: SmtpConfig = {
|
||||
...current,
|
||||
...dto,
|
||||
port,
|
||||
secure,
|
||||
};
|
||||
|
||||
const existing = await this.prisma.setting.findFirst({ where: { category: 'email' } });
|
||||
if (existing) {
|
||||
await this.prisma.setting.update({
|
||||
where: { id: existing.id },
|
||||
data: { value: updated as any },
|
||||
});
|
||||
} else {
|
||||
await this.prisma.setting.create({
|
||||
data: {
|
||||
category: 'email',
|
||||
key: 'smtp_config',
|
||||
value: updated as any,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test SMTP connection with the given or stored configuration
|
||||
*/
|
||||
async testConnection(customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; message: string; banner?: string }> {
|
||||
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||
|
||||
if (!config.host || !config.port) {
|
||||
return { success: false, message: 'آدرس هاست و پورت SMTP الزامی است.' };
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// If port is 465 or secure=true, connect via direct TLS
|
||||
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||
let buffer = '';
|
||||
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=quit
|
||||
let banner = '';
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve({ success: false, message: 'تایماوت در اتصال به سرور SMTP (بیش از ۱۰ ثانیه)' });
|
||||
}, 10000);
|
||||
|
||||
const cleanup = (res: { success: boolean; message: string; banner?: string }) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve(res);
|
||||
};
|
||||
|
||||
const handleData = (chunk: Buffer) => {
|
||||
buffer += chunk.toString('utf8');
|
||||
const lines = buffer.split('\r\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const code = parseInt(line.substring(0, 3), 10);
|
||||
const isFinal = line.charAt(3) === ' ';
|
||||
|
||||
if (!isFinal) continue; // Multi-line response continuation
|
||||
|
||||
if (stage === 0) {
|
||||
banner = line;
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 1;
|
||||
socket.write(`EHLO canina.ir\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, message: `پاسخ ناموفق از سرور: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 1) {
|
||||
if (code >= 200 && code < 300) {
|
||||
if (config.user && config.password) {
|
||||
stage = 2;
|
||||
socket.write('AUTH LOGIN\r\n');
|
||||
} else {
|
||||
stage = 5;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, message: 'اتصال به سرور SMTP بدون احراز هویت با موفقیت برقرار شد.', banner });
|
||||
}
|
||||
} else {
|
||||
return cleanup({ success: false, message: `خطای EHLO: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 2) {
|
||||
if (code === 334) {
|
||||
stage = 3;
|
||||
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, message: `سرور از AUTH LOGIN پشتیبانی نمیکند یا خطا داد: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 3) {
|
||||
if (code === 334) {
|
||||
stage = 4;
|
||||
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, message: `نام کاربری پذیرفته نشد: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 4) {
|
||||
if (code === 235 || (code >= 200 && code < 300)) {
|
||||
stage = 5;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, message: 'اتصال و احراز هویت با سرور SMTP با موفقیت تأیید شد.', banner });
|
||||
} else {
|
||||
return cleanup({ success: false, message: `احراز هویت ناموفق بود (نام کاربری یا رمز عبور اشتباه است): ${line}`, banner });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let socket: net.Socket;
|
||||
|
||||
try {
|
||||
if (isExplicitTls) {
|
||||
socket = tls.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
rejectUnauthorized: false,
|
||||
}, () => {});
|
||||
} else {
|
||||
socket = net.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
}, () => {});
|
||||
}
|
||||
|
||||
socket.on('data', handleData);
|
||||
socket.on('error', (err) => {
|
||||
cleanup({ success: false, message: `خطای شبکه در ارتباط با ${config.host}:${config.port} - ${err.message}` });
|
||||
});
|
||||
} catch (err: any) {
|
||||
cleanup({ success: false, message: `خطا در باز کردن سوکت: ${err?.message}` });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a MIME Email message through SMTP
|
||||
*/
|
||||
async sendMail(options: SendMailOptions, customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; messageId?: string; error?: string }> {
|
||||
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||
|
||||
if (!config.enabled) {
|
||||
return { success: false, error: 'سرویس ارسال ایمیل در تنظیمات غیرفعال است.' };
|
||||
}
|
||||
|
||||
if (!config.host || !options.to) {
|
||||
return { success: false, error: 'هاست SMTP یا آدرس گیرنده مشخص نشده است.' };
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// If port is 465 or secure=true, connect via direct TLS
|
||||
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||
let buffer = '';
|
||||
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=mail_from, 6=rcpt_to, 7=data_cmd, 8=data_body, 9=quit
|
||||
const messageId = `<${Date.now()}.${Math.random().toString(36).substring(2)}@${config.host}>`;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve({ success: false, error: 'تایماوت ارسال ایمیل (۱۵ ثانیه)' });
|
||||
}, 15000);
|
||||
|
||||
const cleanup = (res: { success: boolean; messageId?: string; error?: string }) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve(res);
|
||||
};
|
||||
|
||||
const handleData = (chunk: Buffer) => {
|
||||
buffer += chunk.toString('utf8');
|
||||
const lines = buffer.split('\r\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const code = parseInt(line.substring(0, 3), 10);
|
||||
const isFinal = line.charAt(3) === ' ';
|
||||
|
||||
if (!isFinal) continue;
|
||||
|
||||
if (stage === 0) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 1;
|
||||
socket.write(`EHLO canina.ir\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `پاسخ سرور: ${line}` });
|
||||
}
|
||||
} else if (stage === 1) {
|
||||
if (code >= 200 && code < 300) {
|
||||
if (config.user && config.password) {
|
||||
stage = 2;
|
||||
socket.write('AUTH LOGIN\r\n');
|
||||
} else {
|
||||
stage = 5;
|
||||
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||
}
|
||||
} else {
|
||||
return cleanup({ success: false, error: `خطای EHLO: ${line}` });
|
||||
}
|
||||
} else if (stage === 2) {
|
||||
if (code === 334) {
|
||||
stage = 3;
|
||||
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `خطای احراز هویت: ${line}` });
|
||||
}
|
||||
} else if (stage === 3) {
|
||||
if (code === 334) {
|
||||
stage = 4;
|
||||
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `نام کاربری رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 4) {
|
||||
if (code === 235 || (code >= 200 && code < 300)) {
|
||||
stage = 5;
|
||||
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `رمز عبور رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 5) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 6;
|
||||
socket.write(`RCPT TO:<${options.to}>\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `آدرس فرستنده رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 6) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 7;
|
||||
socket.write('DATA\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `آدرس گیرنده رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 7) {
|
||||
if (code === 354) {
|
||||
stage = 8;
|
||||
const encodedSubject = `=?UTF-8?B?${Buffer.from(options.subject).toString('base64')}?=`;
|
||||
const encodedFromName = `=?UTF-8?B?${Buffer.from(config.fromName).toString('base64')}?=`;
|
||||
const boundary = `boundary_${Date.now()}`;
|
||||
|
||||
let emailBody = '';
|
||||
emailBody += `From: ${encodedFromName} <${config.fromEmail}>\r\n`;
|
||||
emailBody += `To: <${options.to}>\r\n`;
|
||||
emailBody += `Subject: ${encodedSubject}\r\n`;
|
||||
emailBody += `Message-ID: ${messageId}\r\n`;
|
||||
emailBody += `Date: ${new Date().toUTCString()}\r\n`;
|
||||
emailBody += `MIME-Version: 1.0\r\n`;
|
||||
emailBody += `Content-Type: multipart/alternative; boundary="${boundary}"\r\n\r\n`;
|
||||
|
||||
if (options.text) {
|
||||
emailBody += `--${boundary}\r\n`;
|
||||
emailBody += `Content-Type: text/plain; charset=UTF-8\r\n`;
|
||||
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||
emailBody += Buffer.from(options.text).toString('base64') + '\r\n\r\n';
|
||||
}
|
||||
|
||||
const htmlContent = options.html || options.text || '';
|
||||
emailBody += `--${boundary}\r\n`;
|
||||
emailBody += `Content-Type: text/html; charset=UTF-8\r\n`;
|
||||
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||
emailBody += Buffer.from(htmlContent).toString('base64') + '\r\n\r\n';
|
||||
|
||||
emailBody += `--${boundary}--\r\n.\r\n`;
|
||||
|
||||
socket.write(emailBody);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `دستور DATA رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 8) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 9;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, messageId });
|
||||
} else {
|
||||
return cleanup({ success: false, error: `رد شدن ارسال محتوا: ${line}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let socket: net.Socket;
|
||||
|
||||
try {
|
||||
if (isExplicitTls) {
|
||||
socket = tls.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
rejectUnauthorized: false,
|
||||
}, () => {});
|
||||
} else {
|
||||
socket = net.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
}, () => {});
|
||||
}
|
||||
|
||||
socket.on('data', handleData);
|
||||
socket.on('error', (err) => {
|
||||
cleanup({ success: false, error: `خطای ارسال: ${err.message}` });
|
||||
});
|
||||
} catch (err: any) {
|
||||
cleanup({ success: false, error: `خطا در باز کردن اتصال: ${err?.message}` });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { EmailService } from './email.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('NotificationsQueueService', () => {
|
||||
let service: NotificationsQueueService;
|
||||
let prisma: any;
|
||||
let emailService: any;
|
||||
let smsService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
notificationQueue: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
emailService = {
|
||||
sendMail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
|
||||
};
|
||||
|
||||
smsService = {
|
||||
sendPatternSms: jest.fn().mockResolvedValue(true),
|
||||
sendSms: jest.fn().mockResolvedValue(true),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
NotificationsQueueService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: EmailService, useValue: emailService },
|
||||
{ provide: SmsService, useValue: smsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<NotificationsQueueService>(NotificationsQueueService);
|
||||
});
|
||||
|
||||
it('should enqueue notification and preserve idempotency', async () => {
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(null);
|
||||
prisma.notificationQueue.create.mockResolvedValueOnce({
|
||||
id: 'queue-1',
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
event: 'ORDER_CREATED',
|
||||
content: 'Hello World',
|
||||
idempotencyKey: 'idemp-1',
|
||||
status: 'QUEUED',
|
||||
attempts: 0,
|
||||
});
|
||||
|
||||
const res = await service.enqueue({
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
event: 'ORDER_CREATED',
|
||||
content: 'Hello World',
|
||||
idempotencyKey: 'idemp-1',
|
||||
});
|
||||
|
||||
expect(prisma.notificationQueue.findUnique).toHaveBeenCalledWith({ where: { idempotencyKey: 'idemp-1' } });
|
||||
expect(prisma.notificationQueue.create).toHaveBeenCalled();
|
||||
expect(res.id).toBe('queue-1');
|
||||
});
|
||||
|
||||
it('should return existing notification if idempotency key exists', async () => {
|
||||
const existing = {
|
||||
id: 'existing-1',
|
||||
channel: 'SMS',
|
||||
recipient: '09121111111',
|
||||
event: 'OTP',
|
||||
content: '12345',
|
||||
idempotencyKey: 'idemp-2',
|
||||
status: 'SENT',
|
||||
};
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(existing);
|
||||
|
||||
const res = await service.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: '09121111111',
|
||||
event: 'OTP',
|
||||
content: '12345',
|
||||
idempotencyKey: 'idemp-2',
|
||||
});
|
||||
|
||||
expect(prisma.notificationQueue.create).not.toHaveBeenCalled();
|
||||
expect(res.id).toBe('existing-1');
|
||||
});
|
||||
|
||||
it('should process email queue item and mark as SENT', async () => {
|
||||
const item = {
|
||||
id: 'item-1',
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
subject: 'Test Subject',
|
||||
content: 'Test Body',
|
||||
payload: {},
|
||||
status: 'QUEUED',
|
||||
attempts: 0,
|
||||
maxAttempts: 3,
|
||||
};
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(item);
|
||||
prisma.notificationQueue.update.mockResolvedValue({});
|
||||
|
||||
await service.processItem('item-1');
|
||||
|
||||
expect(emailService.sendMail).toHaveBeenCalledWith({
|
||||
to: 'user@example.com',
|
||||
subject: 'Test Subject',
|
||||
text: 'Test Body',
|
||||
html: expect.stringContaining('Test Body'),
|
||||
});
|
||||
const sentHtml = String((emailService.sendMail as jest.Mock).mock.calls[0][0].html);
|
||||
expect(sentHtml).toContain('#1E4053');
|
||||
expect(sentHtml).toContain('#F1B646');
|
||||
expect(sentHtml).toContain('support@canina.ir');
|
||||
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
|
||||
where: { id: 'item-1' },
|
||||
data: expect.objectContaining({ status: 'SENT' }),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,281 +0,0 @@
|
||||
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { EmailService } from './email.service';
|
||||
import { renderCaninaNotificationEmail } from './email-layout';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
|
||||
export interface EnqueueOptions {
|
||||
channel: 'SMS' | 'EMAIL';
|
||||
recipient: string;
|
||||
event: string;
|
||||
subject?: string;
|
||||
content: string;
|
||||
payload?: any;
|
||||
idempotencyKey?: string;
|
||||
maxAttempts?: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(NotificationsQueueService.name);
|
||||
private workerInterval: NodeJS.Timeout | null = null;
|
||||
private isProcessing = false;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly emailService: EmailService,
|
||||
private readonly smsService: SmsService,
|
||||
) {}
|
||||
|
||||
onModuleInit() {
|
||||
// Run background queue processor every 15 seconds
|
||||
this.workerInterval = setInterval(() => {
|
||||
this.processQueue().catch((err) => {
|
||||
this.logger.error(`Error in queue worker: ${err?.message}`);
|
||||
});
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
if (this.workerInterval) {
|
||||
clearInterval(this.workerInterval);
|
||||
this.workerInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue a durable notification with idempotency check
|
||||
*/
|
||||
async enqueue(options: EnqueueOptions) {
|
||||
if (options.idempotencyKey) {
|
||||
const existing = await this.prisma.notificationQueue.findUnique({
|
||||
where: { idempotencyKey: options.idempotencyKey },
|
||||
});
|
||||
if (existing) {
|
||||
this.logger.log(`Notification idempotency matched for key: ${options.idempotencyKey}`);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
const item = await this.prisma.notificationQueue.create({
|
||||
data: {
|
||||
channel: options.channel,
|
||||
recipient: options.recipient,
|
||||
event: options.event,
|
||||
subject: options.subject || null,
|
||||
content: options.content,
|
||||
payload: options.payload ?? null,
|
||||
idempotencyKey: options.idempotencyKey || null,
|
||||
maxAttempts: options.maxAttempts ?? 3,
|
||||
status: 'QUEUED',
|
||||
},
|
||||
});
|
||||
|
||||
// Attempt immediate asynchronous process in the background
|
||||
setImmediate(() => {
|
||||
this.processItem(item.id).catch(() => {});
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single queued item by ID
|
||||
*/
|
||||
async processItem(id: string) {
|
||||
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||
if (!item || item.status === 'SENT') return;
|
||||
|
||||
if (item.attempts >= item.maxAttempts) {
|
||||
await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: { status: 'FAILED' },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'PROCESSING',
|
||||
attempts: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
if (item.channel === 'EMAIL') {
|
||||
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||
const subject = item.subject || 'اطلاعیه کنینا ایران';
|
||||
const res = await this.emailService.sendMail({
|
||||
to: item.recipient,
|
||||
subject,
|
||||
text: item.content,
|
||||
html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''),
|
||||
});
|
||||
|
||||
if (res.success) {
|
||||
await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'SENT',
|
||||
sentAt: new Date(),
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
throw new Error(res.error || 'خطای نامشخص در ارسال ایمیل');
|
||||
}
|
||||
} else if (item.channel === 'SMS') {
|
||||
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||
if (payloadObj.patternId && Array.isArray(payloadObj.args)) {
|
||||
const sent = await this.smsService.sendPatternSms({
|
||||
to: item.recipient,
|
||||
bodyId: Number(payloadObj.patternId),
|
||||
args: payloadObj.args,
|
||||
type: item.event,
|
||||
});
|
||||
if (!sent) {
|
||||
throw new Error(`ارسال پیامک پترن ${payloadObj.patternId} ناموفق بود.`);
|
||||
}
|
||||
} else {
|
||||
const sent = await this.smsService.sendSms(item.recipient, item.content);
|
||||
if (!sent) {
|
||||
throw new Error(`ارسال پیامک متنی به ${item.recipient} ناموفق بود.`);
|
||||
}
|
||||
}
|
||||
|
||||
await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'SENT',
|
||||
sentAt: new Date(),
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (err: any) {
|
||||
const isFinalAttempt = item.attempts + 1 >= item.maxAttempts;
|
||||
await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: isFinalAttempt ? 'FAILED' : 'QUEUED',
|
||||
lastError: err?.message || 'خطا در ارسال پیام',
|
||||
},
|
||||
});
|
||||
this.logger.warn(`Failed to deliver notification ${id} (${item.channel} to ${item.recipient}): ${err?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process pending batch of queue
|
||||
*/
|
||||
async processQueue(batchSize = 10) {
|
||||
if (this.isProcessing) return;
|
||||
this.isProcessing = true;
|
||||
|
||||
try {
|
||||
const pendingItems = await this.prisma.notificationQueue.findMany({
|
||||
where: {
|
||||
status: 'QUEUED',
|
||||
attempts: { lt: 3 },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: batchSize,
|
||||
});
|
||||
|
||||
for (const item of pendingItems) {
|
||||
await this.processItem(item.id);
|
||||
}
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry a failed notification manually
|
||||
*/
|
||||
async retry(id: string) {
|
||||
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||
if (!item) throw new Error('آیتم صف یافت نشد.');
|
||||
|
||||
const updated = await this.prisma.notificationQueue.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'QUEUED',
|
||||
attempts: 0,
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
|
||||
setImmediate(() => {
|
||||
this.processItem(id).catch(() => {});
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue items with filtering and pagination
|
||||
*/
|
||||
async getQueue(query: { page?: number; limit?: number; status?: string; channel?: string; search?: string }) {
|
||||
const page = Math.max(1, Number(query.page || 1));
|
||||
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.channel) where.channel = query.channel;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ recipient: { contains: query.search, mode: 'insensitive' } },
|
||||
{ subject: { contains: query.search, mode: 'insensitive' } },
|
||||
{ event: { contains: query.search, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.notificationQueue.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
}),
|
||||
this.prisma.notificationQueue.count({ where }),
|
||||
]);
|
||||
|
||||
const stats = await this.getStats();
|
||||
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit) || 1,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get overall stats
|
||||
*/
|
||||
async getStats() {
|
||||
const [total, queued, processing, sent, failed] = await Promise.all([
|
||||
this.prisma.notificationQueue.count(),
|
||||
this.prisma.notificationQueue.count({ where: { status: 'QUEUED' } }),
|
||||
this.prisma.notificationQueue.count({ where: { status: 'PROCESSING' } }),
|
||||
this.prisma.notificationQueue.count({ where: { status: 'SENT' } }),
|
||||
this.prisma.notificationQueue.count({ where: { status: 'FAILED' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
total,
|
||||
queued,
|
||||
processing,
|
||||
sent,
|
||||
failed,
|
||||
successRate: total > 0 ? Math.round((sent / total) * 100) : 100,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { EmailService } from './email.service';
|
||||
import { escapeHtml, renderCaninaEmailLayout, textToHtmlParagraphs } from './email-layout';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
UpdateEmailConfigDto,
|
||||
TestSmtpDto,
|
||||
SendTestEmailDto,
|
||||
SendTestSmsDto,
|
||||
ManualSendDto,
|
||||
CreateTemplateDto,
|
||||
} from './notifications.dto';
|
||||
|
||||
@Controller('admin/notifications')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class NotificationsController {
|
||||
constructor(
|
||||
private readonly emailService: EmailService,
|
||||
private readonly queueService: NotificationsQueueService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get notification settings (Email & SMS)
|
||||
*/
|
||||
@Get('config')
|
||||
async getConfig() {
|
||||
const [email, sms] = await Promise.all([
|
||||
this.emailService.getConfig(),
|
||||
this.smsService.getSmsConfig(),
|
||||
]);
|
||||
|
||||
// Mask password for security
|
||||
const maskedEmail = {
|
||||
...email,
|
||||
password: email.password ? '••••••••' : '',
|
||||
};
|
||||
|
||||
const maskedSms = {
|
||||
...sms,
|
||||
password: sms.password ? '••••••••' : '',
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
email: maskedEmail,
|
||||
sms: maskedSms,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update SMTP Email config
|
||||
*/
|
||||
@Put('email-config')
|
||||
async updateEmailConfig(@Body() dto: UpdateEmailConfigDto) {
|
||||
// If password is masked, don't overwrite with dots
|
||||
if (dto.password && dto.password.includes('•')) {
|
||||
delete dto.password;
|
||||
}
|
||||
|
||||
const saved = await this.emailService.saveConfig(dto);
|
||||
return {
|
||||
success: true,
|
||||
message: 'تنظیمات ایمیل با موفقیت ذخیره شد.',
|
||||
data: {
|
||||
...saved,
|
||||
password: saved.password ? '••••••••' : '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test SMTP connection live
|
||||
*/
|
||||
@Post('test-smtp')
|
||||
async testSmtp(@Body() customConfig?: TestSmtpDto) {
|
||||
if (customConfig?.password && customConfig.password.includes('•')) {
|
||||
delete customConfig.password;
|
||||
}
|
||||
|
||||
const res = await this.emailService.testConnection(customConfig);
|
||||
return {
|
||||
success: res.success,
|
||||
message: res.message,
|
||||
banner: res.banner,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send test email
|
||||
*/
|
||||
@Post('send-test-email')
|
||||
async sendTestEmail(@Body() body: SendTestEmailDto) {
|
||||
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
|
||||
|
||||
const subject = body.subject || 'تست اتصال ایمیل - کنینا ایران';
|
||||
const message =
|
||||
body.message ||
|
||||
'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.';
|
||||
const res = await this.emailService.sendMail({
|
||||
to: body.to,
|
||||
subject,
|
||||
text: message,
|
||||
html: renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 16px;">${textToHtmlParagraphs(message)}</p><p style="margin:0;font-size:13px;color:#7A9B9F;">زمان ارسال: ${escapeHtml(new Date().toLocaleString('fa-IR'))}</p>`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new BadRequestException(res.error || 'ارسال ایمیل تستی ناموفق بود.');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `ایمیل تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||
messageId: res.messageId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send test SMS
|
||||
*/
|
||||
@Post('send-test-sms')
|
||||
async sendTestSms(@Body() body: SendTestSmsDto) {
|
||||
if (!body.to || !body.message) {
|
||||
throw new BadRequestException('شماره موبایل و متن پیام الزامی است.');
|
||||
}
|
||||
|
||||
const res = await this.smsService.sendSms(body.to, body.message);
|
||||
if (!res) throw new BadRequestException('ارسال پیامک تستی ناموفق بود.');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `پیامک تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual targeted notification send
|
||||
*/
|
||||
@Post('manual-send')
|
||||
async manualSend(@Body() body: ManualSendDto) {
|
||||
if (!body.channel || !body.content) {
|
||||
throw new BadRequestException('کانال ارسال و متن پیام الزامی است.');
|
||||
}
|
||||
|
||||
let targetList: string[] = [];
|
||||
|
||||
if (body.targetType === 'single') {
|
||||
if (!body.recipient) throw new BadRequestException('گیرنده پیام مشخص نشده است.');
|
||||
targetList = [body.recipient.trim()];
|
||||
} else if (body.targetType === 'custom_list') {
|
||||
if (!Array.isArray(body.recipients) || !body.recipients.length) {
|
||||
throw new BadRequestException('لیست گیرندگان خالی است.');
|
||||
}
|
||||
targetList = body.recipients.map((r) => r.trim()).filter(Boolean);
|
||||
} else if (body.targetType === 'all_users') {
|
||||
const users = await this.prisma.user.findMany({
|
||||
select: { mobile: true, email: true },
|
||||
take: 1000,
|
||||
});
|
||||
|
||||
if (body.channel === 'SMS') {
|
||||
targetList = users.map((u) => u.mobile).filter(Boolean) as string[];
|
||||
} else {
|
||||
targetList = users.map((u) => u.email).filter(Boolean) as string[];
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetList.length) {
|
||||
throw new BadRequestException('هیچ گیرنده معتبری برای ارسال یافت نشد.');
|
||||
}
|
||||
|
||||
// Enqueue all items into durable queue
|
||||
const queuedItems = await Promise.all(
|
||||
targetList.map((rec) =>
|
||||
this.queueService.enqueue({
|
||||
channel: body.channel,
|
||||
recipient: rec,
|
||||
event: 'MANUAL_TARGETED_SEND',
|
||||
subject: body.subject,
|
||||
content: body.content,
|
||||
idempotencyKey: `manual_${body.channel}_${rec}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `${queuedItems.length} پیام با موفقیت در صف ارسال قرار گرفت.`,
|
||||
count: queuedItems.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue items and statistics
|
||||
*/
|
||||
@Get('queue')
|
||||
async getQueue(
|
||||
@Query('page') page?: number,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('channel') channel?: string,
|
||||
@Query('search') search?: string,
|
||||
) {
|
||||
const data = await this.queueService.getQueue({ page, limit, status, channel, search });
|
||||
return {
|
||||
success: true,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry failed queue item
|
||||
*/
|
||||
@Post('queue/:id/retry')
|
||||
async retryQueueItem(@Param('id') id: string) {
|
||||
const retried = await this.queueService.retry(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'پیام مجدداً در صف ارسال قرار گرفت.',
|
||||
data: retried,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get notification templates & event definitions
|
||||
*/
|
||||
@Get('templates')
|
||||
async getTemplates() {
|
||||
const templates = await this.prisma.notificationTemplate.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const defaultEvents = [
|
||||
{ event: 'ORDER_CREATED', name: 'ثبت سفارش جدید', variables: ['order_id', 'customer_name', 'total_amount'] },
|
||||
{ event: 'PAYMENT_SUCCESS', name: 'پرداخت موفق سفارش', variables: ['order_id', 'track_id', 'amount'] },
|
||||
{ event: 'ORDER_SHIPPED', name: 'ارسال سفارش پستی', variables: ['order_id', 'tracking_code', 'carrier'] },
|
||||
{ event: 'NEW_LEAD', name: 'درخواست تماس یا مشاوره جدید', variables: ['lead_name', 'phone', 'product_name'] },
|
||||
{ event: 'USER_REGISTERED', name: 'ثبتنام کاربر جدید', variables: ['user_name', 'mobile'] },
|
||||
{ event: 'TICKET_REPLIED', name: 'پاسخ به تیکت پشتیبانی', variables: ['ticket_id', 'user_name'] },
|
||||
];
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
templates,
|
||||
events: defaultEvents,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update notification template
|
||||
*/
|
||||
@Post('templates')
|
||||
async upsertTemplate(@Body() dto: CreateTemplateDto) {
|
||||
if (!dto.channel || !dto.event || !dto.name || !dto.body) {
|
||||
throw new BadRequestException('اطلاعات ضروری قالب ناقص است.');
|
||||
}
|
||||
|
||||
const data = {
|
||||
channel: dto.channel,
|
||||
event: dto.event,
|
||||
name: dto.name,
|
||||
subject: dto.subject || null,
|
||||
body: dto.body,
|
||||
patternCode: dto.patternCode || null,
|
||||
variables: dto.variables || [],
|
||||
recipientType: dto.recipientType || 'customer',
|
||||
customRecipient: dto.customRecipient || null,
|
||||
isActive: dto.isActive !== undefined ? dto.isActive : true,
|
||||
};
|
||||
|
||||
let template;
|
||||
if (dto.id) {
|
||||
template = await this.prisma.notificationTemplate.update({
|
||||
where: { id: dto.id },
|
||||
data,
|
||||
});
|
||||
} else {
|
||||
template = await this.prisma.notificationTemplate.upsert({
|
||||
where: {
|
||||
channel_event: {
|
||||
channel: dto.channel,
|
||||
event: dto.event,
|
||||
},
|
||||
},
|
||||
create: data,
|
||||
update: data,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'قالب رویداد با موفقیت ذخیره شد.',
|
||||
data: template,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete template
|
||||
*/
|
||||
@Delete('templates/:id')
|
||||
async deleteTemplate(@Param('id') id: string) {
|
||||
await this.prisma.notificationTemplate.delete({ where: { id } });
|
||||
return {
|
||||
success: true,
|
||||
message: 'قالب رویداد حذف شد.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsNumber, IsBoolean, IsIn, IsArray } from 'class-validator';
|
||||
|
||||
export class UpdateEmailConfigDto {
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
enabled?: boolean;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
host!: string;
|
||||
|
||||
@IsNumber()
|
||||
port!: number;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
secure?: boolean = true;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
user?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
password?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
from?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
fromName?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
fromEmail?: string;
|
||||
}
|
||||
|
||||
export class TestSmtpDto {
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
enabled?: boolean;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
host?: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
port?: number;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
secure?: boolean = true;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
user?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
password?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
from?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
fromName?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
fromEmail?: string;
|
||||
}
|
||||
|
||||
export class SendTestEmailDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
to!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
subject?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export class SendTestSmsDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
to!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
message!: string;
|
||||
}
|
||||
|
||||
export class ManualSendDto {
|
||||
@IsString()
|
||||
@IsIn(['SMS', 'EMAIL'])
|
||||
channel!: 'SMS' | 'EMAIL';
|
||||
|
||||
@IsString()
|
||||
@IsIn(['single', 'all_users', 'custom_list'])
|
||||
targetType!: 'single' | 'all_users' | 'custom_list';
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
recipient?: string;
|
||||
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
recipients?: string[];
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
subject?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
content!: string;
|
||||
}
|
||||
|
||||
export class CreateTemplateDto {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
id?: string;
|
||||
|
||||
@IsString()
|
||||
@IsIn(['SMS', 'EMAIL'])
|
||||
channel!: 'SMS' | 'EMAIL';
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
event!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
subject?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
body!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
patternCode?: string;
|
||||
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
variables?: string[];
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
recipientType?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
customRecipient?: string;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
isActive?: boolean;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SmsModule } from '../common/sms.module';
|
||||
import { EmailService } from './email.service';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { NotificationsController } from './notifications.controller';
|
||||
import { TransactionalEmailsService } from './transactional-emails.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, SmsModule],
|
||||
controllers: [NotificationsController],
|
||||
providers: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||
exports: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||
})
|
||||
export class NotificationsModule {}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { EmailService } from './email.service';
|
||||
import {
|
||||
escapeHtml,
|
||||
renderCaninaEmailLayout,
|
||||
textToHtmlParagraphs,
|
||||
} from './email-layout';
|
||||
|
||||
const ADMIN_NOTIFY_TO = [
|
||||
'support@canina.ir',
|
||||
'parsa.aghaee@gmail.com',
|
||||
] as const;
|
||||
|
||||
@Injectable()
|
||||
export class TransactionalEmailsService {
|
||||
private readonly logger = new Logger(TransactionalEmailsService.name);
|
||||
|
||||
constructor(private readonly emailService: EmailService) {}
|
||||
|
||||
private async sendSafe(to: string, subject: string, text: string, html: string) {
|
||||
try {
|
||||
const res = await this.emailService.sendMail({ to, subject, text, html });
|
||||
if (!res.success) {
|
||||
this.logger.warn(`Email to ${to} failed: ${res.error || 'unknown'}`);
|
||||
}
|
||||
return res;
|
||||
} catch (err) {
|
||||
this.logger.warn(`Email to ${to} threw: ${(err as Error).message}`);
|
||||
return { success: false, error: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
async sendWelcome(to: string | null | undefined, firstName?: string | null) {
|
||||
if (!to) return;
|
||||
const name = (firstName || '').trim() || 'کاربر گرامی';
|
||||
const subject = 'به کنینا خوش آمدید';
|
||||
const text = `سلام ${name}،\n\nثبتنام شما در فروشگاه کنینا با موفقیت انجام شد.\n\ncanina.ir`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0;">ثبتنام شما در فروشگاه کنینا با موفقیت انجام شد. از این به بعد میتوانید سفارشها و وضعیت حساب خود را از سایت پیگیری کنید.</p>`,
|
||||
});
|
||||
await this.sendSafe(to, subject, text, html);
|
||||
}
|
||||
|
||||
async sendOrderCreated(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||
if (!to) return;
|
||||
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||
const amount = Number(order.totalAmount || 0);
|
||||
const subject = 'سفارش شما در کنینا ثبت شد';
|
||||
const text = `سفارش شما ثبت شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 12px;">سفارش شما ثبت شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ سفارش: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p><p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">این پیام بهتنهایی بهمعنای تأیید پرداخت نیست؛ وضعیت پرداخت را در حساب کاربری بررسی کنید.</p>`,
|
||||
});
|
||||
await this.sendSafe(to, subject, text, html);
|
||||
}
|
||||
|
||||
async sendOrderPaid(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||
if (!to) return;
|
||||
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||
const amount = Number(order.totalAmount || 0);
|
||||
const subject = 'پرداخت سفارش کنینا تأیید شد';
|
||||
const text = `پرداخت سفارش تأیید شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 12px;">پرداخت سفارش شما با موفقیت تأیید شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ پرداختشده: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p>`,
|
||||
});
|
||||
await this.sendSafe(to, subject, text, html);
|
||||
}
|
||||
|
||||
async sendOrderShipped(
|
||||
to: string | null | undefined,
|
||||
order: { id?: string; trackingNumber?: string | null },
|
||||
trackingCode?: string,
|
||||
) {
|
||||
if (!to) return;
|
||||
const track = escapeHtml(String(trackingCode || order.trackingNumber || 'ارسال با پیک شهری'));
|
||||
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||
const subject = 'سفارش کنینا ارسال شد';
|
||||
const text = `سفارش شما ارسال شد.\nسفارش: ${order.trackingNumber || order.id || ''}\nرهگیری: ${trackingCode || order.trackingNumber || 'ارسال با پیک شهری'}`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 12px;">وضعیت سفارش به ارسالشده تغییر کرد.</p><p style="margin:0 0 8px;">سفارش: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">کد/روش ارسال: <b dir="ltr">${track}</b></p>`,
|
||||
});
|
||||
await this.sendSafe(to, subject, text, html);
|
||||
}
|
||||
|
||||
async sendContactConfirmation(to: string | null | undefined, name: string, message: string, submissionId?: string) {
|
||||
if (!to) return;
|
||||
const subject = 'پیام شما در کنینا ثبت شد';
|
||||
const text = `سلام ${name}،\n\nپیام شما ثبت شد و بهزودی بررسی میشود.\nشناسه: ${submissionId || ''}\n\n${message}`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: subject,
|
||||
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0 0 16px;">پیام شما از طریق فرم تماس کنینا ثبت شد و بهزودی بررسی میشود.</p><div style="padding:14px;background:#F4F7F6;border:1px solid #E5ECE9;border-right:3px solid #F1B646;"><p style="margin:0;white-space:pre-wrap;">${textToHtmlParagraphs(message || '')}</p></div>${submissionId ? `<p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">شناسه پیگیری: <span dir="ltr">#${escapeHtml(submissionId)}</span></p>` : ''}`,
|
||||
});
|
||||
await this.sendSafe(to, subject, text, html);
|
||||
}
|
||||
|
||||
async notifyAdminsAboutContact(dto: {
|
||||
name: string;
|
||||
phone: string;
|
||||
email?: string;
|
||||
subject?: string;
|
||||
message: string;
|
||||
submissionId?: string;
|
||||
}) {
|
||||
const subject = `پیام جدید فرم تماس کنینا${dto.subject ? ` — ${dto.subject}` : ''}`;
|
||||
const text = `نام: ${dto.name}\nتلفن: ${dto.phone}\nایمیل: ${dto.email || '-'}\nموضوع: ${dto.subject || '-'}\nشناسه: ${dto.submissionId || '-'}\n\n${dto.message}`;
|
||||
const html = renderCaninaEmailLayout({
|
||||
title: 'پیام جدید از فرم تماس',
|
||||
bodyHtml: `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">
|
||||
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;width:110px;">نام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;">${escapeHtml(dto.name)}</td></tr>
|
||||
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">تلفن</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.phone)}</td></tr>
|
||||
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">ایمیل</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.email || '-')}</td></tr>
|
||||
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;vertical-align:top;">پیام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;white-space:pre-wrap;">${textToHtmlParagraphs(dto.message || '')}</td></tr>
|
||||
</table>`,
|
||||
});
|
||||
await Promise.all(
|
||||
ADMIN_NOTIFY_TO.map((to) => this.sendSafe(to, subject, text, html)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# Opt-in fragment ONLY: merge into the reviewed Stage backend service definition.
|
||||
# Not a standalone compose file; does not enable the worker automatically.
|
||||
# Host files/dirs must already exist, with reviewed ownership and modes.
|
||||
x-prepare-worker-backend:
|
||||
environment:
|
||||
PREPARE_WORKER_ENABLED: "${PREPARE_WORKER_ENABLED:-false}"
|
||||
secrets:
|
||||
- source: prepare_worker_grants
|
||||
target: prepare_worker_grants
|
||||
mode: 0400
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${PREPARE_WORKER_ARTIFACT_HOST_DIRECTORY:?review private artifact directory}
|
||||
target: /var/lib/canina/prepare-artifacts
|
||||
bind:
|
||||
create_host_path: false
|
||||
secrets:
|
||||
prepare_worker_grants:
|
||||
file: ${PREPARE_WORKER_GRANTS_FILE:?review mounted grants JSON file}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { constants, openSync, closeSync, fstatSync, readSync } from 'fs';
|
||||
import { WorkerTransportConfig, WorkerTransportModule } from './worker-transport.module';
|
||||
|
||||
export const PREPARE_WORKER_CONFIG_PATH = '/run/secrets/prepare_worker_grants';
|
||||
export const PREPARE_WORKER_ARTIFACT_DIRECTORY = '/var/lib/canina/prepare-artifacts';
|
||||
const MAX_BYTES = 16384;
|
||||
const fail = () => { throw new Error('Prepare worker startup configuration rejected'); };
|
||||
function exact(value: any, keys: string[]): boolean {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value) &&
|
||||
Object.keys(value).length === keys.length && keys.every(k => Object.hasOwn(value, k));
|
||||
}
|
||||
|
||||
/** Fixed-path, descriptor-pinned, bounded startup read; never logs file contents. */
|
||||
export function loadPrepareWorkerConfig(): WorkerTransportConfig {
|
||||
let dir: number | undefined, file: number | undefined;
|
||||
try {
|
||||
dir = openSync('/', constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
for (const part of ['run', 'secrets']) {
|
||||
const next = openSync(`/proc/self/fd/${dir}/${part}`, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
closeSync(dir); dir = next;
|
||||
if ((fstatSync(dir).mode & 0o022) !== 0) fail();
|
||||
}
|
||||
file = openSync(`/proc/self/fd/${dir}/prepare_worker_grants`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
const stat = fstatSync(file);
|
||||
if (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o022) !== 0 || stat.size > MAX_BYTES ||
|
||||
(stat.uid !== 0 && stat.uid !== process.getuid!())) fail();
|
||||
const bytes = Buffer.alloc(MAX_BYTES + 1);
|
||||
let length = 0, n: number;
|
||||
do { n = readSync(file, bytes, length, bytes.length - length, length); length += n; }
|
||||
while (n > 0 && length < bytes.length);
|
||||
if (length > MAX_BYTES) fail();
|
||||
const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length)));
|
||||
if (!exact(input, ['grants', 'workerIds', 'stageCiIds', 'artifactBaseUrl']) ||
|
||||
!Array.isArray(input.grants) || input.grants.length < 1 || input.grants.length > 32 ||
|
||||
!Array.isArray(input.workerIds) || !Array.isArray(input.stageCiIds) ||
|
||||
input.workerIds.length < 1 || input.stageCiIds.length < 1 ||
|
||||
input.workerIds.length + input.stageCiIds.length !== input.grants.length ||
|
||||
typeof input.artifactBaseUrl !== 'string' || input.artifactBaseUrl.length > 2048 ||
|
||||
input.grants.some((g: any) => !exact(g, ['id', 'role', 'credentialSha256']))) fail();
|
||||
// Transport registration performs shared role, SHA256, ID, overlap and HTTPS validation.
|
||||
const config: WorkerTransportConfig = { ...input, enabled: true, artifactDirectory: PREPARE_WORKER_ARTIFACT_DIRECTORY };
|
||||
WorkerTransportModule.register(config); // Reuse the real transport's reviewed validation, no IO.
|
||||
config.grants.forEach(Object.freeze);
|
||||
Object.freeze(config.grants); Object.freeze(config.workerIds); Object.freeze(config.stageCiIds);
|
||||
return Object.freeze(config);
|
||||
} catch { return fail(); }
|
||||
finally { if (file !== undefined) closeSync(file); if (dir !== undefined) closeSync(dir); }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Prepare worker startup boundary
|
||||
|
||||
Parent integration API (AppModule remains untouched here):
|
||||
|
||||
```ts
|
||||
import { registerPrepareWorker } from './orchestration-worker/worker-registration';
|
||||
// In AppModule imports:
|
||||
...registerPrepareWorker(),
|
||||
```
|
||||
|
||||
Only literal `PREPARE_WORKER_ENABLED=true` registers the transport. Missing or other values register nothing (404 routes), do not read configuration, and do not instantiate Prisma. Enabled malformed/missing configuration throws synchronously before Nest starts, with one generic error and no secret logging.
|
||||
|
||||
The fixed mount `/run/secrets/prepare_worker_grants` contains JSON with exactly `grants`, `workerIds`, `stageCiIds`, `artifactBaseUrl`. Each grant contains exactly `id`, `role` (`WORKFLOW_WORKER` or `STAGE_CI`), `credentialSha256` (64 lowercase hexadecimal characters; never the bearer credential). Require at least one worker and CI, distinct role-bound IDs/digests, exact allowlist coverage, and at most 32 grants. No enabled flag, directory, token, user, or request-derived fields accepted in JSON.
|
||||
|
||||
`artifactBaseUrl` must be explicitly reviewed by the operator: canonical public-DNS HTTPS origin plus `/internal/prepare-worker/artifacts`, no credentials, IP, alternate port, query or fragment. Shared transport validation is authoritative. This loader does not fetch the URL or perform DNS resolution. Directory is always `/var/lib/canina/prepare-artifacts`.
|
||||
|
||||
Descriptor-relative Linux `/proc/self/fd` traversal refuses symlink directories/files, nonregular files, hardlinks, files over 16 KiB, group/world writable files/directories, and foreign-owned files (root/runtime UID only). Reads are bounded even on concurrent growth. Configuration is frozen recursively and transport takes its own frozen snapshot. Trusted operator owns mounted configuration; edits require restart and review.
|
||||
|
||||
`compose.prepare-worker.fragment.yml` is an extension fragment, not a deployable compose file. Parent must merge its `x-prepare-worker-backend` into the correct reviewed Stage backend service and merge `secrets`. Compose bind-backed secrets may ignore mode/UID declarations: provision actual host grants file as root/runtime-owned mode 0400 and artifact directory runtime-owned mode 0700 first. No mounts or live configuration are created by this change.
|
||||
|
||||
Tests deliberately use the fixed `/run/secrets` path. Run ONLY in a fresh disposable container with source and donor dependencies read-only, private dependency copy, and private `prisma generate`; never on a live service. Tests need a disposable Linux root filesystem and do not require DB credentials. Registration test uses a real Nest HTTP listener to prove disabled routes are absent. Existing DB-backed transport tracer remains separately gated by `WORKER_TRANSPORT_DB=1`.
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { writeFileSync, chmodSync, symlinkSync, mkdirSync, rmSync } from 'fs';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { registerPrepareWorker } from './worker-registration';
|
||||
import { loadPrepareWorkerConfig } from './worker-config';
|
||||
import { linkSync } from 'fs';
|
||||
|
||||
|
||||
describe('reviewed prepare-worker startup registration', () => {
|
||||
const path = '/run/secrets/prepare_worker_grants';
|
||||
const valid = () => ({ grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' });
|
||||
it('loader itself rejects malformed SHA grants', () => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const c = valid(); c.grants[0].credentialSha256 = 'secret-not-a-sha';
|
||||
writeFileSync(path, JSON.stringify(c), { mode: 0o400 });
|
||||
try { expect(() => loadPrepareWorkerConfig()).toThrow('Prepare worker startup configuration rejected'); }
|
||||
finally { rmSync(path, { force: true }); }
|
||||
});
|
||||
it.each(['1', 'TRUE', 'yes', ' true', 'false', ''])('does not opt in for %s', value => {
|
||||
expect(registerPrepareWorker({ PREPARE_WORKER_ENABLED: value })).toEqual([]);
|
||||
});
|
||||
it.each(['missing', 'symlink', 'directory', 'fifo', 'oversize', 'group-write', 'world-write', 'hardlink'])('fails startup on unsafe file: %s', kind => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const other = '/run/secrets/test-other';
|
||||
try {
|
||||
if (kind === 'fifo') execFileSync('mkfifo', [path]);
|
||||
else if (kind === 'directory') mkdirSync(path);
|
||||
else if (kind === 'symlink') symlinkSync(other, path);
|
||||
else if (kind !== 'missing') {
|
||||
writeFileSync(path, kind === 'oversize' ? ' '.repeat(16385) : JSON.stringify(valid()), { mode: 0o400 });
|
||||
if (kind === 'group-write') chmodSync(path, 0o420);
|
||||
if (kind === 'world-write') chmodSync(path, 0o402);
|
||||
if (kind === 'hardlink') linkSync(path, other);
|
||||
}
|
||||
expect(() => registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' })).toThrow('Prepare worker startup configuration rejected');
|
||||
} finally { rmSync(path, { recursive: true, force: true }); rmSync(other, { force: true }); }
|
||||
});
|
||||
it.each(['extra', 'raw-token', 'wrong-role', 'overlap', 'duplicate-sha', 'missing-grant', 'http', 'credentials', 'localhost', 'query', 'bad-json', 'null'])('rejects unreviewed JSON: %s without leaking contents or logging', kind => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const c: any = valid();
|
||||
if (kind === 'extra') c.artifactDirectory = '/user-selected';
|
||||
if (kind === 'raw-token') c.grants[0].token = 'DO_NOT_LOG_THIS_SECRET';
|
||||
if (kind === 'wrong-role') c.grants[0].role = 'Admin';
|
||||
if (kind === 'overlap') c.stageCiIds = ['worker'];
|
||||
if (kind === 'duplicate-sha') c.grants[1].credentialSha256 = c.grants[0].credentialSha256;
|
||||
if (kind === 'missing-grant') c.workerIds.push('unbound');
|
||||
if (kind === 'http') c.artifactBaseUrl = 'http://stage.example.com/internal/prepare-worker/artifacts';
|
||||
if (kind === 'credentials') c.artifactBaseUrl = 'https://DO_NOT_LOG_THIS_SECRET@stage.example.com/internal/prepare-worker/artifacts';
|
||||
if (kind === 'localhost') c.artifactBaseUrl = 'https://127.0.0.1/internal/prepare-worker/artifacts';
|
||||
if (kind === 'query') c.artifactBaseUrl += '?secret=DO_NOT_LOG_THIS_SECRET';
|
||||
writeFileSync(path, kind === 'bad-json' ? 'DO_NOT_LOG_THIS_SECRET' : kind === 'null' ? 'null' : JSON.stringify(c), { mode: 0o400 });
|
||||
const logs = [jest.spyOn(console, 'log'), jest.spyOn(console, 'warn'), jest.spyOn(console, 'error')];
|
||||
try {
|
||||
expect(() => registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' })).toThrow(/^Prepare worker startup configuration rejected$/);
|
||||
logs.forEach(log => expect(log).not.toHaveBeenCalled());
|
||||
} finally { logs.forEach(log => log.mockRestore()); rmSync(path, { force: true }); }
|
||||
});
|
||||
it('defaults to no module/no config IO and exposes no worker routes', async () => {
|
||||
expect(registerPrepareWorker({})).toEqual([]);
|
||||
expect(registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'false' })).toEqual([]);
|
||||
const module = await Test.createTestingModule({ imports: registerPrepareWorker({}) }).compile();
|
||||
const app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
try {
|
||||
const response = await fetch((await app.getUrl()) + '/internal/prepare-worker/claim', { method: 'POST' });
|
||||
expect(response.status).toBe(404);
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
it('loads immutable reviewed JSON into the real transport registration', async () => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const file = '/run/secrets/prepare_worker_grants';
|
||||
const config = { grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' };
|
||||
writeFileSync(file, JSON.stringify(config), { mode: 0o400 });
|
||||
try {
|
||||
const [registered] = registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' });
|
||||
expect(registered.module.name).toBe('WorkerTransportModule');
|
||||
expect(registered.controllers?.length).toBe(1);
|
||||
const snapshot = (registered.providers as any[]).find(p => p.useValue?.artifactDirectory)?.useValue;
|
||||
expect(snapshot).toEqual({ ...config, enabled: true, artifactDirectory: '/var/lib/canina/prepare-artifacts' });
|
||||
expect(Object.isFrozen(snapshot)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.grants[0])).toBe(true);
|
||||
} finally { rmSync(file, { force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { DynamicModule } from '@nestjs/common';
|
||||
import { loadPrepareWorkerConfig } from './worker-config';
|
||||
import { WorkerTransportModule } from './worker-transport.module';
|
||||
|
||||
/** AppModule imports: ...registerPrepareWorker(); disabled means no module or IO. */
|
||||
export function registerPrepareWorker(env: NodeJS.ProcessEnv = process.env): DynamicModule[] {
|
||||
if (env.PREPARE_WORKER_ENABLED !== 'true') return [];
|
||||
try { return [WorkerTransportModule.register(loadPrepareWorkerConfig())]; }
|
||||
catch { throw new Error('Prepare worker startup configuration rejected'); }
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
CanActivate,
|
||||
ConflictException,
|
||||
Controller,
|
||||
DynamicModule,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Inject,
|
||||
Injectable,
|
||||
Module,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from "@nestjs/common";
|
||||
import { IsString, IsUUID, Matches, MaxLength } from "class-validator";
|
||||
import { createHash, timingSafeEqual } from "crypto";
|
||||
import { mkdir, open, FileHandle } from "fs/promises";
|
||||
import { constants } from "fs";
|
||||
import { isAbsolute } from "path";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
PREPARE_WORKFLOW_CONFIG,
|
||||
PrepareWorkflowService,
|
||||
WorkflowIdentity,
|
||||
} from "../orchestration/prepare-workflow.service";
|
||||
|
||||
// This is reviewed static configuration, not a URL fetched by the transport.
|
||||
function validArtifactBase(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value);
|
||||
// DNS name only: reject all IP literals, localhost/private single-label names,
|
||||
// noncanonical paths/escapes, credentials, query, fragment and alternate ports.
|
||||
return u.protocol === "https:" && !u.username && !u.password && !u.port &&
|
||||
/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(u.hostname) &&
|
||||
u.hostname.includes(".") && !/^[0-9.]+$/.test(u.hostname) &&
|
||||
!/(^|\.)(localhost|local|internal|lan|home)$/.test(u.hostname) &&
|
||||
u.pathname === "/internal/prepare-worker/artifacts" &&
|
||||
value === u.origin + u.pathname;
|
||||
} catch { return false; }
|
||||
}
|
||||
const CONFIG = Symbol("WORKER_TRANSPORT_CONFIG");
|
||||
export interface WorkerTransportConfig {
|
||||
enabled: boolean;
|
||||
grants: {
|
||||
id: string;
|
||||
role: "WORKFLOW_WORKER" | "STAGE_CI";
|
||||
credentialSha256: string;
|
||||
}[];
|
||||
workerIds: string[];
|
||||
stageCiIds: string[];
|
||||
artifactDirectory: string;
|
||||
artifactBaseUrl: string;
|
||||
}
|
||||
class ClaimDto {
|
||||
@IsUUID() taskId!: string;
|
||||
}
|
||||
class LeaseDto extends ClaimDto {
|
||||
@IsUUID() runId!: string;
|
||||
@IsUUID() leaseToken!: string;
|
||||
}
|
||||
class CompleteDto extends LeaseDto {
|
||||
@IsString() @MaxLength(2048) report!: string;
|
||||
}
|
||||
class StageEvidenceDto extends ClaimDto {
|
||||
@IsUUID() runId!: string;
|
||||
@Matches(/^[a-f0-9]{40}$/) commitSha!: string;
|
||||
@Matches(/^[a-f0-9]{64}$/) sha256!: string;
|
||||
@Matches(/^[a-f0-9]{64}$/) evidenceSha256!: string;
|
||||
@Matches(/^https:\/\/[^\s]+$/) @MaxLength(2000) uri!: string;
|
||||
}
|
||||
export function tracerReport(lease: {
|
||||
taskId: string;
|
||||
runId: string;
|
||||
commitSha: string;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
kind: "DETERMINISTIC_PREPARE_TRACER",
|
||||
schemaVersion: 1,
|
||||
taskId: lease.taskId,
|
||||
runId: lease.runId,
|
||||
commitSha: lease.commitSha,
|
||||
environment: "staging",
|
||||
llmPilot: false,
|
||||
browserExecuted: false,
|
||||
shellExecuted: false,
|
||||
deploymentExecuted: false,
|
||||
checks: ["lease-bound identity", "deterministic JSON serialization"],
|
||||
actualCents: 0,
|
||||
});
|
||||
}
|
||||
@Injectable()
|
||||
class WorkerIdentityGuard implements CanActivate {
|
||||
constructor(@Inject(CONFIG) private readonly config: WorkerTransportConfig) {}
|
||||
canActivate(context: any) {
|
||||
if (!this.config.enabled)
|
||||
throw new ForbiddenException("Worker transport disabled");
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const auth = req.headers.authorization;
|
||||
if (typeof auth !== "string" || !/^Bearer [\x21-\x7e]{32,512}$/.test(auth))
|
||||
throw new UnauthorizedException();
|
||||
const digest = createHash("sha256").update(auth.slice(7)).digest();
|
||||
const grant = this.config.grants.find((g) =>
|
||||
timingSafeEqual(Buffer.from(g.credentialSha256, "hex"), digest),
|
||||
);
|
||||
if (!grant) throw new UnauthorizedException();
|
||||
req.workerIdentity = { id: grant.id, role: grant.role };
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
class WorkerTransportService {
|
||||
constructor(
|
||||
private readonly workflow: PrepareWorkflowService,
|
||||
private readonly db: PrismaService,
|
||||
@Inject(CONFIG) private readonly config: WorkerTransportConfig,
|
||||
) {}
|
||||
// Linux descriptor-relative traversal pins each directory across renames. Never
|
||||
// realpath-check then reopen by name: that reintroduces a symlink race.
|
||||
private async artifactDir(): Promise<FileHandle> {
|
||||
let dir = await open("/", constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try {
|
||||
for (const part of this.config.artifactDirectory.split("/").filter(Boolean)) {
|
||||
const path = `/proc/self/fd/${dir.fd}/${part}`;
|
||||
try { await mkdir(path, { mode: 0o700 }); }
|
||||
catch (e: any) { if (e.code !== "EEXIST") throw e; }
|
||||
const next = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
await dir.close();
|
||||
dir = next;
|
||||
}
|
||||
const stat = await dir.stat();
|
||||
if (stat.uid !== process.getuid!() || (stat.mode & 0o077) !== 0)
|
||||
throw new Error("Private owned artifact directory required");
|
||||
return dir;
|
||||
} catch (e) { await dir.close(); throw e; }
|
||||
}
|
||||
private worker(a: WorkflowIdentity) {
|
||||
if (a.role !== "WORKFLOW_WORKER" || !this.config.workerIds.includes(a.id))
|
||||
throw new ForbiddenException("Worker allowlist required");
|
||||
}
|
||||
async claim(a: WorkflowIdentity, dto: ClaimDto) {
|
||||
this.worker(a);
|
||||
const t = await this.db.orchestrationTask.findUnique({
|
||||
where: { id: dto.taskId },
|
||||
});
|
||||
// Explicit per-task pilot scope; never opportunistically consume arbitrary queued work.
|
||||
if (!t || !["READY", "RUNNING"].includes(t.state)) return { lease: null };
|
||||
if (t.budgetLimitCents !== 20)
|
||||
throw new ForbiddenException("Pilot hard task cap is 20 cents");
|
||||
return { lease: await this.workflow.claim(a, dto.taskId) };
|
||||
}
|
||||
heartbeat(a: WorkflowIdentity, dto: LeaseDto) {
|
||||
this.worker(a);
|
||||
return this.workflow.heartbeat(a, dto);
|
||||
}
|
||||
async complete(a: WorkflowIdentity, dto: CompleteDto) {
|
||||
this.worker(a);
|
||||
// Recheck stop/interrupt and fencing before artifact creation; core rechecks atomically at commit.
|
||||
await this.workflow.heartbeat(a, dto);
|
||||
const run = await this.db.orchestrationRun.findUniqueOrThrow({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
const expected = tracerReport({ ...dto, commitSha: run.commitSha });
|
||||
if (dto.report !== expected)
|
||||
throw new BadRequestException(
|
||||
"Only deterministic harmless tracer report accepted",
|
||||
);
|
||||
const sha256 = createHash("sha256").update(expected).digest("hex");
|
||||
let dir: FileHandle | undefined, file: FileHandle | undefined;
|
||||
try {
|
||||
dir = await this.artifactDir();
|
||||
file = await open(`/proc/self/fd/${dir.fd}/${sha256}.json`,
|
||||
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
await file.writeFile(expected, "utf8");
|
||||
await file.sync();
|
||||
} catch { throw new ConflictException("Artifact creation refused"); }
|
||||
finally { await file?.close(); await dir?.close(); }
|
||||
const result = await this.workflow.complete(a, {
|
||||
...dto,
|
||||
sha256,
|
||||
uri: this.config.artifactBaseUrl + "/" + sha256,
|
||||
actualCents: 0,
|
||||
});
|
||||
return {
|
||||
state: result.state,
|
||||
taskId: result.id,
|
||||
runId: dto.runId,
|
||||
sha256,
|
||||
actualCents: 0,
|
||||
};
|
||||
}
|
||||
async artifact(a: WorkflowIdentity, hash: string) {
|
||||
if (!/^[a-f0-9]{64}$/.test(hash))
|
||||
throw new BadRequestException("Invalid artifact hash");
|
||||
const registered = await this.db.orchestrationArtifact.findFirst({
|
||||
where: {
|
||||
sha256: hash, kind: "QA", uri: this.config.artifactBaseUrl + "/" + hash,
|
||||
run: { environment: "staging", status: "SUCCEEDED", task: {
|
||||
operationMode: "PREPARE", budgetLimitCents: 20,
|
||||
} },
|
||||
},
|
||||
});
|
||||
if (!registered) throw new NotFoundException("Artifact not registered");
|
||||
const run = await this.db.orchestrationRun.findUniqueOrThrow({ where: { id: registered.runId } });
|
||||
const task = await this.db.orchestrationTask.findUniqueOrThrow({ where: { id: run.taskId } });
|
||||
const outbox = await this.db.prepareWorkflowOutbox.findUnique({ where: { taskId: run.taskId } });
|
||||
if (!outbox || outbox.status !== "DONE" || outbox.runId !== run.id ||
|
||||
(a.role === "WORKFLOW_WORKER" && outbox.leaseOwner !== a.id))
|
||||
throw new NotFoundException("Artifact not registered");
|
||||
const metadata = task.metadata as any;
|
||||
if (metadata?.workflowScope !== "STAGE_PREPARE" || metadata?.commitSha !== run.commitSha)
|
||||
throw new NotFoundException("Artifact not registered");
|
||||
let bytes: string;
|
||||
let dir: FileHandle | undefined, file: FileHandle | undefined;
|
||||
try {
|
||||
dir = await this.artifactDir();
|
||||
file = await open(`/proc/self/fd/${dir.fd}/${hash}.json`,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid!() ||
|
||||
(stat.mode & 0o077) !== 0 || stat.size > 2048)
|
||||
throw new Error("Unsafe artifact file");
|
||||
// Fixed-size descriptor read: concurrent growth cannot allocate unbounded memory.
|
||||
const buffer = Buffer.alloc(2049);
|
||||
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
||||
if (bytesRead > 2048) throw new Error("Oversized artifact");
|
||||
bytes = buffer.subarray(0, bytesRead).toString("utf8");
|
||||
} catch {
|
||||
throw new NotFoundException("Artifact unavailable");
|
||||
} finally { await file?.close(); await dir?.close(); }
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== hash)
|
||||
throw new ConflictException("Artifact integrity mismatch");
|
||||
if (bytes !== tracerReport({ taskId: run.taskId, runId: run.id, commitSha: run.commitSha }))
|
||||
throw new ConflictException("Artifact binding mismatch");
|
||||
return JSON.parse(bytes);
|
||||
}
|
||||
stage(a: WorkflowIdentity, dto: StageEvidenceDto) {
|
||||
return this.workflow.stageEvidence(a, dto);
|
||||
}
|
||||
}
|
||||
@Controller("internal/prepare-worker")
|
||||
@UseGuards(WorkerIdentityGuard)
|
||||
@UsePipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
)
|
||||
class WorkerTransportController {
|
||||
constructor(private readonly service: WorkerTransportService) {}
|
||||
@Post("claim") claim(@Req() req: any, @Body() dto: ClaimDto) {
|
||||
return this.service.claim(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("heartbeat") heartbeat(@Req() req: any, @Body() dto: LeaseDto) {
|
||||
return this.service.heartbeat(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("complete") complete(@Req() req: any, @Body() dto: CompleteDto) {
|
||||
return this.service.complete(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("stage-evidence") stage(
|
||||
@Req() req: any,
|
||||
@Body() dto: StageEvidenceDto,
|
||||
) {
|
||||
return this.service.stage(req.workerIdentity, dto);
|
||||
}
|
||||
@Get("artifacts/:hash") artifact(@Req() req: any, @Param("hash") hash: string) {
|
||||
return this.service.artifact(req.workerIdentity, hash);
|
||||
}
|
||||
}
|
||||
@Module({})
|
||||
export class WorkerTransportModule {
|
||||
static register(config: WorkerTransportConfig): DynamicModule {
|
||||
if (typeof config.enabled !== "boolean" || !Array.isArray(config.grants) ||
|
||||
!Array.isArray(config.workerIds) || !Array.isArray(config.stageCiIds))
|
||||
throw new Error("Explicit boolean enable and credential allowlists required");
|
||||
const allIds = [...config.workerIds, ...config.stageCiIds];
|
||||
if (allIds.some(id => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id)) ||
|
||||
new Set(allIds).size !== allIds.length)
|
||||
throw new Error("Invalid or overlapping worker/CI allowlists");
|
||||
const ids = new Set<string>(),
|
||||
digests = new Set<string>();
|
||||
if (
|
||||
!isAbsolute(config.artifactDirectory) || config.artifactDirectory === "/" ||
|
||||
config.artifactDirectory.split("/").some(p => p === "." || p === "..") ||
|
||||
!validArtifactBase(config.artifactBaseUrl)
|
||||
)
|
||||
throw new Error(
|
||||
"Absolute artifact directory and fixed HTTPS artifact base required",
|
||||
);
|
||||
for (const g of config.grants) {
|
||||
const allowed =
|
||||
g.role === "WORKFLOW_WORKER"
|
||||
? config.workerIds
|
||||
: g.role === "STAGE_CI"
|
||||
? config.stageCiIds
|
||||
: [];
|
||||
if (
|
||||
!/^[a-zA-Z0-9_-]{1,100}$/.test(g.id) ||
|
||||
!allowed.includes(g.id) ||
|
||||
!/^[a-f0-9]{64}$/.test(g.credentialSha256) ||
|
||||
ids.has(g.id) ||
|
||||
digests.has(g.credentialSha256) ||
|
||||
(config.workerIds.includes(g.id) && config.stageCiIds.includes(g.id))
|
||||
)
|
||||
throw new Error("Invalid or overlapping worker/CI credential grants");
|
||||
ids.add(g.id);
|
||||
digests.add(g.credentialSha256);
|
||||
}
|
||||
const snapshot = JSON.parse(JSON.stringify(config)) as WorkerTransportConfig;
|
||||
snapshot.grants.forEach(Object.freeze);
|
||||
Object.freeze(snapshot.grants);
|
||||
Object.freeze(snapshot.workerIds);
|
||||
Object.freeze(snapshot.stageCiIds);
|
||||
Object.freeze(snapshot);
|
||||
return {
|
||||
module: WorkerTransportModule,
|
||||
imports: [PrismaModule],
|
||||
controllers: [WorkerTransportController],
|
||||
providers: [
|
||||
PrepareWorkflowService,
|
||||
WorkerIdentityGuard,
|
||||
WorkerTransportService,
|
||||
{ provide: CONFIG, useValue: snapshot },
|
||||
{
|
||||
provide: PREPARE_WORKFLOW_CONFIG,
|
||||
useValue: Object.freeze({
|
||||
workerIds: snapshot.workerIds,
|
||||
stageCiIds: snapshot.stageCiIds,
|
||||
}),
|
||||
},
|
||||
],
|
||||
exports: [PrepareWorkflowService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PrepareWorkflowService } from "../orchestration/prepare-workflow.service";
|
||||
import { WorkerTransportModule, tracerReport } from "./worker-transport.module";
|
||||
import { createHash, randomUUID } from "crypto";
|
||||
import { mkdtemp, readFile, rm, writeFile, symlink, link, rename } from "fs/promises";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
import { execFile } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
const enabled = process.env.WORKER_TRANSPORT_DB === "1";
|
||||
(enabled ? describe : describe.skip)(
|
||||
"isolated PostgreSQL HTTP executor tracer",
|
||||
() => {
|
||||
const db = new PrismaClient();
|
||||
const token = "test-only-worker-secret-".repeat(3);
|
||||
const ciToken = "test-only-ci-secret-".repeat(3);
|
||||
const digest = (s: string) => createHash("sha256").update(s).digest("hex");
|
||||
let app: INestApplication,
|
||||
workflow: PrepareWorkflowService,
|
||||
base: string,
|
||||
directory: string;
|
||||
let pilot: any;
|
||||
beforeAll(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "worker-artifacts-"));
|
||||
const mod = await Test.createTestingModule({
|
||||
imports: [
|
||||
WorkerTransportModule.register({
|
||||
enabled: true,
|
||||
grants: [
|
||||
{
|
||||
id: "pilot",
|
||||
role: "WORKFLOW_WORKER",
|
||||
credentialSha256: digest(token),
|
||||
},
|
||||
{ id: "ci", role: "STAGE_CI", credentialSha256: digest(ciToken) },
|
||||
{ id: "other", role: "WORKFLOW_WORKER", credentialSha256: digest("other-worker-secret-".repeat(3)) },
|
||||
],
|
||||
workerIds: ["pilot", "other"],
|
||||
stageCiIds: ["ci"],
|
||||
artifactDirectory: directory,
|
||||
artifactBaseUrl:
|
||||
"https://isolated.invalid/internal/prepare-worker/artifacts",
|
||||
}),
|
||||
],
|
||||
})
|
||||
.overrideProvider(PrismaService)
|
||||
.useValue(db)
|
||||
.compile();
|
||||
workflow = mod.get(PrepareWorkflowService);
|
||||
app = mod.createNestApplication();
|
||||
await app.listen(0, "127.0.0.1");
|
||||
base = await app.getUrl();
|
||||
pilot = {
|
||||
runOnce: async (options: any) => {
|
||||
const program =
|
||||
'import {runOnce} from "../infra/hermes-worker/pilot.mjs"; console.log(JSON.stringify(await runOnce(JSON.parse(process.env.TEST_PILOT_OPTIONS))));';
|
||||
const result = await promisify(execFile)(
|
||||
process.execPath,
|
||||
["--input-type=module", "-e", program],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
TEST_PILOT_OPTIONS: JSON.stringify(options),
|
||||
},
|
||||
timeout: 15000,
|
||||
},
|
||||
);
|
||||
return JSON.parse(result.stdout);
|
||||
},
|
||||
};
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await db.$disconnect();
|
||||
if (directory) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
const owner = { id: "author", role: "Admin" },
|
||||
reviewer = { id: "reviewer", role: "SUPER_ADMIN" };
|
||||
async function proposal(queue = true, budget = 20) {
|
||||
let t = await workflow.create(
|
||||
{
|
||||
key: randomUUID(),
|
||||
title: "deterministic tracer",
|
||||
department: "TEST",
|
||||
operationMode: "PREPARE",
|
||||
budgetLimitCents: budget,
|
||||
metadata: {
|
||||
commitSha: "a".repeat(40),
|
||||
scope: "Harmless tracer only",
|
||||
acceptanceCriteria: ["writes deterministic JSON; no release"],
|
||||
},
|
||||
},
|
||||
owner,
|
||||
);
|
||||
if (queue) {
|
||||
t = await workflow.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: "GATE1_PENDING",
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: randomUUID(),
|
||||
},
|
||||
owner,
|
||||
);
|
||||
t = await workflow.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: "APPROVED",
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: randomUUID(),
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
t = await workflow.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: "READY",
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: randomUUID(),
|
||||
},
|
||||
owner,
|
||||
);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
async function post(route: string, body: any = {}, secret = token) {
|
||||
const r = await fetch(base + "/internal/prepare-worker/" + route, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: "Bearer " + secret,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { status: r.status, body: await r.json() };
|
||||
}
|
||||
it("rejects overlapping worker and CI grants and accepts no credentials when disabled", async () => {
|
||||
expect(() =>
|
||||
WorkerTransportModule.register({
|
||||
enabled: true,
|
||||
grants: [
|
||||
{
|
||||
id: "both",
|
||||
role: "WORKFLOW_WORKER",
|
||||
credentialSha256: digest(token),
|
||||
},
|
||||
],
|
||||
workerIds: ["both"],
|
||||
stageCiIds: ["both"],
|
||||
artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts",
|
||||
}),
|
||||
).toThrow(/overlapping/);
|
||||
const mod = await Test.createTestingModule({
|
||||
imports: [
|
||||
WorkerTransportModule.register({
|
||||
enabled: false,
|
||||
grants: [],
|
||||
workerIds: [],
|
||||
stageCiIds: [],
|
||||
artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts",
|
||||
}),
|
||||
],
|
||||
})
|
||||
.overrideProvider(PrismaService)
|
||||
.useValue(db)
|
||||
.compile();
|
||||
const disabled = mod.createNestApplication();
|
||||
await disabled.listen(0, "127.0.0.1");
|
||||
try {
|
||||
const r = await fetch(
|
||||
(await disabled.getUrl()) + "/internal/prepare-worker/claim",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: "Bearer " + token,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ taskId: randomUUID() }),
|
||||
},
|
||||
);
|
||||
expect(r.status).toBe(403);
|
||||
} finally {
|
||||
await disabled.close();
|
||||
}
|
||||
});
|
||||
it("rejects unsafe artifact bases and freezes validated configuration", () => {
|
||||
const config = { enabled: true, grants: [], workerIds: [], stageCiIds: [], artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts" };
|
||||
for (const artifactBaseUrl of ["https://user:pass@isolated.invalid/internal/prepare-worker/artifacts", "https://127.0.0.1/internal/prepare-worker/artifacts", "https://10.1.2.3/internal/prepare-worker/artifacts", "https://localhost/internal/prepare-worker/artifacts", "https://isolated.invalid/arbitrary", "https://isolated.invalid/x/../internal/prepare-worker/artifacts", "https://[::1]/internal/prepare-worker/artifacts"]) {
|
||||
expect(() => WorkerTransportModule.register({ ...config, artifactBaseUrl })).toThrow();
|
||||
}
|
||||
const registered = WorkerTransportModule.register(config);
|
||||
const snapshot = (registered.providers as any[]).find(p => p.useValue?.artifactBaseUrl)?.useValue;
|
||||
expect(Object.isFrozen(snapshot)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.workerIds)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.grants)).toBe(true);
|
||||
const workflowConfig = (registered.providers as any[]).find(p => p.provide === "PREPARE_WORKFLOW_CONFIG").useValue;
|
||||
expect(Object.isFrozen(workflowConfig)).toBe(true);
|
||||
expect(() => WorkerTransportModule.register({ ...config, enabled: "true" as any })).toThrow();
|
||||
});
|
||||
it("denies untrusted identities and body impersonation; dispatches nothing before Gate1", async () => {
|
||||
const t = await proposal(false);
|
||||
expect((await post("claim", {}, "wrong")).status).toBe(401);
|
||||
expect((await post("claim", { taskId: t.id }, ciToken)).status).toBe(403);
|
||||
expect(
|
||||
(await post("claim", { taskId: t.id, actorId: "pilot" })).status,
|
||||
).toBe(400);
|
||||
expect((await post("claim", { taskId: t.id })).body).toEqual({
|
||||
lease: null,
|
||||
});
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
0,
|
||||
);
|
||||
});
|
||||
it("races claims, fences expired leases and reserves unknown cost against the 20 cent cap", async () => {
|
||||
const t = await proposal();
|
||||
const claims = await Promise.all([
|
||||
post("claim", { taskId: t.id }),
|
||||
post("claim", { taskId: t.id }),
|
||||
]);
|
||||
const leases = claims.map((r) => r.body.lease).filter(Boolean);
|
||||
expect(leases).toHaveLength(1);
|
||||
const lease = leases[0],
|
||||
binding = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
leaseToken: lease.leaseToken,
|
||||
};
|
||||
expect(
|
||||
(await post("heartbeat", { ...binding, leaseToken: randomUUID() }))
|
||||
.status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await post("complete", {
|
||||
...binding,
|
||||
report: "arbitrary shell or prompt",
|
||||
})
|
||||
).status,
|
||||
).toBe(400);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}", actualCents: 21 }))
|
||||
.status,
|
||||
).toBe(400);
|
||||
await db.prepareWorkflowOutbox.update({
|
||||
where: { taskId: t.id },
|
||||
data: { leaseUntil: new Date(Date.now() - 1000) },
|
||||
});
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect((await post("claim", { taskId: t.id })).status).toBe(403);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
})
|
||||
)._sum.amountCents,
|
||||
).toBe(20);
|
||||
const larger = await proposal(true, 40);
|
||||
expect((await post("claim", { taskId: larger.id })).status).toBe(403);
|
||||
});
|
||||
it("rechecks kill switch and task interrupt on heartbeat and completion; separates CI authority", async () => {
|
||||
const t = await proposal(),
|
||||
lease = (await post("claim", { taskId: t.id })).body.lease;
|
||||
const binding = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
leaseToken: lease.leaseToken,
|
||||
};
|
||||
await db.orchestrationKillSwitch.upsert({
|
||||
where: { scope: "GLOBAL" },
|
||||
create: {
|
||||
scope: "GLOBAL",
|
||||
level: "STOP_AGENTS",
|
||||
active: true,
|
||||
reason: "isolated test",
|
||||
actorId: "test",
|
||||
},
|
||||
update: { level: "STOP_AGENTS", active: true },
|
||||
});
|
||||
try {
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect((await post("claim", { taskId: t.id })).status).toBe(403);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: t.id },
|
||||
data: { state: "CANCELLED" },
|
||||
});
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
await db.orchestrationArtifact.count({ where: { runId: lease.runId } }),
|
||||
).toBe(0);
|
||||
const evidence = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
commitSha: "a".repeat(40),
|
||||
sha256: "b".repeat(64),
|
||||
evidenceSha256: "c".repeat(64),
|
||||
uri: "https://isolated.invalid/not-real-ci",
|
||||
};
|
||||
expect((await post("stage-evidence", evidence)).status).toBe(403);
|
||||
expect((await post("stage-evidence", evidence, ciToken)).status).toBe(
|
||||
403,
|
||||
);
|
||||
});
|
||||
it("never follows or overwrites preexisting artifact links on completion", async () => {
|
||||
const t = await proposal();
|
||||
const lease = (await post("claim", { taskId: t.id })).body.lease;
|
||||
const report = tracerReport(lease), hash = digest(report);
|
||||
const target = join(directory, "sentinel");
|
||||
await writeFile(target, "do not overwrite");
|
||||
const file = join(directory, hash + ".json");
|
||||
await symlink(target, file);
|
||||
const result = await post("complete", { taskId: t.id, runId: lease.runId, leaseToken: lease.leaseToken, report });
|
||||
expect(await readFile(target, "utf8")).toBe("do not overwrite");
|
||||
expect(result.status).toBe(409);
|
||||
expect(await db.orchestrationArtifact.count({ where: { runId: lease.runId } })).toBe(0);
|
||||
await rm(file);
|
||||
await link(target, file);
|
||||
expect((await post("complete", { taskId: t.id, runId: lease.runId, leaseToken: lease.leaseToken, report })).status).toBe(409);
|
||||
expect(await readFile(target, "utf8")).toBe("do not overwrite");
|
||||
});
|
||||
it("runs actual HTTP deterministic executor to VERIFYING with retrievable content-addressed artifact", async () => {
|
||||
const t = await proposal();
|
||||
const result = await pilot.runOnce({
|
||||
baseUrl: base,
|
||||
credential: token,
|
||||
taskId: t.id,
|
||||
allowLoopbackHttp: true,
|
||||
});
|
||||
expect(result.state).toBe("VERIFYING");
|
||||
const row = await db.orchestrationTask.findUniqueOrThrow({
|
||||
where: { id: t.id },
|
||||
});
|
||||
expect(row.state).toBe("VERIFYING");
|
||||
const artifact = await db.orchestrationArtifact.findFirstOrThrow({
|
||||
where: { run: { taskId: t.id } },
|
||||
});
|
||||
const bytes = await readFile(join(directory, artifact.sha256 + ".json"));
|
||||
expect(digest(bytes.toString())).toBe(artifact.sha256);
|
||||
expect(JSON.parse(bytes.toString())).toMatchObject({
|
||||
kind: "DETERMINISTIC_PREPARE_TRACER",
|
||||
commitSha: "a".repeat(40),
|
||||
environment: "staging",
|
||||
llmPilot: false,
|
||||
});
|
||||
const get = await fetch(
|
||||
base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + token } },
|
||||
);
|
||||
expect(get.status).toBe(200);
|
||||
expect(await get.text()).toBe(bytes.toString());
|
||||
const artifactGet = (secret: string) => fetch(base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + secret } });
|
||||
expect((await artifactGet("other-worker-secret-".repeat(3))).status).toBe(404);
|
||||
expect((await artifactGet(ciToken)).status).toBe(200);
|
||||
const foreignHash = digest("{}");
|
||||
await writeFile(join(directory, foreignHash + ".json"), "{}");
|
||||
await db.orchestrationArtifact.create({ data: { runId: artifact.runId, kind: "QA", sha256: foreignHash, uri: "https://foreign.invalid/" + foreignHash } });
|
||||
expect((await fetch(base + "/internal/prepare-worker/artifacts/" + foreignHash, { headers: { authorization: "Bearer " + token } })).status).toBe(404);
|
||||
const moved = directory + "-moved";
|
||||
await rename(directory, moved);
|
||||
try {
|
||||
await symlink(moved, directory);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
} finally { await rm(directory, { force: true }); await rename(moved, directory); }
|
||||
const file = join(directory, artifact.sha256 + ".json"), saved = file + ".saved";
|
||||
await rename(file, saved);
|
||||
try {
|
||||
await symlink(saved, file);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
await rm(file);
|
||||
await link(saved, file);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
await rm(file);
|
||||
} finally { await rm(file, { force: true }); await rename(saved, file); }
|
||||
const cost = await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
expect(cost._sum.amountCents).toBe(0);
|
||||
expect(
|
||||
await db.orchestrationAttestation.findFirst({
|
||||
where: { run: { taskId: t.id }, kind: "STAGE" },
|
||||
}),
|
||||
).toBeNull();
|
||||
const evidence = {
|
||||
taskId: t.id,
|
||||
state: row.state,
|
||||
sha256: artifact.sha256,
|
||||
artifact: JSON.parse(bytes.toString()),
|
||||
httpGet: get.status,
|
||||
costCents: cost._sum.amountCents,
|
||||
uriExternalReachability: "NOT_TESTED_ISOLATED_FIXTURE_HOST",
|
||||
};
|
||||
console.log("TRACER_EVIDENCE", JSON.stringify(evidence));
|
||||
if (process.env.TRACER_EVIDENCE_PATH)
|
||||
await writeFile(
|
||||
process.env.TRACER_EVIDENCE_PATH,
|
||||
JSON.stringify(evidence, null, 2),
|
||||
);
|
||||
await writeFile(
|
||||
join(directory, artifact.sha256 + ".json"),
|
||||
'{"tampered":true}',
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await fetch(
|
||||
base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + token } },
|
||||
)
|
||||
).status,
|
||||
).toBe(409);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,43 @@
|
||||
# Bounded Stage PREPARE workflow foundation
|
||||
|
||||
This slice is NOT a runtime executor, deployment mechanism, or full v4 completion. It enables authenticated proposal/Gate1/queue APIs and provides internal worker/CI service methods. Default worker/CI identity allowlists are empty: no browser or production execution route exists.
|
||||
|
||||
## Panel HTTP contract
|
||||
All routes require existing JWT authentication with `Admin` or `SUPER_ADMIN`. Actor is exclusively `req.user.id ?? req.user.sub`, role exclusively `req.user.role`. Top-level unknown mutation fields return 400; client actor/profile fields are never trusted.
|
||||
|
||||
Base `/admin/orchestration`:
|
||||
|
||||
- `GET /tasks`: task array.
|
||||
- `GET /tasks/:id`: task object.
|
||||
- `GET /overview`: existing inventory items plus capabilities `{mutations:true, prepare:true, release:false, gate2Decisions:false, chat:false, runtime:false}`, reason `bounded_stage_prepare_only`.
|
||||
- `POST /tasks`: existing CreateOrchestrationTaskDto `{key,title,department,operationMode:"PREPARE",budgetLimitCents,metadata:{commitSha,scope,acceptanceCriteria}}`; commitSha is required lowercase 40hex; scope is a non-blank string of at most 2000 characters; acceptanceCriteria is 1..20 non-blank strings of at most 500 characters each; budget is integer 20..10000 cents. Returns 201 projected task, state DRAFT/version1. Validated scope and acceptance criteria are persisted exactly and remain unchanged by workflow transitions. The internal `workflowScope:"STAGE_PREPARE"`, environment and createdBy are server-owned; input profile/actor/other arbitrary keys are discarded. Key max120, title max255, department max50. Proposal key is unique; sequential or concurrent duplicate keys return 409, without updating the original task or appending another proposal event. Fetch/reconcile the existing task rather than retry blindly.
|
||||
- `PUT /tasks/:id/transition`: `{toState:"GATE1_PENDING"|"READY",expectedVersion,idempotencyKey,reason?}`. Only DRAFT->GATE1_PENDING and GATE1_APPROVED->READY. Owner or SUPER_ADMIN. Returns 200 projected task. READY atomically creates dispatch outbox. Requires unexpired Gate1.
|
||||
- `POST /tasks/:id/gates/1/decide`: existing GateDecisionDto `{decision:"APPROVED"|"REJECTED",expectedVersion,idempotencyKey,expiresAt,notes?}`. SUPER_ADMIN independent from proposer. Future expiry <=24h. Returns 201 **projected task**, not decision object.
|
||||
- Gate2 decision, budget writes/reconcile, command routes (including release), chat and kill-switch HTTP mutations remain 403. Runtime resource reads remain 503.
|
||||
|
||||
Task projection keeps existing scalar fields and safe nested runs/artifacts, decisions, events and ledger. Adds only `metadata:{scope,acceptanceCriteria,environment:"staging",commitSha}` for bounded proposals, otherwise `{}`. Never includes createdBy, workflowScope, payloads, URI, signatures, tokens or lease credentials. Pre-fix rows with the legacy scope sentinel remain readable/operable but have no recovered acceptance criteria: do not represent those as complete immutable scope review evidence.
|
||||
|
||||
`availableActions:string[]` is state/identity-derived: DRAFT owner -> `SUBMIT_GATE1`; GATE1_PENDING independent SUPER_ADMIN -> `APPROVE_GATE1`,`REJECT_GATE1`; GATE1_APPROVED owner/SUPER_ADMIN -> `QUEUE_PREPARE`; all worker/verification/Gate2 and legacy states -> `[]`. Actions indicate workflow eligibility, not a guarantee: current kill switch, approval expiry and concurrent versions are rechecked transactionally on mutation. Panel must not infer actions from state or send actor identity.
|
||||
|
||||
Common errors: 400 invalid DTO/binding; 403 wrong scope/identity/independence/kill/budget/expiry; 409 duplicate proposal key, stale version or idempotency payload mismatch. Transition/decision replay returns current persisted task and does not duplicate side effects.
|
||||
|
||||
## Internal service contracts (NOT browser endpoints)
|
||||
`PrepareWorkflowService` is exported by OrchestrationModule. Trusted backend composition must override `PREPARE_WORKFLOW_CONFIG` with explicit `workerIds` and `stageCiIds`, default both empty. Do not populate from request bodies or user-selected runtime profiles. Worker identities require role WORKFLOW_WORKER AND ID allowlist; Stage identities require STAGE_CI AND separate ID allowlist. Credential/session provisioning and transport remain the integrating runtime owner's responsibility.
|
||||
|
||||
- `claim(identity, taskId?) -> null | {taskId,runId,attempt,leaseToken,leaseUntil,commitSha,environment:"staging",maxCostCents:20}`. Transactional task row lock with SKIP LOCKED, immutable run binding, 30s lease, max3 attempts. Each attempt reserves **a fixed hard upper bound of 20 cents**, not an estimated or measured departmental cost. Unknown cost on expired attempts remains reserved conservatively.
|
||||
- `heartbeat(identity,{taskId,runId,leaseToken}) -> {leaseUntil}`. Same owner/token, unexpired active lease required.
|
||||
- `complete(identity,{taskId,runId,leaseToken,sha256,uri,actualCents}) -> task`. QA success ingestion only; lowercase sha256, HTTPS URI, actual cost integer0..20 from trusted worker. Atomically records immutable QA artifact/attestation, SUCCEEDED run, reservation reconciliation, DONE outbox and VERIFYING task. Expired/stale/foreign token cannot finish. Not replayable after success; caller must read persisted task/run after response loss.
|
||||
- `stageEvidence(identity,{taskId,runId,sha256,commitSha,evidenceSha256,uri}) -> task`. Independently allowlisted Stage CI identity, successful exact staging commit/run, registered QA subject, independent QA signer. Atomically records Stage artifact/attestation and reaches GATE2_PENDING. No release or Gate2 approval. Does not perform or claim deployment itself. Caller supplies actual trusted CI evidence, not browser assertions.
|
||||
|
||||
## Verification and explicit gaps
|
||||
Real isolated PostgreSQL16, no published ports/no live volumes. Added migrations applied with ON_ERROR_STOP. TDD RED logs cover missing workflow behavior, heartbeat/QA behavior and HTTP enablement. Full backend regression excluding existing legacy release-containing orchestration.integration.spec: 106 suites /851 tests including seven real-DB workflow cases, build exit0. No RELEASE_AUTHORIZE service operation executed.
|
||||
|
||||
DB regressions: concurrent claim winner, queue race/replay mismatch, hard budget rollback, stale lease fencing, max3 attempts, conservative expired costs, kill switch, self approval, trusted IDs, QA reconciliation and Stage evidence to Gate2 pending. Test fixture artifact URIs/hashes are not real deployment evidence.
|
||||
|
||||
Remaining: actual authenticated runtime worker transport/executor and pinned CI evidence transport; shared department/company budget model and locking (NOT implemented or represented by fake totals); retry backoff/dead-letter UX/cancellation; hard total execution wall-time; durable request replay of completion/evidence; kill-switch concurrent insertion/version locking; migration rehearsal with full legacy schema; real Stage CI artifact/deployment verification. No push/deploy/live DB/runtime edits. Production release remains denied at HTTP boundary; unsafe legacy core release method is deliberately untouched and must never be called by this slice.
|
||||
|
||||
## Contract repair verification
|
||||
|
||||
Actual frontend inspection confirmed proposal submission sent human scope and acceptanceCriteria but omitted required commitSha. Frontend repair is separately assigned; no frontend file changed here. New proposals now require all three fields. Internal Stage restriction uses a separate server-owned workflowScope marker rather than overwriting user scope. No metadata update route exists in this bounded workflow.
|
||||
|
||||
TDD RED→GREEN against isolated PostgreSQL16 reproduced dropped scope/criteria, nine invalid metadata acceptances (including array-to-string commit coercion), and duplicate-key P2002 leakage. Final database suite: 24 cases, including authenticated HTTP create/list/detail persistence, 400 validation, and 409 duplicate responses. Full allowed backend regression: 106 suites / 868 tests passed; legacy orchestration.integration.spec.ts excluded to avoid executing RELEASE_AUTHORIZE. Build exit0. Scoped lint remains failing on inherited require-await/no-unnecessary-type-assertion errors (13 errors); no lint suppression or config change applied. Disposable DB only; no live edits/push/deploy.
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsEnum,
|
||||
IsHash,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { OperationMode, WorkflowState } from '../orchestration.domain';
|
||||
export class CreateOrchestrationTaskDto {
|
||||
@IsString() @IsNotEmpty() key!: string;
|
||||
@IsString() @IsNotEmpty() title!: string;
|
||||
@IsString() @IsNotEmpty() department!: string;
|
||||
@IsEnum(OperationMode) operationMode!: OperationMode;
|
||||
@Type(() => Number) @IsInt() @Min(0) budgetLimitCents!: number;
|
||||
@IsOptional() metadata?: Record<string, unknown>;
|
||||
}
|
||||
export class TransitionTaskDto {
|
||||
@IsEnum(WorkflowState) toState!: WorkflowState;
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsOptional() @IsString() reason?: string;
|
||||
}
|
||||
export class GateDecisionDto {
|
||||
@IsIn(['APPROVED', 'REJECTED']) decision!: 'APPROVED' | 'REJECTED';
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsISO8601() expiresAt!: string;
|
||||
@IsOptional() @IsString() notes?: string;
|
||||
@IsOptional() @IsString() runId?: string;
|
||||
@IsOptional() @IsHash('sha256') artifactHash?: string;
|
||||
@IsOptional() @IsString() commitSha?: string;
|
||||
@IsOptional() @IsString() environment?: string;
|
||||
}
|
||||
export class RecordBudgetDto {
|
||||
@Type(() => Number) @IsInt() @Min(1) amountCents!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsString() @IsNotEmpty() kind!: string;
|
||||
@IsOptional() metadata?: Record<string, unknown>;
|
||||
}
|
||||
export class SetKillSwitchDto {
|
||||
@IsIn([
|
||||
'FREEZE_NEW_WORK',
|
||||
'STOP_AGENTS',
|
||||
'DISABLE_MUTATIONS',
|
||||
'EMERGENCY_HALT',
|
||||
])
|
||||
level!: string;
|
||||
@IsString() @IsNotEmpty() reason!: string;
|
||||
}
|
||||
|
||||
export class ReconcileBudgetDto {
|
||||
@IsString() @IsNotEmpty() reservationId!: string;
|
||||
@Type(() => Number) @IsInt() @Min(0) actualCents!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
}
|
||||
export class OrchestrationCommandDto {
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsOptional() @IsString() commitSha?: string;
|
||||
@IsOptional()
|
||||
@IsIn(['development', 'staging', 'production'])
|
||||
environment?: string;
|
||||
@IsOptional() @IsString() runId?: string;
|
||||
@IsOptional() @IsString() approvalId?: string;
|
||||
@IsOptional() @IsString() dependsOnTaskId?: string;
|
||||
@IsOptional() @IsIn(['SUCCEEDED', 'FAILED']) status?: string;
|
||||
@IsOptional()
|
||||
@IsIn([
|
||||
'TRANSIENT',
|
||||
'RATE_LIMITED',
|
||||
'DEPENDENCY',
|
||||
'VALIDATION',
|
||||
'POLICY',
|
||||
'PERMANENT',
|
||||
])
|
||||
retryClass?: string;
|
||||
@IsOptional() @IsHash('sha256') sha256?: string;
|
||||
@IsOptional() @IsHash('sha256') artifactHash?: string;
|
||||
@IsOptional() @IsHash('sha256') subjectHash?: string;
|
||||
@IsOptional() @IsString() kind?: string;
|
||||
@IsOptional() @IsString() uri?: string;
|
||||
@IsOptional() predicate?: Record<string, unknown>;
|
||||
@IsOptional() @IsString() signature?: string;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
|
||||
describe('KillSwitchService', () => {
|
||||
const prisma = { orchestrationKillSwitch: { findUnique: jest.fn() } };
|
||||
const service = new KillSwitchService(prisma as never);
|
||||
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it.each([
|
||||
['FREEZE_NEW_WORK', 'CREATE_TASK'],
|
||||
['STOP_AGENTS', 'RUN_AGENT'],
|
||||
['DISABLE_MUTATIONS', 'MUTATE_PRODUCTION'],
|
||||
['EMERGENCY_HALT', 'OBSERVE'],
|
||||
])('blocks %s at its policy boundary', async (level, action) => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({
|
||||
scope: 'GLOBAL',
|
||||
level,
|
||||
active: true,
|
||||
});
|
||||
await expect(service.assertAllowed(action as never)).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
|
||||
it('freezes new claims while allowing an already running agent to finish', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({scope:'GLOBAL',level:'FREEZE_NEW_WORK',active:true});
|
||||
await expect(service.assertAllowed('CLAIM_TASK' as never)).rejects.toThrow(ForbiddenException);
|
||||
await expect(service.assertAllowed('RUN_AGENT')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails closed when an active persisted kill level is unknown', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({scope:'GLOBAL',level:'CORRUPT_LEVEL',active:true});
|
||||
await expect(service.assertAllowed('RUN_AGENT')).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('allows observation while production mutations are disabled', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({
|
||||
scope: 'GLOBAL',
|
||||
level: 'DISABLE_MUTATIONS',
|
||||
active: true,
|
||||
});
|
||||
await expect(service.assertAllowed('OBSERVE')).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { KillSwitchLevel } from './orchestration.domain';
|
||||
export type GuardedAction =
|
||||
| 'CREATE_TASK'
|
||||
| 'CLAIM_TASK'
|
||||
| 'RUN_AGENT'
|
||||
| 'MUTATE_PRODUCTION'
|
||||
| 'OBSERVE';
|
||||
@Injectable()
|
||||
export class KillSwitchService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async assertAllowed(action: GuardedAction): Promise<void> {
|
||||
const state = await (this.prisma as any).orchestrationKillSwitch.findUnique(
|
||||
{ where: { scope: 'GLOBAL' } },
|
||||
);
|
||||
if (!state?.active) return;
|
||||
const blocked: Record<KillSwitchLevel, GuardedAction[]> = {
|
||||
FREEZE_NEW_WORK: ['CREATE_TASK', 'CLAIM_TASK'],
|
||||
STOP_AGENTS: ['CREATE_TASK', 'CLAIM_TASK', 'RUN_AGENT'],
|
||||
DISABLE_MUTATIONS: ['CREATE_TASK', 'CLAIM_TASK', 'RUN_AGENT', 'MUTATE_PRODUCTION'],
|
||||
EMERGENCY_HALT: [
|
||||
'CREATE_TASK',
|
||||
'CLAIM_TASK',
|
||||
'RUN_AGENT',
|
||||
'MUTATE_PRODUCTION',
|
||||
'OBSERVE',
|
||||
],
|
||||
};
|
||||
if (!Object.values(KillSwitchLevel).includes(state.level) ||
|
||||
blocked[state.level as KillSwitchLevel].includes(action))
|
||||
throw new ForbiddenException(
|
||||
`Orchestration kill switch ${state.level} blocks ${action}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
describe('orchestration migration safety', () => {
|
||||
it('is additive and never mutates legacy governance tables', () => {
|
||||
const sql = readFileSync(
|
||||
join(
|
||||
process.cwd(),
|
||||
'prisma/migrations/20261022000000_add_orchestration_v4_core/migration.sql',
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
expect(sql).not.toMatch(/^\s*(DROP|TRUNCATE|DELETE|UPDATE)\b/im);
|
||||
expect(sql).not.toMatch(
|
||||
/ALTER TABLE "(approval_requests|department_tasks|audit_logs)"/i,
|
||||
);
|
||||
expect(sql.match(/CREATE TABLE "orchestration_/g)).toHaveLength(9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
|
||||
describe('ModelTierPolicyService', () => {
|
||||
const policy = new ModelTierPolicyService();
|
||||
|
||||
it.each([
|
||||
[
|
||||
{
|
||||
complexity: 0,
|
||||
risk: 0,
|
||||
operationMode: 'OBSERVE',
|
||||
remainingBudgetCents: 1,
|
||||
},
|
||||
'L0',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 2,
|
||||
risk: 1,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 100,
|
||||
},
|
||||
'L1',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 5,
|
||||
risk: 4,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 500,
|
||||
},
|
||||
'L2',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 7,
|
||||
risk: 7,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 1500,
|
||||
},
|
||||
'L3',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 9,
|
||||
risk: 9,
|
||||
operationMode: 'MUTATE_PRODUCTION',
|
||||
remainingBudgetCents: 5000,
|
||||
},
|
||||
'L4',
|
||||
],
|
||||
])('selects a deterministic tier for policy inputs', (input, expected) => {
|
||||
expect(policy.select(input as never)).toBe(expected);
|
||||
expect(policy.select(input as never)).toBe(expected);
|
||||
});
|
||||
|
||||
it('fails closed when the selected tier exceeds the remaining hard budget', () => {
|
||||
expect(() =>
|
||||
policy.select({
|
||||
complexity: 9,
|
||||
risk: 9,
|
||||
operationMode: 'MUTATE_PRODUCTION',
|
||||
remainingBudgetCents: 100,
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { OperationMode } from './orchestration.domain';
|
||||
export type ModelTier = 'L0' | 'L1' | 'L2' | 'L3' | 'L4';
|
||||
@Injectable()
|
||||
export class ModelTierPolicyService {
|
||||
select(input: {
|
||||
complexity: number;
|
||||
risk: number;
|
||||
operationMode: OperationMode | string;
|
||||
remainingBudgetCents: number;
|
||||
}): ModelTier {
|
||||
const score =
|
||||
Math.max(input.complexity, input.risk) +
|
||||
(String(input.operationMode) === String(OperationMode.MUTATE_PRODUCTION)
|
||||
? 1
|
||||
: 0);
|
||||
const tier: ModelTier =
|
||||
score <= 1
|
||||
? 'L0'
|
||||
: score <= 3
|
||||
? 'L1'
|
||||
: score <= 5
|
||||
? 'L2'
|
||||
: score <= 8
|
||||
? 'L3'
|
||||
: 'L4';
|
||||
const floor: Record<ModelTier, number> = {
|
||||
L0: 1,
|
||||
L1: 25,
|
||||
L2: 100,
|
||||
L3: 500,
|
||||
L4: 2000,
|
||||
};
|
||||
if (input.remainingBudgetCents < floor[tier])
|
||||
throw new BadRequestException(
|
||||
`Hard budget cannot fund selected model tier ${tier}`,
|
||||
);
|
||||
return tier;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('integration read boundary', () => {
|
||||
let app: INestApplication;
|
||||
const task = {
|
||||
id: 't1',
|
||||
key: 'k',
|
||||
title: 'Review',
|
||||
department: 'SEO',
|
||||
state: 'GATE2_APPROVED',
|
||||
version: 1,
|
||||
operationMode: 'PREPARE',
|
||||
budgetLimitCents: 0,
|
||||
metadata: { token: 'secret' },
|
||||
runs: [
|
||||
{
|
||||
id: 'r',
|
||||
status: 'VERIFIED',
|
||||
commitSha: 'abc',
|
||||
environment: 'stage',
|
||||
artifacts: [
|
||||
{
|
||||
id: 'a',
|
||||
sha256: 'f'.repeat(64),
|
||||
sizeBytes: 1n,
|
||||
uri: 'secret-uri',
|
||||
metadata: { token: 'secret' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
events: [
|
||||
{
|
||||
id: 'e',
|
||||
eventType: 'CREATED',
|
||||
sequence: 1,
|
||||
payload: { token: 'secret' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const service = {
|
||||
findAll: jest.fn(() => Promise.resolve([task])),
|
||||
findOne: jest.fn(() => Promise.resolve(task)),
|
||||
createTask: jest.fn(),
|
||||
transition: jest.fn(),
|
||||
decideGate: jest.fn(),
|
||||
recordBudget: jest.fn(),
|
||||
setKillSwitch: jest.fn(),
|
||||
command: jest.fn(),
|
||||
reconcileBudget: jest.fn(),
|
||||
};
|
||||
beforeAll(async () => {
|
||||
const m = await Test.createTestingModule({
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
{ provide: OrchestrationService, useValue: service },
|
||||
RolesGuard,
|
||||
],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({
|
||||
canActivate(c: any) {
|
||||
const req = c.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = { id: 'verified-user', role: req.headers.authorization };
|
||||
return true;
|
||||
},
|
||||
})
|
||||
.compile();
|
||||
app = m.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
afterAll(async () => app.close());
|
||||
it('denies every mutation before legacy core is invoked', async () => {
|
||||
for (const [method, path] of [
|
||||
['post', 'tasks'],
|
||||
['put', 'tasks/t1/transition'],
|
||||
['post', 'tasks/t1/gates/2/decide'],
|
||||
['post', 'tasks/t1/budget'],
|
||||
['post', 'tasks/t1/commands/RUN_CREATE'],
|
||||
['post', 'tasks/t1/budget/reconcile'],
|
||||
['put', 'kill-switch'],
|
||||
['post', 'chat/messages'],
|
||||
] as const) {
|
||||
await request(app.getHttpServer())
|
||||
[method]('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.send({})
|
||||
.expect(path === 'tasks' || path.endsWith('/transition') ? 400 : 403);
|
||||
}
|
||||
for (const name of [
|
||||
'createTask',
|
||||
'transition',
|
||||
'decideGate',
|
||||
'recordBudget',
|
||||
'setKillSwitch',
|
||||
'command',
|
||||
'reconcileBudget',
|
||||
] as const)
|
||||
expect(service[name]).not.toHaveBeenCalled();
|
||||
});
|
||||
it('projects list and detail with no actions, arbitrary secrets or BigInt transport failures', async () => {
|
||||
for (const path of ['tasks', 'tasks/t1']) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
const t = Array.isArray(r.body) ? r.body[0] : r.body;
|
||||
expect(t.availableActions).toEqual([]);
|
||||
expect(t.budgetLimitCents).toBe(0);
|
||||
expect(JSON.stringify(t)).not.toMatch(/secret|sizeBytes|payload|token/);
|
||||
}
|
||||
});
|
||||
it('returns actual inventory overview and explicit unavailable runtime resources', async () => {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/overview')
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
expect(r.body.items).toEqual([
|
||||
expect.objectContaining({ id: 'tasks', count: 1 }),
|
||||
]);
|
||||
expect(r.body.capabilities).toMatchObject({
|
||||
mutations: false,
|
||||
chat: false,
|
||||
runtime: false,
|
||||
});
|
||||
for (const path of ['agents', 'schedules', 'model-policy'])
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(503);
|
||||
const releases = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/releases')
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
expect(releases.body.items[0]).toMatchObject({
|
||||
id: 'r',
|
||||
commitSha: 'abc',
|
||||
environment: 'stage',
|
||||
});
|
||||
});
|
||||
it('protects read surfaces from anonymous and customer access', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/overview')
|
||||
.expect(403);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/tasks')
|
||||
.set('Authorization', 'CUSTOMER')
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
Controller,
|
||||
Body,
|
||||
Req,
|
||||
Optional,
|
||||
ValidationPipe,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
ForbiddenException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import {
|
||||
PrepareWorkflowService,
|
||||
WorkflowIdentity,
|
||||
} from './prepare-workflow.service';
|
||||
import {
|
||||
CreateOrchestrationTaskDto,
|
||||
TransitionTaskDto,
|
||||
GateDecisionDto,
|
||||
} from './dto/orchestration.dto';
|
||||
const workflowValidation = new ValidationPipe({
|
||||
transform: true,
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
});
|
||||
|
||||
// Explicit response allowlists: never serialize arbitrary JSON, signatures, URIs or BigInt.
|
||||
function pick(row: any, keys: string[]) {
|
||||
return Object.fromEntries(
|
||||
keys.filter((k) => row[k] !== undefined).map((k) => [k, row[k]]),
|
||||
);
|
||||
}
|
||||
function project(row: any) {
|
||||
return {
|
||||
...pick(row, [
|
||||
'id',
|
||||
'key',
|
||||
'title',
|
||||
'department',
|
||||
'state',
|
||||
'version',
|
||||
'operationMode',
|
||||
'budgetLimitCents',
|
||||
]),
|
||||
availableActions: [],
|
||||
runs: (row.runs ?? []).map((run: any) => ({
|
||||
...pick(run, ['id', 'commitSha', 'environment', 'status']),
|
||||
artifacts: (run.artifacts ?? []).map((a: any) =>
|
||||
pick(a, ['id', 'kind', 'sha256']),
|
||||
),
|
||||
})),
|
||||
decisions: (row.decisions ?? []).map((d: any) =>
|
||||
pick(d, [
|
||||
'id',
|
||||
'gate',
|
||||
'decision',
|
||||
'expiresAt',
|
||||
'runId',
|
||||
'artifactHash',
|
||||
'commitSha',
|
||||
'environment',
|
||||
'createdAt',
|
||||
]),
|
||||
),
|
||||
events: (row.events ?? []).map((e: any) =>
|
||||
pick(e, [
|
||||
'id',
|
||||
'eventType',
|
||||
'fromState',
|
||||
'toState',
|
||||
'sequence',
|
||||
'createdAt',
|
||||
]),
|
||||
),
|
||||
budgetLedger: (row.budgetLedger ?? []).map((b: any) =>
|
||||
pick(b, ['id', 'amountCents', 'kind', 'createdAt']),
|
||||
),
|
||||
};
|
||||
}
|
||||
@ApiTags('Admin - Orchestration v4')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/orchestration')
|
||||
export class OrchestrationController {
|
||||
constructor(
|
||||
private readonly service: OrchestrationService,
|
||||
@Optional() private readonly workflow?: PrepareWorkflowService,
|
||||
) {}
|
||||
private actor(req: any): WorkflowIdentity {
|
||||
const id = req?.user?.id ?? req?.user?.sub;
|
||||
if (
|
||||
typeof id !== 'string' ||
|
||||
!id ||
|
||||
!['Admin', 'SUPER_ADMIN'].includes(req?.user?.role)
|
||||
)
|
||||
throw new ForbiddenException('Authenticated workflow identity required');
|
||||
return { id, role: req.user.role };
|
||||
}
|
||||
private safe(row: any, req: any) {
|
||||
const view = project(row);
|
||||
if (!this.workflow) return view;
|
||||
const w = this.workflow.project(row, this.actor(req));
|
||||
return {
|
||||
...view,
|
||||
metadata: w.metadata,
|
||||
availableActions: w.availableActions,
|
||||
};
|
||||
}
|
||||
@Get('tasks') async all(@Req() req: any) {
|
||||
return (await this.service.findAll()).map((row: any) =>
|
||||
this.safe(row, req),
|
||||
);
|
||||
}
|
||||
@Get('tasks/:id') async one(@Param('id') id: string, @Req() req: any) {
|
||||
return this.safe(await this.service.findOne(id), req);
|
||||
}
|
||||
@Get('overview') async overview() {
|
||||
const tasks = await this.service.findAll();
|
||||
return {
|
||||
items: [
|
||||
{ id: 'tasks', title: 'Persisted task inventory', count: tasks.length },
|
||||
],
|
||||
measuredAt: new Date().toISOString(),
|
||||
capabilities: {
|
||||
mutations: !!this.workflow,
|
||||
prepare: !!this.workflow,
|
||||
release: false,
|
||||
gate2Decisions: false,
|
||||
chat: false,
|
||||
runtime: false,
|
||||
},
|
||||
reason: this.workflow
|
||||
? 'bounded_stage_prepare_only'
|
||||
: 'security_hardening_pending',
|
||||
};
|
||||
}
|
||||
@Get('releases') async releases() {
|
||||
const tasks = await this.service.findAll();
|
||||
const details = await Promise.all(
|
||||
tasks.map((t: any) => this.service.findOne(t.id)),
|
||||
);
|
||||
return {
|
||||
items: details.flatMap((t: any) =>
|
||||
(t.runs ?? []).map((run: any) =>
|
||||
pick(run, ['id', 'status', 'commitSha', 'environment']),
|
||||
),
|
||||
),
|
||||
measuredAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
@Get('agents') agents() {
|
||||
throw new ServiceUnavailableException(
|
||||
'Hermes runtime unavailable: trusted identity and runtime authentication not configured',
|
||||
);
|
||||
}
|
||||
@Get('schedules') schedules() {
|
||||
throw new ServiceUnavailableException(
|
||||
'Hermes schedules unavailable; runtime remains disabled',
|
||||
);
|
||||
}
|
||||
@Get('model-policy') models() {
|
||||
throw new ServiceUnavailableException(
|
||||
'No persisted model policy read contract available',
|
||||
);
|
||||
}
|
||||
// Only the separate bounded PREPARE service is exposed; legacy commands remain denied.
|
||||
@Post('tasks') async create(
|
||||
@Body(workflowValidation) dto: CreateOrchestrationTaskDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow) return this.deny();
|
||||
return this.safe(await this.workflow.create(dto, this.actor(req)), req);
|
||||
}
|
||||
@Put('tasks/:id/transition') async transition(
|
||||
@Param('id') id: string,
|
||||
@Body(workflowValidation) dto: TransitionTaskDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow) return this.deny();
|
||||
return this.safe(
|
||||
await this.workflow.transition(id, dto, this.actor(req)),
|
||||
req,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/gates/:gate/decide') async decide(
|
||||
@Param('id') id: string,
|
||||
@Param('gate') gate: string,
|
||||
@Body() body: unknown,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow || gate !== '1') return this.deny();
|
||||
const dto = await workflowValidation.transform(body, {
|
||||
type: 'body',
|
||||
metatype: GateDecisionDto,
|
||||
});
|
||||
return this.safe(
|
||||
await this.workflow.decide(id, 1, dto, this.actor(req)),
|
||||
req,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/budget') budget() {
|
||||
return this.deny();
|
||||
}
|
||||
@Put('kill-switch') kill() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('chat/messages') chat() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/commands/:command') command() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/budget/reconcile') reconcile() {
|
||||
return this.deny();
|
||||
}
|
||||
private deny(): never {
|
||||
throw new ForbiddenException(
|
||||
'Orchestration mutations and chat disabled pending hardened core and trusted runtime integration',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
assertTransition,
|
||||
nextStateForGateDecision,
|
||||
OperationMode,
|
||||
WorkflowState,
|
||||
} from './orchestration.domain';
|
||||
|
||||
describe('orchestration domain', () => {
|
||||
it('allows only declared workflow transitions', () => {
|
||||
expect(() =>
|
||||
assertTransition(WorkflowState.DRAFT, WorkflowState.GATE1_PENDING),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
assertTransition(WorkflowState.DRAFT, WorkflowState.RUNNING),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('keeps gate 1 as execution authorization rather than release authorization', () => {
|
||||
expect(nextStateForGateDecision(1, 'APPROVED')).toBe(
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
);
|
||||
expect(nextStateForGateDecision(2, 'APPROVED')).toBe(
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an unsupported gate decision', () => {
|
||||
expect(() => nextStateForGateDecision(1, 'PENDING' as never)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([WorkflowState.GATE1_PENDING, WorkflowState.GATE2_PENDING])('does not revive an expired proposal into %s', (state) => {
|
||||
expect(() => assertTransition(WorkflowState.EXPIRED,state)).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('classifies production mutation separately from observe and prepare', () => {
|
||||
expect(OperationMode.OBSERVE).toBe('OBSERVE');
|
||||
expect(OperationMode.PREPARE).toBe('PREPARE');
|
||||
expect(OperationMode.MUTATE_PRODUCTION).toBe('MUTATE_PRODUCTION');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 348 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user