Compare commits
110
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc34c57a0c | ||
|
|
c97ea01ba9 | ||
|
|
00ba4360cf | ||
|
|
8669d183d5 | ||
|
|
66b9d75524 | ||
|
|
d3a0a61d79 | ||
|
|
0ad39bb92c | ||
|
|
0e952ef701 | ||
|
|
f1382e943c | ||
|
|
53fccc2d3c | ||
|
|
9ae839138c | ||
|
|
0fa6abc53d | ||
|
|
2a32f31097 | ||
|
|
52a7aebb51 | ||
|
|
af32ec14e1 | ||
|
|
e34156b2d3 | ||
|
|
721118787a | ||
|
|
292ed7f920 | ||
|
|
432f6a21c7 | ||
|
|
2087001ecd | ||
|
|
ec93af0064 | ||
|
|
effe30ee58 | ||
|
|
99f0c0d626 | ||
|
|
1e27387016 | ||
|
|
c733a806bd | ||
|
|
23cbd693a8 | ||
|
|
366bc9fc88 | ||
|
|
b4420e54b7 | ||
|
|
44d74d35e6 | ||
|
|
5897abcbad | ||
|
|
b3b9e617b5 | ||
|
|
6f9529d31f | ||
|
|
c25b10f7f3 | ||
|
|
c69a779ecc | ||
|
|
688a0e4de5 | ||
|
|
cf9b80bbb3 | ||
|
|
2a341d3969 | ||
|
|
9275233d09 | ||
|
|
13dceaa460 | ||
|
|
0ab2980ff4 | ||
|
|
fd14c05f3a | ||
|
|
cc0358bb12 | ||
|
|
f94ef580fb | ||
|
|
1bb6274b35 | ||
|
|
448c250944 | ||
|
|
5f5c3eb3b9 | ||
|
|
3805057923 | ||
|
|
f4678c48ca | ||
|
|
c40e931168 | ||
|
|
e96a13b255 | ||
|
|
4413c2ef6c | ||
|
|
65063e224a | ||
|
|
c8063b5f2a | ||
|
|
bfeb464bfb | ||
|
|
860324e3a9 | ||
|
|
f705511164 | ||
|
|
70a5449d35 | ||
|
|
80a2e188cf | ||
|
|
e036c5d436 | ||
|
|
ed77f87ab5 | ||
|
|
4712433903 | ||
|
|
f4add07780 | ||
|
|
01b6f1d3d7 | ||
|
|
60a4e14b4b | ||
|
|
6e465663bd | ||
|
|
b1142bd0c0 | ||
|
|
50d0df822c | ||
|
|
ab2f330eb8 | ||
|
|
ca3d4f6a16 | ||
|
|
3321bac22d | ||
|
|
3e78b89cc1 | ||
|
|
bfb1841370 | ||
|
|
6ba2c51403 | ||
|
|
ba0aa5ee4e | ||
|
|
7485c89e9b | ||
|
|
8869ce2583 | ||
|
|
64419f6755 | ||
|
|
8cedc2cd67 | ||
|
|
65a6fe1f0c | ||
|
|
afbee9cf70 | ||
|
|
5984242ce4 | ||
|
|
c523acc9e8 | ||
|
|
c78bdbcdb5 | ||
|
|
7a081e28df | ||
|
|
93d43fb261 | ||
|
|
8c435ab09e | ||
|
|
4388a5c2e6 | ||
|
|
62a7a87378 | ||
|
|
19583c5ad8 | ||
|
|
1858eba3e6 | ||
|
|
cb20c2acb5 | ||
|
|
105ab07fbd | ||
|
|
bf84e5da43 | ||
|
|
02badd0e25 | ||
|
|
aa23c7ef91 | ||
|
|
4b147b0091 | ||
|
|
6950ff0d79 | ||
|
|
cc9ec25388 | ||
|
|
be2ff0719a | ||
|
|
9d93707848 | ||
|
|
aa99216c49 | ||
|
|
58d3794050 | ||
|
|
16f9610027 | ||
|
|
2023dd4e36 | ||
|
|
0bed6e0313 | ||
|
|
f29ba4ab8b | ||
|
|
56b6696ca3 | ||
|
|
0d0c67704c | ||
|
|
09e8a890e0 | ||
|
|
4b17a6fcc3 |
No files matched your search
@@ -12,3 +12,7 @@ uploads
|
||||
**/uploads
|
||||
*.pdf
|
||||
graphify-out
|
||||
**/.revalidation.env*
|
||||
**/.support*.env*
|
||||
**/*runtime.env
|
||||
**/release.override.json
|
||||
@@ -5,6 +5,7 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
- release/blog-timestamp-limited-20261030
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
@@ -12,11 +13,23 @@ jobs:
|
||||
steps:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_REF: ${{ github.ref }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set -eu
|
||||
case "${DEPLOY_REF}" in
|
||||
refs/heads/main) BRANCH=main; STAGE_SOURCE_REF= ;;
|
||||
refs/heads/develop|refs/heads/release/blog-timestamp-limited-20261030)
|
||||
BRANCH=develop; STAGE_SOURCE_REF="$DEPLOY_REF" ;;
|
||||
*) printf 'Unsupported deployment ref\n' >&2; exit 2 ;;
|
||||
esac
|
||||
# Bind downloads and both release dispatchers to the exact event commit.
|
||||
case "$DEPLOY_SHA" in
|
||||
*[!0-9a-f]*|'') exit 2 ;;
|
||||
esac
|
||||
[ "${#DEPLOY_SHA}" -eq 40 ] || exit 2
|
||||
export BRANCH STAGE_SOURCE_REF
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
@@ -28,7 +41,9 @@ jobs:
|
||||
# 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
|
||||
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
|
||||
|
||||
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh "${BRANCH}"
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -1,24 +0,0 @@
|
||||
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.
|
||||
@@ -16,3 +16,7 @@ playwright-report/
|
||||
playwright/.auth/
|
||||
blob-report/
|
||||
|
||||
|
||||
# Python CI helpers must not dirty immutable release checkouts.
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
FROM node:20-alpine AS app-builder
|
||||
FROM node:22-alpine AS app-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
@@ -7,18 +7,17 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/application/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
|
||||
COPY frontend/application ./
|
||||
ARG NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS admin-builder
|
||||
FROM node:22-alpine AS admin-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV VITE_API_URL=https://api.canina.ir/api
|
||||
@@ -26,18 +25,17 @@ ENV VITE_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry (inherits build-arg)
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/admin-panel/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
|
||||
COPY frontend/admin-panel ./
|
||||
ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
FROM node:22-alpine
|
||||
USER root
|
||||
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
|
||||
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
|
||||
@@ -49,6 +47,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app .
|
||||
COPY --from=admin-builder /app/dist ./admin_static
|
||||
# Build-context umask must not make public assets unreadable by nginx workers.
|
||||
RUN chmod -R a+rX /app/admin_static
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||
|
||||
|
||||
+3
-2
@@ -12,7 +12,6 @@ ENV npm_config_cache=/tmp/npm-cache
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false && \
|
||||
echo "Using npm registry: $NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
@@ -32,8 +31,10 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
||||
FROM node:20-alpine
|
||||
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
|
||||
RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
||||
WORKDIR /app
|
||||
ARG STAGE_TEST_ARTIFACT_SHA=disabled
|
||||
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
|
||||
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
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
|
||||
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
|
||||
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
-- Drop legacy governance and orchestration tables
|
||||
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "department_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "audit_logs" CASCADE;
|
||||
DROP TABLE IF EXISTS "approval_requests" CASCADE;
|
||||
@@ -16,6 +16,9 @@ model User {
|
||||
mobile String @unique @db.VarChar(15)
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
||||
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
|
||||
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@ -1017,218 +1020,3 @@ model SmsCampaign {
|
||||
@@map("sms_campaigns")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 5. ApprovalRequest (CEO Governance & Decision Gate)
|
||||
// ------------------------------------------------------------------------------
|
||||
model ApprovalRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
department String @db.VarChar(50)
|
||||
category String @db.VarChar(50)
|
||||
title String @db.VarChar(255)
|
||||
payload Json @db.JsonB
|
||||
testContext Json? @map("test_context") @db.JsonB
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
ceoNotes String? @map("ceo_notes") @db.Text
|
||||
executedAt DateTime? @map("executed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([category])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("approval_requests")
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 6. AuditLog (System & Database Changes History)
|
||||
// ------------------------------------------------------------------------------
|
||||
model AuditLog {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
|
||||
entityId String? @map("entity_id") @db.VarChar(100)
|
||||
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
|
||||
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
actor String @default("SYSTEM") @db.VarChar(100)
|
||||
summary String @db.VarChar(255)
|
||||
oldValues Json? @map("old_values") @db.JsonB
|
||||
newValues Json? @map("new_values") @db.JsonB
|
||||
metadata Json? @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([entity])
|
||||
@@index([action])
|
||||
@@index([department])
|
||||
@@index([createdAt])
|
||||
@@map("audit_logs")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model DepartmentTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
title String @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE
|
||||
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL
|
||||
assignee String? @db.VarChar(100)
|
||||
acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB
|
||||
executionLogs Json? @map("execution_logs") @db.JsonB
|
||||
deliverableUrl String? @map("deliverable_url") @db.VarChar(255)
|
||||
approvalId String? @map("approval_id") @db.Uuid
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
completedAt DateTime? @map("completed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([status])
|
||||
@@index([priority])
|
||||
@@index([createdAt])
|
||||
@@map("department_tasks")
|
||||
}
|
||||
|
||||
// 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()
|
||||
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")
|
||||
}
|
||||
model OrchestrationRun {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationArtifact {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationDependency {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationApprovalDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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 OrchestrationBudgetLedger {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("admin users list contract", () => {
|
||||
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
|
||||
let service: AdminService;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdminService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: RedisService, useValue: {} },
|
||||
{ provide: RevalidationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AdminService);
|
||||
});
|
||||
|
||||
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
|
||||
// Deliberately return extra fields even if the query selects safely.
|
||||
prisma.user.findMany.mockResolvedValue([{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User",
|
||||
mobile: "fixture-mobile", email: null, role: "ADMIN",
|
||||
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
password: "test-only-password-hash", passwordHash: "test-only-hash",
|
||||
refreshToken: "test-only-token", futureSecret: "must-not-leak",
|
||||
walletTransactions: [{ transactionReference: "private-reference" }],
|
||||
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
|
||||
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
|
||||
}]);
|
||||
prisma.user.count.mockResolvedValue(11);
|
||||
const controller = new AdminController(service, {} as never);
|
||||
const result = await controller.getUsers({ page: 2, limit: 10 });
|
||||
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
|
||||
expect(body).toEqual({
|
||||
data: [{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
|
||||
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
|
||||
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
|
||||
}],
|
||||
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
|
||||
});
|
||||
const query = prisma.user.findMany.mock.calls[0][0];
|
||||
expect(query.select).toBeDefined();
|
||||
expect(query.select.password).toBeUndefined();
|
||||
expect(query.include).toBeUndefined();
|
||||
expect(query.skip).toBe(10);
|
||||
});
|
||||
|
||||
it("preserves the empty paginated list contract and filters", async () => {
|
||||
prisma.user.findMany.mockResolvedValue([]);
|
||||
prisma.user.count.mockResolvedValue(0);
|
||||
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
|
||||
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
|
||||
});
|
||||
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
@@ -62,8 +64,8 @@ export class AdminController {
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -80,8 +82,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -91,8 +93,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -101,8 +103,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -113,6 +115,7 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -130,6 +133,7 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -21,9 +21,6 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
|
||||
import { B2BLeadsController } from "./b2b-leads.controller";
|
||||
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
||||
import { SmsCampaignsController } from "./sms-campaigns.controller";
|
||||
import { ApprovalsController } from "./approvals.controller";
|
||||
import { AuditLogsController } from "./audit-logs.controller";
|
||||
import { DepartmentTasksController } from "./department-tasks.controller";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { SettingsModule } from "../settings/settings.module";
|
||||
@@ -46,9 +43,6 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
ApprovalsController,
|
||||
AuditLogsController,
|
||||
DepartmentTasksController,
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
|
||||
@@ -61,15 +61,10 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { randomUUID } from "crypto";
|
||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -168,12 +163,17 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,9 +197,19 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const { orders: _orders, ...rest } = u;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
return {
|
||||
...rest,
|
||||
id: u.id,
|
||||
firstName: u.firstName,
|
||||
lastName: u.lastName,
|
||||
mobile: u.mobile,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
walletBalance: u.walletBalance,
|
||||
charityDonationTotal: u.charityDonationTotal,
|
||||
createdAt: u.createdAt,
|
||||
addresses: u.addresses,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
@@ -227,7 +237,12 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto) {
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
return this.persistUser(dto);
|
||||
}
|
||||
|
||||
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -260,6 +275,7 @@ export class AdminService {
|
||||
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
mobile,
|
||||
@@ -274,7 +290,30 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
||||
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
|
||||
if (existing) {
|
||||
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
|
||||
return existing; // Never renew TTL on retry.
|
||||
}
|
||||
if (password.length < 32) throw new Error('Server generated secret required');
|
||||
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
|
||||
}
|
||||
|
||||
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
if (!existing) { onRevoked(); return; }
|
||||
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
|
||||
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
|
||||
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
|
||||
onRevoked();
|
||||
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -286,6 +325,8 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -340,17 +381,11 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
}
|
||||
|
||||
async deleteUser(id: string) {
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -360,7 +395,17 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.deleteUserRecords(id);
|
||||
}
|
||||
|
||||
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (stage) {
|
||||
// Acquire the row lock with an exact fence before deleting any related rows.
|
||||
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
|
||||
}
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
await tx.pet.deleteMany({ where: { userId: id } });
|
||||
@@ -1397,12 +1442,15 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,134 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } 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 { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
CreateApprovalRequestDto,
|
||||
DecideApprovalDto,
|
||||
QueryApprovalDto,
|
||||
} from "./dto/approval-request.dto";
|
||||
|
||||
@ApiTags("Admin - CEO Approvals & Governance")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/approvals")
|
||||
export class ApprovalsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
|
||||
async findAll(@Query() query: QueryApprovalDto) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.category) where.category = query.category;
|
||||
if (query.status) where.status = query.status;
|
||||
|
||||
const [total, items, pendingCount] = await Promise.all([
|
||||
(this.prisma as any).approvalRequest.count({ where }),
|
||||
(this.prisma as any).approvalRequest.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
(this.prisma as any).approvalRequest.count({
|
||||
where: { status: "PENDING" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
pendingCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@ApiOperation({ summary: "اجرای شبیهسازی تست زنده برای آیتم کارتابل" })
|
||||
async runTestSimulation(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
impact: "Price change simulation",
|
||||
currentPrice: payload.currentPrice,
|
||||
newPrice: payload.newPrice,
|
||||
marginDiff: payload.newPrice && payload.buyPrice
|
||||
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
|
||||
: "N/A",
|
||||
torobFeedReflectEstimate: "< 5 seconds",
|
||||
};
|
||||
} else if (item.category === "PURCHASE_ORDER") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
document: "PO Pre-check",
|
||||
itemsCount: payload.items ? payload.items.length : 1,
|
||||
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
|
||||
fulfillmentCapacity: "انبار آماده پذیرش",
|
||||
};
|
||||
} else {
|
||||
testResult = {
|
||||
executionSafe: true,
|
||||
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, testResult };
|
||||
}
|
||||
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
Param,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } 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 { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - System Audit & History")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/audit-logs")
|
||||
export class AuditLogsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست لاگهای تغییرات دیتابیس و سیستم" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 30;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.entity) where.entity = query.entity;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ summary: { contains: query.search, mode: "insensitive" } },
|
||||
{ actor: { contains: query.search, mode: "insensitive" } },
|
||||
{ entityId: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).auditLog.count({ where }),
|
||||
(this.prisma as any).auditLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("recent")
|
||||
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
|
||||
async getRecent(@Query("limit") limitParam?: string) {
|
||||
const limit = Number(limitParam) || 10;
|
||||
const items = await (this.prisma as any).auditLog.findMany({
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return { success: true, data: items };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
|
||||
async create(@Body() body: any) {
|
||||
const item = await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: body.entity,
|
||||
entityId: body.entityId ? String(body.entityId) : null,
|
||||
action: body.action || "UPDATE",
|
||||
department: body.department || "system",
|
||||
actor: body.actor || "ADMIN",
|
||||
summary: body.summary,
|
||||
oldValues: body.oldValues || null,
|
||||
newValues: body.newValues || null,
|
||||
metadata: body.metadata || null,
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
|
||||
// Stateful transactional double: deliberately interleave after snapshot read.
|
||||
// Complements the DB integration test; it does not assert PostgreSQL locking.
|
||||
describe("BlogsService atomic optimistic update", () => {
|
||||
const token = "2026-10-24T23:36:08.501Z";
|
||||
let row: any;
|
||||
let service: BlogsService;
|
||||
let prisma: any;
|
||||
let revalidate: jest.Mock;
|
||||
let afterRead: (() => void) | undefined;
|
||||
let failRelations: boolean;
|
||||
beforeEach(() => {
|
||||
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
|
||||
afterRead = undefined;
|
||||
failRelations = false;
|
||||
const blog = {
|
||||
findUnique: jest.fn(async () => {
|
||||
const snapshot = { ...row };
|
||||
afterRead?.();
|
||||
return snapshot;
|
||||
}),
|
||||
updateMany: jest.fn(async ({ where, data }) => {
|
||||
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
|
||||
row = { ...row, ...data };
|
||||
return { count: 1 };
|
||||
}
|
||||
return { count: 0 };
|
||||
}),
|
||||
update: jest.fn(async ({ data }) => {
|
||||
if (failRelations) throw new Error("relation failure");
|
||||
row = { ...row, ...data };
|
||||
return { ...row };
|
||||
}),
|
||||
};
|
||||
// Serialize transactions like row locks. Rollback restores only transaction writes.
|
||||
let tail = Promise.resolve();
|
||||
prisma = { blog, $transaction: jest.fn((cb) => {
|
||||
const next = tail.then(async () => {
|
||||
const before = { ...row };
|
||||
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
|
||||
});
|
||||
tail = next.catch(() => undefined);
|
||||
return next;
|
||||
}) };
|
||||
revalidate = jest.fn().mockResolvedValue(true);
|
||||
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
|
||||
});
|
||||
|
||||
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
|
||||
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects stale token and leaves all relations untouched", async () => {
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
|
||||
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
|
||||
expect(result.title).toBe("new");
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
|
||||
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("detects writer interleaving after read before write", async () => {
|
||||
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.title).toBe("winner");
|
||||
expect(row.tags).toEqual(["winner"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("permits exactly one of two requests sharing a token", async () => {
|
||||
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
|
||||
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
|
||||
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
|
||||
expect(rejected.reason).toBeInstanceOf(ConflictException);
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("advances token even when clock is within same millisecond", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date(token));
|
||||
try {
|
||||
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
|
||||
} finally { jest.useRealTimers(); }
|
||||
});
|
||||
it("rolls back claim on nested relation failure without invalidating cache", async () => {
|
||||
failRelations = true;
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
|
||||
expect(row.updatedAt.toISOString()).toBe(token);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves legacy omission without demanding a token", async () => {
|
||||
await service.updateBlog("b1", { title: "legacy" });
|
||||
expect(row.title).toBe("legacy");
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns 404 for a missing blog", async () => {
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
it("does not fail committed writes if revalidation throws", async () => {
|
||||
revalidate.mockRejectedValue(new Error("cache down"));
|
||||
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
|
||||
expect(result.cacheRevalidation).toBe("failed");
|
||||
expect(row.title).toBe("saved");
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,8 @@ describe("Admin BlogsService", () => {
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
mockRevalidationService.revalidateBlog.mockReset();
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -200,7 +202,10 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"new-health-post",
|
||||
);
|
||||
expect(result).toEqual(createdBlog);
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
@@ -272,6 +277,66 @@ describe("Admin BlogsService", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog", () => {
|
||||
@@ -314,7 +379,61 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"my-post",
|
||||
);
|
||||
expect(result).toEqual(updated);
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -255,8 +256,21 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
},
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(created.slug);
|
||||
return created;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...created,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async updateBlog(id: string, data: any) {
|
||||
@@ -272,8 +286,30 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
readingTime,
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
expectedUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const conflict = () => new ConflictException(
|
||||
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
|
||||
);
|
||||
let expectedTime: number | undefined;
|
||||
if (expectedUpdatedAt !== undefined) {
|
||||
// Only accept the millisecond, timezone-qualified ISO token returned by GET
|
||||
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
|
||||
// and its normalization of impossible calendar dates.
|
||||
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
|
||||
);
|
||||
if (!match) throw conflict();
|
||||
expectedTime = Date.parse(expectedUpdatedAt);
|
||||
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
|
||||
if (!Number.isFinite(expectedTime) ||
|
||||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
|
||||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
||||
throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
@@ -390,25 +426,68 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
};
|
||||
}
|
||||
|
||||
const updated = await this.prisma.blog.update({
|
||||
where: { id },
|
||||
data: updatePayload,
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
},
|
||||
});
|
||||
const include = {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
};
|
||||
// Legacy UI requests without a token intentionally retain last-write-wins.
|
||||
// Guarded requests claim the row using a DB predicate, not the earlier read.
|
||||
const updated = expectedTime === undefined
|
||||
? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
|
||||
: await this.prisma.$transaction(async (tx) => {
|
||||
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
|
||||
// milliseconds. Match the entire represented millisecond, then move
|
||||
// strictly beyond it (including same-ms writes and clock rollback).
|
||||
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
|
||||
const claim = await tx.blog.updateMany({
|
||||
where: {
|
||||
id,
|
||||
updatedAt: {
|
||||
gte: new Date(expectedTime),
|
||||
lt: new Date(expectedTime + 1),
|
||||
},
|
||||
},
|
||||
data: { updatedAt: claimedAt },
|
||||
});
|
||||
if (claim.count !== 1) throw conflict();
|
||||
// The claim holds the row lock until this nested mutation commits.
|
||||
// Any relation failure rolls back both the claim and all data writes.
|
||||
return tx.blog.update({
|
||||
where: { id },
|
||||
data: { ...updatePayload, updatedAt: claimedAt },
|
||||
include,
|
||||
});
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(updated.slug);
|
||||
return updated;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...updated,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteBlog(id: string) {
|
||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
const res = await this.prisma.blog.delete({ where: { id } });
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
try {
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
|
||||
);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,93 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } 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 { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - Department & Agent Tasks")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/department-tasks")
|
||||
export class DepartmentTasksController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست تسکهای دپارتمانها و ایجنتها" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.priority) where.priority = query.priority;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ code: { contains: query.search, mode: "insensitive" } },
|
||||
{ title: { contains: query.search, mode: "insensitive" } },
|
||||
{ description: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).departmentTask.count({ where }),
|
||||
(this.prisma as any).departmentTask.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("stats")
|
||||
@ApiOperation({ summary: "آمار تسکها به تفکیک استیت و دپارتمان" })
|
||||
async getStats() {
|
||||
const tasks = await (this.prisma as any).departmentTask.findMany({
|
||||
select: { department: true, status: true, priority: true },
|
||||
});
|
||||
|
||||
const statusCounts: Record<string, number> = {
|
||||
TODO: 0,
|
||||
IN_PROGRESS: 0,
|
||||
TEST: 0,
|
||||
DONE: 0,
|
||||
BACKLOG: 0,
|
||||
IN_REVIEW: 0,
|
||||
APPROVED: 0,
|
||||
DEPLOYING: 0,
|
||||
};
|
||||
const departmentCounts: Record<string, number> = {};
|
||||
|
||||
for (const t of tasks) {
|
||||
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
|
||||
departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
total: tasks.length,
|
||||
byStatus: statusCounts,
|
||||
byDepartment: departmentCounts,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک تسک" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const task = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!task) throw new NotFoundException(`Task ${id} not found`);
|
||||
return { success: true, data: task };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
|
||||
async updateStatus(
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsString, IsOptional, IsObject } from "class-validator";
|
||||
|
||||
export class CreateApprovalRequestDto {
|
||||
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
|
||||
@IsString()
|
||||
department: string;
|
||||
|
||||
@ApiProperty({ description: "دستهبندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
|
||||
@IsString()
|
||||
category: string;
|
||||
|
||||
@ApiProperty({ description: "عنوان مورد تایید" })
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiProperty({ description: "دادههای تغییرات پیشنهادی" })
|
||||
@IsObject()
|
||||
payload: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional({ description: "دادههای سناریوی تست و ارزیابی" })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
testContext?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class DecideApprovalDto {
|
||||
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
|
||||
@IsString()
|
||||
decision: "APPROVED" | "REJECTED";
|
||||
|
||||
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
outcome?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
evidence?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
department?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
limit?: number;
|
||||
}
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -41,6 +44,7 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -85,6 +89,7 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
|
||||
export const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
|
||||
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
|
||||
];
|
||||
|
||||
export interface UserAdminActor {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
}
|
||||
|
||||
// Match RolesGuard semantics; keep stored values unchanged.
|
||||
export function isSuperAdminRole(role?: string): boolean {
|
||||
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
|
||||
return normalized === "superadmin" || normalized === "adminsuper";
|
||||
}
|
||||
|
||||
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
|
||||
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
|
||||
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
|
||||
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
|
||||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
|
||||
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { RouterUsageModule } from './router-usage/router-usage.module';
|
||||
import { HermesManagementModule } from './hermes-management/hermes-management.module';
|
||||
import { TasksModule } from './common/services/tasks.module';
|
||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||
import { PrismaModule } from "./prisma/prisma.module";
|
||||
@@ -39,16 +37,11 @@ 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 { OrchestrationModule } from "./orchestration/orchestration.module";
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
RouterUsageModule,
|
||||
// Deny-all registration: no request identity or runtime credentials are accepted yet.
|
||||
HermesManagementModule.register({origin:'http://canina-hermes:9119',token:async()=>''}),
|
||||
OrchestrationModule,
|
||||
SupportChatModule,
|
||||
RevalidationModule,
|
||||
SmsModule,
|
||||
|
||||
@@ -14,6 +14,7 @@ import { SmsService } from "../common/services/sms.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtRefreshSecret } from "./auth.constants";
|
||||
|
||||
export class RegisterInput {
|
||||
@@ -200,7 +201,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -257,7 +259,8 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -300,7 +303,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
@@ -326,10 +330,12 @@ export class AuthService {
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||
if (isMatch) {
|
||||
assertPrincipalActive(dbAdmin);
|
||||
const payload = {
|
||||
sub: dbAdmin.id,
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
@@ -443,11 +449,14 @@ export class AuthService {
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (user) {
|
||||
assertPrincipalActive(user);
|
||||
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
userPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phoneNumber: user.mobile,
|
||||
role: user.role,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
@@ -487,12 +496,15 @@ export class AuthService {
|
||||
email?: string;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
phoneNumber: user.mobile,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const sha='a'.repeat(40), generation='8311eb41-23b4-4aab-ade2-e97b90debc11';
|
||||
const env={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'cleanup-session',STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
describe('durable cleanup ownership fence',()=>{
|
||||
it('does not revoke a replacement generation',async()=>{
|
||||
const update=jest.fn();
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:'replacement',authExpiresAt:new Date()}),update}};
|
||||
await expect(new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal(env,sha)).rejects.toThrow('Refusing');
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
it('confirms revocation before relational deletion failure',async()=>{
|
||||
const events:string[]=[];
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:generation,authExpiresAt:new Date()}),update:async()=>events.push('revoke')},$transaction:async()=>{events.push('delete');throw Error('FK failure');}};
|
||||
await expect((new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal as any)(env,sha,()=>events.push('handle-removed'))).rejects.toThrow('FK failure');
|
||||
expect(events).toEqual(['revoke','handle-removed','delete']);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
@@ -12,6 +13,8 @@ export interface JwtPayload {
|
||||
email?: string;
|
||||
role?: string;
|
||||
phoneNumber?: string;
|
||||
stageTestSession?: string;
|
||||
stageTestGeneration?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -59,6 +62,13 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
||||
if (user.stageTestSession) {
|
||||
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
|
||||
const path = req.originalUrl?.split('?')[0] || '';
|
||||
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure|editorial-completed-recovery)$/.test(path));
|
||||
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID } from './stage-test-principal';
|
||||
import { createServer, Server } from 'http';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST==='true';
|
||||
(enabled?describe:describe.skip)('actual internal CLI disposable lifecycle',()=>{
|
||||
const sha='a'.repeat(40), generation='b411eb41-23b4-4aab-ade2-e97b90debc11', session='cli-integration-session';
|
||||
const handle=`/app/private-stage-test/${session}.json`;
|
||||
const db=new PrismaClient({log:[]}), redis=new RedisService(); let server:Server;
|
||||
const env={...process.env,APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:session,STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
const cli=(action:string)=>promisify(execFile)(process.execPath,['-r','ts-node/register','src/auth/stage-test-principal.cli.ts',action],{env,timeout:90000});
|
||||
beforeAll(async()=>{
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw Error('Disposable database only');
|
||||
writeFileSync('/app/STAGE_TEST_ARTIFACT_SHA',sha); redis.onModuleInit();
|
||||
const auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
server=createServer(async(req,res)=>{
|
||||
try {let body='';for await(const chunk of req) body+=chunk;
|
||||
if(req.url!=='/api/auth/admin-login') {res.writeHead(404).end();return;}
|
||||
const login=await auth.adminLogin(JSON.parse(body));res.setHeader('content-type','application/json');res.end(JSON.stringify(login));
|
||||
} catch {res.writeHead(401).end();}
|
||||
});
|
||||
await new Promise<void>(r=>server.listen(3000,'127.0.0.1',r));
|
||||
},120000);
|
||||
afterAll(async()=>{await new Promise<void>(r=>server.close(()=>r()));redis.onModuleDestroy();await db.$disconnect();});
|
||||
it('logs in using persisted credentials and removes handle on confirmed revocation despite failed delete',async()=>{
|
||||
await cli('open'); expect(existsSync(handle)).toBe(true);
|
||||
const credential=JSON.parse(readFileSync(handle,'utf8'));expect(credential.accessToken).toBeTruthy();
|
||||
expect((await db.user.findUnique({where:{id:STAGE_TEST_ID}}))?.stageTestGeneration).toBe(generation);
|
||||
await db.$executeRawUnsafe(`CREATE FUNCTION deny_principal_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test FK deletion failure'; END $$`);
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER deny_principal_delete BEFORE DELETE ON users FOR EACH ROW EXECUTE FUNCTION deny_principal_delete()`);
|
||||
try {
|
||||
await expect(cli('close')).rejects.toThrow();
|
||||
expect(existsSync(handle)).toBe(false);
|
||||
const revoked=await db.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
expect(revoked?.authExpiresAt?.getTime()).toBe(0);expect(revoked?.password).toBe('');
|
||||
} finally {await db.$executeRawUnsafe(`DROP TRIGGER deny_principal_delete ON users`);await db.$executeRawUnsafe(`DROP FUNCTION deny_principal_delete()`);}
|
||||
await cli('close');expect(await db.user.findUnique({where:{id:STAGE_TEST_ID}})).toBeNull();
|
||||
},240000);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'reflect-metadata';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { mkdirSync, openSync, writeFileSync, closeSync, readFileSync, statSync, unlinkSync, constants } from 'fs';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { authorizeStageSession, STAGE_TEST_EMAIL } from './stage-test-principal';
|
||||
|
||||
// CI-only internal seed command; deliberately not registered in AppModule.
|
||||
async function main() {
|
||||
const sha = readFileSync('/app/STAGE_TEST_ARTIFACT_SHA', 'utf8').trim();
|
||||
const grant = authorizeStageSession(process.env, sha);
|
||||
const action = process.argv[2];
|
||||
if (action === 'cleanup-capability') { process.stdout.write('stage-generation-cleanup-v1'); return; }
|
||||
if (!['open','close'].includes(action)) throw new Error('Unknown command');
|
||||
const root = '/app/private-stage-test';
|
||||
mkdirSync(root,{recursive:true,mode:0o700});
|
||||
const st = statSync(root);
|
||||
if (st.uid !== process.getuid!() || (st.mode & 0o777) !== 0o700) throw new Error('Unsafe private directory');
|
||||
if (!/^[a-f0-9-]{36}$/.test(process.env.STAGE_TEST_GENERATION || '')) throw new Error('Generation required');
|
||||
const handle = `${root}/${grant.session}.json`;
|
||||
const removeHandle = () => { try {unlinkSync(handle);} catch(e:any) {if(e.code !== 'ENOENT') throw e;} };
|
||||
const audit = (event:string) => {
|
||||
const fd = openSync(`${root}/audit.jsonl`, constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND|constants.O_NOFOLLOW,0o600);
|
||||
try { writeFileSync(fd,JSON.stringify({event,sha,session:grant.session,at:new Date().toISOString()})+'\n'); } finally {closeSync(fd);}
|
||||
};
|
||||
const db = new PrismaClient({log:[]});
|
||||
const service = new AdminService(db as any,undefined as any,undefined as any);
|
||||
try {
|
||||
audit(`${action}-requested`);
|
||||
if(action === 'close') {
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle);
|
||||
audit('revoked-and-deleted');
|
||||
return;
|
||||
}
|
||||
let fd:number;
|
||||
let password:string;
|
||||
try {
|
||||
fd = openSync(handle,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
|
||||
password = randomBytes(48).toString('base64url');
|
||||
try {writeFileSync(fd,JSON.stringify({password}));} finally {closeSync(fd);}
|
||||
} catch(e:any) {
|
||||
if(e.code !== 'EEXIST') throw e;
|
||||
fd = openSync(handle,constants.O_RDONLY|constants.O_NOFOLLOW);
|
||||
try {
|
||||
const {fstatSync} = await import('fs'); const s=fstatSync(fd);
|
||||
if(!s.isFile() || s.uid !== process.getuid!() || (s.mode & 0o777) !== 0o600) throw new Error('Unsafe handle');
|
||||
password=JSON.parse(readFileSync(fd,'utf8')).password;
|
||||
} finally {closeSync(fd);}
|
||||
}
|
||||
const user=await service.provisionStageTestPrincipal(process.env,sha,password);
|
||||
// Use deployed persisted-account HTTP login, never sign tokens here.
|
||||
const response=await fetch('http://127.0.0.1:3000/api/auth/admin-login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:STAGE_TEST_EMAIL,password}),signal:AbortSignal.timeout(15000)});
|
||||
if(!response.ok) throw new Error('Persisted login failed');
|
||||
const result:any=await response.json();
|
||||
if(result.data?.user?.id !== user.id || result.data?.user?.role !== 'SUPER_ADMIN' || !result.data?.accessToken) throw new Error('Persisted login mismatch');
|
||||
fd=openSync(handle,constants.O_WRONLY|constants.O_TRUNC|constants.O_NOFOLLOW);
|
||||
try {writeFileSync(fd,JSON.stringify({password,...result.data,expiresAt:user.authExpiresAt}));} finally {closeSync(fd);}
|
||||
audit('created-and-login-verified');
|
||||
// Only an opaque local path is public. Never upload this file as a CI artifact.
|
||||
process.stdout.write(`Stage credential handle: ${handle}\n`);
|
||||
} catch {
|
||||
audit('failed');
|
||||
// Leave only a revoked account if relational cleanup fails.
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle).catch(()=>undefined);
|
||||
throw new Error('Stage test principal operation failed; inspect private audit');
|
||||
} finally {await db.$disconnect();}
|
||||
}
|
||||
main().catch(()=>{process.stderr.write('Stage test principal denied or failed\n');process.exitCode=1;});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST === 'true';
|
||||
(enabled ? describe : describe.skip)('disposable persisted Stage principal lifecycle',()=>{
|
||||
const sha='a'.repeat(40), grant={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'integration-session',STAGE_TEST_TTL_SECONDS:'600'};
|
||||
const db=new PrismaClient({log:[]}); const redis=new RedisService();
|
||||
let admin:AdminService,auth:AuthService,strategy:JwtStrategy,password:string;
|
||||
beforeAll(async()=>{
|
||||
// Deliberately require a disposable database name; never point this suite at Stage.
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw new Error('Disposable database required');
|
||||
redis.onModuleInit(); password=randomBytes(48).toString('base64url');
|
||||
admin=new AdminService(db as any,redis,undefined as any);
|
||||
auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
strategy=new JwtStrategy(new UsersService(db as any),redis);
|
||||
});
|
||||
afterAll(async()=>{await admin.cleanupStageTestPrincipal(grant,sha); await db.$disconnect();redis.onModuleDestroy();});
|
||||
it('rejects unowned collision and never changes it',async()=>{
|
||||
const collision=await db.user.create({data:{firstName:'Unowned',lastName:'Account',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE}});
|
||||
try {
|
||||
await expect(admin.provisionStageTestPrincipal(grant,sha,password)).rejects.toThrow('Refusing');
|
||||
expect((await db.user.findUnique({where:{id:collision.id}}))?.role).toBe('User_PetOwner');
|
||||
} finally {await db.user.delete({where:{id:collision.id}});}
|
||||
});
|
||||
it('creates through account service, logs in, verifies signed tokens, never renews retry TTL',async()=>{
|
||||
const u=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(u.id).toBe(STAGE_TEST_ID); expect(u.role).toBe('SUPER_ADMIN'); expect(u.password).not.toBe(password);
|
||||
const retry=await admin.provisionStageTestPrincipal(grant,sha,password); expect(retry.authExpiresAt).toEqual(u.authExpiresAt);
|
||||
await expect(admin.provisionStageTestPrincipal({...grant,STAGE_TEST_SESSION:'different-session'},sha,password)).rejects.toThrow('Refusing');
|
||||
const login=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const payload=jwt.verify(login.data.accessToken); expect(payload.sub).toBe(u.id);expect(payload.role).toBe('SUPER_ADMIN');
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{authorization:`Bearer ${login.data.accessToken}`}};
|
||||
expect((await strategy.validate(req,payload)).id).toBe(u.id);
|
||||
await expect(strategy.validate({...req,originalUrl:'/api/admin/users'},payload)).rejects.toThrow('scope denied');
|
||||
await expect(strategy.validate({...req,method:'POST',originalUrl:'/api/admin/orchestration/tasks/abcd/gates/2/decide'},payload)).rejects.toThrow('scope denied');
|
||||
// Fixture time travel: persisted expiry is enforced independently of the long-lived signed token.
|
||||
await db.user.update({where:{id:u.id},data:{authExpiresAt:new Date(0)}});
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.adminLogin({email:STAGE_TEST_EMAIL,password})).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
await admin.cleanupStageTestPrincipal(grant,sha);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
expect(await db.user.findUnique({where:{id:u.id}})).toBeNull();
|
||||
const replacement=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(replacement.stageTestGeneration).not.toBe(u.stageTestGeneration);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
const fresh=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
expect((await strategy.validate(req,jwt.verify(fresh.data.accessToken))).id).toBe(u.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { assertPrincipalActive, authorizeStageSession } from './stage-test-principal';
|
||||
const sha = 'a'.repeat(40);
|
||||
const valid = { APP_ENV: 'stage', STAGE_TEST_PRINCIPAL_ENABLED: 'true', CI: 'true', STAGE_TEST_APPROVAL: 'owner-authorized-stage-editorial', STAGE_TEST_SHA: sha, STAGE_TEST_SESSION: 'editorial-20261024', STAGE_TEST_TTL_SECONDS: '600' };
|
||||
describe('Stage CI authority', () => {
|
||||
it('denies by default and in Production despite opt in', () => {
|
||||
expect(() => authorizeStageSession({}, sha)).toThrow();
|
||||
expect(() => authorizeStageSession({...valid, APP_ENV:'production'}, sha)).toThrow();
|
||||
});
|
||||
it('requires immutable matching SHA and bounded explicit authorization', () => {
|
||||
expect(authorizeStageSession(valid, sha).ttl).toBe(600);
|
||||
for(const patch of [{STAGE_TEST_SHA:'main'}, {STAGE_TEST_SHA:'b'.repeat(40)}, {STAGE_TEST_TTL_SECONDS:'3601'}, {STAGE_TEST_TTL_SECONDS:'0'}, {STAGE_TEST_APPROVAL:''}, {CI:''}]) expect(() => authorizeStageSession({...valid,...patch},sha)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
|
||||
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
|
||||
export const STAGE_TEST_MOBILE = '09999999071';
|
||||
export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: string) {
|
||||
if (env.APP_ENV !== 'stage' || env.STAGE_TEST_PRINCIPAL_ENABLED !== 'true' || env.CI !== 'true' || env.STAGE_TEST_APPROVAL !== 'owner-authorized-stage-editorial' || !/^[a-f0-9]{40}$/.test(artifactSha) || env.STAGE_TEST_SHA !== artifactSha || !/^[a-z0-9-]{8,64}$/.test(env.STAGE_TEST_SESSION || '')) throw new Error('Stage CI authority denied');
|
||||
const ttl = Number(env.STAGE_TEST_TTL_SECONDS);
|
||||
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
|
||||
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
|
||||
}
|
||||
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
|
||||
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('Stage credentials remain fenced to their creation session', () => {
|
||||
const id='e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)};
|
||||
const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()};
|
||||
beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';});
|
||||
it('rejects an old-session access token after fixed account ID is recreated',async()=>{
|
||||
const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any);
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}};
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id})).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id});
|
||||
});
|
||||
it('rejects an old-session refresh token even while its Redis entry remains active',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
|
||||
const token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET});
|
||||
await expect(auth.refreshToken(token)).rejects.toThrow();
|
||||
});
|
||||
it('includes session fencing in newly issued credentials',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({} as any,jwt,redis,undefined as any);
|
||||
const result=await auth.refresh(current);
|
||||
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
|
||||
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
|
||||
expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session');
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,15 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
normalizeSearchText,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
export interface BlogFilterDto extends PaginationDto {
|
||||
categoryId?: string;
|
||||
categorySlug?: string;
|
||||
tagSlug?: string;
|
||||
featured?: boolean | string;
|
||||
@@ -20,6 +27,7 @@ export class BlogsService {
|
||||
limit = 10,
|
||||
sortBy = "publishedAt",
|
||||
sortOrder = "desc",
|
||||
categoryId,
|
||||
categorySlug,
|
||||
tagSlug,
|
||||
featured,
|
||||
@@ -32,20 +40,23 @@ export class BlogsService {
|
||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||
};
|
||||
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
whereClause.AND = [
|
||||
{
|
||||
OR: [
|
||||
{ title: { contains: search, mode: "insensitive" } },
|
||||
{ excerpt: { contains: search, mode: "insensitive" } },
|
||||
{ content: { contains: search, mode: "insensitive" } },
|
||||
{ keywords: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
OR: tokens.flatMap((token) => [
|
||||
{ title: { contains: token, mode: "insensitive" } },
|
||||
{ excerpt: { contains: token, mode: "insensitive" } },
|
||||
{ keywords: { contains: token, mode: "insensitive" } },
|
||||
{ tags: { some: { name: { contains: token, mode: "insensitive" } } } },
|
||||
]),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (categorySlug) {
|
||||
if (categoryId && categoryId !== "ALL") {
|
||||
whereClause.categoryId = categoryId;
|
||||
} else if (categorySlug && categorySlug !== "all") {
|
||||
whereClause.category = { slug: categorySlug };
|
||||
}
|
||||
|
||||
@@ -57,13 +68,15 @@ export class BlogsService {
|
||||
whereClause.featured = String(featured) === "true";
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawBlogs, total] = await Promise.all([
|
||||
this.prisma.blog.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
@@ -88,14 +101,30 @@ export class BlogsService {
|
||||
this.prisma.blog.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawBlogs;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawBlogs]
|
||||
.map((b) => ({
|
||||
blog: b,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
title: b.title,
|
||||
slug: b.slug,
|
||||
shortDescription: b.excerpt,
|
||||
tags: b.tags,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.blog)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page: Number(page),
|
||||
lastPage: Math.ceil(total / Number(limit)) || 1,
|
||||
limit: Number(limit),
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,16 @@ describe("RevalidationService", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it("uses the Next server rather than the nginx API proxy as production fallback", async () => {
|
||||
delete process.env.FRONTEND_INTERNAL_URL;
|
||||
delete process.env.FRONTEND_URL;
|
||||
delete process.env.NEXT_PUBLIC_SITE_URL;
|
||||
process.env.NODE_ENV = "production";
|
||||
const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue({ ok: true } as Response);
|
||||
await service.revalidate(["blogs"], ["/blog"]);
|
||||
expect(fetchSpy).toHaveBeenCalledWith("http://frontend_prod:3000/api/revalidate", expect.anything());
|
||||
});
|
||||
|
||||
describe("revalidateTag", () => {
|
||||
it("should send POST request with tag and secret header and return true on 200", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
@@ -111,6 +121,48 @@ describe("RevalidationService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidateBlog", () => {
|
||||
it("should trigger all tags and paths for blog slug and return true when all succeed", async () => {
|
||||
const tagSpy = jest
|
||||
.spyOn(service, "revalidateTag")
|
||||
.mockResolvedValue(true);
|
||||
const pathSpy = jest
|
||||
.spyOn(service, "revalidatePath")
|
||||
.mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(tagSpy).toHaveBeenCalledWith("blogs");
|
||||
expect(tagSpy).toHaveBeenCalledWith("home-data");
|
||||
expect(tagSpy).toHaveBeenCalledWith("blog-test-slug");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/blog");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/sitemap.xml");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/blog/test-slug");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when a tag or path revalidation fails rather than swallowing false", async () => {
|
||||
jest.spyOn(service, "revalidateTag").mockImplementation(async (tag: string) => {
|
||||
return tag !== "blogs";
|
||||
});
|
||||
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation errors and return false", async () => {
|
||||
jest.spyOn(service, "revalidateTag").mockRejectedValue(new Error("Network disconnected"));
|
||||
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
@@ -10,7 +10,7 @@ export class RevalidationService {
|
||||
process.env.FRONTEND_URL ||
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(process.env.NODE_ENV === "production"
|
||||
? "http://frontend_prod:8080"
|
||||
? "http://frontend_prod:3000"
|
||||
: "http://localhost:3000");
|
||||
return raw.replace(/\/+$/, "");
|
||||
}
|
||||
@@ -135,7 +135,7 @@ export class RevalidationService {
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
|
||||
async revalidateBlog(slug?: string): Promise<void> {
|
||||
async revalidateBlog(slug?: string): Promise<boolean> {
|
||||
const tasks: Promise<boolean>[] = [
|
||||
this.revalidateTag("blogs"),
|
||||
this.revalidateTag("home-data"),
|
||||
@@ -149,7 +149,18 @@ export class RevalidationService {
|
||||
tasks.push(this.revalidatePath(`/blog/${slug}`));
|
||||
}
|
||||
|
||||
await Promise.allSettled(tasks);
|
||||
try {
|
||||
const results = await Promise.allSettled(tasks);
|
||||
return (
|
||||
results.length > 0 &&
|
||||
results.every(
|
||||
(result) => result.status === "fulfilled" && result.value === true,
|
||||
)
|
||||
);
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Revalidation blog skipped or failed: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateSettings(): Promise<void> {
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class HermesClientService {
|
||||
private readonly logger = new Logger(HermesClientService.name);
|
||||
private readonly baseUrl: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor() {
|
||||
this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642";
|
||||
this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || "";
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${this.baseUrl}/v1/health`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
});
|
||||
return res.status === 200;
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Hermes health check failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async triggerEvent(eventName: string, payload: Record<string, any>) {
|
||||
try {
|
||||
this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`);
|
||||
const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "hermes-agent",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { success: true, data };
|
||||
} catch (error: any) {
|
||||
this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
normalizeSearchText,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
createPaginationMeta,
|
||||
} from "./search.utils";
|
||||
|
||||
describe("search.utils", () => {
|
||||
describe("createPaginationMeta", () => {
|
||||
it("builds consistent pagination metadata", () => {
|
||||
const meta = createPaginationMeta(52, 2, 10);
|
||||
expect(meta).toEqual({
|
||||
total: 52,
|
||||
page: 2,
|
||||
limit: 10,
|
||||
totalPages: 6,
|
||||
lastPage: 6,
|
||||
hasNextPage: true,
|
||||
hasPrevPage: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("handles boundary zero and single page counts safely", () => {
|
||||
const metaZero = createPaginationMeta(0, 1, 10);
|
||||
expect(metaZero.totalPages).toBe(1);
|
||||
expect(metaZero.hasNextPage).toBe(false);
|
||||
expect(metaZero.hasPrevPage).toBe(false);
|
||||
|
||||
const metaOne = createPaginationMeta(5, 1, 10);
|
||||
expect(metaOne.totalPages).toBe(1);
|
||||
expect(metaOne.hasNextPage).toBe(false);
|
||||
expect(metaOne.hasPrevPage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeSearchText", () => {
|
||||
it("normalizes Arabic kaf and yeh to Persian equivalents", () => {
|
||||
expect(normalizeSearchText("قطره قلب كنينای ايران")).toBe("قطره قلب کنینای ایران");
|
||||
});
|
||||
|
||||
it("strips parentheses, diacritics, and half-spaces", () => {
|
||||
expect(normalizeSearchText("ال-کارنیتین (L-Carnitine) \u200c دارویی")).toBe("ال کارنیتین l carnitine دارویی");
|
||||
expect(normalizeSearchText("مُکَمِّل")).toBe("مکمل");
|
||||
});
|
||||
|
||||
it("converts Persian digits to English digits", () => {
|
||||
expect(normalizeSearchText("محصول شماره ۱۲۳")).toBe("محصول شماره 123");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractSearchTokens", () => {
|
||||
it("extracts meaningful tokens and removes stop words", () => {
|
||||
const tokens = extractSearchTokens("بهترین قطره برای تقویت قلب سگ و گربه");
|
||||
expect(tokens).toContain("قطره");
|
||||
expect(tokens).toContain("تقویت");
|
||||
expect(tokens).toContain("قلب");
|
||||
expect(tokens).toContain("سگ");
|
||||
expect(tokens).toContain("گربه");
|
||||
expect(tokens).not.toContain("برای");
|
||||
expect(tokens).not.toContain("و");
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateRelevanceScore", () => {
|
||||
it("ranks exact title / ingredient matches far higher than general description mentions", () => {
|
||||
const herzVital = {
|
||||
title: "هیرتز ویتال (مکمل تقویت قلب) کنینا",
|
||||
slug: "canina-herz-vital-100ml",
|
||||
ingredients: [{ nameFa: "ال-کارنیتین (L-Carnitine)", nameEn: "L-Carnitine" }],
|
||||
symptoms: [{ symptom: "بیماری قلبی" }],
|
||||
shortDescription: "حمایت تخصصی از عضله قلب سگ و گربه",
|
||||
description: "توضیحات مفصل درباره کارکرد قلب و عروق...",
|
||||
};
|
||||
|
||||
const genericProduct = {
|
||||
title: "پودر ویتامین پلاس سگ",
|
||||
slug: "canina-vitamin-plus",
|
||||
ingredients: [{ nameFa: "ویتامین A", nameEn: "Vitamin A" }],
|
||||
symptoms: [],
|
||||
shortDescription: "تقویت عمومی بدن",
|
||||
description: "این مولتی ویتامین برای تمام اندامهای بدن از جمله قلب، کبد و مفاصل مفید است.",
|
||||
};
|
||||
|
||||
const tokens = extractSearchTokens("ال-کارنیتین قلب");
|
||||
const scoreHerz = calculateRelevanceScore(herzVital, "ال-کارنیتین قلب", tokens);
|
||||
const scoreGeneric = calculateRelevanceScore(genericProduct, "ال-کارنیتین قلب", tokens);
|
||||
|
||||
expect(scoreHerz).toBeGreaterThan(scoreGeneric * 4);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
export interface PaginationMeta {
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
lastPage: number;
|
||||
hasNextPage: boolean;
|
||||
hasPrevPage: boolean;
|
||||
}
|
||||
|
||||
export function createPaginationMeta(
|
||||
total: number,
|
||||
page: number,
|
||||
limit: number,
|
||||
): PaginationMeta {
|
||||
const safeTotal = Math.max(0, Number(total) || 0);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const totalPages = Math.ceil(safeTotal / safeLimit) || 1;
|
||||
|
||||
return {
|
||||
total: safeTotal,
|
||||
page: safePage,
|
||||
limit: safeLimit,
|
||||
totalPages,
|
||||
lastPage: totalPages,
|
||||
hasNextPage: safePage < totalPages,
|
||||
hasPrevPage: safePage > 1,
|
||||
};
|
||||
}
|
||||
|
||||
const PERSIAN_ARABIC_DIGITS: Record<string, string> = {
|
||||
"۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
|
||||
"۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
|
||||
"٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4",
|
||||
"٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9",
|
||||
};
|
||||
|
||||
export const COMMON_STOP_WORDS = new Set([
|
||||
"از", "به", "در", "با", "برای", "و", "یا", "که", "این", "آن", "ها", "های",
|
||||
"تر", "ترین", "روی", "توی", "را", "تا", "بر", "اما", "اگر", "ولی", "یک",
|
||||
"the", "a", "an", "and", "or", "for", "with", "in", "on", "at", "to", "of",
|
||||
]);
|
||||
|
||||
export const SEARCH_EXPANSION_MAP: Record<string, string[]> = {
|
||||
"تایورین": ["تورین", "taurine", "taurin"],
|
||||
"تائورین": ["تورین", "taurine", "taurin"],
|
||||
"تورین": ["تایورین", "تائورین", "taurine", "taurin"],
|
||||
"taurine": ["تورین", "تایورین", "تائورین", "taurin"],
|
||||
"taurin": ["تورین", "تایورین", "تائورین", "taurine"],
|
||||
"کارنیتین": ["carnitine", "l-carnitine"],
|
||||
"carnitine": ["کارنیتین", "l-carnitine"],
|
||||
"گلوکزامین": ["گلوکوزامین", "glucosamine"],
|
||||
"گلوکوزامین": ["گلوکزامین", "glucosamine"],
|
||||
"glucosamine": ["گلوکوزامین", "گلوکزامین"],
|
||||
"امگا": ["omega", "امگا ۳", "سالمون", "salmon"],
|
||||
"omega": ["امگا", "امگا ۳", "salmon"],
|
||||
"کندرویتین": ["chondroitin"],
|
||||
"chondroitin": ["کندرویتین"],
|
||||
"بیوتین": ["biotin"],
|
||||
"biotin": ["بیوتین"],
|
||||
"کلسیم": ["calcium"],
|
||||
"calcium": ["کلسیم"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes Persian and English text by standardizing characters,
|
||||
* removing diacritics, half-spaces, punctuation, and folding case.
|
||||
*/
|
||||
export function normalizeSearchText(text?: string | null): string {
|
||||
if (!text) return "";
|
||||
|
||||
let s = String(text);
|
||||
|
||||
// Convert Persian/Arabic digits
|
||||
s = s.replace(/[۰-۹٠-٩]/g, (ch) => PERSIAN_ARABIC_DIGITS[ch] || ch);
|
||||
|
||||
// Normalize Arabic letters to standard Persian/English
|
||||
s = s
|
||||
.replace(/[يى]/g, "ی")
|
||||
.replace(/[ك]/g, "ک")
|
||||
.replace(/[ة]/g, "ه")
|
||||
.replace(/[آأإٱ]/g, "ا")
|
||||
.replace(/[ؤ]/g, "و")
|
||||
.replace(/[ئ]/g, "ی");
|
||||
|
||||
// Remove Arabic/Persian diacritics (fatha, damma, kasra, tanwin, sukun, tashdid)
|
||||
s = s.replace(/[\u064B-\u065F\u0670]/g, "");
|
||||
|
||||
// Replace half-space, non-breaking space, parentheses, brackets, quotes, punctuation with single space
|
||||
s = s.replace(/[\u200B-\u200D\uFEFF\u00A0\u200E\u200F_~`!@#$%^&*()+=[\]{}|\\;:'",.<>/?،؛؟]/g, " ");
|
||||
|
||||
// Collapse hyphens surrounded by spaces or replace hyphen with space
|
||||
s = s.replace(/-/g, " ");
|
||||
|
||||
// Lowercase & collapse whitespace
|
||||
return s.toLowerCase().replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts meaningful tokens from a query, eliminating stop words
|
||||
* unless the entire query only consists of stop words.
|
||||
*/
|
||||
export function extractSearchTokens(rawQuery?: string | null): string[] {
|
||||
const normalized = normalizeSearchText(rawQuery);
|
||||
if (!normalized) return [];
|
||||
|
||||
const rawTokens = normalized.split(" ").filter((t) => t.length > 0);
|
||||
if (rawTokens.length === 0) return [];
|
||||
|
||||
// Filter out stop words
|
||||
const meaningful = rawTokens.filter(
|
||||
(t) => !COMMON_STOP_WORDS.has(t) && t.length >= 2,
|
||||
);
|
||||
|
||||
// If filtering left nothing, return original non-empty tokens
|
||||
const baseTokens = meaningful.length > 0 ? meaningful : rawTokens;
|
||||
|
||||
// Expand with domain aliases (e.g. تائورین <-> تورین <-> taurine)
|
||||
const expanded = new Set<string>(baseTokens);
|
||||
for (const token of baseTokens) {
|
||||
const directAliases =
|
||||
SEARCH_EXPANSION_MAP[token] ||
|
||||
SEARCH_EXPANSION_MAP[token.toLowerCase()] ||
|
||||
SEARCH_EXPANSION_MAP[normalizeSearchText(token)];
|
||||
if (directAliases) {
|
||||
for (const alias of directAliases) {
|
||||
expanded.add(normalizeSearchText(alias));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(expanded).filter((t) => t.length >= 2);
|
||||
}
|
||||
|
||||
export interface SearchScoreItem {
|
||||
artNo?: string | null;
|
||||
barcode?: string | null;
|
||||
slug?: string | null;
|
||||
title?: string | null;
|
||||
shortDescription?: string | null;
|
||||
description?: string | null;
|
||||
tags?: Array<{ name?: string | null } | string> | null;
|
||||
ingredients?: Array<
|
||||
| { ingredient?: string | null; nameFa?: string | null; nameEn?: string | null }
|
||||
| string
|
||||
> | null;
|
||||
symptoms?: Array<{ symptom?: string | null } | string> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates a relevance score for a product or blog item against search tokens.
|
||||
*/
|
||||
export function calculateRelevanceScore(
|
||||
item: SearchScoreItem,
|
||||
rawQuery: string,
|
||||
tokens: string[],
|
||||
): number {
|
||||
if (!rawQuery || tokens.length === 0) return 0;
|
||||
|
||||
const normalizedQuery = normalizeSearchText(rawQuery);
|
||||
const normalizedTitle = normalizeSearchText(item.title);
|
||||
const normalizedArtNo = normalizeSearchText(item.artNo);
|
||||
const normalizedBarcode = normalizeSearchText(item.barcode);
|
||||
const normalizedSlug = normalizeSearchText(item.slug);
|
||||
|
||||
let score = 0;
|
||||
|
||||
// Exact matches get massive priority
|
||||
if (normalizedArtNo && normalizedArtNo === normalizedQuery) score += 200;
|
||||
if (normalizedBarcode && normalizedBarcode === normalizedQuery) score += 180;
|
||||
if (normalizedTitle && normalizedTitle === normalizedQuery) score += 150;
|
||||
if (normalizedSlug && normalizedSlug === normalizedQuery) score += 140;
|
||||
|
||||
// Title starts with full query
|
||||
if (normalizedTitle && normalizedTitle.startsWith(normalizedQuery)) score += 80;
|
||||
|
||||
// Title contains exact full query phrase
|
||||
if (normalizedTitle && normalizedTitle.includes(normalizedQuery)) score += 60;
|
||||
|
||||
// Token level matching in title (highest relevance)
|
||||
const titleTokens = normalizedTitle.split(" ");
|
||||
for (const token of tokens) {
|
||||
if (titleTokens.includes(token)) {
|
||||
score += 35;
|
||||
} else if (normalizedTitle.includes(token)) {
|
||||
score += 20;
|
||||
}
|
||||
}
|
||||
|
||||
// Ingredient / scientific terms matching
|
||||
if (item.ingredients && Array.isArray(item.ingredients)) {
|
||||
for (const ing of item.ingredients) {
|
||||
let ingName = "";
|
||||
if (typeof ing === "string") {
|
||||
ingName = ing;
|
||||
} else if (ing) {
|
||||
ingName = `${ing.ingredient || ""} ${ing.nameFa || ""} ${ing.nameEn || ""}`.trim();
|
||||
}
|
||||
const normIng = normalizeSearchText(ingName);
|
||||
if (normIng.includes(normalizedQuery)) score += 40;
|
||||
for (const token of tokens) {
|
||||
if (normIng.includes(token)) score += 15;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Symptoms matching
|
||||
if (item.symptoms && Array.isArray(item.symptoms)) {
|
||||
for (const sym of item.symptoms) {
|
||||
const symName = typeof sym === "string" ? sym : sym.symptom || "";
|
||||
const normSym = normalizeSearchText(symName);
|
||||
if (normSym.includes(normalizedQuery)) score += 30;
|
||||
for (const token of tokens) {
|
||||
if (normSym.includes(token)) score += 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tags matching
|
||||
if (item.tags && Array.isArray(item.tags)) {
|
||||
for (const tag of item.tags) {
|
||||
const tagName = typeof tag === "string" ? tag : tag.name || "";
|
||||
const normTag = normalizeSearchText(tagName);
|
||||
if (normTag.includes(normalizedQuery)) score += 25;
|
||||
for (const token of tokens) {
|
||||
if (normTag.includes(token)) score += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Short description matching
|
||||
const normShort = normalizeSearchText(item.shortDescription);
|
||||
if (normShort) {
|
||||
for (const token of tokens) {
|
||||
if (normShort.includes(token)) score += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// Long description (low weight, capped so it never overwhelms title/ingredients)
|
||||
const normDesc = normalizeSearchText(item.description);
|
||||
if (normDesc) {
|
||||
let descHits = 0;
|
||||
for (const token of tokens) {
|
||||
if (normDesc.includes(token)) descHits += 1;
|
||||
}
|
||||
score += Math.min(descHits * 2, 6);
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,126 +0,0 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
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: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],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
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: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');
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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: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);}
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,269 +0,0 @@
|
||||
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;
|
||||
}
|
||||
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 (config.origin !== 'http://canina-hermes:9119')
|
||||
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);
|
||||
}
|
||||
return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
|
||||
} catch (error) {
|
||||
if (error instanceof HermesError) throw error;
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this.inflight--;
|
||||
}
|
||||
}
|
||||
async health(): Promise<Health> {
|
||||
const health = fields(await this.request('/api/health'), {
|
||||
ok: 'boolean',
|
||||
version: 'string',
|
||||
commit: 'string',
|
||||
auth_required: 'boolean',
|
||||
}) 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 };
|
||||
}
|
||||
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',
|
||||
}),
|
||||
);
|
||||
}
|
||||
async modelInfo(profile: string): Promise<Row> {
|
||||
return fields(await this.request('/api/model/info', profile), {
|
||||
model: 'string',
|
||||
provider: 'string',
|
||||
effective_context_length: 'number',
|
||||
});
|
||||
}
|
||||
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' }),
|
||||
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 };
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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())),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "../../../.hermes-contract-build",
|
||||
"incremental": false,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["./*.ts"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
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(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);
|
||||
});
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
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';
|
||||
|
||||
// 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) {}
|
||||
@Get('tasks') async all() {
|
||||
return (await this.service.findAll()).map(project);
|
||||
}
|
||||
@Get('tasks/:id') async one(@Param('id') id: string) {
|
||||
return project(await this.service.findOne(id));
|
||||
}
|
||||
@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: false, chat: false, runtime: false },
|
||||
reason: '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',
|
||||
);
|
||||
}
|
||||
// The committed legacy core is not safe to expose. No env switch or role may bypass this boundary.
|
||||
@Post('tasks') create() {
|
||||
return this.deny();
|
||||
}
|
||||
@Put('tasks/:id/transition') transition() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/gates/:gate/decide') decide() {
|
||||
return this.deny();
|
||||
}
|
||||
@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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
export enum WorkflowState {
|
||||
DRAFT = 'DRAFT',
|
||||
GATE1_PENDING = 'GATE1_PENDING',
|
||||
GATE1_APPROVED = 'GATE1_APPROVED',
|
||||
READY = 'READY',
|
||||
CLAIMED = 'CLAIMED',
|
||||
RUNNING = 'RUNNING',
|
||||
VERIFYING = 'VERIFYING',
|
||||
GATE2_PENDING = 'GATE2_PENDING',
|
||||
GATE2_APPROVED = 'GATE2_APPROVED',
|
||||
RELEASING = 'RELEASING',
|
||||
PRODUCTION_VERIFYING = 'PRODUCTION_VERIFYING',
|
||||
LIVE_VERIFIED = 'LIVE_VERIFIED',
|
||||
MEASURING = 'MEASURING',
|
||||
CLOSED = 'CLOSED',
|
||||
REJECTED = 'REJECTED',
|
||||
BLOCKED = 'BLOCKED',
|
||||
CANCELLED = 'CANCELLED',
|
||||
FAILED = 'FAILED',
|
||||
EXPIRED = 'EXPIRED',
|
||||
}
|
||||
export enum OperationMode {
|
||||
OBSERVE = 'OBSERVE',
|
||||
PREPARE = 'PREPARE',
|
||||
MUTATE_PRODUCTION = 'MUTATE_PRODUCTION',
|
||||
}
|
||||
export enum RetryClass {
|
||||
TRANSIENT = 'TRANSIENT',
|
||||
RATE_LIMITED = 'RATE_LIMITED',
|
||||
DEPENDENCY = 'DEPENDENCY',
|
||||
VALIDATION = 'VALIDATION',
|
||||
POLICY = 'POLICY',
|
||||
PERMANENT = 'PERMANENT',
|
||||
}
|
||||
export enum KillSwitchLevel {
|
||||
FREEZE_NEW_WORK = 'FREEZE_NEW_WORK',
|
||||
STOP_AGENTS = 'STOP_AGENTS',
|
||||
DISABLE_MUTATIONS = 'DISABLE_MUTATIONS',
|
||||
EMERGENCY_HALT = 'EMERGENCY_HALT',
|
||||
}
|
||||
|
||||
const transitions: Record<WorkflowState, WorkflowState[]> = {
|
||||
DRAFT: [WorkflowState.GATE1_PENDING, WorkflowState.CANCELLED],
|
||||
GATE1_PENDING: [
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
WorkflowState.REJECTED,
|
||||
WorkflowState.EXPIRED,
|
||||
],
|
||||
GATE1_APPROVED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
READY: [
|
||||
WorkflowState.CLAIMED,
|
||||
WorkflowState.BLOCKED,
|
||||
WorkflowState.CANCELLED,
|
||||
],
|
||||
CLAIMED: [
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.READY,
|
||||
WorkflowState.CANCELLED,
|
||||
],
|
||||
RUNNING: [
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.FAILED,
|
||||
WorkflowState.BLOCKED,
|
||||
],
|
||||
VERIFYING: [
|
||||
WorkflowState.GATE2_PENDING,
|
||||
WorkflowState.FAILED,
|
||||
WorkflowState.RUNNING,
|
||||
],
|
||||
GATE2_PENDING: [
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
WorkflowState.REJECTED,
|
||||
WorkflowState.EXPIRED,
|
||||
],
|
||||
GATE2_APPROVED: [WorkflowState.RELEASING, WorkflowState.CANCELLED],
|
||||
RELEASING: [WorkflowState.PRODUCTION_VERIFYING, WorkflowState.FAILED],
|
||||
PRODUCTION_VERIFYING: [WorkflowState.LIVE_VERIFIED, WorkflowState.FAILED],
|
||||
LIVE_VERIFIED: [WorkflowState.MEASURING, WorkflowState.CLOSED],
|
||||
MEASURING: [WorkflowState.CLOSED, WorkflowState.FAILED],
|
||||
CLOSED: [],
|
||||
REJECTED: [],
|
||||
BLOCKED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
CANCELLED: [],
|
||||
FAILED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
EXPIRED: [WorkflowState.CANCELLED],
|
||||
};
|
||||
export function assertTransition(from: WorkflowState, to: WorkflowState): void {
|
||||
if (!transitions[from]?.includes(to))
|
||||
throw new BadRequestException(
|
||||
`Invalid orchestration transition ${from} -> ${to}`,
|
||||
);
|
||||
}
|
||||
export function nextStateForGateDecision(
|
||||
gate: 1 | 2,
|
||||
decision: 'APPROVED' | 'REJECTED',
|
||||
): WorkflowState {
|
||||
if (!(['APPROVED', 'REJECTED'] as string[]).includes(decision))
|
||||
throw new BadRequestException('Decision must be APPROVED or REJECTED');
|
||||
return decision === 'REJECTED'
|
||||
? WorkflowState.REJECTED
|
||||
: gate === 1
|
||||
? WorkflowState.GATE1_APPROVED
|
||||
: WorkflowState.GATE2_APPROVED;
|
||||
}
|
||||
@@ -1,577 +0,0 @@
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { DepartmentTasksController } from '../admin/department-tasks.controller';
|
||||
import { ApprovalsController } from '../admin/approvals.controller';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
import { WorkflowState, OperationMode } from './orchestration.domain';
|
||||
const enabled = process.env.ORCHESTRATION_INTEGRATION === '1';
|
||||
(enabled ? describe : describe.skip)(
|
||||
'v4 disposable PostgreSQL invariants',
|
||||
() => {
|
||||
const db = new PrismaClient();
|
||||
const service = new OrchestrationService(
|
||||
db as never,
|
||||
new KillSwitchService(db as never),
|
||||
);
|
||||
let n = 0;
|
||||
async function task(state = 'DRAFT', budget = 100) {
|
||||
return db.orchestrationTask.create({
|
||||
data: {
|
||||
key: `test-${Date.now()}-${n++}`,
|
||||
title: 'test',
|
||||
department: 'TEST',
|
||||
operationMode: 'PREPARE',
|
||||
state,
|
||||
budgetLimitCents: budget,
|
||||
},
|
||||
});
|
||||
}
|
||||
afterAll(async () => db.$disconnect());
|
||||
it('release rejects PREPARE operation class even with gate approval', async()=>{
|
||||
const t=await task('GATE2_APPROVED');
|
||||
await expect(service.command(t.id,'RELEASE_AUTHORIZE',{expectedVersion:1,idempotencyKey:`mode-${t.id}`},'ci')).rejects.toThrow(/operation mode/i);
|
||||
});
|
||||
|
||||
it('append-only ledger rejects direct rewrites in PostgreSQL', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 50,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `immutable-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
);
|
||||
await expect(
|
||||
db.orchestrationBudgetLedger.update({
|
||||
where: { id: r.id },
|
||||
data: { amountCents: 0 },
|
||||
}),
|
||||
).rejects.toThrow(/append.only/i);
|
||||
await expect(
|
||||
db.orchestrationBudgetLedger.delete({ where: { id: r.id } }),
|
||||
).rejects.toThrow(/append.only/i);
|
||||
});
|
||||
it('generic transitions cannot fake run lifecycle or production verification', async () => {
|
||||
for (const [from, to] of [
|
||||
['CLAIMED', 'RUNNING'],
|
||||
['RUNNING', 'VERIFYING'],
|
||||
['FAILED', 'READY'],
|
||||
['PRODUCTION_VERIFYING', 'LIVE_VERIFIED'],
|
||||
]) {
|
||||
const t = await task(from);
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `fake-${t.id}`,
|
||||
toState: to as WorkflowState,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/dedicated/i);
|
||||
}
|
||||
});
|
||||
it('exposes command and reconcile HTTP handlers', () => {
|
||||
const c = new OrchestrationController(service);
|
||||
expect(typeof c.command).toBe('function');
|
||||
expect(typeof c.reconcile).toBe('function');
|
||||
});
|
||||
it('highest kill level blocks reads and reconciliation', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
kind: 'RESERVE',
|
||||
amountCents: 10,
|
||||
idempotencyKey: `stop-res-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
);
|
||||
await service.setKillSwitch(
|
||||
['EMERGENCY', 'HALT'].join('_'),
|
||||
'test',
|
||||
'ceo',
|
||||
);
|
||||
try {
|
||||
await expect(service.findOne(t.id)).rejects.toThrow(/kill switch/i);
|
||||
await expect(
|
||||
service.reconcileBudget(
|
||||
t.id,
|
||||
{
|
||||
reservationId: r.id,
|
||||
actualCents: 0,
|
||||
idempotencyKey: `stop-recon-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
),
|
||||
).rejects.toThrow(/kill switch/i);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
});
|
||||
it('legacy arbitrary status and approval endpoints fail closed', async () => {
|
||||
await expect(
|
||||
new DepartmentTasksController(db as never).create({
|
||||
title: 'bypass',
|
||||
status: 'DONE',
|
||||
}),
|
||||
).rejects.toThrow(/v4/i);
|
||||
await expect(
|
||||
new DepartmentTasksController(db as never).updateStatus('none', {
|
||||
status: 'DONE',
|
||||
}),
|
||||
).rejects.toThrow(/v4/i);
|
||||
await expect(
|
||||
new ApprovalsController(db as never).decide('none', {
|
||||
decision: 'APPROVED',
|
||||
} as any),
|
||||
).rejects.toThrow(/v4/i);
|
||||
});
|
||||
it('release consumes only matching fresh production Gate2 via dedicated command', async () => {
|
||||
const t = await task('GATE2_PENDING');
|
||||
const hash = 'f'.repeat(64),
|
||||
commitSha = 'a'.repeat(40);
|
||||
const r = await db.orchestrationRun.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
status: 'SUCCEEDED',
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
idempotencyKey: `rel-run-${t.id}`,
|
||||
},
|
||||
});
|
||||
await db.orchestrationArtifact.create({
|
||||
data: {
|
||||
runId: r.id,
|
||||
kind: 'BUILD',
|
||||
uri: 'https://ci.example/build',
|
||||
sha256: hash,
|
||||
},
|
||||
});
|
||||
await db.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: r.id,
|
||||
kind: 'TEST',
|
||||
subjectHash: hash,
|
||||
signer: 'ci',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
});
|
||||
const decision = await service.decideGate(
|
||||
t.id,
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `rel-approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
runId: r.id,
|
||||
artifactHash: hash,
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
const dto = {
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `rel-${t.id}`,
|
||||
approvalId: decision.id,
|
||||
runId: r.id,
|
||||
artifactHash: hash,
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
};
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
{ ...dto, artifactHash: '0'.repeat(64) },
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow(/binding/i);
|
||||
const result = await (service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
dto,
|
||||
'ci',
|
||||
);
|
||||
expect(result.authorized).toBe(true);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.state,
|
||||
).toBe('RELEASING');
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
{ ...dto, expectedVersion: 3, idempotencyKey: `rel-again-${t.id}` },
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it('gate decision replay rejects changed immutable expiry and actor', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
const dto = {
|
||||
decision: 'APPROVED' as const,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `bind-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
};
|
||||
await service.decideGate(t.id, 1, dto, 'ceo');
|
||||
await expect(
|
||||
service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{ ...dto, expiresAt: new Date(Date.now() + 120000).toISOString() },
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
await expect(service.decideGate(t.id, 1, dto, 'other')).rejects.toThrow(
|
||||
/Idempotency/i,
|
||||
);
|
||||
});
|
||||
it('dependencies block admission and reject cycles', async () => {
|
||||
const a = await task();
|
||||
const b = await task();
|
||||
await (service as any).command(
|
||||
a.id,
|
||||
'DEPENDENCY_ADD',
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `dep-a-${a.id}`,
|
||||
dependsOnTaskId: b.id,
|
||||
},
|
||||
'actor',
|
||||
);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
b.id,
|
||||
'DEPENDENCY_ADD',
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `dep-b-${b.id}`,
|
||||
dependsOnTaskId: a.id,
|
||||
},
|
||||
'actor',
|
||||
),
|
||||
).rejects.toThrow(/cycle/i);
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: a.id },
|
||||
data: { state: 'GATE1_PENDING' },
|
||||
});
|
||||
await service.decideGate(
|
||||
a.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `dep-approval-${a.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await expect(
|
||||
service.transition(
|
||||
a.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `dep-ready-${a.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/dependency/i);
|
||||
});
|
||||
it('registers artifact and attestation for owned run, blocks unregistered subjects', async () => {
|
||||
const t = await task('CLAIMED');
|
||||
const base = {
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `life-${t.id}`,
|
||||
commitSha: 'c'.repeat(40),
|
||||
environment: 'staging',
|
||||
};
|
||||
const r = await (service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
base,
|
||||
'agent',
|
||||
);
|
||||
const hash = 'd'.repeat(64);
|
||||
const a = await (service as any).command(
|
||||
t.id,
|
||||
'ARTIFACT_ADD',
|
||||
{
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `art-${t.id}`,
|
||||
runId: r.id,
|
||||
sha256: hash,
|
||||
kind: 'BUILD',
|
||||
uri: 'https://ci.example/artifact',
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(a.sha256).toBe(hash);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'ATTESTATION_ADD',
|
||||
{
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `bad-att-${t.id}`,
|
||||
runId: r.id,
|
||||
subjectHash: 'e'.repeat(64),
|
||||
kind: 'TEST',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow(/artifact/i);
|
||||
const att = await (service as any).command(
|
||||
t.id,
|
||||
'ATTESTATION_ADD',
|
||||
{
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `att-${t.id}`,
|
||||
runId: r.id,
|
||||
subjectHash: hash,
|
||||
kind: 'TEST',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
'ci',
|
||||
);
|
||||
expect(att.signer).toBe('ci');
|
||||
});
|
||||
it('creates immutable versioned runs with bounded transient retries', async () => {
|
||||
const t = await task('CLAIMED');
|
||||
const dto = {
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `run-${t.id}`,
|
||||
commitSha: 'a'.repeat(40),
|
||||
environment: 'staging',
|
||||
};
|
||||
const r = await (service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
dto,
|
||||
'agent',
|
||||
);
|
||||
expect(r.attempt).toBe(1);
|
||||
expect(
|
||||
await (service as any).command(t.id, 'RUN_CREATE', dto, 'agent'),
|
||||
).toEqual(r);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
{ ...dto, commitSha: 'b'.repeat(40) },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
await (service as any).command(
|
||||
t.id,
|
||||
'RUN_FINISH',
|
||||
{
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `finish-${t.id}`,
|
||||
runId: r.id,
|
||||
status: 'FAILED',
|
||||
retryClass: 'POLICY',
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
{ ...dto, expectedVersion: 3, idempotencyKey: `retry-${t.id}` },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/retry/i);
|
||||
});
|
||||
it('selects tier at admission using backend risk and budget', async () => {
|
||||
const t = await task('GATE1_PENDING', 1000);
|
||||
await service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `approve-tier-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `admit-tier-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.modelTier,
|
||||
).toBe('L0');
|
||||
});
|
||||
it('STOP_AGENTS prevents claims and running transitions', async () => {
|
||||
await service.setKillSwitch('STOP_AGENTS', 'test', 'ceo');
|
||||
try {
|
||||
const t = await task('READY');
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.CLAIMED,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `kill-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/kill switch/i);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
});
|
||||
it('Gate1 admission consumes only unexpired approval', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
await service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 100).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `admit-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/expired/i);
|
||||
});
|
||||
it('versioned transition replay returns original result and rejects changed payload', async () => {
|
||||
const t = await task();
|
||||
const dto = {
|
||||
toState: WorkflowState.GATE1_PENDING,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `tr-${t.id}`,
|
||||
};
|
||||
const first = await service.transition(t.id, dto, 'actor');
|
||||
expect(await service.transition(t.id, dto, 'actor')).toEqual(first);
|
||||
await expect(
|
||||
service.transition(t.id, { ...dto, reason: 'different' }, 'actor'),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
});
|
||||
it('reconciles a reservation exactly once without erasing spent cost', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{ amountCents: 80, kind: 'RESERVE', idempotencyKey: `res-${t.id}` },
|
||||
'agent',
|
||||
);
|
||||
const dto = {
|
||||
reservationId: r.id,
|
||||
actualCents: 35,
|
||||
idempotencyKey: `reconcile-${t.id}`,
|
||||
};
|
||||
await (service as any).reconcileBudget(t.id, dto, 'agent');
|
||||
await (service as any).reconcileBudget(t.id, dto, 'agent');
|
||||
await expect(
|
||||
(service as any).reconcileBudget(
|
||||
t.id,
|
||||
{ ...dto, idempotencyKey: `second-${t.id}` },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/reconciled/i);
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
})
|
||||
)._sum.amountCents,
|
||||
).toBe(35);
|
||||
await expect(
|
||||
service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 66,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `too-much-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/budget/i);
|
||||
});
|
||||
it('concurrent budget reservations never exceed hard cap and replay is harmless', async () => {
|
||||
const t = await task();
|
||||
const result = await Promise.allSettled(
|
||||
Array.from({ length: 8 }, (_, i) =>
|
||||
service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 30,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `reserve-${t.id}-${i}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(result.filter((x) => x.status === 'fulfilled')).toHaveLength(3);
|
||||
const sum = await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
expect(sum._sum.amountCents).toBe(90);
|
||||
const first = await db.orchestrationBudgetLedger.findFirstOrThrow({
|
||||
where: { taskId: t.id },
|
||||
});
|
||||
await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 30,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: first.idempotencyKey,
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.count({ where: { taskId: t.id } }),
|
||||
).toBe(3);
|
||||
});
|
||||
it('generic transition cannot approve gate 1', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.GATE1_APPROVED,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `gate-bypass-${n}`,
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(/gate/i);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.state,
|
||||
).toBe('GATE1_PENDING');
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [OrchestrationController],
|
||||
providers: [OrchestrationService, KillSwitchService, ModelTierPolicyService],
|
||||
exports: [OrchestrationService, KillSwitchService, ModelTierPolicyService],
|
||||
})
|
||||
export class OrchestrationModule {}
|
||||
@@ -1,260 +0,0 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
|
||||
function mockPrisma() {
|
||||
const tx: any = {
|
||||
$queryRaw: jest.fn().mockResolvedValue([]),
|
||||
orchestrationTask: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
orchestrationRun: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationArtifact: { findFirst: jest.fn(), create: jest.fn() },
|
||||
orchestrationAttestation: { create: jest.fn() },
|
||||
orchestrationApprovalDecision: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationEvent: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationBudgetLedger: {
|
||||
findUnique: jest.fn(),
|
||||
aggregate: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
orchestrationKillSwitch: { findUnique: jest.fn(), upsert: jest.fn() },
|
||||
};
|
||||
tx.$transaction = jest.fn((cb: any) => Promise.resolve(cb(tx)));
|
||||
return tx;
|
||||
}
|
||||
|
||||
describe('OrchestrationService', () => {
|
||||
let prisma: any;
|
||||
let service: OrchestrationService;
|
||||
beforeEach(() => {
|
||||
prisma = mockPrisma();
|
||||
service = new OrchestrationService(prisma, {
|
||||
assertAllowed: jest.fn(),
|
||||
} as never);
|
||||
});
|
||||
|
||||
it('rejects an unknown kill level before overwriting persisted protection', async () => {
|
||||
await expect(service.setKillSwitch('INVALID_LEVEL','test','admin')).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.orchestrationKillSwitch.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates a task and append-only event transactionally', async () => {
|
||||
prisma.orchestrationTask.create.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'DRAFT',
|
||||
version: 1,
|
||||
});
|
||||
const result = await service.createTask(
|
||||
{
|
||||
key: 'seo-1',
|
||||
title: 'SEO',
|
||||
department: 'SEO',
|
||||
operationMode: 'PREPARE' as never,
|
||||
budgetLimitCents: 1000,
|
||||
},
|
||||
'actor-1',
|
||||
);
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.orchestrationTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ state: 'DRAFT', version: 1 }),
|
||||
});
|
||||
expect(prisma.orchestrationEvent.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ eventType: 'TASK_CREATED', sequence: 1 }),
|
||||
});
|
||||
expect(result.id).toBe('task-1');
|
||||
});
|
||||
|
||||
it('uses compare-and-swap versioning for transitions', async () => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'DRAFT',
|
||||
version: 3,
|
||||
});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 0 });
|
||||
await expect(
|
||||
service.transition(
|
||||
'task-1',
|
||||
{
|
||||
toState: 'GATE1_PENDING' as never,
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: 'i-1',
|
||||
},
|
||||
'actor',
|
||||
),
|
||||
).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it('makes gate decisions immutable and idempotent', async () => {
|
||||
const expiresAt = new Date(Date.now() + 10000).toISOString();
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue({
|
||||
id: 'd1',
|
||||
decision: 'APPROVED',
|
||||
gate: 1,
|
||||
taskId: 'task-1',
|
||||
});
|
||||
prisma.orchestrationEvent.findUnique.mockResolvedValue({
|
||||
payload: {
|
||||
fingerprint: JSON.stringify({
|
||||
taskId: 'task-1',
|
||||
gate: 1,
|
||||
dto: {
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-1',
|
||||
expiresAt,
|
||||
},
|
||||
actorId: 'ceo',
|
||||
}),
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-1',
|
||||
expiresAt,
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).resolves.toMatchObject({ id: 'd1' });
|
||||
expect(prisma.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an expired approval', async () => {
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-expired',
|
||||
expiresAt: new Date(0).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('binds gate 2 approval to run, artifact hash, commit and environment', async () => {
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'GATE2_PENDING',
|
||||
version: 7,
|
||||
});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({
|
||||
id: 'run-1',
|
||||
taskId: 'task-1',
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
status: 'SUCCEEDED',
|
||||
});
|
||||
prisma.orchestrationArtifact.findFirst.mockResolvedValue({
|
||||
id: 'artifact-1',
|
||||
runId: 'run-1',
|
||||
sha256: 'f'.repeat(64),
|
||||
});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 1 });
|
||||
prisma.orchestrationApprovalDecision.create.mockResolvedValue({
|
||||
id: 'decision-2',
|
||||
gate: 2,
|
||||
});
|
||||
await service.decideGate(
|
||||
'task-1',
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 7,
|
||||
idempotencyKey: 'gate-2',
|
||||
expiresAt: new Date(Date.now() + 10000).toISOString(),
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
expect(prisma.orchestrationApprovalDecision.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['RUNNING', 'FAILED', 'CANCELLED'])('refuses Gate 2 approval for an unfinished or unsuccessful %s run', async (status) => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({id:'task-1',state:'GATE2_PENDING',version:7});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({id:'run-1',taskId:'task-1',commitSha:'abc123',environment:'staging',status});
|
||||
prisma.orchestrationArtifact.findFirst.mockResolvedValue({id:'artifact-1'});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({count:1});
|
||||
await expect(service.decideGate('task-1',2,{
|
||||
decision:'APPROVED',expectedVersion:7,idempotencyKey:'failed-run',
|
||||
expiresAt:new Date(Date.now()+10000).toISOString(),runId:'run-1',
|
||||
artifactHash:'f'.repeat(64),commitSha:'abc123',environment:'staging',
|
||||
},'ceo')).rejects.toThrow(/successful run/i);
|
||||
expect(prisma.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
expect(prisma.orchestrationTask.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses gate 2 when binding does not match the immutable run', async () => {
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'GATE2_PENDING',
|
||||
version: 7,
|
||||
});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({
|
||||
id: 'run-1',
|
||||
taskId: 'task-1',
|
||||
commitSha: 'real',
|
||||
environment: 'staging',
|
||||
});
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 7,
|
||||
idempotencyKey: 'gate-bad',
|
||||
expiresAt: new Date(Date.now() + 10000).toISOString(),
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'wrong',
|
||||
environment: 'staging',
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('enforces hard task budget atomically', async () => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
budgetLimitCents: 1000,
|
||||
});
|
||||
prisma.orchestrationBudgetLedger.aggregate.mockResolvedValue({
|
||||
_sum: { amountCents: 900 },
|
||||
});
|
||||
await expect(
|
||||
service.recordBudget(
|
||||
'task-1',
|
||||
{ amountCents: 101, idempotencyKey: 'cost-1', kind: 'SPEND' },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(prisma.orchestrationBudgetLedger.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,665 +0,0 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
CreateOrchestrationTaskDto,
|
||||
GateDecisionDto,
|
||||
RecordBudgetDto,
|
||||
TransitionTaskDto,
|
||||
} from './dto/orchestration.dto';
|
||||
import {
|
||||
KillSwitchLevel,
|
||||
assertTransition,
|
||||
nextStateForGateDecision,
|
||||
OperationMode,
|
||||
WorkflowState,
|
||||
} from './orchestration.domain';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
@Injectable()
|
||||
export class OrchestrationService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly killSwitch: KillSwitchService,
|
||||
) {}
|
||||
async createTask(dto: CreateOrchestrationTaskDto, actorId: string) {
|
||||
await this.killSwitch.assertAllowed('CREATE_TASK');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
const task = await tx.orchestrationTask.create({
|
||||
data: {
|
||||
key: dto.key,
|
||||
title: dto.title,
|
||||
department: dto.department,
|
||||
operationMode: dto.operationMode,
|
||||
budgetLimitCents: dto.budgetLimitCents,
|
||||
metadata: dto.metadata ?? {},
|
||||
state: WorkflowState.DRAFT,
|
||||
version: 1,
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: task.id,
|
||||
eventType: 'TASK_CREATED',
|
||||
fromState: null,
|
||||
toState: WorkflowState.DRAFT,
|
||||
sequence: 1,
|
||||
actorId,
|
||||
payload: { key: dto.key },
|
||||
},
|
||||
});
|
||||
return task;
|
||||
});
|
||||
}
|
||||
async transition(id: string, dto: TransitionTaskDto, actorId: string) {
|
||||
if (
|
||||
[
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
WorkflowState.RELEASING,
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.PRODUCTION_VERIFYING,
|
||||
WorkflowState.LIVE_VERIFIED,
|
||||
WorkflowState.MEASURING,
|
||||
WorkflowState.CLOSED,
|
||||
].includes(dto.toState)
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Gate approvals and release require dedicated commands',
|
||||
);
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${id}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ id, dto, actorId });
|
||||
const replay = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.payload.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return replay.payload.result;
|
||||
}
|
||||
const existing = await tx.orchestrationTask.findUnique({ where: { id } });
|
||||
if (!existing)
|
||||
throw new NotFoundException(`Orchestration task ${id} not found`);
|
||||
if (existing.state === WorkflowState.FAILED)
|
||||
throw new ForbiddenException('Retries require dedicated run command');
|
||||
assertTransition(existing.state, dto.toState);
|
||||
await this.killSwitch.assertAllowed(
|
||||
[
|
||||
WorkflowState.READY,
|
||||
WorkflowState.CLAIMED,
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.GATE2_PENDING,
|
||||
].includes(dto.toState)
|
||||
? 'RUN_AGENT'
|
||||
: 'OBSERVE',
|
||||
);
|
||||
if ([WorkflowState.READY, WorkflowState.CLAIMED].includes(dto.toState))
|
||||
await this.killSwitch.assertAllowed('CLAIM_TASK');
|
||||
let selectedTier = existing.modelTier;
|
||||
if (dto.toState === WorkflowState.READY) {
|
||||
const dependencies = await tx.orchestrationDependency.findMany({
|
||||
where: { taskId: id },
|
||||
include: { dependsOnTask: true },
|
||||
});
|
||||
if (dependencies.some((d: any) => d.dependsOnTask.state !== 'CLOSED'))
|
||||
throw new ForbiddenException('Unresolved dependency');
|
||||
const costs = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
selectedTier = new ModelTierPolicyService().select({
|
||||
complexity: Number(existing.metadata?.complexity ?? 0),
|
||||
risk: Number(existing.metadata?.risk ?? 0),
|
||||
operationMode: existing.operationMode,
|
||||
remainingBudgetCents:
|
||||
existing.budgetLimitCents - (costs._sum.amountCents ?? 0),
|
||||
});
|
||||
const approval = await tx.orchestrationApprovalDecision.findFirst({
|
||||
where: { taskId: id, gate: 1, decision: 'APPROVED' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (!approval || approval.expiresAt <= new Date())
|
||||
throw new ForbiddenException('Gate 1 approval missing or expired');
|
||||
}
|
||||
if (
|
||||
existing.operationMode === OperationMode.MUTATE_PRODUCTION &&
|
||||
dto.toState === WorkflowState.RELEASING
|
||||
)
|
||||
await this.killSwitch.assertAllowed('MUTATE_PRODUCTION');
|
||||
const changed = await tx.orchestrationTask.updateMany({
|
||||
where: { id, version: dto.expectedVersion, state: existing.state },
|
||||
data: {
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
if (changed.count !== 1)
|
||||
throw new ConflictException(
|
||||
'Task version or state changed; reload before retrying',
|
||||
);
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
eventType: 'STATE_TRANSITION',
|
||||
fromState: existing.state,
|
||||
toState: dto.toState,
|
||||
sequence: dto.expectedVersion + 1,
|
||||
actorId,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
payload: {
|
||||
fingerprint,
|
||||
result: JSON.parse(
|
||||
JSON.stringify({
|
||||
...existing,
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: dto.expectedVersion + 1,
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
return JSON.parse(
|
||||
JSON.stringify({
|
||||
...existing,
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: dto.expectedVersion + 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
async decideGate(
|
||||
taskId: string,
|
||||
gate: 1 | 2,
|
||||
dto: GateDecisionDto,
|
||||
actorId: string,
|
||||
) {
|
||||
if (![1, 2].includes(gate)) throw new BadRequestException('Invalid gate');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ taskId, gate, dto, actorId });
|
||||
const prior = await tx.orchestrationApprovalDecision.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
const event = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: `event:${dto.idempotencyKey}` },
|
||||
});
|
||||
if (event?.payload?.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
if (
|
||||
!Number.isFinite(Date.parse(dto.expiresAt)) ||
|
||||
new Date(dto.expiresAt) <= new Date()
|
||||
)
|
||||
throw new BadRequestException('Approval decision has expired');
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${taskId} not found`);
|
||||
const expected =
|
||||
gate === 1 ? WorkflowState.GATE1_PENDING : WorkflowState.GATE2_PENDING;
|
||||
if (task.state !== expected)
|
||||
throw new ConflictException(`Gate ${gate} requires ${expected}`);
|
||||
if (gate === 2 && dto.decision === 'APPROVED') {
|
||||
if (
|
||||
!dto.runId ||
|
||||
!dto.artifactHash ||
|
||||
!dto.commitSha ||
|
||||
!dto.environment
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Gate 2 requires runId, artifactHash, commitSha and environment',
|
||||
);
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.commitSha !== dto.commitSha ||
|
||||
run.environment !== dto.environment
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Gate 2 binding does not match immutable run',
|
||||
);
|
||||
if (run.status !== 'SUCCEEDED')
|
||||
throw new ForbiddenException('Gate 2 requires a successful run');
|
||||
const artifact = await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: dto.runId, sha256: dto.artifactHash },
|
||||
});
|
||||
if (!artifact)
|
||||
throw new ForbiddenException(
|
||||
'Gate 2 artifact hash is not registered for run',
|
||||
);
|
||||
}
|
||||
const next = nextStateForGateDecision(gate, dto.decision);
|
||||
const changed = await tx.orchestrationTask.updateMany({
|
||||
where: { id: taskId, version: dto.expectedVersion, state: expected },
|
||||
data: { state: next, version: { increment: 1 } },
|
||||
});
|
||||
if (changed.count !== 1)
|
||||
throw new ConflictException(
|
||||
'Task version or state changed; approval not applied',
|
||||
);
|
||||
const decision = await tx.orchestrationApprovalDecision.create({
|
||||
data: {
|
||||
taskId,
|
||||
gate,
|
||||
decision: dto.decision,
|
||||
actorId,
|
||||
notes: dto.notes,
|
||||
expiresAt: new Date(dto.expiresAt),
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
runId: dto.runId,
|
||||
artifactHash: dto.artifactHash,
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId,
|
||||
eventType: `GATE${gate}_${dto.decision}`,
|
||||
fromState: expected,
|
||||
toState: next,
|
||||
sequence: dto.expectedVersion + 1,
|
||||
actorId,
|
||||
idempotencyKey: `event:${dto.idempotencyKey}`,
|
||||
payload: { decisionId: decision.id, fingerprint },
|
||||
},
|
||||
});
|
||||
return decision;
|
||||
});
|
||||
}
|
||||
async recordBudget(taskId: string, dto: RecordBudgetDto, actorId: string) {
|
||||
if (
|
||||
!Number.isSafeInteger(dto.amountCents) ||
|
||||
dto.amountCents < 1 ||
|
||||
!['RESERVE', 'SPEND'].includes(dto.kind)
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Use RESERVE or SPEND with positive integer cents',
|
||||
);
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const prior = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
if (
|
||||
prior.taskId !== taskId ||
|
||||
prior.kind !== dto.kind ||
|
||||
prior.amountCents !== dto.amountCents ||
|
||||
prior.actorId !== actorId ||
|
||||
JSON.stringify(prior.metadata) !== JSON.stringify(dto.metadata ?? {})
|
||||
)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
await this.killSwitch.assertAllowed('RUN_AGENT');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${taskId} not found`);
|
||||
const sum = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
if ((sum._sum.amountCents ?? 0) + dto.amountCents > task.budgetLimitCents)
|
||||
throw new ForbiddenException('Hard task budget exceeded');
|
||||
return tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId,
|
||||
amountCents: dto.amountCents,
|
||||
kind: dto.kind,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
actorId,
|
||||
metadata: dto.metadata ?? {},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
async command(taskId: string, command: string, dto: any, actorId: string) {
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ taskId, command, dto, actorId });
|
||||
const replay = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.payload.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return replay.payload.result;
|
||||
}
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task) throw new NotFoundException('Task not found');
|
||||
if (task.version !== dto.expectedVersion)
|
||||
throw new ConflictException('Stale task version');
|
||||
await this.killSwitch.assertAllowed('RUN_AGENT');
|
||||
let result: any;
|
||||
let state = task.state;
|
||||
if (command === 'RUN_CREATE') {
|
||||
if (
|
||||
!/^[a-f0-9]{40,64}$/.test(dto.commitSha) ||
|
||||
!['development', 'staging', 'production'].includes(dto.environment)
|
||||
)
|
||||
throw new BadRequestException('Invalid immutable run binding');
|
||||
const last = await tx.orchestrationRun.findFirst({
|
||||
where: { taskId },
|
||||
orderBy: { attempt: 'desc' },
|
||||
});
|
||||
if (
|
||||
last &&
|
||||
(last.status !== 'FAILED' ||
|
||||
!['TRANSIENT', 'RATE_LIMITED', 'DEPENDENCY'].includes(
|
||||
last.retryClass,
|
||||
) ||
|
||||
last.attempt >= 3)
|
||||
)
|
||||
throw new ForbiddenException('Retry denied or exhausted');
|
||||
if (!last && task.state !== 'CLAIMED')
|
||||
throw new ConflictException('Run requires CLAIMED task');
|
||||
result = await tx.orchestrationRun.create({
|
||||
data: {
|
||||
taskId,
|
||||
attempt: (last?.attempt ?? 0) + 1,
|
||||
status: 'RUNNING',
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
startedAt: new Date(),
|
||||
},
|
||||
});
|
||||
state = 'RUNNING';
|
||||
} else if (command === 'RUN_FINISH') {
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.status !== 'RUNNING' ||
|
||||
task.state !== 'RUNNING'
|
||||
)
|
||||
throw new ConflictException('Active run required');
|
||||
if (
|
||||
!['SUCCEEDED', 'FAILED'].includes(dto.status) ||
|
||||
(dto.status === 'FAILED' &&
|
||||
![
|
||||
'TRANSIENT',
|
||||
'RATE_LIMITED',
|
||||
'DEPENDENCY',
|
||||
'VALIDATION',
|
||||
'POLICY',
|
||||
'PERMANENT',
|
||||
].includes(dto.retryClass))
|
||||
)
|
||||
throw new BadRequestException('Invalid outcome taxonomy');
|
||||
result = await tx.orchestrationRun.update({
|
||||
where: { id: run.id },
|
||||
data: {
|
||||
status: dto.status,
|
||||
retryClass: dto.status === 'FAILED' ? dto.retryClass : null,
|
||||
finishedAt: new Date(),
|
||||
},
|
||||
});
|
||||
state = dto.status === 'FAILED' ? 'FAILED' : 'VERIFYING';
|
||||
} else if (command === 'ARTIFACT_ADD' || command === 'ATTESTATION_ADD') {
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
!['RUNNING', 'VERIFYING'].includes(task.state)
|
||||
)
|
||||
throw new ConflictException('Owned active run required');
|
||||
const hash = command === 'ARTIFACT_ADD' ? dto.sha256 : dto.subjectHash;
|
||||
if (!/^[a-f0-9]{64}$/.test(hash) || !dto.kind)
|
||||
throw new BadRequestException('Invalid artifact hash or kind');
|
||||
if (command === 'ARTIFACT_ADD') {
|
||||
if (!/^https:\/\//.test(dto.uri))
|
||||
throw new BadRequestException('Artifact URI must be HTTPS');
|
||||
result = await tx.orchestrationArtifact.create({
|
||||
data: { runId: run.id, kind: dto.kind, sha256: hash, uri: dto.uri },
|
||||
});
|
||||
} else {
|
||||
if (
|
||||
!(await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: run.id, sha256: hash },
|
||||
}))
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Attestation subject is not a registered artifact',
|
||||
);
|
||||
result = await tx.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: run.id,
|
||||
kind: dto.kind,
|
||||
subjectHash: hash,
|
||||
predicate: dto.predicate ?? {},
|
||||
signer: actorId,
|
||||
signature: dto.signature,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (command === 'DEPENDENCY_ADD') {
|
||||
if (task.state !== 'DRAFT')
|
||||
throw new ConflictException(
|
||||
'Dependencies are frozen after submission',
|
||||
);
|
||||
await tx.$executeRaw`LOCK TABLE orchestration_dependencies IN EXCLUSIVE MODE`;
|
||||
const cycles =
|
||||
await tx.$queryRaw`WITH RECURSIVE chain(id) AS (SELECT ${dto.dependsOnTaskId}::uuid UNION SELECT d.depends_on_task_id FROM orchestration_dependencies d JOIN chain c ON d.task_id=c.id) SELECT id FROM chain WHERE id=${taskId}::uuid`;
|
||||
if (cycles.length) throw new ForbiddenException('Dependency cycle');
|
||||
result = await tx.orchestrationDependency.create({
|
||||
data: { taskId, dependsOnTaskId: dto.dependsOnTaskId },
|
||||
});
|
||||
} else if (command === 'RELEASE_AUTHORIZE') {
|
||||
await this.killSwitch.assertAllowed('MUTATE_PRODUCTION');
|
||||
if (task.state !== 'GATE2_APPROVED')
|
||||
throw new ConflictException(
|
||||
'Gate 2 approval required; already consumed or invalid state',
|
||||
);
|
||||
const approval = await tx.orchestrationApprovalDecision.findUnique({
|
||||
where: { id: dto.approvalId },
|
||||
});
|
||||
if (
|
||||
!approval ||
|
||||
approval.taskId !== taskId ||
|
||||
approval.gate !== 2 ||
|
||||
approval.decision !== 'APPROVED' ||
|
||||
approval.expiresAt <= new Date()
|
||||
)
|
||||
throw new ForbiddenException('Gate 2 missing or expired');
|
||||
for (const key of ['runId', 'artifactHash', 'commitSha', 'environment'])
|
||||
if (approval[key] !== dto[key])
|
||||
throw new ForbiddenException('Release binding mismatch');
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.status !== 'SUCCEEDED' ||
|
||||
run.commitSha !== dto.commitSha ||
|
||||
run.environment !== dto.environment
|
||||
)
|
||||
throw new ForbiddenException('Run binding mismatch');
|
||||
if (
|
||||
!(await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: run.id, sha256: dto.artifactHash },
|
||||
})) ||
|
||||
!(await tx.orchestrationAttestation.findFirst({
|
||||
where: {
|
||||
runId: run.id,
|
||||
subjectHash: dto.artifactHash,
|
||||
kind: 'TEST',
|
||||
},
|
||||
}))
|
||||
)
|
||||
throw new ForbiddenException('Artifact evidence missing');
|
||||
result = {
|
||||
authorized: true,
|
||||
approvalId: approval.id,
|
||||
runId: run.id,
|
||||
artifactHash: dto.artifactHash,
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
execution: 'CI_CD_ONLY',
|
||||
};
|
||||
state = 'RELEASING';
|
||||
} else throw new BadRequestException('Unknown command');
|
||||
await tx.orchestrationTask.update({
|
||||
where: { id: taskId },
|
||||
data: { state, version: { increment: 1 } },
|
||||
});
|
||||
const serialized = JSON.parse(JSON.stringify(result));
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId,
|
||||
eventType: command,
|
||||
fromState: task.state,
|
||||
toState: state,
|
||||
sequence: task.version + 1,
|
||||
actorId,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
payload: { fingerprint, result: serialized },
|
||||
},
|
||||
});
|
||||
return serialized;
|
||||
});
|
||||
}
|
||||
async reconcileBudget(
|
||||
taskId: string,
|
||||
dto: { reservationId: string; actualCents: number; idempotencyKey: string },
|
||||
actorId: string,
|
||||
) {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
if (!Number.isSafeInteger(dto.actualCents) || dto.actualCents < 0)
|
||||
throw new BadRequestException('Invalid actual cost');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const prior = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
if (
|
||||
prior.taskId !== taskId ||
|
||||
prior.actorId !== actorId ||
|
||||
prior.metadata.reservationId !== dto.reservationId ||
|
||||
prior.metadata.actualCents !== dto.actualCents
|
||||
)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
const reservation = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { id: dto.reservationId },
|
||||
});
|
||||
if (
|
||||
!reservation ||
|
||||
reservation.taskId !== taskId ||
|
||||
reservation.kind !== 'RESERVE'
|
||||
)
|
||||
throw new BadRequestException('Reservation not found');
|
||||
if (
|
||||
await tx.orchestrationBudgetLedger.findFirst({
|
||||
where: {
|
||||
taskId,
|
||||
kind: 'RECONCILE',
|
||||
metadata: { path: ['reservationId'], equals: dto.reservationId },
|
||||
},
|
||||
})
|
||||
)
|
||||
throw new ConflictException('Reservation already reconciled');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
const total = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
const delta = dto.actualCents - reservation.amountCents;
|
||||
if (total._sum.amountCents + delta > task.budgetLimitCents)
|
||||
throw new ForbiddenException('Hard task budget exceeded');
|
||||
return tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId,
|
||||
kind: 'RECONCILE',
|
||||
amountCents: delta,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
actorId,
|
||||
metadata: {
|
||||
reservationId: dto.reservationId,
|
||||
actualCents: dto.actualCents,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
async findAll() {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
return (this.prisma as any).orchestrationTask.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
async findOne(id: string) {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
const task = await (this.prisma as any).orchestrationTask.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
runs: { include: { artifacts: true, attestations: true } },
|
||||
dependencies: true,
|
||||
decisions: true,
|
||||
events: { orderBy: { sequence: 'asc' } },
|
||||
budgetLedger: true,
|
||||
},
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${id} not found`);
|
||||
return task;
|
||||
}
|
||||
async setKillSwitch(level: string, reason: string, actorId: string) {
|
||||
if (!Object.values(KillSwitchLevel).includes(level as KillSwitchLevel))
|
||||
throw new BadRequestException('Invalid kill switch level');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
const value = await tx.orchestrationKillSwitch.upsert({
|
||||
where: { scope: 'GLOBAL' },
|
||||
create: { scope: 'GLOBAL', level, active: true, reason, actorId },
|
||||
update: {
|
||||
level,
|
||||
active: true,
|
||||
reason,
|
||||
actorId,
|
||||
version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
eventType: 'KILL_SWITCH_CHANGED',
|
||||
sequence: value.version ?? 1,
|
||||
actorId,
|
||||
payload: { scope: 'GLOBAL', level, reason },
|
||||
},
|
||||
});
|
||||
return value;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,11 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
import { GetProductsDto } from "./dto/get-products.dto";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
@@ -62,37 +67,60 @@ export class ProductsService {
|
||||
andConditions.push({ priceValue: { lte: Number(maxPrice) } });
|
||||
}
|
||||
|
||||
if (search) {
|
||||
andConditions.push({
|
||||
OR: [
|
||||
{ artNo: { contains: search, mode: "insensitive" } },
|
||||
{ barcode: { contains: search, mode: "insensitive" } },
|
||||
{ nameFa: { contains: search, mode: "insensitive" } },
|
||||
{ nameEn: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
{ shortDescription: { contains: search, mode: "insensitive" } },
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
const searchConditions: Prisma.ProductWhereInput[] = [
|
||||
{ artNo: { contains: search, mode } },
|
||||
{ barcode: { contains: search, mode } },
|
||||
{ slug: { contains: search, mode } },
|
||||
{ nameFa: { contains: search, mode } },
|
||||
{ nameEn: { contains: search, mode } },
|
||||
{ shortDescription: { contains: search, mode } },
|
||||
];
|
||||
|
||||
for (const token of tokens) {
|
||||
searchConditions.push(
|
||||
{ nameFa: { contains: token, mode } },
|
||||
{ nameEn: { contains: token, mode } },
|
||||
{
|
||||
symptoms: {
|
||||
ingredientList: {
|
||||
some: {
|
||||
symptom: { contains: search, mode: "insensitive" },
|
||||
OR: [
|
||||
{ ingredient: { contains: token, mode } },
|
||||
{ ingredientCardSlug: { contains: token, mode } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
symptoms: {
|
||||
some: {
|
||||
symptom: { contains: token, mode },
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
andConditions.push({
|
||||
OR: searchConditions,
|
||||
});
|
||||
}
|
||||
|
||||
const whereClause: Prisma.ProductWhereInput =
|
||||
andConditions.length > 0 ? { AND: andConditions } : {};
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 50);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
// 1. Fetch products with lean relations (no heavy N+1 orderItems join)
|
||||
// 1. Fetch products with lean relations
|
||||
const [rawProducts, total] = await Promise.all([
|
||||
this.prisma.product.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
include: {
|
||||
ingredientList: true,
|
||||
@@ -102,8 +130,34 @@ export class ProductsService {
|
||||
this.prisma.product.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
// Rank by relevance if searching
|
||||
let candidateProducts = rawProducts;
|
||||
if (tokens.length > 0 && search) {
|
||||
candidateProducts = [...rawProducts]
|
||||
.map((p) => ({
|
||||
product: p,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
artNo: p.artNo,
|
||||
barcode: p.barcode,
|
||||
slug: p.slug,
|
||||
title: p.nameFa || p.nameEn,
|
||||
shortDescription: p.shortDescription,
|
||||
description: p.description,
|
||||
ingredients: p.ingredientList,
|
||||
symptoms: p.symptoms,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.product)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
// 2. Efficient single aggregate query for total sold counts for the current page slice
|
||||
const productIds = rawProducts.map((p) => p.id);
|
||||
const productIds = candidateProducts.map((p) => p.id);
|
||||
let salesMap: Record<string, number> = {};
|
||||
|
||||
if (productIds.length > 0) {
|
||||
@@ -131,7 +185,7 @@ export class ProductsService {
|
||||
userRole === "SuperAdmin";
|
||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||
|
||||
const data = rawProducts.map((p) => {
|
||||
const data = candidateProducts.map((p) => {
|
||||
const totalSold = salesMap[p.id] || 0;
|
||||
const { buyPrice, wholesalePrice, ...publicProduct } = p;
|
||||
void buyPrice;
|
||||
@@ -146,12 +200,7 @@ export class ProductsService {
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit) || 1,
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
const stats = {totalRequests:0,totalPromptTokens:0,totalCompletionTokens:0,totalCachedTokens:0,byModel:{},byProvider:{},byAccount:{}};
|
||||
describe('bounded read-only adapter', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
it('uses only authenticated GET stats with a validated period and never follows redirects', async () => {
|
||||
const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue(new Response(JSON.stringify(stats)));
|
||||
const adapter = new RouterUsageAdapter();
|
||||
process.env.ROUTER_USAGE_BASE_URL = 'https://nr.parsaaghayi.ir';
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN = 'server-only-secret';
|
||||
const result = await adapter.summary('24h');
|
||||
expect(result.status).toBe('available');
|
||||
expect(result.attribution).toEqual({scope:'9router_total',hermes:null,additive:false});
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(fetcher).toHaveBeenCalledWith('https://nr.parsaaghayi.ir/api/usage/stats?period=24h', expect.objectContaining({method:'GET',redirect:'error',headers:{'x-9r-cli-token':'server-only-secret',Accept:'application/json'}}));
|
||||
expect(JSON.stringify(result)).not.toContain('server-only-secret');
|
||||
});
|
||||
it('rejects invalid time filters before IO', async () => {
|
||||
const fetcher = jest.spyOn(global,'fetch');
|
||||
await expect(new RouterUsageAdapter().summary('../providers')).rejects.toThrow();
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('fails closed when credential is missing', async () => {
|
||||
delete process.env.ROUTER_USAGE_CLI_TOKEN;
|
||||
const fetcher = jest.spyOn(global,'fetch');
|
||||
const result = await new RouterUsageAdapter().summary('7d');
|
||||
expect(result).toMatchObject({status:'unavailable',data:null,reason:'not_configured'});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([401,403,429,500])('returns unknown data without upstream error text for %s', async status => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValue(new Response('credential-secret',{status}));
|
||||
const result = await new RouterUsageAdapter().summary('7d');
|
||||
expect(result).toMatchObject({status:'unavailable',data:null,reason:'upstream_unavailable'});
|
||||
expect(JSON.stringify(result)).not.toContain('credential-secret');
|
||||
});
|
||||
it('rejects oversized bodies even without content length', async () => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValue(new Response('x'.repeat(1048577)));
|
||||
expect(await new RouterUsageAdapter().summary('7d')).toMatchObject({status:'unavailable',data:null});
|
||||
});
|
||||
it('does not return stale last-good totals after a failure', async () => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValueOnce(new Response(JSON.stringify(stats))).mockRejectedValueOnce(new Error('token-secret'));
|
||||
const adapter=new RouterUsageAdapter();
|
||||
expect((await adapter.summary('7d')).status).toBe('available');
|
||||
expect(await adapter.summary('7d')).toMatchObject({status:'unavailable',data:null});
|
||||
});
|
||||
});
|
||||
|
||||
describe('transport boundaries', () => {
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
it('never sends credentials to a configured alternate origin', async()=>{
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
process.env.ROUTER_USAGE_BASE_URL='https://attacker.invalid';
|
||||
const fetcher=jest.spyOn(global,'fetch');
|
||||
expect(await new RouterUsageAdapter().summary()).toMatchObject({status:'unavailable',reason:'invalid_configuration'});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
delete process.env.ROUTER_USAGE_BASE_URL;
|
||||
});
|
||||
it('bounds simultaneous upstream calls and exposes no stale totals', async()=>{
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
let resolve!: (value: Response) => void;
|
||||
const pending=new Promise<Response>(r=>{resolve=r;});
|
||||
jest.spyOn(global,'fetch').mockReturnValue(pending);
|
||||
const adapter=new RouterUsageAdapter();
|
||||
const calls=Array.from({length:4},()=>adapter.summary());
|
||||
expect(await adapter.summary()).toMatchObject({status:'unavailable',reason:'busy',data:null});
|
||||
resolve(new Response('',{status:503}));
|
||||
await Promise.all(calls);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { normalizeStats } from './router-usage.contract';
|
||||
export const ROUTER_PERIODS = ['today','24h','7d','30d','60d','all'] as const;
|
||||
@Injectable()
|
||||
export class RouterUsageAdapter {
|
||||
private active = 0;
|
||||
async summary(period = '7d') {
|
||||
if (!ROUTER_PERIODS.includes(period as typeof ROUTER_PERIODS[number])) throw new BadRequestException('Invalid period');
|
||||
const base = {source:'9router' as const,period,attribution:{scope:'9router_total',hermes:null,additive:false},
|
||||
capabilities:{errors:false,reasoningTokens:false,cacheWriteTokens:false,quota:false,customTimeRange:false},
|
||||
freshness:{retrievedAt:null as string | null,sourceUpdatedAt:null,stale:null as boolean | null}};
|
||||
const unavailable = (reason: string) => ({...base,status:'unavailable' as const,reason,data:null});
|
||||
const token=process.env.ROUTER_USAGE_CLI_TOKEN;
|
||||
if (!token) return unavailable('not_configured');
|
||||
if (this.active >= 4) return unavailable('busy');
|
||||
this.active++;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(),5000);
|
||||
try {
|
||||
const url=new URL(process.env.ROUTER_USAGE_BASE_URL || 'https://nr.parsaaghayi.ir');
|
||||
if (url.origin !== 'https://nr.parsaaghayi.ir' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) return unavailable('invalid_configuration');
|
||||
const response=await fetch(`${url.origin}/api/usage/stats?period=${period}`,{
|
||||
method:'GET',redirect:'error',signal:controller.signal,
|
||||
headers:{'x-9r-cli-token':token,Accept:'application/json'},
|
||||
});
|
||||
if (!response.ok || !response.body) throw new Error('Upstream unavailable');
|
||||
const reader=response.body.getReader();
|
||||
const chunks:Uint8Array[]=[];
|
||||
let size=0;
|
||||
try {
|
||||
while (true) {
|
||||
const {done,value}=await reader.read();
|
||||
if (done) break;
|
||||
size+=value.byteLength;
|
||||
if (size>1048576) {await reader.cancel(); throw new Error('Response too large');}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally { reader.releaseLock(); }
|
||||
const data=normalizeStats(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
||||
return {...base,status:'available' as const,reason:null,data,
|
||||
freshness:{retrievedAt:new Date().toISOString(),sourceUpdatedAt:null,stale:null}};
|
||||
} catch { return unavailable('upstream_unavailable'); }
|
||||
finally { clearTimeout(timeout); this.active--; }
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
type RecordValue = Record<string, unknown>;
|
||||
export function record(value: unknown): RecordValue {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid upstream schema');
|
||||
return value as RecordValue;
|
||||
}
|
||||
function count(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
function identifier(value: unknown): string | null {
|
||||
return typeof value === 'string' && /^[a-zA-Z0-9_./:@()+ -]{1,180}$/.test(value) && !value.includes('@') && !/^(sk-|Bearer )/i.test(value) ? value : null;
|
||||
}
|
||||
function metrics(row: RecordValue, prefix = '') {
|
||||
const key = (name: string) => prefix ? prefix + name[0].toUpperCase() + name.slice(1) : name;
|
||||
return {
|
||||
requests: count(row[key('requests')]), inputTokens: count(row[key('promptTokens')]),
|
||||
outputTokens: count(row[key('completionTokens')]), cacheReadTokens: count(row[key('cachedTokens')]),
|
||||
cacheWriteTokens: null, reasoningTokens: null, errors: null,
|
||||
};
|
||||
}
|
||||
export function normalizeStats(value: unknown) {
|
||||
const stats = record(value);
|
||||
if (count(stats.totalRequests) === null) throw new Error('Invalid stats');
|
||||
const rows = (key: string) => {
|
||||
const entries = Object.entries(record(stats[key]));
|
||||
if (entries.length > 2000) throw new Error('Too many aggregates');
|
||||
return entries;
|
||||
};
|
||||
return {
|
||||
totals: metrics(stats, 'total'),
|
||||
providers: rows('byProvider').map(([id, row]) => ({provider: identifier(id), ...metrics(record(row))})),
|
||||
models: rows('byModel').map(([, row]) => { const r = record(row); return {model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r)}; }),
|
||||
accounts: rows('byAccount').map(([, row]) => { const r = record(row); return {
|
||||
accountId: identifier(r.connectionId), model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r),
|
||||
quota: {status: 'unknown' as const, remaining: null, resetAt: null, reason: 'upstream_quota_get_mutates_credentials'},
|
||||
}; }),
|
||||
};
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Controller, Get, Header, Query, UseGuards, ValidationPipe } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IsIn, IsOptional } from 'class-validator';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { ROUTER_PERIODS, RouterUsageAdapter } from './router-usage.adapter';
|
||||
export class RouterUsageQuery {
|
||||
@IsOptional()
|
||||
@IsIn(ROUTER_PERIODS)
|
||||
period?: string;
|
||||
}
|
||||
@Controller('admin/router-usage')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles('admin')
|
||||
export class RouterUsageController {
|
||||
constructor(private readonly adapter: RouterUsageAdapter) {}
|
||||
@Get()
|
||||
@Header('Cache-Control','private, no-store')
|
||||
summary(@Query(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true})) query: RouterUsageQuery) {
|
||||
return this.adapter.summary(query.period ?? '7d');
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import request from 'supertest';
|
||||
import { RouterUsageModule } from './router-usage.module';
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
|
||||
describe('protected router usage HTTP contract', () => {
|
||||
let app: INestApplication;
|
||||
const summary=jest.fn().mockResolvedValue({status:'available',data:{}});
|
||||
beforeAll(async () => {
|
||||
const module=await Test.createTestingModule({imports:[RouterUsageModule]})
|
||||
.overrideProvider(RouterUsageAdapter).useValue({summary})
|
||||
.overrideGuard(AuthGuard('jwt')).useValue({canActivate(context: any){
|
||||
const req=context.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user={role:req.headers.authorization}; return true;
|
||||
}}).compile();
|
||||
app=module.createNestApplication();
|
||||
app.useGlobalPipes(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true}));
|
||||
await app.init();
|
||||
});
|
||||
afterAll(async()=>app.close());
|
||||
it('blocks unauthenticated access', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').expect(403); });
|
||||
it('blocks non-admin users', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','customer').expect(403); });
|
||||
it('permits admins and defaults to 7d', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','admin').expect(200);
|
||||
expect(summary).toHaveBeenCalledWith('7d');
|
||||
});
|
||||
it('rejects unsupported custom time range', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage?from=2026-01-01').set('Authorization','admin').expect(400);
|
||||
});
|
||||
it('rejects invalid period', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage?period=invalid').set('Authorization','admin').expect(400);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RouterUsageController } from './router-usage.controller';
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
@Module({controllers:[RouterUsageController],providers:[RouterUsageAdapter,RolesGuard],exports:[RouterUsageAdapter]})
|
||||
export class RouterUsageModule {}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { normalizeStats } from './router-usage.contract';
|
||||
|
||||
describe('9router stats allowlist', () => {
|
||||
it('maps real aggregate fields without leaking API-key map keys or account labels', () => {
|
||||
const result = normalizeStats({totalRequests:2,totalPromptTokens:10,totalCompletionTokens:4,totalCachedTokens:3,
|
||||
byProvider:{codex:{requests:2,promptTokens:10,completionTokens:4,cachedTokens:3}},
|
||||
byModel:{'m (codex)':{rawModel:'m',provider:'codex',requests:2}},
|
||||
byAccount:{'private@example.com':{rawModel:'m',provider:'codex',connectionId:'account-1',accountName:'private@example.com',requests:2}},
|
||||
byApiKey:{'SECRET-KEY|m':{apiKey:'SECRET-KEY'}},accessToken:'SECRET-TOKEN'});
|
||||
expect(result.totals).toEqual({requests:2,inputTokens:10,outputTokens:4,cacheReadTokens:3,cacheWriteTokens:null,reasoningTokens:null,errors:null});
|
||||
expect(result.models[0]).toMatchObject({model:'m',provider:'codex',requests:2});
|
||||
expect(result.accounts[0]).toMatchObject({accountId:'account-1',quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}});
|
||||
expect(JSON.stringify(result)).not.toMatch(/SECRET|private@|accountName|byApiKey/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unknown rather than fabricated metrics', () => {
|
||||
const empty = {totalRequests:0,byProvider:{},byModel:{},byAccount:{}};
|
||||
it('preserves known zero and unknown missing counters separately', () => {
|
||||
expect(normalizeStats(empty).totals).toEqual({requests:0,inputTokens:null,outputTokens:null,cacheReadTokens:null,cacheWriteTokens:null,reasoningTokens:null,errors:null});
|
||||
});
|
||||
it.each([null,{},[],{...empty,totalRequests:-1},{...empty,byModel:null}])('rejects invalid schemas', value => {
|
||||
expect(()=>normalizeStats(value)).toThrow();
|
||||
});
|
||||
it('rejects unsafe metric values instead of coercing them to zero', () => {
|
||||
expect(normalizeStats({...empty,totalPromptTokens:'10',totalCompletionTokens:-4,totalCachedTokens:Infinity}).totals).toMatchObject({inputTokens:null,outputTokens:null,cacheReadTokens:null});
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,10 @@ describe('support HTTP boundary', () => {
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
||||
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
|
||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }));
|
||||
// Own the listener for the entire suite. Otherwise Supertest lets the first
|
||||
// request start the server and close it while its concurrent peer is using it.
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(() => app.close());
|
||||
beforeEach(() => {
|
||||
@@ -45,7 +48,14 @@ describe('support HTTP boundary', () => {
|
||||
});
|
||||
it('scopes wallet to validated identity across concurrent callers', async () => {
|
||||
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201)));
|
||||
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
expect(replies[0].body.answer).toBe('موجودی کیف پول شما: 11 تومان.');
|
||||
expect(replies[1].body.answer).toBe('موجودی کیف پول شما: 22 تومان.');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledTimes(2);
|
||||
for (const id of ['alice', 'bob']) {
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { id }, select: { walletBalance: true } });
|
||||
}
|
||||
expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
expect(prisma.order.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
||||
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
||||
|
||||
@@ -2,6 +2,11 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class WikiService {
|
||||
@@ -19,33 +24,57 @@ export class WikiService {
|
||||
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
|
||||
|
||||
const whereClause: Prisma.ScientificTermWhereInput = {};
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
whereClause.OR = [
|
||||
{ term: { contains: search, mode: "insensitive" } },
|
||||
{ definition: { contains: search, mode: "insensitive" } },
|
||||
{ term: { contains: search, mode } },
|
||||
{ key: { contains: search, mode } },
|
||||
{ definition: { contains: search, mode } },
|
||||
...tokens.flatMap((token) => [
|
||||
{ term: { contains: token, mode } },
|
||||
{ key: { contains: token, mode } },
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawTerms, total] = await Promise.all([
|
||||
this.prisma.scientificTerm.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
}),
|
||||
this.prisma.scientificTerm.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawTerms;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawTerms]
|
||||
.map((t) => ({
|
||||
term: t,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
slug: t.key,
|
||||
title: t.term,
|
||||
description: t.definition,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.term)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit),
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Narrow auth schema operation — approval required
|
||||
|
||||
## Exact scope
|
||||
`auth-schema-reconcile.sql` adds only users.auth_expires_at TIMESTAMPTZ NULL, stage_test_session VARCHAR(64) NULL, stage_test_generation UUID NULL (no defaults/backfill), and prepare_workflow_outbox with its original CHECKs, three RESTRICT FKs, task uniqueness, lease and due indexes, including nullable not_before. No existing rows changed, no auth behavior disabled, no Prisma metadata altered.
|
||||
|
||||
Read-only production PostgreSQL 16.14 catalogs verified all three users columns and outbox absent; users.id and orchestration_tasks/runs/budget_ledger.id are UUID PKs. Existing users wallet CHECK and orchestration constraints stay intact. Production has six ledger rows (one historical rolled-back admin_modules attempt), no Oct22–24 entries despite orchestration objects existing. Never run generic migrate deploy or mark whole pending history applied.
|
||||
|
||||
Historical principal migration at e036c5d has two columns, SHA256 8b4fe1fdedd2ae459b720f78479cfcb13da465eec821b422ece5e9bb41dc47ae; 80a2e18 edited it to three, SHA256 a458a94329b1ad078298b042ae0bd2e25439c1f0bb5a086beb55c517d9e0aa28. Read-only Stage ledger records the latter, not the former. Preserve both historical files unchanged here. This operation is separately journaled by CI/backup receipt, not invented Prisma history. Broader baseline/history repair remains separate work.
|
||||
|
||||
## Execution contract
|
||||
Dedicated push workflow `auth-schema-reconcile.yml` uses DEPLOY_KEY and pinned DEPLOY_KNOWN_HOSTS, fixed SSH endpoint, isolated immutable Git checkout; it does not deploy applications. It accepts only exact branches `ops/auth-schema-stage` and `ops/auth-schema-production`, mapping their full refs to Stage and production respectively. It requires REVIEWED_AUTH_SCHEMA_COMMIT matching the event SHA and checks detached checkout HEAD equals that SHA. SQL digest is fixed to `8a22f3e89efb3dacc24f3ed9337ae87d0b4345da003a607bc1994478f69c6feb`, approval ID to `CEO-AUTH-SCHEMA-20261025`; neither is push-supplied input. Production additionally requires PRODUCTION_AUTH_SCHEMA_APPROVAL = SHA:SQL_SHA256:APPROVAL_ID and STAGE_AUTH_SCHEMA_ACCEPTANCE = SHA:SQL_SHA256, provisioned only after real review and Stage auth acceptance. These are explicit approval records, not automatically issued receipts. The repository's workflow/secret permissions must restrict dedicated-ref mutation to trusted maintainers; unrestricted malicious workflow edits can bypass any workflow-local gate. Review/protect this boundary before provisioning production approval.
|
||||
|
||||
Stage already has the DDL: Stage mode backs up production read-only, restores into isolated network-none temporary PostgreSQL, applies exact SQL there, compares resulting catalog with Stage read-only, and writes a SHA-bound structural receipt only. Production requires that receipt, repeats fresh full backup and restore/patch rehearsal, then executes only exact approved SQL. Full dumps remain mode600 host-only under /opt/backups/canina-auth-reconcile; never upload/log PII. Backup nonempty and pg_restore TOC checked. Restore errors/capacity failure stop before DDL. tmpfs is capped at 1GiB: if full restore exceeds capacity, separately review capacity rather than skipping restore. Existing read-only schema backup was 94,694 bytes / 67 tables, no PII copied; its restored PostgreSQL rehearsal is genuine, not a full data-backup recovery claim.
|
||||
|
||||
SQL lock_timeout 3s, statement_timeout 30s, idle transaction 60s; advisory lock plus host flock. DDL transactional; lock/contention failure aborts all. No automatic retries. Re-execution with existing outbox fails closed pending comparison, rather than silently accepting drift. Stage/production outputs compare columns/types/nullability/defaults, all outbox constraints/indexes to fresh rehearsed expected schema.
|
||||
|
||||
## Gitea 1.22.6 trigger semantics and operator sequence
|
||||
Gitea [1.22 comparison](https://docs.gitea.com/1.22/usage/actions/comparison) explicitly marks `workflow_dispatch` ignored. The [v1.22.6 notifier implementation](https://github.com/go-gitea/gitea/blob/v1.22.6/services/actions/notifier_helper.go) resolves the pushed ref's commit, detects workflows at that commit and records `Ref` and `CommitSHA` on the run. Push is not default-branch-only. The dedicated branch must therefore contain this workflow and point to the **final integrated reviewed commit**, not a new trigger-only commit. Existing app deployment listens only to `main`/`develop`, not either operations branch.
|
||||
|
||||
After independent review/authorization, a trusted operator can push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-stage` to origin. Inspect that CI run's SHA and structural receipt, then complete real Stage auth tests. Only after separate production and Stage acceptance approval records exist for the **same** SHA/digest may the operator push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-production`. No empty commits, merges, arbitrary ref inputs, secret updates by this workflow, automatic acceptance, or app promotion. A no-op push does not retrigger; do not change the reviewed SHA to manufacture a run. Any SHA change requires fresh review, approval bindings and Stage evidence. Workflow preparation has not pushed either branch, changed secrets/protections or executed the operation.
|
||||
|
||||
## Acceptance and rollback
|
||||
1. Parent DBA review exact commit/diff plus SQL hash and workflow trusted-ref/secret permissions. Approve read-only production full backup + isolated full restore scope separately from production DDL.
|
||||
2. Run Stage workflow from exact commit; inspect successful backup/restore/catalog comparison. Existing Stage backend must pass ordinary admin password login + protected dashboard, OTP flow with authorized principal, refresh, and expiry/session/generation rejection tests. Do not manufacture acceptance if no approved credential/test principal is available. Record actual test run identifiers before setting Stage acceptance approval.
|
||||
3. Obtain explicit approval: execute only this commit's SQL in caninodb_prod, three nullable users columns + empty outbox and declared constraints/indexes, 3s lock/30s statement budgets, no unrelated migrations/history writes/seeds. Provision approval binding SHA, SQL digest, approval record. Trigger production workflow, inspect terminal CI log. No production execution has been performed during preparation.
|
||||
4. Release separately via existing code-only develop→Stage→main CI, using actual regenerated backend client, runtime-image/schema guard, immutable image receipts and authenticated login/OTP/refresh/protected data acceptance. Keep current compatible backend until this passes. Schema approval alone does not authorize application promotion.
|
||||
5. Before commit failure: transaction rollback. After successful DDL: leave additive nullable fields/table intact, roll back application to known compatible immutable image via approved CI; do not DROP columns or outbox after writes. Restore full backup only under separately approved incident/data-loss recovery process. Existing backup tables remain untouched.
|
||||
|
||||
## Verified preparation / limitations
|
||||
Disposable network-none PG16 schema-only restore and exact SQL executed successfully (see JSON). Missing-column SELECT failed before patch and passed after; invalid status rejected; second application rejected without changes; container removed. Independent reviewer found SQL definition matched history; requested stronger gating, Stage preexisting-schema handling, capacity awareness and postcondition validation, addressed or explicit prerequisites above. Full-data restore and dedicated workflow SSH path are implemented but not yet executed in actual CI. No production writes or deployments occurred. Approval/environment gates must not be represented as production repair completion.
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schema_backup_bytes": 94694,
|
||||
"schema_backup_sha256": "9c6367a06acaf97c1afe9355e4306d2a10f878b7fe156c7dbc5d58d675262c72",
|
||||
"schema_tables": 67,
|
||||
"pii_copied": false,
|
||||
"postgres": "16.14",
|
||||
"restore_and_patch_seconds": 3.669,
|
||||
"pre_patch_missing_columns_failed": true,
|
||||
"post_patch_queries": " auth_expires_at | stage_test_session | stage_test_generation \n-----------------+--------------------+-----------------------\n(0 rows)\n\n count \n-------\n 0\n(1 row)\n\n count \n-------\n 0\n(1 row)\n\n",
|
||||
"constraints": " conname | pg_get_constraintdef \n---------------------------------------------+-----------------------------------------------------------------------------------------------------------\n prepare_workflow_outbox_attempts_check | CHECK (((attempts >= 0) AND (attempts <= 3)))\n prepare_workflow_outbox_pkey | PRIMARY KEY (id)\n prepare_workflow_outbox_reservation_id_fkey | FOREIGN KEY (reservation_id) REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT\n prepare_workflow_outbox_run_id_fkey | FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE RESTRICT\n prepare_workflow_outbox_status_check | CHECK (((status)::text = ANY ((ARRAY['PENDING'::character varying, 'DONE'::character varying])::text[])))\n prepare_workflow_outbox_task_id_fkey | FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE RESTRICT\n prepare_workflow_outbox_task_id_key | UNIQUE (task_id)\n(7 rows)\n\n",
|
||||
"invalid_status_rejected": true,
|
||||
"repeat_execution_rejected_without_writes": true,
|
||||
"production_writes": false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Host disk retention
|
||||
|
||||
Successful authenticated CI rollout runs release-retention.py. Default keep policy is only the current active release per environment; Docker mounts and Compose working directories always protect older still-used artifacts. Dry/unpublished source and unknown ignored files are preserved, so this is not a hard quota. CI restores only its own tracked nginx/dockerignore render changes after successful acceptance. New clones use sparse checkout to omit the 85 MiB tracked graphify-out history. No node_modules were bundled in the audited releases: their ~218 MiB is tracked source/assets plus an independent ~44 MiB Git store. Historical dirty releases require individual source review; never reset them for cleanup.
|
||||
|
||||
Retained small private runtime configuration is copied mode0600 under .retained-runtime before deleting a clean obsolete release. This avoids secret deletion; this archive is not a release rollback and requires explicit secret retention review separately. No volumes, databases, sessions, evidence, images or build cache are deleted.
|
||||
|
||||
The CI-installed canina-disk-watch.timer checks every five minutes with stdlib Python, no model calls. It logs daemon.err and returns nonzero at >=85% usage or <10GiB free. This is local detection, NOT off-host paging. systemctl status canina-disk-watch.service and journalctl -t canina-disk-watch expose alarms. Monitoring does not guarantee the disk cannot fill.
|
||||
|
||||
Audit 2026-10-26: Docker daemon already bounds new json-file containers to 3x10MiB and BuildKit GC to 6GB. Fifteen pre-existing containers (including Nexus, Gitea, databases and proxy) have empty LogConfig and remain unbounded until their owners roll them through their own Git/CI. Journald has no explicit SystemMaxUse and currently occupies 1.3GB. Nexus data is real persistent storage; retention tasks were not authenticated/audited and no blobs were deleted. Neither unrelated service config nor daemon/journal configuration is changed by Canina CI. Worktree branches with unpushed commits remain intentionally retained. These residual growth mechanisms prevent any honest claim of a globally bounded host or <50GB total.
|
||||
@@ -0,0 +1,95 @@
|
||||
**Superseded wiring/provenance: see [snapshot repair](hermes-snapshot-provenance.md). Do not use literal grants or the old DNS alias below.**
|
||||
|
||||
# Runtime read vertical slice (not deployed)
|
||||
|
||||
Branch feature/v4-runtime-completion, base 5507fbc. No AppModule, live gateway,
|
||||
production database, cron, dispatch, or existing compose was changed.
|
||||
|
||||
## Parent registration
|
||||
|
||||
Import `RuntimeReadModule.register({ '<verified-user-id>': ['default', '<department>'] })`
|
||||
from `backend/src/hermes-management/runtime-read.module` into AppModule.
|
||||
This module uses the existing Passport `jwt` strategy (DB-resolved user identity),
|
||||
not the API-key fallback. Parent must retain AuthModule/JwtStrategy initialization.
|
||||
Missing grants deny. Never construct grants from browser body, JWT profile claims,
|
||||
or unreviewed environment input. Allowlist is copied/frozen. Admin/SUPER_ADMIN
|
||||
role AND exact subject grant required; API-key identities forbidden.
|
||||
|
||||
GET `/admin/orchestration/runtime/{health,profiles,status,usage,sessions,schedules,model-info}`.
|
||||
All except health/profiles require exactly one allowed `profile` query string.
|
||||
Usage accepts days 1..365 (30); sessions limit 1..100 (20), offset 0..10000 (0).
|
||||
Unknown parameters on profile routes rejected. Profiles is filtered to server grants.
|
||||
Responses use existing adapter projections, no prompts/transcripts/config/tokens.
|
||||
Missing/forged JWT ->401; missing grant/role/profile ->403; runtime auth/network/
|
||||
contract failure ->503 `Runtime unavailable`; limits ->429. No browser Hermes
|
||||
cookie, credential, socket ticket or mutation handler is provided.
|
||||
|
||||
Mount backend `/run/secrets/hermes_username` and `hermes_password` as files.
|
||||
Only these fixed secret paths are read, after authorization. Broker login/cache
|
||||
stays server-side. Backend and isolated inventory runtime must receive matching
|
||||
credentials. Runtime additionally mounts `hermes_signing_key` (>=32 random chars).
|
||||
Do not put credentials in YAML/env, commands, logs or Git. Rotate key to invalidate
|
||||
sessions; rotate password and restart inventory plus backend to clear cached access.
|
||||
Stateless old sessions remain valid until TTL/key rotation.
|
||||
|
||||
## Deliberately separate snapshot topology
|
||||
|
||||
Installed Hermes `serve` lifespan starts reconciliation and hosted-room recovery;
|
||||
GET sessions auto-archives. Sharing its writable home with existing gateway is
|
||||
therefore NOT a safe read-only sidecar. `serve.py` runs the pinned installed app
|
||||
with lifespan OFF and an outer exact GET allowlist, password-login only and all
|
||||
WebSockets denied1008. It does NOT start scheduler/gateway/MCP/rooms/provider chat.
|
||||
The existing gateway and external volume `canina-hermes_canina_hermes_data` remain
|
||||
unchanged, solely owned by existing gateway. Inventory mounts an independently
|
||||
provisioned snapshot volume `canina_hermes_inventory_snapshot`; it NEVER mounts
|
||||
original home. Its incidental session auto-archive writes affect only snapshot.
|
||||
This is snapshot inventory, NOT live runtime freshness/status acceptance. A copy
|
||||
of gateway PID state is not evidence of live gateway health. UI must not claim live
|
||||
readiness from this deployment. Parent should expose snapshot provenance/freshness
|
||||
before enabling it for business use.
|
||||
|
||||
Provisioning must use an approved consistent SQLite backup/checkpoint/export and
|
||||
redacted profile config inventory, not raw `cp` of changing SQLite/WAL or credentials.
|
||||
No automatic snapshot job is installed here. No secrets need be copied from live
|
||||
home. Review which configs the model/status APIs need and omit auth.json/.env.
|
||||
Missing store/schema -> unavailable, not fabricated empty healthy telemetry.
|
||||
Dedicated internal network must contain only backend and inventory; do NOT connect
|
||||
existing gateway with same `canina-hermes` DNS alias. Backend name resolves inventory.
|
||||
Inventory network must have no external egress. Compose refers to external network;
|
||||
operator must create it `--internal`. No host ports/socket are published.
|
||||
|
||||
## CI ownership / apply
|
||||
|
||||
`compose.readonly.yml` is deployable ONLY after external snapshot, internal network,
|
||||
secret files and backend mounts/registration are provisioned. `ci-apply.sh` requires
|
||||
CI=true, exact reviewed HEAD SHA, clean checkout, snapshot-reviewed assertion,
|
||||
existing volume/network/files, then compose config/up. Never run alongside any
|
||||
other inventory instance writing same snapshot. CI job fragment is tracked under
|
||||
infra ownership; parent owns real workflow wiring and approval environment. No
|
||||
active deployment trigger added. Existing review-only compose template is unchanged.
|
||||
|
||||
## Executed evidence
|
||||
|
||||
Remote `/opt/services/canina/validation/v4-runtime-completion/`:
|
||||
- read-red.log missing controller regression; read-green.log 6 suites/27 tests.
|
||||
- read-http-green.log 7 suites/30 tests: real Nest HTTP with signed JWT strategy,
|
||||
bad signature/no auth401, ungranted admin403, allowed admin200, no cookie,
|
||||
mutation404. This uses a mocked runtime service, not live Canina credentials.
|
||||
- pinned-http.log exact installed image FastAPI login/protected inventory:
|
||||
wrong password401, real login200/HttpOnly provider-verifiable token, profiles200,
|
||||
tampered token401. No lifespan/live home.
|
||||
- serve-http.log actual loopback TCP9119 in network-none disposable pinned image:
|
||||
unauth inventory401, wrong password401, login200, profiles200, health auth true,
|
||||
mutation/config/ws HTTP404. Generated test-only credentials. No live volume.
|
||||
- ws-red.log existing socket rejection code differed; ws-green.log explicit
|
||||
outer boundary denies authenticated sockets1008 independently of upstream tickets.
|
||||
- build.log private Prisma generation and full backend tsc build exit0.
|
||||
|
||||
Pinned local exact image ID sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f;
|
||||
tracked registry digest sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784.
|
||||
Node22 disposable runner copied read-only source/dependency donor privately;
|
||||
no DB migration. broker-pinned-e2e.log proves actual compiled Node broker -> TCP pinned Hermes login -> adapter -> policy-filtered inventory (and deny zero secret reads). Nest HTTP authentication tested separately; these tests do not establish full Canina application E2E, snapshot
|
||||
refresh, CI deployment, live gateway truth or business workflow acceptance.
|
||||
Those remain explicit integration/provisioning gates, not claimed completion.
|
||||
|
||||
Final full non-DB regression: 106 suites / 850 tests pass; expected legacy negative SSL/payment logs. Scoped ESLint has zero errors, six type-safety warnings; full build passes. No RELEASE_AUTHORIZE integration suite run.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Snapshot provenance repair — integration contract
|
||||
|
||||
This is independent snapshot inventory, **not a live Hermes executor**. No Production,
|
||||
deployment, live gateway edits, or RELEASE_AUTHORIZE execution is included.
|
||||
|
||||
## Parent-owned application wiring
|
||||
|
||||
Keep AuthModule/JwtStrategy. Replace literal user grants in parent-owned app.module.ts with:
|
||||
|
||||
```ts
|
||||
RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
```
|
||||
|
||||
Nest supports the resulting Promise<DynamicModule> in imports. Alternatively pass the
|
||||
reviewed nonsecret file `/etc/canina/runtime-grants.json`. No env/JWT/browser grant
|
||||
input is accepted by this registration. File is JSON object mapping exact verified DB
|
||||
user IDs to nonempty unique profile arrays; `{}` explicitly denies everyone. Missing,
|
||||
malformed, symlinked, group/world-writable, oversized files fail startup closed. Mount
|
||||
read-only and provision via reviewed configuration/secrets management; do not commit
|
||||
real user grants. Existing explicit register(grants) remains for tests/legacy consumers.
|
||||
Backend also mounts `/run/secrets/hermes_username` and `hermes_password` read-only.
|
||||
No app.module.ts modification belongs to this commit.
|
||||
|
||||
## Required coordinated origin change
|
||||
|
||||
Authenticated management module and broker now exclusively use
|
||||
`http://canina-hermes-inventory:9119`. compose.readonly.yml uses the distinct alias
|
||||
`canina-hermes-inventory`, NEVER `canina-hermes`. Generic adapter allowlist retains
|
||||
both reviewed exact origins for compatibility with separate existing consumers.
|
||||
No arbitrary origin/env URL accepted. Parent must cherry-pick broker/module/adapter
|
||||
and inventory compose together; do not add an alias to the existing gateway.
|
||||
No deployment performed. External network should still be internal and only contain
|
||||
backend/inventory; the distinct alias cannot shadow the live canina-hermes hostname.
|
||||
|
||||
## Snapshot exporter/operator gate
|
||||
|
||||
Every independent inventory root must include `snapshot-manifest.json`:
|
||||
|
||||
```json
|
||||
{"schemaVersion":1,"source":"snapshot","capturedAt":"2026-10-23T12:00:00Z"}
|
||||
```
|
||||
|
||||
The example is a schema example, NOT an actual capture attestation. Exporter must
|
||||
write the real capture instant from the approved consistent export. Never copy the
|
||||
example, use startup time, filesystem mtime, or claim this change captures/refreshes
|
||||
snapshots. Missing/invalid/future manifest prevents startup. It is revalidated per
|
||||
successful GET; invalid after startup returns503. Manifest is exporter metadata,
|
||||
not a cryptographic proof of consistency. Immutable reviewed export provisioning
|
||||
remains required. Fresh means age <=3600 seconds, otherwise stale; even fresh is
|
||||
NOT live readiness. No snapshot scheduler installed.
|
||||
|
||||
## Additive public response fields / panel handoff
|
||||
|
||||
All object read DTOs (health/status/usage/sessions/model-info) add:
|
||||
`provenance:{source:'snapshot',capturedAt:string,ageSeconds:number,freshness:'fresh'|'stale',liveProcess:'unknown'}`.
|
||||
Profile and schedule array shapes are preserved: provenance is on each row. Empty
|
||||
arrays have no rows to annotate; use the health response to display snapshot metadata.
|
||||
Profile rows add `liveGatewayState:'unknown'`; status adds the same plus
|
||||
`liveActiveAgents:null`. Existing required scalars remain typed but are conservative
|
||||
placeholders: `gateway_running:false`, `active_agents:0`, `gateway_state:null`,
|
||||
`overall:'unknown'`. False/zero MUST NOT render as measured offline/idle: when
|
||||
provenance.source is snapshot use the explicit unknown fields, label snapshot and
|
||||
show capturedAt/freshness. Health.ok only means inventory HTTP app responsiveness,
|
||||
never live gateway readiness. Profile existence is inventory availability, NOT
|
||||
process readiness. Adapter enforces provenance on dedicated snapshot origin and
|
||||
conservatively overwrites copied PID-derived status/profile scalars again.
|
||||
|
||||
Installed status handler was unsafe here: it probes gateway HTTP/PIDs/platforms and
|
||||
can stall despite this being an independent snapshot. Snapshot server replaces that
|
||||
route with measured package version and explicit unknown process fields; no status
|
||||
probe is run. Password auth/mutation denial/WebSocket denial remain intact.
|
||||
|
||||
## Executed acceptance
|
||||
|
||||
Remote disposable network-none exact pinned Hermes image, no original volumes:
|
||||
manifest-missing regression failed first; TCP login/profile/health/status provenance
|
||||
and stale capture assertions now pass; authenticated sockets denied1008. Disposable
|
||||
Node22 copy of source/dependencies: 9 hermes-management suites /34 tests pass and
|
||||
full backend tsc build passes. Adapter copied-live-state regression failed first;
|
||||
grants-loader missing-function regression failed first. Compiled actual Node broker
|
||||
-> TCP pinned server -> adapter -> policy-filtered profiles/status passes, deny reads
|
||||
zero credentials. Test timestamps/credentials are fixtures, not live telemetry.
|
||||
The first HTTP retry raced fixture startup and returned UNAVAILABLE; retry after
|
||||
server startup passed. No claim of full app/user-flow or live runtime integration.
|
||||
|
||||
Full non-DB Jest regression: 108 suites/854 tests passed; 1 suite/18 tests skipped. No RELEASE_AUTHORIZE suite was enabled.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Queued Gate1 validity correction
|
||||
|
||||
## Read-only Stage evidence (2026-10-24)
|
||||
|
||||
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
|
||||
|
||||
## Behavior
|
||||
|
||||
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
|
||||
|
||||
## Owner steps after parent CI integration
|
||||
|
||||
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
|
||||
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
|
||||
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
|
||||
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
|
||||
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
|
||||
|
||||
## Verification
|
||||
|
||||
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Durable Stage cleanup verification
|
||||
|
||||
This change replaces the SHA-pinned transient timer with a root-owned intent journal
|
||||
and a fixed host systemd retry worker. No host service is installed or enabled by
|
||||
the CI credential command. The tracked `deploy.yml` → `ci-host-deploy.sh` →
|
||||
`deploy.sh` path invokes `install-stage-principal-cleanup.py` from the verified
|
||||
immutable release before `stage_rollout`. It atomically installs the root-owned
|
||||
worker (0755) and supplied systemd units (0644), reloads systemd, enables/starts
|
||||
the timer and verifies enabled/active state. Failure aborts rollout. No manual
|
||||
sudo provisioning is required or permitted during review. The open wrapper refuses to operate
|
||||
without an enabled and active timer. Never overwrite or delete the 0700 root-owned
|
||||
`/opt/services/canina/stage-principal-cleanup` journal during deployments.
|
||||
|
||||
A journal entry is fsynced before provisioning and contains the exact session,
|
||||
random generation, creation SHA, bounded TTL and immutable cleanup deadline.
|
||||
Repeated opens fail rather than replace an intent or renew TTL. Close and the
|
||||
30-second boot/periodic retry worker retain intents on lock contention, unavailable
|
||||
containers/DB, and relational deletion failures. Cleanup resolves the current Stage
|
||||
container ID once, verifies its cleanup capability, and authenticates against its
|
||||
current artifact SHA while retaining original session/generation ownership. Older
|
||||
artifacts without generation cleanup support fail closed; never roll back to one
|
||||
with a pending principal. Persisted expiry remains independently enforced at login,
|
||||
refresh and every scoped JWT request.
|
||||
|
||||
Revocation commits before private-handle removal; relational deletion is subsequent.
|
||||
A transaction acquires a generation/session-fenced row lock before touching related
|
||||
records. Failed deletion retains a revoked row and a pending retry intent, but no
|
||||
credential handle. Wrong ownership/generation never invokes the handle callback.
|
||||
The CLI requires the generation supplied by the private journal; no broader admin
|
||||
or production authority was introduced.
|
||||
|
||||
Verification performed in a new isolated worktree and disposable Docker network:
|
||||
- Cleanup fence tests: RED (replacement generation was revoked; callback missing),
|
||||
then GREEN (2 tests).
|
||||
- Python simulated worker tests: restart/redeploy, failed-delete retry, lock
|
||||
contention, immutable container ID/current artifact and old-CLI refusal (4 tests).
|
||||
- Persisted account lifecycle plus delete/recreate access AND refresh regression.
|
||||
- Actual CLI via ts-node with real disposable Postgres/Redis and HTTP adminLogin
|
||||
handler, injected PostgreSQL delete trigger failure: confirmed revocation,
|
||||
private handle removal, then successful repeated cleanup after trigger removal.
|
||||
- TypeScript `tsc --noEmit`: passed.
|
||||
- Full migration chain attempt on fresh disposable database: baseline failure in
|
||||
20261020000000_add_blog_freshness_authorship (`blogs` missing). Not concealed.
|
||||
Independent migration test constructed the pre-Stage schema excluding all three
|
||||
new fields, then applied the EXACT committed 20261024090000 migration with psql
|
||||
ON_ERROR_STOP before exercising persisted lifecycle. Not db-push-only testing.
|
||||
|
||||
No live account, Stage/Production DB mutation, deployment, push, host service change,
|
||||
or retry of the previous pending-approval operation was performed.
|
||||
|
||||
Invocation after normal reviewed deployment and host prerequisite provisioning:
|
||||
`sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/<promoted-sha>/scripts/stage-test-principal-host.sh <promoted-sha> <unique-session> 600 open`
|
||||
Use the same command with `close` immediately after the authorized test.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Opt-in Stage runtime provisioning (parent wiring contract)
|
||||
|
||||
This provisions **snapshot inventory** and credentials for the existing PREPARE
|
||||
transport. It does NOT create a real LLM executor. The current deterministic worker
|
||||
is still `llmPilot:false`. No provider credentials are collected, no cron installed,
|
||||
no task claimed and no worker polling/service started by the provisioner.
|
||||
|
||||
## CI-only host invocation
|
||||
|
||||
Parent owns workflow/deploy.sh/AppModule; none are changed here. Run only through
|
||||
the existing pinned authenticated SSH CI boundary, under its Stage environment
|
||||
approval and serialized rollout lock. `CI=true` is an accident guard, not an auth
|
||||
boundary. Provisioner checks clean HEAD equals the full approved commit; no branch
|
||||
promotion, push, Production, RELEASE_AUTHORIZE, Docker or DB writes are performed.
|
||||
Only the CI account should be able to invoke this on a root-owned trusted parent.
|
||||
|
||||
From the clean pinned release checkout on the host (not the dirty Stage checkout):
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000
|
||||
```
|
||||
|
||||
Default output root is `/opt/services/canina/stage-runtime` and its parent must
|
||||
already exist. First creation is staged and atomically renamed. Repeating validates
|
||||
existing state without rotating credentials. Corrupt/missing/unsafe files fail
|
||||
closed, not repaired. CI MUST serialize execution and prevent untrusted edits to
|
||||
source/output parents; this is not a hostile-filesystem sandbox. `--root` is for
|
||||
CI-reviewed test/Stage locations only, not arbitrary browser input. Secure backup
|
||||
and separately approved rotation are parent/operator responsibilities.
|
||||
|
||||
- `secrets/` 0700, files 0400 owned by the runtime UID (1000 in the current backend
|
||||
image); `hermes_username/password/signing_key` are new independent random values.
|
||||
- `prepare_worker_grants` contains SHA256 only, exact separate service identities
|
||||
`stage-prepare-worker`/WORKFLOW_WORKER and `stage-evidence-ci`/STAGE_CI. These are
|
||||
transport service identities, **not invented DB admin users**.
|
||||
- Raw `credentials/prepare_worker_token` and `credentials/stage_ci_token` stay in a
|
||||
CI-owner-only 0700 directory, 0400 files. Do NOT mount either into inventory or
|
||||
backend, log them, upload them as artifacts or send them to browsers. A later
|
||||
reviewed one-shot executor receives only its own token through a private file.
|
||||
- `artifacts/` is 0700 owned by backend UID; backend alone writes it. Persistent
|
||||
local disk is not object storage or external publication evidence.
|
||||
- `hermes_runtime_grants` is `{}`: deny all. No live admin query was needed/performed.
|
||||
Parent must separately query actual Stage admin IDs read-only, review exact ID to
|
||||
profile mapping and provision a private replacement via configuration management
|
||||
before claiming panel access. Never infer identities from usernames or JWT input.
|
||||
Deliberately changed grants require separate review; default provisioner refuses
|
||||
nonempty runtime grants on repeat.
|
||||
- Compose file-backed secrets preserve host permissions/ownership; `uid/gid/mode`
|
||||
declarations do not fix bind mount ownership. Verify effective host IDs if Docker
|
||||
uses userns remapping; do not chmod 0444 as a workaround.
|
||||
|
||||
## Consistent restricted export
|
||||
|
||||
After approval, the SAME CI invocation may explicitly request one profile's source
|
||||
SQLite DB. Resolve its real `HERMES_HOME/state.db` through reviewed host mounts;
|
||||
never guess a gateway volume path or mount the original home into inventory.
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000 \
|
||||
--snapshot-db "$REVIEWED_STATE_DB" --profile default \
|
||||
--snapshot-name "$UNIQUE_CI_CAPTURE_ID"
|
||||
```
|
||||
|
||||
SQLite online `Connection.backup()` reads committed WAL frames into memory (never
|
||||
`cp state.db`, never `immutable=1`). A 30-second callback deadline bounds busy
|
||||
backup. Only explicit source/time/token/cost columns from `sessions` are projected.
|
||||
Private session IDs become capture-local ordinal IDs; sources use an enum; no
|
||||
messages, titles, prompts, user/chat IDs, paths, URLs, model config, credentials,
|
||||
config.yaml, auth.json, .env, cron commands, memory or skills are exported. Unknown
|
||||
schema/nonnumeric metadata fails. One profile per immutable capture; there is no
|
||||
multi-DB atomicity claim. A source DB may be large: backup is memory-bound, so size
|
||||
and host resources need operator review before a real capture.
|
||||
|
||||
Output directory is new/immutable (0500, 0400 files), never overwritten:
|
||||
`inventory.json`, exact three-field `snapshot-manifest.json` and `export-report.json`.
|
||||
Manifest `capturedAt` is measured immediately after successful backup, not startup,
|
||||
mtime or an example. Report records actual projected row count, inventory digest,
|
||||
method/exclusions; it is not a signature or proof of source authenticity. No live
|
||||
capture was performed in this change. Never reuse fixture manifests as evidence.
|
||||
|
||||
Projected HTTP readers never consult gateway config, state DB or cron files:
|
||||
model/provider are explicit `unknown`, context length is a placeholder zero,
|
||||
cron arrays empty mean **not captured**, session activity false is a placeholder,
|
||||
profile inventory doesn't establish live process availability. Status retains
|
||||
`liveProcess:unknown`. Usage days are relative to actual capture time. Snapshot
|
||||
fresh/stale provenance from the existing adapter remains mandatory. No real LLM
|
||||
pilot readiness follows from this inventory responding 200.
|
||||
|
||||
## Exact parent compose/application wiring
|
||||
|
||||
`infra/hermes-runtime/compose.stage-provision.yml` is an opt-in merge fragment,
|
||||
NOT called by the existing deploy script or ci-apply.sh. Parent must include it
|
||||
in **every** Stage compose command after provisioning, using the existing stable
|
||||
Compose project identity and existing release isolation/volume rules:
|
||||
|
||||
```sh
|
||||
export STAGE_RUNTIME_SERVE_FILE="$PINNED_RELEASE/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SNAPSHOT="/opt/services/canina/stage-runtime/snapshots/$UNIQUE_CI_CAPTURE_ID"
|
||||
# Only inside approved CI rollout, never manually:
|
||||
# docker compose -p <existing-stage-project> -f <parent-stage-compose> \
|
||||
# -f "$PINNED_RELEASE/infra/hermes-runtime/compose.stage-provision.yml" \
|
||||
# --profile stage-runtime-inventory <parent-approved command>
|
||||
```
|
||||
|
||||
The fragment adds backend `PREPARE_WORKER_ENABLED=true`, fixed-path secrets
|
||||
`/run/secrets/prepare_worker_grants`, `/run/secrets/hermes_runtime_grants`,
|
||||
`hermes_username/password`, and artifact bind at
|
||||
`/var/lib/canina/prepare-artifacts`. It adds a project-scoped **internal** network
|
||||
between backend and inventory only, alias `canina-hermes-inventory` (not the live
|
||||
`canina-hermes`). No host port, Docker socket or live gateway volume. Inventory is
|
||||
read-only, nonroot, no capabilities, restricted tmpfs and pinned image, mounts only
|
||||
its immutable projected export and script. `create_host_path:false` fails on missing
|
||||
exports/storage. Original compose.readonly.yml/ci-apply.sh remain legacy review-only;
|
||||
do not combine those with this provisioning fragment.
|
||||
|
||||
AppModule must keep AuthModule/JwtStrategy, import
|
||||
`RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')` for reads,
|
||||
and spread `...registerPrepareWorker()` for the opt-in worker transport (verify
|
||||
existing AppModule before adding duplicates). The latter defaults to no module
|
||||
unless exact env `true`; enabling compose alone cannot add missing imports. Routes
|
||||
remain service-authenticated. Artifact base is fixed to
|
||||
`https://stageapi.canina.ir/api/internal/prepare-worker/artifacts`; parent must verify
|
||||
its actual global `/api` prefix/proxy/authenticated retrieval after CI deployment.
|
||||
No URL here is asserted externally reachable by disposable tests.
|
||||
|
||||
Parent still must implement/review a bounded one-shot real LLM executor separately;
|
||||
this commit intentionally adds neither model/provider secrets nor automatic polling.
|
||||
After CI rollout verify backend UID/secret readability by names only, deny-all reads,
|
||||
worker unauth denial, snapshot provenance and authenticated artifact digest readback
|
||||
before a separately authorized task. Do not call RELEASE_AUTHORIZE.
|
||||
|
||||
## Executed disposable validation
|
||||
|
||||
Pinned Hermes image, `--network none`, repository mounted read-only; private
|
||||
TemporaryDirectory fixtures only. RED observed missing provisioner, missing exporter,
|
||||
wrong projected profile and acceptance of malformed credential; GREEN: four
|
||||
provision/export/security/CI-guard unittest cases; projected HTTP auth/profile/session/
|
||||
wrong-profile/model/cron assertions; existing exact-image HTTP acceptance, TCP serve
|
||||
mutation denial and authenticated WebSocket 1008 denial. Compose merged config
|
||||
`--quiet` passed without applying it. An initial test mount mismatch was corrected
|
||||
(`/source` for repo-relative tests, `/contract` for legacy tests). No application
|
||||
backend code changed; full backend suites not rerun. No host credentials, artifact
|
||||
storage, snapshots, DB users, services or networks were provisioned live.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Temporary Stage editorial reviewer (disabled by default)
|
||||
|
||||
Authority: repository write/CI-dispatch permission plus the existing authenticated,
|
||||
pinned Stage deployment SSH boundary. This is a narrowly scoped seed operation,
|
||||
not an API-key actor, owner JWT, or a public bootstrap endpoint. The destructive
|
||||
legacy seed is not used. `AdminService` shares its normal hashing/persistence and
|
||||
relational cleanup implementation with the internal command; normal user mutation
|
||||
role checks remain unchanged. The canonical default administrator is untouched.
|
||||
|
||||
## Activation after independent review
|
||||
|
||||
1. Promote this commit through the normal Git/CI Stage deployment. Do not run the
|
||||
seed command against an old image: the embedded immutable SHA must match.
|
||||
Apply the additive migration through the existing migration deployment step.
|
||||
2. Dispatch **Owner authorized Stage test principal** on develop with `approval`
|
||||
exactly `owner-authorized-stage-editorial`, unique `session` such as
|
||||
`editorial-20261024-a`, `ttl` explicitly 600 (maximum 3600), and `action=open`.
|
||||
The workflow uses existing DEPLOY_KEY / pinned DEPLOY_KNOWN_HOSTS only.
|
||||
3. CI reports only `/app/private-stage-test/<session>.json` inside
|
||||
`canino_backend_stage`. This mode-0600 file in a mode-0700 directory contains
|
||||
the process-generated password and real persisted-account login tokens.
|
||||
Consume it only from an approved in-container CI HTTP process; never print,
|
||||
download, publish as an artifact, or type it into a browser. No owner secret is
|
||||
needed. Audit records contain events, session and SHA, never credentials.
|
||||
4. Use this independent reviewer for Gate1 only; the proposer/PMO must be a
|
||||
distinct actor. Existing self-review checks are not changed. This session does
|
||||
NOT authorize Gate2, publication, release, general admin APIs, worker identity
|
||||
replacement, or budget increases. Approve a separate explicit bounded test
|
||||
budget before running inference; unknown prior reservations remain retained.
|
||||
5. Dispatch the same workflow/session/ttl with `action=close` immediately after
|
||||
tests. This revokes persisted authentication BEFORE relational deletion and
|
||||
removes the private credential file. Close is idempotent when absent.
|
||||
|
||||
A durable root-owned host cleanup journal and boot/periodic systemd retry worker must be provisioned before opening a session. Cleanup follows the current Stage artifact but retains the original exact session and generation fence; persisted expiry cannot be extended. See [cleanup verification and promotion prerequisites](stage-principal-cleanup-verification.md). No live host services are changed by review tests.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit guards and existing independent self-review/role tests run with Jest.
|
||||
`stage-test-principal.integration.spec.ts` is opt-in via
|
||||
`STAGE_PRINCIPAL_DISPOSABLE_TEST=true` and requires a database URL ending in
|
||||
`/principal_disposable`; use a new isolated Postgres and Redis, then remove both.
|
||||
It verifies real account persistence/hash, signed access/refresh login tokens,
|
||||
collision refusal, nonrenewing retries, request scope, expiry, deletion/revocation.
|
||||
Never run it against Stage or Production.
|
||||
@@ -1,46 +0,0 @@
|
||||
# Integration milestone: read-only v4
|
||||
|
||||
This integration supersedes mutation/chat expectations below. All orchestration POST/PUT routes return 403 **before calling legacy services**, including task creation, transitions, gate decisions, budget writes, kill-switch and chat. No feature flag can enable them. `availableActions` is always `[]`. Do not enable mutation controls until hardened core is merged and independently verified.
|
||||
|
||||
GET `/admin/orchestration/overview` returns `{items:[{id:"tasks",title:"Persisted task inventory",count:number}], measuredAt, capabilities:{mutations:false,chat:false,runtime:false},reason:"security_hardening_pending"}`. The timestamp describes this DB inventory observation, not runtime health. Frontend capability fetch defaults to all false on failure or missing fields.
|
||||
|
||||
GET tasks and detail use explicit allowlists: task identity/state/version/mode/budget; run identity/status/commit/environment; artifact identity/kind/hash; decision identity/gate/decision/expiry/bindings; event identity/type/states/sequence/time; ledger identity/amount/kind/time. Arbitrary metadata, notes, event payloads, artifact URI/signature and BigInt size are not exposed. Scope/acceptance metadata remains withheld pending a reviewed structured schema.
|
||||
|
||||
GET `/releases` is persisted run evidence only, not a claim of release authorization or deployment. GET `/agents`, `/schedules`, `/model-policy` return 503 with explicit unavailable reasons: there are no trusted runtime identity/auth or persisted model policy read contracts. HermesManagementModule is registered deny-all with an empty token and no HTTP controllers; no runtime calls or cron changes occur. RouterUsageModule is registered with its admin-protected read-only endpoint and returns unavailable when credentials are absent. No new secrets are configured.
|
||||
|
||||
## Historical component contract (mutation proposals disabled)
|
||||
|
||||
# Admin orchestration v4 adapter contract
|
||||
|
||||
All client traffic uses existing authenticated Axios client (`src/services/api.ts`). Relative `/admin/...` paths are served below `/api`. No runtime secrets, Hermes tokens, PTY, terminal websocket or direct gateway credentials may enter these DTOs. Backend must project/redact task metadata, artifacts, audit payloads and chat text before returning them. Browser does not enforce authorization.
|
||||
|
||||
## Implemented core API observed in sibling core worktree
|
||||
- GET `/admin/orchestration/tasks`: bare Task[] or `{success:true,data:Task[]}`.
|
||||
- GET `/admin/orchestration/tasks/:id`: immutable task detail with runs/artifacts, decisions, events and budgetLedger.
|
||||
- POST `/admin/orchestration/tasks`: key,title,department,operationMode,budgetLimitCents,metadata {scope,acceptanceCriteria[]} (no execution authorization).
|
||||
- PUT `/admin/orchestration/tasks/:id/transition`: toState,expectedVersion,idempotencyKey,reason.
|
||||
- POST `/admin/orchestration/tasks/:id/gates/{1|2}/decide`: decision,expectedVersion,idempotencyKey,expiresAt,notes. Gate2 APPROVED additionally binds runId,artifactHash,commitSha,environment to registered immutable run and artifact.
|
||||
- PUT `/admin/orchestration/kill-switch`: level,reason. Levels FREEZE_NEW_WORK,STOP_AGENTS,DISABLE_MUTATIONS,EMERGENCY_HALT. No invented reset/resume route.
|
||||
|
||||
Task fields and optional service DTOs are declared in `src/services/orchestration.ts`.
|
||||
|
||||
## Required integration additions (fail closed until backend provides)
|
||||
Task `availableActions: {id,label,toState?,gate?:1|2,decision?:APPROVED|REJECTED,disabledReason?}[]` must be advertised by backend after permission, state, gate, policy and kill-switch evaluation. Browser never derives transitions from state. Missing actions means read-only, not an invitation to synthesize controls. Backend core inspected initially did not advertise these actions. This is an integration blocker for execution.
|
||||
|
||||
Optional read-only resources GET `/admin/orchestration/{agents|model-policy|schedules|releases}` return `{items:[{id,title?,status?,department?,readiness?,model?,budgetLimitCents?,spentCents?,cron?,timezone?,environment?,commitSha?,reason?}],measuredAt:ISO8601}`. May be wrapped in `{success:true,data:...}`. 404/403/network/malformed replies render unavailable, not mock cards. These endpoint contracts are proposals requiring backend reconciliation, not claims that endpoints exist. Schedule editing, model policy editing, budget adjustments, agent start/stop and release execution require separately advertised typed backend commands; intentionally not implemented against guessed routes. Existing task run/evidence, decisions, ledger and ordered events remain inspectable independent of optional feeds.
|
||||
|
||||
POST `/admin/orchestration/chat/messages`: {sessionId,message,idempotencyKey} -> {id,role:'assistant',content}. Advisory-only bridge; no browser runtime connection or auto-execution of text. Backend must bind sessions to authenticated user and redact sensitive output.
|
||||
|
||||
## Retry and concurrency
|
||||
Command dialog snapshots immutable task version and allocates one key. On first attempt inputs lock; failed retries use identical payload/key. Cancel and refresh to reconcile 409 conflict; refresh invalidates selection and dialog. Successful command refetches authoritative tasks; no optimistic status. Backend must enforce idempotency transactionally, compare payload bindings and versions; frontend is not a safety boundary. Task creation is keyed by unique business key; reconcile ambiguous failures by refreshing before retry.
|
||||
|
||||
## 9router usage concrete contract (aligned with backend worker b0f4636)
|
||||
GET `/admin/router-usage?period=today|24h|7d|30d|60d|all` default7d; authenticated admin. Response: source,period,status available|unavailable,reason,data null|{totals,providers[],models[],accounts[]},freshness {retrievedAt,sourceUpdatedAt,stale},attribution {scope:9router_total,hermes:null,additive:false}.
|
||||
Metrics: requests,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,errors. Last three unsupported=null. Account quota {status:unknown,remaining:null,resetAt:null,reason:upstream_quota_get_mutates_credentials}. No upstream quota GET because it refreshes credentials. No estimates or raw credentials. Nullable provider/model/account IDs are sanitized by backend.
|
||||
Breakdowns overlap and are never summed. Hermes attribution unknown, not zero and not added. Retrieved timestamp is not source freshness. SourceUpdatedAt and stale remain explicitly unknown. Frontend explicitly projects DTO fields and rejects malformed/unavailable replies. No direct gateway connection.
|
||||
|
||||
## Monitoring
|
||||
Existing payment stats/health and SMS credit are read independently. Only returned values displayed. Request failures remain unknown with source and client observation timestamp. Database/Redis/Post/OCR/uptime/environment/agent runtime remain unknown without measured endpoints. No fabricated 14-day uptime, Production label, derived DB ping, SMS count or healthy post service.
|
||||
|
||||
## Verification caveats
|
||||
All verification uses disposable node:22-bookworm Docker runners against this worktree. Plain `npm run typecheck` uses solution-style config and does not verify app files. `tsc --noEmit -p tsconfig.app.json` exposes pre-existing errors in legacy Approvals/Audit/HQ/Tasks imports and Orders/Symptoms types; report these separately, not as a green full application typecheck. Build warning: unresolved existing Shabnam font remains runtime-resolved.
|
||||
@@ -1,21 +0,0 @@
|
||||
# Verification and remaining integration work
|
||||
|
||||
Remote branch: feature/orchestration-v4-admin. All source changes limited to frontend/admin-panel. No push, deployment, production container command, or live operational mutation performed.
|
||||
|
||||
Disposable node:22-bookworm runners, --userns=host:
|
||||
- Full `vitest run --maxWorkers=2`: 57 files, 326 tests passed, zero failed.
|
||||
- Scoped ESLint for all new services/components/tests plus Monitoring: exit 0.
|
||||
- `npm run typecheck` (solution config): exit 0, not an app check.
|
||||
- `tsc --noEmit -p tsconfig.app.json`: exit 2, 33 pre-existing diagnostics (legacy unused imports/locals, Orders requiresRx type, Symptoms ConfirmModal props). No diagnostics in new files or Monitoring. Baseline captured before implementation had same legacy errors.
|
||||
- `npm run build`: exit 0; pre-existing unresolved Shabnam font warning.
|
||||
|
||||
TDD red/green cycles exercised adapter missing exports, unadvertised actions, incomplete/expired Gate2 bindings, exact version/idempotency payloads and retry lock, task creation bounds, UI explicit confirmation, monitoring fake values and failures, navigation, router usage contract migration/unavailable state. Full UI tests use mocked HTTP boundary with realistic backend DTOs; they are not a live backend integration test. Additional UI tests cover immutable artifact binding, kill authorization failure, readiness BLOCKED response, chat escaping and typed bridge. Router usage aligned to concrete backend b0f4636 contract.
|
||||
|
||||
Remaining gaps / do not claim full end-to-end operation:
|
||||
- Backend must advertise availableActions. Initial core worktree lacks them; client intentionally fails closed read-only without actions.
|
||||
- Agents/model-policy/schedules/releases snapshots and typed chat bridge are proposed contracts, not initially present core routes. UI displays explicit unavailable errors, never synthetic content. Mutating model policy/schedules/agent operations not implemented against guessed endpoints.
|
||||
- Kill switch current level cannot be read until backend exposes a status contract. No invented resume command.
|
||||
- No live auth credentials used; endpoint auth/RBAC and cross-worker DTO integration still need isolated stack smoke tests.
|
||||
- Legacy Approvals/Tasks/HQ/Audit pages remain separately available and unchanged. New v4 control center is at /orchestration inside existing protected layout; these legacy pages are not v4 authority and should be retired/migrated during integration.
|
||||
- Full app typecheck is not green due existing errors listed above.
|
||||
- Browser chat is advisory; no Hermes terminal or raw runtime connection.
|
||||
@@ -1,14 +0,0 @@
|
||||
import {fireEvent,render,screen} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import CreateOrchestrationTask from './CreateOrchestrationTask';
|
||||
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
|
||||
it('submits explicit bounded scope and acceptance criteria, only after valid input',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
|
||||
expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Bounded scope':'Staging schema audit only','Acceptance criteria (one per line)':'Report all failures','Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
|
||||
await screen.findByText('Task created by backend.');
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
|
||||
expect(done).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import {useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',scope:'',criteria:'',budget:''});
|
||||
const [mode,setMode]=useState<CreateTaskInput['operationMode']>('PREPARE');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&Number.isSafeInteger(Number(fields.budget))&&Number(fields.budget)>=0;
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message:'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE','MUTATE_PRODUCTION'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy}>Create bounded task</Button>
|
||||
</form></details>;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { render,screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { it,expect,vi } from 'vitest';
|
||||
import Sidebar from './Sidebar';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:{success:true,data:{}}})}}));
|
||||
it('exposes command center inside existing authenticated navigation',async()=>{
|
||||
render(<MemoryRouter initialEntries={['/orchestration']}><Sidebar isOpen setIsOpen={vi.fn()}/></MemoryRouter>);
|
||||
expect(await screen.findByRole('link',{name:'Orchestration command center'})).toHaveAttribute('href','/orchestration');
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {routerUsage,usagePeriods} from '../services/routerUsage';
|
||||
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
|
||||
const shown=(value:unknown)=>value===null||value===undefined?'Unknown — not reported':String(value);
|
||||
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{key}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
|
||||
export default function RouterUsagePanel(){
|
||||
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
|
||||
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'Usage unavailable')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
|
||||
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">9router usage & provider-reported quota</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>Refresh usage</Button></header>
|
||||
<label>Usage period<select aria-label="Usage period" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
|
||||
<p>Gateway totals include all clients. Provider/model/account breakdowns overlap; never add them together. Cache/reasoning counters may overlap token counts. No derived totals or quota estimates.</p>
|
||||
<p>Hermes attribution: Unknown — not reported; do not add to gateway totals.</p>
|
||||
{loading&&<p role="status">Loading gateway usage…</p>}{error&&<p role="alert">Unknown / unavailable: {error}</p>}
|
||||
{data&&<><dl><dt>Source</dt><dd>{data.source}</dd><dt>Retrieved at (not source freshness)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>Source updated at</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>Stale</dt><dd>{shown(data.freshness.stale)}</dd><dt>Reported period</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>Gateway totals (includes Hermes)</h3><Counters data={data.data.totals}/></article>
|
||||
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{group}</h3>{!data.data[group].length&&<p>No {group} reported.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>Provider-reported quota remaining</dt><dd>{shown(row.quota?.remaining)}</dd><dt>Provider-reported quota reset</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>Quota availability reason</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
|
||||
<p>Quota is unknown: upstream quota GET refreshes credentials, so this read-only adapter does not call it.</p></>}
|
||||
</section>;
|
||||
}
|
||||
@@ -112,19 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'governance',
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ icon: Building2, label: 'Orchestration command center', path: '/orchestration' },
|
||||
{ icon: Building2, label: 'نمای وضعیت دپارتمانها', path: '/governance/hq' },
|
||||
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاریها', path: '/manager-actions' },
|
||||
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },
|
||||
{ icon: Briefcase, label: 'وظایف دپارتمانها و ایجنتها', path: '/tasks' },
|
||||
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'monitoring',
|
||||
title: 'مرکز مانیتورینگ و سلامت',
|
||||
|
||||
@@ -12,9 +12,6 @@ interface TopbarProps {
|
||||
}
|
||||
|
||||
const SEARCHABLE_PAGES = [
|
||||
{ label: "اقدامات مدیریتی و همکاریها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
|
||||
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
|
||||
{ label: "وضعیت دپارتمانها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
|
||||
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
|
||||
{ label: 'مرکز مانیتورینگ و سلامت سرویسها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
|
||||
{ label: 'مدیریت نسخههای پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخهها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
@font-face {
|
||||
font-family: 'Shabnam';
|
||||
src: url('/fonts/shabnam-font-v33.003/fonts/webfonts/Shabnam.woff2') format('woff2');
|
||||
src: url('/fonts/shabnam-font-v5.0.1/Shabnam.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import ApprovalsPage from "./ApprovalsPage";
|
||||
|
||||
vi.mock("../services/api", () => {
|
||||
return {
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ApprovalsPage Component", () => {
|
||||
const mockApprovals = [
|
||||
{
|
||||
id: "app-1",
|
||||
department: "CONTENT",
|
||||
category: "CAMPAIGN",
|
||||
title: "کمپین تخصصی مفاصل: برتری بالینی صدف لبسبز کنینا نسبت به وتاکسپرت",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T10:00:00Z",
|
||||
payload: {
|
||||
"1_مسئله_و_شکاف_بازار": "قیمت گزاف قرص مفاصل وتاکسپرت لهستان باعث شکست دورههای درمانی شده است.",
|
||||
"2_راهحل_و_مزیت_کنینا": "معرفی مکمل بیرقیب Velox Gelenkenergie ۱۰۰٪ عصاره صدف لبسبز با نصف قیمت رقیب.",
|
||||
"3_طرح_اقدام_عملیاتی": "تولید لندینگپیج جامع و سئومحور و اتصال مستقیم به ترب.",
|
||||
"4_دپارتمانهای_مسئول": "CONTENT, SEO, CLINICAL_RD",
|
||||
"5_معیار_پذیرش_و_تکمیل": "رندر شدن لندینگ بدون خطای SSR و افزایش ایمپرشن ارگانیک."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-2",
|
||||
department: "PRICING",
|
||||
category: "PRICE_CHANGE",
|
||||
title: "پیشنهاد اصلاح قیمت و همگامسازی با ترب: Canina Flexan 150g",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T11:00:00Z",
|
||||
payload: {
|
||||
product_name: "Canina Flexan 150g",
|
||||
current_price: 34800000,
|
||||
suggested_price: 36500000,
|
||||
margin_percent: 20.5,
|
||||
competitor_min_torob: 37200000,
|
||||
reason: "افزایش قیمت تامینکننده و میانگین قیمت ترب روی ۳۷.۲ میلیون ریال است."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-3",
|
||||
department: "MARKETING",
|
||||
category: "SMS_CAMPAIGN",
|
||||
title: "کمپین یادآوری تمدید دوره مکملهای مفاصل و GAG",
|
||||
status: "APPROVED",
|
||||
createdAt: "2026-10-18T09:00:00Z",
|
||||
executedAt: "2026-10-18T10:00:00Z",
|
||||
ceoNotes: "تایید شد و پیامکها ارسال شدند.",
|
||||
payload: {
|
||||
campaign_name: "Refill GAG 60-Day Reminder",
|
||||
sms_pattern: "سلام {name} عزیز، دوره مکمل مفاصل کنینا رو به اتمام است.",
|
||||
target_count: 86,
|
||||
estimated_cost_irr: 860000,
|
||||
expected_revenue_irr: 54000000,
|
||||
expected_conversion_rate: "18%"
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(api.get as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockApprovals,
|
||||
meta: {
|
||||
total: 3,
|
||||
pendingCount: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("renders header, KPI cards, and maps strategic 5-part proposal nicely", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کارتابل حاکمیت سازمانی و تاییدات مدیرعامل/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/2 پیشنهاد منتظر تصمیم شما/i)).toBeInTheDocument();
|
||||
|
||||
// Verify 5-part structured fields are cleanly mapped
|
||||
expect(screen.getByText(/مسئله و شکاف شناساییشده در بازار:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قیمت گزاف قرص مفاصل وتاکسپرت لهستان/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/راهحل، محصول و مزیت رقابتی کنینا:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Velox Gelenkenergie/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders pricing payload with current price, suggested price, and margin", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/پیشنهاد اصلاح قیمت و همگامسازی با ترب/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/محاسبه قیمتگذاری و سود ناخالص:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/20.5٪/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("approves a pending request with CEO directive note", async () => {
|
||||
(api.put as any).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کمپین تخصصی مفاصل/i)).toBeInTheDocument();
|
||||
|
||||
const approveButtons = screen.getAllByRole("button", { name: /تایید و صدور مجوز اجرا/i });
|
||||
expect(approveButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(approveButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
"/admin/approvals/app-2/decide",
|
||||
expect.objectContaining({ decision: "APPROVED" })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("runs simulation test when clicking play button", async () => {
|
||||
(api.post as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
testResult: {
|
||||
status: "SIMULATION_SUCCESS",
|
||||
executionSafe: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
const runTestButtons = await screen.findAllByRole("button", { name: /اجرای تست و شبیهسازی/i });
|
||||
expect(runTestButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(runTestButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/approvals/app-2/test");
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/نتیجه تست سلامت و شبیهسازی:/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 282 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user