Compare commits
337
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69dd6922f6 | ||
|
|
a0d588ba12 | ||
|
|
5c93517b9e | ||
|
|
2408bafc49 | ||
|
|
46da1c5339 | ||
|
|
6ed0e73311 | ||
|
|
bee9c4d6e1 | ||
|
|
90dcec413d | ||
|
|
94f08b8c8a | ||
|
|
b642833b8b | ||
|
|
435a75a442 | ||
|
|
d80845af0d | ||
|
|
cc365bcda2 | ||
|
|
5550c80a75 | ||
|
|
3b05fe2e85 | ||
|
|
1f01b9dab9 | ||
|
|
8197259e54 | ||
|
|
fb1deadbbc | ||
|
|
0a156fd7b4 | ||
|
|
db3979d212 | ||
|
|
13dc74807a | ||
|
|
c62d9836e9 | ||
|
|
312fcc2acc | ||
|
|
5750e1589e | ||
|
|
df5584d214 | ||
|
|
6102556eae | ||
|
|
39f5b705c5 | ||
|
|
13f4fdc58d | ||
|
|
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 | ||
|
|
5507fbcb29 | ||
|
|
176cc08a6b | ||
|
|
5953c3cf75 | ||
|
|
0952a482fb | ||
|
|
c7f1d25e98 | ||
|
|
841eab0556 | ||
|
|
ac065fa911 | ||
|
|
70d8128bfb | ||
|
|
8c8ae66c7d | ||
|
|
c8a3f35b0a | ||
|
|
e5c83e87fe | ||
|
|
eb17c8e284 | ||
|
|
459f8b59fe | ||
|
|
e6c705cef7 | ||
|
|
19c4bb451d | ||
|
|
f71b79a17f | ||
|
|
e3eb7ca205 | ||
|
|
2e54163d9e | ||
|
|
344f79039f | ||
|
|
02fe634944 | ||
|
|
7b1f64d727 | ||
|
|
d53e38a48f | ||
|
|
740e738fca | ||
|
|
ee90284129 | ||
|
|
de42b3126b | ||
|
|
71dccbc590 | ||
|
|
4c6127786f | ||
|
|
bf082c59fe | ||
|
|
ee35c10454 | ||
|
|
1651fd00a2 | ||
|
|
d9e4447903 | ||
|
|
f59dd6ebec | ||
|
|
10413547c1 | ||
|
|
2f178db2c6 | ||
|
|
28485d51f7 | ||
|
|
24362b89d7 | ||
|
|
159e4a4cbf | ||
|
|
13a7919c91 | ||
|
|
d670690816 | ||
|
|
62c58c7c89 | ||
|
|
0b4d9a8463 | ||
|
|
51ca8c7e34 | ||
|
|
64047054b8 | ||
|
|
3f5258a76c | ||
|
|
3b93308b71 | ||
|
|
bf53f2e17c | ||
|
|
c2eca11a3b | ||
|
|
4c3f8de1fb | ||
|
|
b3e1869724 | ||
|
|
624f58c723 | ||
|
|
aedc0f6979 | ||
|
|
1e53ceeda6 | ||
|
|
f08ed0c22c | ||
|
|
ee0f877d97 | ||
|
|
b3d4e08914 | ||
|
|
ec9dd83e77 | ||
|
|
4930e2a870 | ||
|
|
5e21cc76fc | ||
|
|
529110a693 | ||
|
|
0b5f2a88cc | ||
|
|
ff6f04fe46 | ||
|
|
2e9a0e30c1 | ||
|
|
ad0acaccc2 | ||
|
|
30019a02d8 | ||
|
|
87999be3d2 | ||
|
|
4ce9f6000c | ||
|
|
0529962391 | ||
|
|
14c45e4f6c | ||
|
|
1c38b95fb0 | ||
|
|
dab66a2dce | ||
|
|
86eb0cfcae | ||
|
|
d3aa10c769 | ||
|
|
15524609fe | ||
|
|
aacb91ac70 | ||
|
|
f91502026b | ||
|
|
7f2f638f38 | ||
|
|
7879ead486 | ||
|
|
dda1caf3e0 | ||
|
|
bb483d3e68 | ||
|
|
73bc79b4bb | ||
|
|
9520426a66 | ||
|
|
b077423ab2 | ||
|
|
94867fbd5a | ||
|
|
6a37f2f4c7 | ||
|
|
b54338f91f | ||
|
|
c7b95b4d2b | ||
|
|
8e4388c325 | ||
|
|
305995cbe2 | ||
|
|
468170349d | ||
|
|
52446592e7 | ||
|
|
7bca0ef335 | ||
|
|
80717680a1 | ||
|
|
bb81f2c944 | ||
|
|
69094a8646 | ||
|
|
bed0b480d7 | ||
|
|
f8f9329c50 | ||
|
|
189e1f1202 | ||
|
|
5cf2863987 | ||
|
|
83cf70ac74 | ||
|
|
87bf867513 | ||
|
|
961bb383db | ||
|
|
5d5cc14f9e | ||
|
|
bfe228adee | ||
|
|
b5b4e64453 | ||
|
|
f23efbf90d | ||
|
|
81d1fa816b | ||
|
|
f5c970f82e | ||
|
|
6d0dea07f8 | ||
|
|
c4d95762f8 | ||
|
|
23724df4e4 | ||
|
|
21f7768cce | ||
|
|
92065cc7f2 | ||
|
|
956ef3b4d3 | ||
|
|
0d8125bd37 | ||
|
|
ea4d33b6bb | ||
|
|
b4fdd7abb8 | ||
|
|
f9d70bc196 | ||
|
|
5b20bab381 | ||
|
|
2c3e4bb752 | ||
|
|
570f0acc66 | ||
|
|
297aaadbe6 | ||
|
|
5573bb3568 | ||
|
|
80d9dc2f45 | ||
|
|
092933860a | ||
|
|
3d45b618ab | ||
|
|
2ab2318732 | ||
|
|
f3806cd6de | ||
|
|
8326e10ce8 | ||
|
|
d77ddd4bb2 | ||
|
|
9149e2b5ab | ||
|
|
5534d050af | ||
|
|
994086e580 | ||
|
|
dbd7d8b37d | ||
|
|
f440c60891 | ||
|
|
8672d4bcac | ||
|
|
87ad359e60 | ||
|
|
5afa2a37be | ||
|
|
d73b2e51c6 | ||
|
|
26f5f68708 | ||
|
|
86cfa4b3c8 | ||
|
|
e2b6d2acae | ||
|
|
8ef98cb415 | ||
|
|
6dbee69601 | ||
|
|
1aad481930 | ||
|
|
4393de5d8f | ||
|
|
5380bb66bb | ||
|
|
9a9ab149ed | ||
|
|
bec76393bb | ||
|
|
427b0d8591 | ||
|
|
1de8fd9a60 | ||
|
|
5c90d1629d | ||
|
|
c1a5223798 | ||
|
|
139aaff86c | ||
|
|
d9ff4aef58 | ||
|
|
a68e9b2c1e | ||
|
|
66cbf4c68d | ||
|
|
30ca17712c | ||
|
|
781b437c11 | ||
|
|
cf8f920aa6 | ||
|
|
c16e34df02 | ||
|
|
e67a4bd51c | ||
|
|
18e59efdcc | ||
|
|
c596c3a8b2 | ||
|
|
1f68210d08 | ||
|
|
fb4669e5a5 | ||
|
|
7b376f1126 | ||
|
|
e3426449e8 | ||
|
|
8795617d7f | ||
|
|
0dbf9cabb5 | ||
|
|
b6ac30d0e3 | ||
|
|
d79612b7e8 | ||
|
|
33c605132b | ||
|
|
686de48a95 | ||
|
|
043488fe55 | ||
|
|
f292195edf | ||
|
|
b61ba761bc | ||
|
|
4d64ad96b2 | ||
|
|
def903734f | ||
|
|
59ab154d0f | ||
|
|
31c55525c3 | ||
|
|
332d400a37 | ||
|
|
b5dcdec18c | ||
|
|
c6cf2e31aa | ||
|
|
b7268d0c47 | ||
|
|
a7b7164fc0 | ||
|
|
73f5d6d278 | ||
|
|
c04f1675f6 | ||
|
|
50cbd5b8ae | ||
|
|
19a029291b | ||
|
|
bd7345078a | ||
|
|
4969ec3fcd | ||
|
|
ec420e6053 | ||
|
|
4749ec91e4 | ||
|
|
679a551243 | ||
|
|
240a176151 | ||
|
|
d2c227c733 | ||
|
|
a532e2c73f | ||
|
|
3ff77d585d | ||
|
|
200ddda352 | ||
|
|
419e478489 | ||
|
|
2271291c87 |
No files matched your search
@@ -12,3 +12,7 @@ uploads
|
||||
**/uploads
|
||||
*.pdf
|
||||
graphify-out
|
||||
**/.revalidation.env*
|
||||
**/.support*.env*
|
||||
**/*runtime.env
|
||||
**/release.override.json
|
||||
@@ -13,7 +13,8 @@ jobs:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
run: |
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
@@ -25,8 +26,10 @@ jobs:
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh
|
||||
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}"
|
||||
@@ -0,0 +1,42 @@
|
||||
name: Stage author bootstrap (dedicated repair)
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ops/author-bootstrap-stage-rehearse
|
||||
- ops/author-bootstrap-stage-apply
|
||||
jobs:
|
||||
bootstrap:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Exact SHA build then isolated rehearsal and authorized repair
|
||||
env:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
GITHUB_REF: ${{ github.ref }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA }}
|
||||
# Path only, NOT a token value. Parent supplies an existing private file
|
||||
# visible to the runner; absent file blocks repair AFTER image build.
|
||||
AUTHOR_BOOTSTRAP_TOKEN_FILE: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE }}
|
||||
run: |
|
||||
set -eu
|
||||
set +x
|
||||
umask 077
|
||||
case "$GITHUB_REF" in
|
||||
refs/heads/ops/author-bootstrap-stage-rehearse|refs/heads/ops/author-bootstrap-stage-apply) ;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
test "$STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA" = "$GITHUB_SHA"
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
|
||||
root=$(mktemp -d)
|
||||
chmod 700 "$root"
|
||||
git init "$root/source"
|
||||
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
|
||||
git -C "$root/source" checkout --detach FETCH_HEAD
|
||||
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
export AUTHOR_BOOTSTRAP_EVIDENCE="$root/evidence"
|
||||
printf 'Private Stage evidence directory (retained on failure): %s\n' "$root/evidence"
|
||||
python3 "$root/source/scripts/stage-author-bootstrap/ci.py"
|
||||
# Retain private dumps locally; never upload archive or credential files.
|
||||
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Stage SEO schema operation
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ops/seo-schema-stage-rehearse
|
||||
- ops/seo-schema-stage-apply
|
||||
jobs:
|
||||
schema:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Exact immutable Stage operation
|
||||
env:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
GITHUB_REF: ${{ github.ref }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
STAGE_SCHEMA_REVIEWED_SHA: ${{ secrets.STAGE_SCHEMA_REVIEWED_SHA }}
|
||||
run: |
|
||||
set -eu
|
||||
case "$GITHUB_REF" in
|
||||
refs/heads/ops/seo-schema-stage-rehearse) mode=rehearse ;;
|
||||
refs/heads/ops/seo-schema-stage-apply) mode=apply ;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
|
||||
root=$(mktemp -d)
|
||||
chmod 700 "$root"
|
||||
git init "$root/source"
|
||||
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
|
||||
git -C "$root/source" checkout --detach FETCH_HEAD
|
||||
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 "$root/source/scripts/stage-schema/operation.py" "$mode" --sha "$GITHUB_SHA" --evidence "$root/evidence"
|
||||
# Private backups remain in this restricted runner directory; never upload dumps.
|
||||
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
|
||||
@@ -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
|
||||
|
||||
|
||||
+6
-3
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||
ENV DISABLE_OPENCOLLECTIVE=1
|
||||
@@ -11,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
|
||||
|
||||
@@ -31,8 +31,11 @@ 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
|
||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||
@@ -45,4 +48,4 @@ COPY --chown=node:node --from=builder /app/src ./src
|
||||
COPY --chown=node:node --from=builder /app/test ./test
|
||||
EXPOSE 3000
|
||||
USER node
|
||||
CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"]
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -0,0 +1,28 @@
|
||||
# Prisma migration history and Orchestration v4 rollout boundary
|
||||
|
||||
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
|
||||
|
||||
## Actual tracked history
|
||||
|
||||
| Migration | What its SQL actually does |
|
||||
| --- | --- |
|
||||
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
|
||||
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
|
||||
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
|
||||
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
|
||||
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
|
||||
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
|
||||
|
||||
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
|
||||
|
||||
## Required rollout safeguards (not authorization to deploy)
|
||||
|
||||
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
|
||||
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
|
||||
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
|
||||
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
|
||||
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
|
||||
|
||||
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
|
||||
|
||||
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id));
|
||||
CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id));
|
||||
CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence);
|
||||
CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at);
|
||||
CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at);
|
||||
CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at);
|
||||
ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,211 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"key" VARCHAR(120) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
|
||||
"operation_mode" VARCHAR(30) NOT NULL,
|
||||
"model_tier" VARCHAR(2),
|
||||
"budget_limit_cents" INTEGER NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_runs" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"attempt" INTEGER NOT NULL DEFAULT 1,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"commit_sha" VARCHAR(64) NOT NULL,
|
||||
"environment" VARCHAR(50) NOT NULL,
|
||||
"retry_class" VARCHAR(30),
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"started_at" TIMESTAMPTZ,
|
||||
"finished_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_artifacts" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"uri" TEXT NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size_bytes" BIGINT,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"subject_hash" CHAR(64) NOT NULL,
|
||||
"predicate" JSONB NOT NULL,
|
||||
"signer" VARCHAR(150) NOT NULL,
|
||||
"signature" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_dependencies" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"depends_on_task_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_approval_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"gate" INTEGER NOT NULL,
|
||||
"decision" VARCHAR(20) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"notes" TEXT,
|
||||
"expires_at" TIMESTAMPTZ NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"run_id" UUID,
|
||||
"artifact_hash" CHAR(64),
|
||||
"commit_sha" VARCHAR(64),
|
||||
"environment" VARCHAR(50),
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID,
|
||||
"event_type" VARCHAR(60) NOT NULL,
|
||||
"from_state" VARCHAR(40),
|
||||
"to_state" VARCHAR(40),
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150),
|
||||
"payload" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_budget_ledger" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"amount_cents" INTEGER NOT NULL,
|
||||
"kind" VARCHAR(40) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_kill_switches" (
|
||||
"scope" VARCHAR(80) NOT NULL,
|
||||
"level" VARCHAR(30) NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Immutable evidence and accounting; corrections are new entries.
|
||||
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
|
||||
$$;
|
||||
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
@@ -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;
|
||||
@@ -0,0 +1,89 @@
|
||||
-- SEO models existed in schema.prisma without a tracked CREATE migration.
|
||||
-- Create only missing SEO objects, then additively upgrade existing SEO tables.
|
||||
-- This does not reconcile the repository's broader incomplete baseline: blogs
|
||||
-- must already exist (see prisma/MIGRATION_BASELINE.md). No live SQL is run here.
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE "ResearchFindingStatus" AS ENUM ('RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED');
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "content_research_findings" (
|
||||
"id" UUID NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"hypothesis" TEXT NOT NULL,
|
||||
"target_keywords" TEXT[],
|
||||
"primary_keyword" VARCHAR(128) NOT NULL,
|
||||
"expected_outcome" TEXT NOT NULL,
|
||||
"status" "ResearchFindingStatus" NOT NULL DEFAULT 'RESEARCHED',
|
||||
"blog_id" UUID,
|
||||
"ceo_feedback" TEXT,
|
||||
"feedback_submitted_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT "content_research_findings_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "content_research_findings_blog_id_fkey" FOREIGN KEY ("blog_id") REFERENCES "blogs"("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE "content_research_findings"
|
||||
ADD COLUMN IF NOT EXISTS "version" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS "feedback_version" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS "search_text" TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS "goal_metric" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "goal_target" DOUBLE PRECISION,
|
||||
ADD COLUMN IF NOT EXISTS "action_id" TEXT;
|
||||
-- action_id is a plain external reference, deliberately without a foreign key.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "content_research_findings_blog_id_key" ON "content_research_findings"("blog_id");
|
||||
CREATE INDEX IF NOT EXISTS "content_research_findings_status_idx" ON "content_research_findings"("status");
|
||||
CREATE INDEX IF NOT EXISTS "content_research_findings_primary_keyword_idx" ON "content_research_findings"("primary_keyword");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "content_performance_snapshots" (
|
||||
"id" UUID NOT NULL,
|
||||
"finding_id" UUID NOT NULL,
|
||||
"snapshot_date" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"gsc_impressions" INTEGER,
|
||||
"gsc_clicks" INTEGER,
|
||||
"gsc_position" DOUBLE PRECISION,
|
||||
"ga4_active_users" INTEGER,
|
||||
"ga4_avg_engagement_sec" DOUBLE PRECISION,
|
||||
"ga4_bounce_rate" DOUBLE PRECISION,
|
||||
"ga4_scroll_depth_rate" DOUBLE PRECISION,
|
||||
"attributed_orders_count" INTEGER,
|
||||
"attributed_sales_value" DECIMAL(15,2),
|
||||
"action_recommendation" VARCHAR(64),
|
||||
"analysis_notes" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "content_performance_snapshots_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "content_performance_snapshots_finding_id_fkey" FOREIGN KEY ("finding_id") REFERENCES "content_research_findings"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE "content_performance_snapshots"
|
||||
ADD COLUMN IF NOT EXISTS "period_start" TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS "period_end" TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS "source_metadata" JSONB,
|
||||
ADD COLUMN IF NOT EXISTS "ingestion_key" TEXT,
|
||||
ALTER COLUMN "gsc_impressions" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_impressions" DROP DEFAULT,
|
||||
ALTER COLUMN "gsc_clicks" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_clicks" DROP DEFAULT,
|
||||
ALTER COLUMN "gsc_position" DROP NOT NULL,
|
||||
ALTER COLUMN "gsc_position" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_active_users" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_active_users" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_avg_engagement_sec" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_avg_engagement_sec" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_bounce_rate" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_bounce_rate" DROP DEFAULT,
|
||||
ALTER COLUMN "ga4_scroll_depth_rate" DROP NOT NULL,
|
||||
ALTER COLUMN "ga4_scroll_depth_rate" DROP DEFAULT,
|
||||
ALTER COLUMN "attributed_orders_count" DROP NOT NULL,
|
||||
ALTER COLUMN "attributed_orders_count" DROP DEFAULT,
|
||||
ALTER COLUMN "attributed_sales_value" DROP NOT NULL,
|
||||
ALTER COLUMN "attributed_sales_value" DROP DEFAULT;
|
||||
|
||||
-- Do not rewrite historical metrics: old zeros remain zeros, not proven measures.
|
||||
-- Newly added metadata/period/key columns remain SQL NULL for legacy snapshots;
|
||||
-- no provenance, observation period, or idempotency key can be inferred safely.
|
||||
CREATE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_snapshot_date_idx" ON "content_performance_snapshots"("finding_id", "snapshot_date");
|
||||
-- PostgreSQL permits multiple NULL keys, preserving all historical snapshots.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_ingestion_key_key" ON "content_performance_snapshots"("finding_id", "ingestion_key");
|
||||
@@ -0,0 +1,244 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CorporateTaskStatus" AS ENUM ('TODO', 'IN_PROGRESS', 'TEST', 'DONE', 'BLOCKED', 'REJECTED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CorporatePriority" AS ENUM ('CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskCode" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"normalizedTitle" TEXT NOT NULL,
|
||||
"normalizedCode" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL,
|
||||
"department" TEXT NOT NULL,
|
||||
"priority" "CorporatePriority" NOT NULL DEFAULT 'CEO_EXPEDITE',
|
||||
"status" "CorporateTaskStatus" NOT NULL DEFAULT 'TODO',
|
||||
"actionType" TEXT NOT NULL DEFAULT 'CEO_DIRECTIVE',
|
||||
"dueCycle" TEXT,
|
||||
"parentId" UUID,
|
||||
"goalId" UUID,
|
||||
"assignedAgent" TEXT,
|
||||
"claimToken" UUID,
|
||||
"leasedUntil" TIMESTAMPTZ,
|
||||
"executionCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"qaCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"rejectionCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "corporate_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"speaker" TEXT NOT NULL,
|
||||
"speakerName" TEXT NOT NULL,
|
||||
"step" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"payload" JSONB,
|
||||
"timestamp" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_evidence" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"claimToken" UUID NOT NULL,
|
||||
"executor" TEXT NOT NULL,
|
||||
"artifactUri" TEXT NOT NULL,
|
||||
"sha256" TEXT NOT NULL,
|
||||
"summary" TEXT NOT NULL,
|
||||
"tool" TEXT NOT NULL,
|
||||
"result" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_evidence_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_reviews" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"evidenceId" UUID NOT NULL,
|
||||
"reviewer" TEXT NOT NULL,
|
||||
"passed" BOOLEAN NOT NULL,
|
||||
"findings" TEXT NOT NULL,
|
||||
"verification" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_reviews_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_research" (
|
||||
"id" UUID NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"opportunity" TEXT NOT NULL,
|
||||
"impact" TEXT NOT NULL,
|
||||
"recommendedAction" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'DISCOVERED',
|
||||
"cadence" TEXT NOT NULL,
|
||||
"provenance" JSONB NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_research_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_sources" (
|
||||
"id" UUID NOT NULL,
|
||||
"researchId" UUID NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"excerpt" TEXT NOT NULL,
|
||||
"retrievedAt" TIMESTAMPTZ NOT NULL,
|
||||
"sha256" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "corporate_sources_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_roadmaps" (
|
||||
"id" UUID NOT NULL,
|
||||
"researchId" UUID NOT NULL,
|
||||
"cycleName" TEXT NOT NULL,
|
||||
"month" TEXT NOT NULL,
|
||||
"seasonalTheme" TEXT NOT NULL,
|
||||
"strategicGoals" TEXT[],
|
||||
"plannedArticlesCount" INTEGER NOT NULL,
|
||||
"plannedRefreshesCount" INTEGER NOT NULL,
|
||||
"plannedCatalogEnrichments" INTEGER NOT NULL,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_roadmaps_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_goals" (
|
||||
"id" UUID NOT NULL,
|
||||
"roadmapId" UUID NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"department" TEXT NOT NULL,
|
||||
"acceptanceCriteria" TEXT NOT NULL,
|
||||
"metric" TEXT NOT NULL,
|
||||
"target" DOUBLE PRECISION,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_goals_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_effects" (
|
||||
"id" UUID NOT NULL,
|
||||
"taskId" UUID NOT NULL,
|
||||
"metric" TEXT NOT NULL,
|
||||
"availability" TEXT NOT NULL,
|
||||
"baseline" DOUBLE PRECISION,
|
||||
"observed" DOUBLE PRECISION,
|
||||
"source" TEXT NOT NULL,
|
||||
"observedAt" TIMESTAMPTZ NOT NULL,
|
||||
"recordedBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_effects_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_reports" (
|
||||
"id" UUID NOT NULL,
|
||||
"day" TEXT NOT NULL,
|
||||
"summary" TEXT NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_reports_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "corporate_operations" (
|
||||
"key" TEXT NOT NULL,
|
||||
"payloadHash" TEXT NOT NULL,
|
||||
"response" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "corporate_operations_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "corporate_tasks_taskCode_key" ON "corporate_tasks"("taskCode");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_status_priority_updatedAt_idx" ON "corporate_tasks"("status", "priority", "updatedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_parentId_idx" ON "corporate_tasks"("parentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_tasks_goalId_idx" ON "corporate_tasks"("goalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_events_taskId_timestamp_idx" ON "corporate_events"("taskId", "timestamp");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_evidence_taskId_idx" ON "corporate_evidence"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_reviews_taskId_idx" ON "corporate_reviews"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_sources_researchId_idx" ON "corporate_sources"("researchId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_roadmaps_month_idx" ON "corporate_roadmaps"("month");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_goals_roadmapId_idx" ON "corporate_goals"("roadmapId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "corporate_effects_taskId_idx" ON "corporate_effects"("taskId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "corporate_reports_day_key" ON "corporate_reports"("day");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "corporate_tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_goalId_fkey" FOREIGN KEY ("goalId") REFERENCES "corporate_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_events" ADD CONSTRAINT "corporate_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_evidence" ADD CONSTRAINT "corporate_evidence_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_evidenceId_fkey" FOREIGN KEY ("evidenceId") REFERENCES "corporate_evidence"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_sources" ADD CONSTRAINT "corporate_sources_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_roadmaps" ADD CONSTRAINT "corporate_roadmaps_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_goals" ADD CONSTRAINT "corporate_goals_roadmapId_fkey" FOREIGN KEY ("roadmapId") REFERENCES "corporate_roadmaps"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "corporate_effects" ADD CONSTRAINT "corporate_effects_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Reviewed attribution-only storage; no business data or historical ledger writes.
|
||||
DO $$ BEGIN
|
||||
IF current_database() NOT IN ('caninodb_stage', 'rehearsal') THEN
|
||||
RAISE EXCEPTION 'public author bootstrap is Stage-only';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS is_public_author BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET NOT NULL;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN mobile DROP NOT NULL;
|
||||
-- Repeated application is transactional and revalidates every existing row.
|
||||
ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_public_author_identity_check;
|
||||
ALTER TABLE public.users ADD CONSTRAINT users_public_author_identity_check CHECK (
|
||||
(is_public_author = false AND mobile IS NOT NULL)
|
||||
OR
|
||||
(is_public_author = true
|
||||
AND mobile IS NULL AND email IS NULL AND password IS NULL
|
||||
AND role = 'User_PetOwner'
|
||||
AND auth_expires_at IS NULL
|
||||
AND stage_test_generation IS NULL AND stage_test_session IS NULL
|
||||
AND wallet_balance = 0 AND charity_donation_total = 0)
|
||||
);
|
||||
+314
-67
@@ -1,3 +1,202 @@
|
||||
enum CorporateTaskStatus {
|
||||
TODO
|
||||
IN_PROGRESS
|
||||
TEST
|
||||
DONE
|
||||
BLOCKED
|
||||
REJECTED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum CorporatePriority {
|
||||
CEO_EXPEDITE
|
||||
CRITICAL
|
||||
HIGH
|
||||
MEDIUM
|
||||
LOW
|
||||
}
|
||||
|
||||
model CorporateTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskCode String @unique
|
||||
title String
|
||||
normalizedTitle String
|
||||
normalizedCode String
|
||||
description String
|
||||
department String
|
||||
priority CorporatePriority @default(CEO_EXPEDITE)
|
||||
status CorporateTaskStatus @default(TODO)
|
||||
actionType String @default("CEO_DIRECTIVE")
|
||||
dueCycle String?
|
||||
parentId String? @db.Uuid
|
||||
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
|
||||
children CorporateTask[] @relation("TaskChildren")
|
||||
goalId String? @db.Uuid
|
||||
goal CorporateGoal? @relation(fields: [goalId], references: [id])
|
||||
assignedAgent String?
|
||||
claimToken String? @db.Uuid
|
||||
leasedUntil DateTime? @db.Timestamptz()
|
||||
executionCount Int @default(0)
|
||||
qaCount Int @default(0)
|
||||
rejectionCount Int @default(0)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @db.Timestamptz()
|
||||
logs CorporateEvent[]
|
||||
evidence CorporateEvidence[]
|
||||
reviews CorporateReview[]
|
||||
effects CorporateEffect[]
|
||||
@@index([status, priority, updatedAt])
|
||||
@@index([parentId])
|
||||
@@index([goalId])
|
||||
@@map("corporate_tasks")
|
||||
}
|
||||
|
||||
model CorporateEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
speaker String
|
||||
speakerName String
|
||||
step String
|
||||
content String
|
||||
payload Json?
|
||||
timestamp DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId, timestamp])
|
||||
@@map("corporate_events")
|
||||
}
|
||||
|
||||
model CorporateEvidence {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
claimToken String @db.Uuid
|
||||
executor String
|
||||
artifactUri String
|
||||
sha256 String
|
||||
summary String
|
||||
tool String
|
||||
result String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
reviews CorporateReview[]
|
||||
@@index([taskId])
|
||||
@@map("corporate_evidence")
|
||||
}
|
||||
|
||||
model CorporateReview {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
evidenceId String @db.Uuid
|
||||
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
|
||||
reviewer String
|
||||
passed Boolean
|
||||
findings String
|
||||
verification Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_reviews")
|
||||
}
|
||||
|
||||
model CorporateResearch {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String
|
||||
category String
|
||||
source String
|
||||
opportunity String
|
||||
impact String
|
||||
recommendedAction String
|
||||
status String @default("DISCOVERED")
|
||||
cadence String
|
||||
provenance Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
sources CorporateSource[]
|
||||
roadmaps CorporateRoadmap[]
|
||||
@@map("corporate_research")
|
||||
}
|
||||
|
||||
model CorporateSource {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
url String
|
||||
title String
|
||||
excerpt String
|
||||
retrievedAt DateTime @db.Timestamptz()
|
||||
sha256 String
|
||||
@@index([researchId])
|
||||
@@map("corporate_sources")
|
||||
}
|
||||
|
||||
model CorporateRoadmap {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
researchId String @db.Uuid
|
||||
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||
cycleName String
|
||||
month String
|
||||
seasonalTheme String
|
||||
strategicGoals String[]
|
||||
plannedArticlesCount Int
|
||||
plannedRefreshesCount Int
|
||||
plannedCatalogEnrichments Int
|
||||
isActive Boolean @default(false)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
goals CorporateGoal[]
|
||||
@@index([month])
|
||||
@@map("corporate_roadmaps")
|
||||
}
|
||||
|
||||
model CorporateGoal {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roadmapId String @db.Uuid
|
||||
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
|
||||
title String
|
||||
department String
|
||||
acceptanceCriteria String
|
||||
metric String
|
||||
target Float?
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
tasks CorporateTask[]
|
||||
@@index([roadmapId])
|
||||
@@map("corporate_goals")
|
||||
}
|
||||
|
||||
model CorporateEffect {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @db.Uuid
|
||||
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||
metric String
|
||||
availability String
|
||||
baseline Float?
|
||||
observed Float?
|
||||
source String
|
||||
observedAt DateTime @db.Timestamptz()
|
||||
recordedBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@index([taskId])
|
||||
@@map("corporate_effects")
|
||||
}
|
||||
|
||||
model CorporateReport {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
day String @unique
|
||||
summary String
|
||||
snapshot Json
|
||||
createdBy String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_reports")
|
||||
}
|
||||
|
||||
model CorporateOperation {
|
||||
key String @id
|
||||
payloadHash String
|
||||
response Json
|
||||
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||
@@map("corporate_operations")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
|
||||
@@ -13,9 +212,13 @@ model User {
|
||||
firstName String @map("first_name") @db.VarChar(100)
|
||||
lastName String @map("last_name") @db.VarChar(100)
|
||||
email String? @unique @db.VarChar(150)
|
||||
mobile String @unique @db.VarChar(15)
|
||||
mobile String? @unique @db.VarChar(15)
|
||||
isPublicAuthor Boolean @default(false) @map("is_public_author")
|
||||
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()
|
||||
@@ -32,12 +235,49 @@ model User {
|
||||
tickets Ticket[]
|
||||
reviews ProductReview[]
|
||||
blogComments BlogComment[]
|
||||
supportConversations SupportConversation[]
|
||||
|
||||
@@index([role])
|
||||
@@index([createdAt])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model SupportConversation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String? @map("user_id") @db.Uuid
|
||||
anonymousBrowserId String? @map("anonymous_browser_id") @db.VarChar(64)
|
||||
entryPath String? @map("entry_path") @db.VarChar(512)
|
||||
productSlugs Json? @map("product_slugs")
|
||||
topics Json?
|
||||
unanswered Boolean @default(false)
|
||||
needsFollowup Boolean @default(false) @map("needs_followup")
|
||||
escalationSignal Boolean @default(false) @map("escalation_signal")
|
||||
summary String? @db.Text
|
||||
summaryStatus String @default("pending") @map("summary_status") @db.VarChar(20)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
messages SupportConversationMessage[]
|
||||
@@index([userId, updatedAt])
|
||||
@@index([anonymousBrowserId, updatedAt])
|
||||
@@map("support_conversations")
|
||||
}
|
||||
|
||||
model SupportConversationMessage {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
conversationId String @map("conversation_id") @db.Uuid
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
sequence Int
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
||||
@@unique([conversationId, sequence])
|
||||
@@index([conversationId, createdAt])
|
||||
@@map("support_conversation_messages")
|
||||
}
|
||||
|
||||
model UserAddress {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
@@ -141,7 +381,9 @@ model Blog {
|
||||
slug String @unique @db.VarChar(200)
|
||||
content String @db.Text
|
||||
excerpt String? @db.Text
|
||||
authorId String @map("author_id") @db.Uuid
|
||||
authorId String? @map("author_id") @db.Uuid
|
||||
authorTeam String? @map("author_team") @db.VarChar(200)
|
||||
authorRole String? @map("author_role") @db.VarChar(200)
|
||||
categoryId String? @map("category_id") @db.Uuid
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||
@@ -161,6 +403,7 @@ model Blog {
|
||||
isPublished Boolean @default(true) @map("is_published")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
||||
readingTime Int @default(3) @map("reading_time")
|
||||
featured Boolean @default(false)
|
||||
allowComments Boolean @default(true) @map("allow_comments")
|
||||
@@ -172,10 +415,11 @@ model Blog {
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
author User @relation(fields: [authorId], references: [id])
|
||||
author User? @relation(fields: [authorId], references: [id])
|
||||
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||
tags BlogTag[]
|
||||
comments BlogComment[]
|
||||
researchFinding ContentResearchFinding?
|
||||
|
||||
@@index([categoryId])
|
||||
@@index([status])
|
||||
@@ -978,76 +1222,79 @@ model SmsCampaign {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 5. ApprovalRequest (CEO Governance & Decision Gate)
|
||||
// 5. SEO & Performance Tracking Models
|
||||
// ------------------------------------------------------------------------------
|
||||
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()
|
||||
enum ResearchFindingStatus {
|
||||
RESEARCHED
|
||||
ACTIONED
|
||||
EVALUATING
|
||||
SCALED
|
||||
PRUNED
|
||||
}
|
||||
|
||||
model ContentResearchFinding {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String @db.VarChar(255)
|
||||
hypothesis String @db.Text
|
||||
targetKeywords String[] @map("target_keywords")
|
||||
primaryKeyword String @map("primary_keyword") @db.VarChar(128)
|
||||
expectedOutcome String @map("expected_outcome") @db.Text
|
||||
status ResearchFindingStatus @default(RESEARCHED)
|
||||
version Int @default(0)
|
||||
feedbackVersion Int @default(0) @map("feedback_version")
|
||||
searchText String @default("") @map("search_text") @db.Text
|
||||
goalMetric String? @map("goal_metric")
|
||||
goalTarget Float? @map("goal_target")
|
||||
// External action reference only; no orchestration relation or foreign key.
|
||||
actionId String? @map("action_id")
|
||||
|
||||
blogId String? @unique @map("blog_id") @db.Uuid
|
||||
blog Blog? @relation(fields: [blogId], references: [id], onDelete: SetNull)
|
||||
|
||||
ceoFeedback String? @map("ceo_feedback") @db.Text
|
||||
feedbackSubmittedAt DateTime? @map("feedback_submitted_at") @db.Timestamptz()
|
||||
|
||||
snapshots ContentPerformanceSnapshot[]
|
||||
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([category])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("approval_requests")
|
||||
@@index([primaryKeyword])
|
||||
@@map("content_research_findings")
|
||||
}
|
||||
|
||||
model ContentPerformanceSnapshot {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
findingId String @map("finding_id") @db.Uuid
|
||||
finding ContentResearchFinding @relation(fields: [findingId], references: [id], onDelete: Cascade)
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 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()
|
||||
snapshotDate DateTime @default(now()) @map("snapshot_date") @db.Timestamptz()
|
||||
|
||||
@@index([entity])
|
||||
@@index([action])
|
||||
@@index([department])
|
||||
@@index([createdAt])
|
||||
@@map("audit_logs")
|
||||
periodStart DateTime? @map("period_start") @db.Timestamptz()
|
||||
periodEnd DateTime? @map("period_end") @db.Timestamptz()
|
||||
sourceMetadata Json? @map("source_metadata")
|
||||
ingestionKey String? @map("ingestion_key")
|
||||
|
||||
gscImpressions Int? @map("gsc_impressions")
|
||||
gscClicks Int? @map("gsc_clicks")
|
||||
gscPosition Float? @map("gsc_position")
|
||||
|
||||
ga4ActiveUsers Int? @map("ga4_active_users")
|
||||
ga4AvgEngagementSec Float? @map("ga4_avg_engagement_sec")
|
||||
ga4BounceRate Float? @map("ga4_bounce_rate")
|
||||
ga4ScrollDepthRate Float? @map("ga4_scroll_depth_rate")
|
||||
|
||||
attributedOrdersCount Int? @map("attributed_orders_count")
|
||||
attributedSalesValue Decimal? @map("attributed_sales_value") @db.Decimal(15, 2)
|
||||
|
||||
actionRecommendation String? @map("action_recommendation") @db.VarChar(64)
|
||||
analysisNotes String? @map("analysis_notes") @db.Text
|
||||
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([findingId, snapshotDate])
|
||||
@@unique([findingId, ingestionKey])
|
||||
@@map("content_performance_snapshots")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 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")
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand api-keys.integration.spec
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 5 passed, 5 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.044 s
|
||||
Ran all test suites matching api-keys.integration.spec.
|
||||
@@ -0,0 +1,104 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand api-keys.integration.spec
|
||||
FAIL src/admin/api-keys.integration.spec.ts
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies get to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies post to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 201 "Created"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies patch to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● human-only key administration / real key authentication and PostgreSQL › denies delete to authenticated admin API key without mutating keys
|
||||
|
||||
expected 403 "Forbidden", got 200 "OK"
|
||||
|
||||
34 | const before = await db.apiKey.count();
|
||||
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
|
||||
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
|
||||
| ^
|
||||
37 | expect(await db.apiKey.count()).toBe(before);
|
||||
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
|
||||
39 | });
|
||||
|
||||
at admin/api-keys.integration.spec.ts:36:174
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 4 failed, 1 passed, 5 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.608 s
|
||||
Ran all test suites matching api-keys.integration.spec.
|
||||
@@ -0,0 +1,207 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:22 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:07 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:08 PM [31m ERROR[39m [38;5;3m[SslService] [39m[31mFailed to parse SSL certificate[39m
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:08 PM [31m ERROR[39m [38;5;3m[SslService] [39mError: error:0480006C:PEM routines::no start line
|
||||
[90m at new X509Certificate (node:internal/crypto/x509:121:21)[39m
|
||||
at SslService.getStatus [90m(/opt/data/cache/scratch/corporate-hardening-base/backend/[39msrc/admin/ssl.service.ts:104:20[90m)[39m
|
||||
at Object.<anonymous> [90m(/opt/data/cache/scratch/corporate-hardening-base/backend/[39msrc/admin/ssl.service.spec.ts:179:30[90m)[39m
|
||||
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1561:28)
|
||||
at new Promise (<anonymous>)
|
||||
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1501:10)
|
||||
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1011:40)
|
||||
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:951:3)
|
||||
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:853:7
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:866:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:765:3)
|
||||
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1993:21)
|
||||
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/runner.js:111:19)
|
||||
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:276:16)
|
||||
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:344:7) {
|
||||
library: [32m'PEM routines'[39m,
|
||||
reason: [32m'no start line'[39m,
|
||||
code: [32m'ERR_OSSL_PEM_NO_START_LINE'[39m
|
||||
}
|
||||
[31m[Nest] 3987292 - [39m10/28/2026, 12:44:12 PM [31m ERROR[39m [38;5;3m[PaymentService] [39m[31mSecurity Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.[39m
|
||||
FAIL src/seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
[33m[Nest] 3987292 - [39m10/28/2026, 12:44:18 PM [33m WARN[39m [38;5;3m[BlogsService] [39m[33mCache revalidation failed for updated blog [post]: cache down[39m
|
||||
FAIL src/wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Summary of all failing tests
|
||||
FAIL seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
FAIL wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Test Suites: 2 failed, 5 skipped, 95 passed, 97 of 102 total
|
||||
Tests: 1 failed, 13 skipped, 818 passed, 832 total
|
||||
Snapshots: 0 total
|
||||
Time: 55.893 s
|
||||
Ran all test suites.
|
||||
@@ -0,0 +1,44 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t bounds detail|oversized
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › bounds detail relations and report snapshots with explicit truncation and immutable replay
|
||||
|
||||
expect(received).toHaveLength(expected)
|
||||
|
||||
Expected length: 100
|
||||
Received length: 106
|
||||
Received array: [[Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], …]
|
||||
|
||||
153 | await db.corporateEvent.createMany({ data: Array.from({ length: 105 }, () => ({ taskId: task.id, speaker: 'SYSTEM', speakerName: 'fixture', step: 'FIXTURE', content: 'x'.repeat(10000), payload: { nested: ['x'.repeat(10000)] } })) });
|
||||
154 | const detail = await request(app.getHttpServer()).get('/admin/hermes/tasks/' + task.id).set('x-api-key', 'executor').expect(200);
|
||||
> 155 | expect(detail.body.logs).toHaveLength(100);
|
||||
| ^
|
||||
156 | expect(detail.body.relationsMeta.logs).toEqual({ total: 106, returned: 100, limit: 100, truncated: true });
|
||||
157 | const op = key(), body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||
158 | const report = (await post('reports', body, 'executor', op).expect(201)).body;
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:155:30)
|
||||
|
||||
● corporate API / disposable PostgreSQL › rolls back oversized mutation responses instead of persisting huge idempotency values
|
||||
|
||||
expect(received).rejects.toThrow()
|
||||
|
||||
Received promise resolved instead of rejected
|
||||
Resolved to value: {"value": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
168 | const service = app.get(CorporateService) as any;
|
||||
169 | const before = await db.corporateTask.count();
|
||||
> 170 | await expect(service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||
| ^
|
||||
171 | await tx.corporateTask.create({ data: { title: 'rollback', description: 'fixture', taskCode: key(), normalizedTitle: 'rollback', normalizedCode: key(), department: 'CONTENT_SEO', createdBy: 'fixture' } });
|
||||
172 | return { value: 'x'.repeat(1100000) };
|
||||
173 | })).rejects.toThrow('Operation response exceeds limit');
|
||||
|
||||
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:170:11)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 2 failed, 10 skipped, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.583 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "bounds detail|oversized".
|
||||
@@ -0,0 +1,2 @@
|
||||
npm notice run backend@0.0.1 build
|
||||
npm notice run tsc -b
|
||||
@@ -0,0 +1,8 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec api-keys.integration.spec
|
||||
|
||||
Test Suites: 3 passed, 3 total
|
||||
Tests: 20 passed, 20 total
|
||||
Snapshots: 0 total
|
||||
Time: 9.263 s
|
||||
Ran all test suites matching corporate.integration.spec|corporate-policy.spec|api-keys.integration.spec.
|
||||
@@ -0,0 +1,207 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:29 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:14 PM [31m ERROR[39m [38;5;3m[ZibalEBankService] [39m[31m[Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:15 PM [31m ERROR[39m [38;5;3m[SslService] [39m[31mFailed to parse SSL certificate[39m
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:15 PM [31m ERROR[39m [38;5;3m[SslService] [39mError: error:0480006C:PEM routines::no start line
|
||||
[90m at new X509Certificate (node:internal/crypto/x509:121:21)[39m
|
||||
at SslService.getStatus [90m(/opt/data/cache/scratch/corporate-hardening/backend/[39msrc/admin/ssl.service.ts:104:20[90m)[39m
|
||||
at Object.<anonymous> [90m(/opt/data/cache/scratch/corporate-hardening/backend/[39msrc/admin/ssl.service.spec.ts:179:30[90m)[39m
|
||||
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1561:28)
|
||||
at new Promise (<anonymous>)
|
||||
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1501:10)
|
||||
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1011:40)
|
||||
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:951:3)
|
||||
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:853:7
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:866:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:861:11)
|
||||
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:765:3)
|
||||
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/jestAdapterInit.js:1993:21)
|
||||
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-circus[24m/build/runner.js:111:19)
|
||||
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:276:16)
|
||||
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/[4mjest-runner[24m/build/index.js:344:7) {
|
||||
library: [32m'PEM routines'[39m,
|
||||
reason: [32m'no start line'[39m,
|
||||
code: [32m'ERR_OSSL_PEM_NO_START_LINE'[39m
|
||||
}
|
||||
[31m[Nest] 3985069 - [39m10/28/2026, 12:42:19 PM [31m ERROR[39m [38;5;3m[PaymentService] [39m[31mSecurity Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.[39m
|
||||
FAIL src/seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
[33m[Nest] 3985069 - [39m10/28/2026, 12:42:26 PM [33m WARN[39m [38;5;3m[BlogsService] [39m[33mCache revalidation failed for updated blog [post]: cache down[39m
|
||||
FAIL src/wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Summary of all failing tests
|
||||
FAIL seo-tracking/publication.postgres.spec.ts
|
||||
● Test suite failed to run
|
||||
|
||||
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
|
||||
It should have this form: { url: "CONNECTION_STRING" }
|
||||
Read more at https://pris.ly/d/client-constructor
|
||||
|
||||
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
|
||||
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
|
||||
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
|
||||
| ^
|
||||
23 | let user: any;
|
||||
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
|
||||
25 | const service = new SeoTrackingService(db as any, cache as any);
|
||||
|
||||
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
|
||||
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
|
||||
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
|
||||
at seo-tracking/publication.postgres.spec.ts:22:14
|
||||
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
|
||||
|
||||
FAIL wiki/wiki.service.spec.ts
|
||||
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
|
||||
|
||||
expect(jest.fn()).toHaveBeenCalledWith(...expected)
|
||||
|
||||
- Expected
|
||||
+ Received
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
Object {
|
||||
"orderBy": Object {
|
||||
"term": "desc",
|
||||
},
|
||||
- "skip": 0,
|
||||
- "take": 10,
|
||||
+ "skip": undefined,
|
||||
+ "take": 100,
|
||||
"where": Object {
|
||||
"OR": Array [
|
||||
Object {
|
||||
"term": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
Object {
|
||||
+ "key": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
"definition": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "term": Object {
|
||||
+ "contains": "مفصل",
|
||||
+ "mode": "insensitive",
|
||||
+ },
|
||||
+ },
|
||||
+ Object {
|
||||
+ "key": Object {
|
||||
"contains": "مفصل",
|
||||
"mode": "insensitive",
|
||||
},
|
||||
},
|
||||
],,
|
||||
|
||||
Number of calls: 1
|
||||
|
||||
56 | });
|
||||
57 |
|
||||
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
|
||||
| ^
|
||||
59 | where: {
|
||||
60 | OR: [
|
||||
61 | { term: { contains: "مفصل", mode: "insensitive" } },
|
||||
|
||||
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
|
||||
|
||||
|
||||
Test Suites: 2 failed, 6 skipped, 95 passed, 97 of 103 total
|
||||
Tests: 1 failed, 25 skipped, 818 passed, 844 total
|
||||
Snapshots: 0 total
|
||||
Time: 56.587 s
|
||||
Ran all test suites.
|
||||
@@ -0,0 +1,7 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 7 passed, 7 total
|
||||
Snapshots: 0 total
|
||||
Time: 6.041 s
|
||||
Ran all test suites matching corporate.integration.spec.
|
||||
@@ -0,0 +1,25 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t rejects children
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects children after a parent claim commits while child creation waits on its row lock
|
||||
|
||||
expect(received).toBe(expected) // Object.is equality
|
||||
|
||||
Expected: 409
|
||||
Received: 201
|
||||
|
||||
103 | expect(waiting).toBe(true);
|
||||
104 | } finally { release(); await claiming; }
|
||||
> 105 | expect((await pending).status).toBe(409);
|
||||
| ^
|
||||
106 | expect(await db.corporateTask.count({ where: { parentId: parent.id } })).toBe(0);
|
||||
107 | });
|
||||
108 | it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:105:36)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 6 skipped, 7 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.263 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "rejects children".
|
||||
@@ -0,0 +1,7 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t public reads
|
||||
Test Suites: 1 passed, 1 total
|
||||
Tests: 9 skipped, 1 passed, 10 total
|
||||
Snapshots: 0 total
|
||||
Time: 4.131 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
|
||||
@@ -0,0 +1,25 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t public reads
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › public reads strip claim tokens recursively while claim and replay retain ownership token
|
||||
|
||||
expect(received).not.toContain(expected) // indexOf
|
||||
|
||||
Expected substring: not "claimToken"
|
||||
Received string: "{\"data\":[{\"id\":\"df2e8641-026a-4ed0-80ca-36fc10db3b3c\",\"taskCode\":\"TSK-257421eb-e384-403f-837c-f09345000cf2\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-257421eb-e384-403f-837c-f09345000cf2\",\"description\":\"integration fixture\",\"department\":\"CONTENT_SEO\",\"priority\":\"CEO_EXPEDITE\",\"status\":\"TEST\",\"actionType\":\"CEO_DIRECTIVE\",\"dueCycle\":null,\"parentId\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"goalId\":null,\"assignedAgent\":\"apikey:executor\",\"claimToken\":\"b57fc669-e7c8-41c3-8904-f3bc60d2dc51\",\"leasedUntil\":null,\"executionCount\":1,\"qaCount\":0,\"rejectionCount\":0,\"createdBy\":\"apikey:executor\",\"createdAt\":\"2026-10-28T12:37:42.198Z\",\"updatedAt\":\"2026-10-28T12:37:42.296Z\"},{\"id\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"taskCode\":\"TSK-40ee89e7-7127-4e85-aac2-dad7ea156be6\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-40ee89e7-7127-4
|
||||
|
||||
145 | for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||
146 | const r = await request(app.getHttpServer()).get('/admin/hermes/' + path).set('x-api-key', 'competitor').expect(200);
|
||||
> 147 | expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||
| ^
|
||||
148 | expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||
149 | }
|
||||
150 | });
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:147:42)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 9 skipped, 10 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.842 s, estimated 6 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
|
||||
@@ -0,0 +1,32 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t malformed
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
|
||||
|
||||
expected 400 "Bad Request", got 201 "Created"
|
||||
|
||||
166 | 'urn:sha256:' + 'b'.repeat(64),
|
||||
167 | ]) {
|
||||
> 168 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||
| ^
|
||||
169 | 400,
|
||||
170 | );
|
||||
171 | }
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:168:73)
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 1 failed, 11 skipped, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.923 s, estimated 8 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "malformed".
|
||||
@@ -0,0 +1,8 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec
|
||||
|
||||
Test Suites: 2 passed, 2 total
|
||||
Tests: 12 passed, 12 total
|
||||
Snapshots: 0 total
|
||||
Time: 6.595 s
|
||||
Ran all test suites matching corporate.integration.spec|corporate-policy.spec.
|
||||
@@ -0,0 +1,50 @@
|
||||
npm notice run backend@0.0.1 test
|
||||
npm notice run jest --runInBand corporate.integration.spec -t malformed|coercions
|
||||
FAIL src/admin/hermes/corporate.integration.spec.ts
|
||||
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
|
||||
|
||||
expected 400 "Bad Request", got 201 "Created"
|
||||
|
||||
119 | const body = { claimToken: claim.claimToken, artifactUri: '', sha256: 'a'.repeat(64), summary: 'receipt', tool: 'jest', result: 'passed' };
|
||||
120 | for (const artifactUri of ['https://', 'https://?x', 'https://bad host/x', 'https://user:pass@host.org/a', 'https://localhost/a', 'https://127.1/a', 'https://[::1]/a', 'urn:sha256:', 'urn:sha256:' + 'b'.repeat(64)]) {
|
||||
> 121 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(400);
|
||||
| ^
|
||||
122 | }
|
||||
123 | expect(await db.corporateEvidence.count()).toBe(0);
|
||||
124 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/' }).expect(201);
|
||||
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:121:73)
|
||||
----
|
||||
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
|
||||
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
|
||||
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
|
||||
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
|
||||
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
|
||||
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
|
||||
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
|
||||
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
|
||||
|
||||
● corporate API / disposable PostgreSQL › rejects implicit timestamp coercions in source and effect inputs
|
||||
|
||||
expect(received).rejects.toThrow()
|
||||
|
||||
Received promise resolved instead of rejected
|
||||
Resolved to value: {"cadence": "MONTHLY", "category": "TREND", "createdAt": "2026-10-28T12:34:28.558Z", "createdBy": "fixture", "id": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "impact": "LOW", "opportunity": "investigate", "provenance": {"collector": "fixture", "context": "isolated", "method": "test"}, "recommendedAction": "measure", "source": "receipt", "sources": [{"excerpt": "receipt", "id": "108f61d9-0e90-4d53-804e-0330d129a299", "researchId": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "retrievedAt": "1970-01-01T00:00:00.000Z", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "title": "source", "url": "https://pubmed.ncbi.nlm.nih.gov/"}], "status": "DISCOVERED", "title": "research"}
|
||||
|
||||
128 | const research = { title: 'research', category: 'TREND', source: 'receipt', opportunity: 'investigate', impact: 'LOW', recommendedAction: 'measure', cadence: 'MONTHLY', provenance: { method: 'test', collector: 'fixture', context: 'isolated' }, sources: [{ url: 'https://pubmed.ncbi.nlm.nih.gov/', title: 'source', excerpt: 'receipt', retrievedAt: '', sha256: 'a'.repeat(64) }] };
|
||||
129 | for (const time of [null, 0, false, [], '2026-01-01', '2026-02-30T00:00:00Z']) {
|
||||
> 130 | await expect(service.research('fixture', key(), { ...research, sources: [{ ...research.sources[0], retrievedAt: time }] })).rejects.toThrow();
|
||||
| ^
|
||||
131 | await expect(service.effect('fixture', key(), key(), { metric: 'views', availability: 'UNAVAILABLE', source: 'none', observedAt: time })).rejects.toThrow('Invalid observation time');
|
||||
132 | }
|
||||
133 | for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||
|
||||
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
|
||||
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:130:13)
|
||||
|
||||
Test Suites: 1 failed, 1 total
|
||||
Tests: 2 failed, 7 skipped, 9 total
|
||||
Snapshots: 0 total
|
||||
Time: 3.997 s, estimated 6 s
|
||||
Ran all test suites matching corporate.integration.spec with tests matching "malformed|coercions".
|
||||
@@ -0,0 +1,3 @@
|
||||
# Plan
|
||||
Dedicated human-principal guard after authentication and role guard. Keep scope rules unchanged. Reuse parent row lock. Centralize locator/time validation and public projection. Bound detail/report queries with deterministic ordering, counts and metadata; cap serialized operation responses.
|
||||
Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, 4304 nodes, build provenance unverified (navigation only). ApiKeysController -> JwtAuthGuard -> ApiKeysService verified directly at cc365bc; CorporateController -> CorporateService -> Prisma verified directly (corporate absent from stale map).
|
||||
@@ -0,0 +1,2 @@
|
||||
# Corporate hardening
|
||||
Base cc365bc. Backend only, no push/deploy. Humans retain admin key management; API keys cannot manage keys. Children attach only to TODO/BLOCKED under parent lock. Validate HTTPS locators/digest URNs and explicit ISO timestamp strings. Public reads omit claimToken recursively; claim retains it. Detail relations and report snapshots bounded with truncation metadata and idempotency response size guard. Acceptance: real disposable PG HTTP tests, ordering tests, backend build.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Tasks
|
||||
- [x] RED/GREEN human key-admin gate with real key authentication
|
||||
- [x] RED/GREEN parent ordering on PostgreSQL
|
||||
- [x] RED/GREEN locator/time validation
|
||||
- [x] RED/GREEN public token projection
|
||||
- [x] RED/GREEN bounded reads/report/replay
|
||||
- [x] regression suite, backend build, commit (no push)
|
||||
@@ -0,0 +1,14 @@
|
||||
# Verification
|
||||
Base cc365bc; backend isolated branch hardening/corporate-security. No push/deploy/runtime changes.
|
||||
|
||||
Real PostgreSQL 16.2 started locally on 127.0.0.1:55439, corporate_test. Prisma db push applied only to disposable fixture (existing fixture lacked api_keys); tests use explicit opt-in, never runtime DATABASE_URL. Dependencies symlinked from corporate-backend/backend/node_modules, unchanged lockfile.
|
||||
|
||||
- RED auth: four key-management verbs returned 200/201 instead of 403 with real ApiKeysService validation against PG. GREEN 5 tests. Human path uses signed test-only Passport strategy (does not claim production JWT user lookup).
|
||||
- RED parent: child HTTP request observed waiting on PostgreSQL parent row lock; after IN_PROGRESS commit returned 201 instead of 409. GREEN includes TODO/BLOCKED child-first gating, existing SKIP LOCKED coverage.
|
||||
- RED validation: malformed HTTPS accepted, null timestamp persisted as epoch. GREEN malformed hosts, userinfo, loopback, malformed/mismatched digest URN, numeric/null/boolean/array/date-only/invalid calendar timestamp rejected.
|
||||
- RED projection: public reads exposed claimToken. GREEN list/detail/evidence/children omit it; claim and immutable claim replay retain ownership token.
|
||||
- RED bounds: detail returned 106 logs and oversized response persisted. GREEN limits 100 for each detail relation/report section, counts/truncation metadata, report 1000-character fields and omitted payloads; immutable report replay after source deletion; oversized operation rolls back task and operation.
|
||||
- Final targeted: 3 suites / 20 tests passed with real PG enabled. Backend tsc -b passed.
|
||||
- Full suite without opt-in: 95 passed suites, 2 failed, 6 skipped; 818 passed tests, 1 failed, 25 skipped. Exact clean cc365bc same dependencies: 95 passed suites, same 2 failed (publication.postgres undefined datasource in skipped describe; wiki stale pagination/search expectation), 5 skipped; 818 passed, same 1 failed, 13 skipped. Extra skips are new/expanded opt-in security tests, not regressions.
|
||||
|
||||
Report snapshot is intentionally partial, not a complete daily export. Relation metadata supports explicit partial display; no frontend changes owned here. Public detail relation count is capped, not arbitrary legacy JSON field bytes. All newly created idempotency responses capped at 1,000,000 UTF-8 bytes before durable save; rejection rolls back transaction. Existing legacy idempotency records are unchanged.
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
describe("AdminController - Stage Author Restoration endpoint", () => {
|
||||
let controller: AdminController;
|
||||
let mockStageAuthorRestorationService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockStageAuthorRestorationService = {
|
||||
restoreStageAuthors: jest.fn().mockResolvedValue({
|
||||
success: true,
|
||||
totalConfigured: 5,
|
||||
restoredCount: 5,
|
||||
existingCount: 0,
|
||||
authors: [],
|
||||
}),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AdminController],
|
||||
providers: [
|
||||
{ provide: AdminService, useValue: {} },
|
||||
{ provide: SettingsService, useValue: {} },
|
||||
{
|
||||
provide: StageAuthorRestorationService,
|
||||
useValue: mockStageAuthorRestorationService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AdminController>(AdminController);
|
||||
});
|
||||
|
||||
it.each([undefined, "10.0.0.2", "127.0.0.1.evil", "::ffff:10.0.0.2"])("denies non-loopback socket %s despite forwarded headers", async (remoteAddress) => {
|
||||
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { "x-forwarded-for": "127.0.0.1" }, ip: "127.0.0.1" } as any)).rejects.toThrow();
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["::1", "::ffff:127.0.0.1"])("accepts loopback socket %s", async remoteAddress => {
|
||||
await controller.restoreStageAuthors({ socket: { remoteAddress } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
|
||||
const result = await controller.restoreStageAuthors({ socket: { remoteAddress: "127.0.0.1" } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.restoredCount).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -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) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
describe("AdminController", () => {
|
||||
let controller: AdminController;
|
||||
@@ -12,6 +13,7 @@ describe("AdminController", () => {
|
||||
providers: [
|
||||
{ provide: AdminService, useValue: {} },
|
||||
{ provide: SettingsService, useValue: {} },
|
||||
{ provide: StageAuthorRestorationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
} from "@nestjs/common";
|
||||
import { AdminService, CouponInput } from "./admin.service";
|
||||
import { ProductDto } from "./dto/product.dto";
|
||||
@@ -27,7 +29,9 @@ 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 { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
@@ -41,6 +45,7 @@ export class AdminController {
|
||||
constructor(
|
||||
private readonly adminService: AdminService,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly stageAuthorRestorationService?: StageAuthorRestorationService,
|
||||
) {}
|
||||
|
||||
@Get("dashboard/stats")
|
||||
@@ -57,13 +62,13 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getUsers(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getUsers(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("users")
|
||||
@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: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -71,6 +76,22 @@ export class AdminController {
|
||||
};
|
||||
}
|
||||
|
||||
@Post("users/stage-author-restoration")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
|
||||
})
|
||||
async restoreStageAuthors(@Req() req: { socket?: { remoteAddress?: string } }) {
|
||||
const peer = req?.socket?.remoteAddress;
|
||||
if (!peer || !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(peer)) {
|
||||
throw new ForbiddenException("Stage author restoration requires a loopback socket");
|
||||
}
|
||||
if (!this.stageAuthorRestorationService) {
|
||||
throw new Error("StageAuthorRestorationService not initialized");
|
||||
}
|
||||
return this.stageAuthorRestorationService.restoreStageAuthors();
|
||||
}
|
||||
|
||||
@Get("users/:id")
|
||||
@ApiOperation({ summary: "جزئیات کاربر" })
|
||||
async getUserDetails(@Param("id") id: string) {
|
||||
@@ -80,8 +101,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 +112,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 +122,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 +134,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 +152,7 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
@@ -145,7 +168,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getProducts(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getProducts(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("products")
|
||||
@@ -206,7 +229,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
||||
async getOrders(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getOrders(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get("orders/:id")
|
||||
@@ -354,4 +377,34 @@ export class AdminController {
|
||||
await this.settingsService.updateBulkUiTexts(body);
|
||||
return { success: true, data: body };
|
||||
}
|
||||
|
||||
|
||||
@Get("symptoms")
|
||||
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحهبندی، جستجو و متادیتا" })
|
||||
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
|
||||
const res = await this.adminService.getSymptoms(query);
|
||||
return res;
|
||||
}
|
||||
|
||||
@Post("symptoms")
|
||||
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
|
||||
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
const res = await this.adminService.createSymptom(body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Put("symptoms/:id")
|
||||
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
|
||||
async updateSymptom(@Param("id") id: string, @Body() body: any) {
|
||||
const res = await this.adminService.updateSymptom(id, body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Delete("symptoms/:id")
|
||||
@ApiOperation({ summary: "حذف علامت درمانی" })
|
||||
async deleteSymptom(@Param("id") id: string) {
|
||||
const res = await this.adminService.deleteSymptom(id);
|
||||
return res;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { CorporateController } from "./hermes/corporate.controller";
|
||||
import { CorporateService } from "./hermes/corporate.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
@@ -21,16 +23,17 @@ 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";
|
||||
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
|
||||
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||
controllers: [
|
||||
CorporateController,
|
||||
AdminController,
|
||||
ReportsController,
|
||||
MediaController,
|
||||
@@ -44,11 +47,10 @@ import { SettingsModule } from "../settings/settings.module";
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
ApprovalsController,
|
||||
AuditLogsController,
|
||||
DepartmentTasksController,
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
CorporateService,
|
||||
AdminService,
|
||||
ReportsService,
|
||||
MediaService,
|
||||
@@ -58,6 +60,8 @@ import { SettingsModule } from "../settings/settings.module";
|
||||
PetsService,
|
||||
SslService,
|
||||
ApiKeysService,
|
||||
SupportChatAnalyticsService,
|
||||
StageAuthorRestorationService,
|
||||
],
|
||||
exports: [ApiKeysService, MediaService],
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
@@ -1869,4 +1917,164 @@ export class AdminService {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
|
||||
const page = Math.max(1, Number(params?.page) || 1);
|
||||
const limit = Math.max(1, Number(params?.limit) || 20);
|
||||
const offset = (page - 1) * limit;
|
||||
const search = params?.search?.trim() || '';
|
||||
|
||||
let items: any[] = [];
|
||||
let total = 0;
|
||||
|
||||
if (search) {
|
||||
const searchPattern = `%${search}%`;
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
} else {
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s;
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
}
|
||||
|
||||
const lastPage = Math.ceil(total / limit) || 1;
|
||||
|
||||
return {
|
||||
data: items,
|
||||
meta: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
lastPage,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
|
||||
const name = dto.name.trim();
|
||||
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
|
||||
|
||||
return await this.prisma.$queryRawUnsafe(`
|
||||
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
|
||||
}
|
||||
|
||||
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
// 1. Get existing symptom
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const oldName = existing[0].name;
|
||||
const newName = dto.name?.trim() || oldName;
|
||||
const newSlug = dto.slug?.trim() || existing[0].slug;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Update symptoms table
|
||||
const updated = await tx.$queryRawUnsafe(`
|
||||
UPDATE symptoms
|
||||
SET
|
||||
name = $2,
|
||||
slug = $3,
|
||||
description = $4,
|
||||
meta_title = $5,
|
||||
meta_description = $6,
|
||||
keywords = $7,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1::uuid
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
|
||||
|
||||
// If name changed, cascade update across product_symptoms & products JSON
|
||||
if (oldName !== newName) {
|
||||
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
|
||||
await tx.$executeRaw`
|
||||
UPDATE products
|
||||
SET dosage_config = jsonb_set(
|
||||
dosage_config,
|
||||
'{symptoms}',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
|
||||
ELSE elem
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
|
||||
)
|
||||
)
|
||||
WHERE dosage_config ? 'symptoms'
|
||||
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
|
||||
`;
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async deleteSymptom(id: string) {
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const name = existing[0].name;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Delete join links
|
||||
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
|
||||
// Delete symptom row
|
||||
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
|
||||
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,33 +8,34 @@ import {
|
||||
Param,
|
||||
UseGuards,
|
||||
HttpStatus,
|
||||
} from "@nestjs/common";
|
||||
import { ApiKeysService } from "./api-keys.service";
|
||||
import { CreateApiKeyDto } from "./dto/api-key.dto";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
} from '@nestjs/common';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
import { CreateApiKeyDto } from './dto/api-key.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
} from "@nestjs/swagger";
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
|
||||
@ApiTags("Admin - مدیریت کلیدهای دسترسی (API Keys)")
|
||||
@ApiTags('Admin - مدیریت کلیدهای دسترسی (API Keys)')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/api-keys")
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/api-keys')
|
||||
export class ApiKeysController {
|
||||
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "دریافت لیست کلیدهای دسترسی API" })
|
||||
@ApiOperation({ summary: 'دریافت لیست کلیدهای دسترسی API' })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.OK,
|
||||
description: "لیست کلیدها با موفقیت دریافت شد",
|
||||
description: 'لیست کلیدها با موفقیت دریافت شد',
|
||||
})
|
||||
async findAll() {
|
||||
const keys = await this.apiKeysService.findAll();
|
||||
@@ -45,39 +46,39 @@ export class ApiKeysController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد یک API Key جدید" })
|
||||
@ApiOperation({ summary: 'ایجاد یک API Key جدید' })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.CREATED,
|
||||
description: "کلید جدید با موفقیت ایجاد شد",
|
||||
description: 'کلید جدید با موفقیت ایجاد شد',
|
||||
})
|
||||
async create(@Body() dto: CreateApiKeyDto) {
|
||||
const result = await this.apiKeysService.create(dto);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
"کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.",
|
||||
'کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.',
|
||||
data: result,
|
||||
};
|
||||
}
|
||||
|
||||
@Patch(":id/toggle")
|
||||
@ApiOperation({ summary: "تغییر وضعیت فعال/غیرفعال کلید" })
|
||||
async toggleStatus(@Param("id") id: string) {
|
||||
@Patch(':id/toggle')
|
||||
@ApiOperation({ summary: 'تغییر وضعیت فعال/غیرفعال کلید' })
|
||||
async toggleStatus(@Param('id') id: string) {
|
||||
const updated = await this.apiKeysService.toggleStatus(id);
|
||||
return {
|
||||
success: true,
|
||||
message: "وضعیت کلید با موفقیت بهروزرسانی شد",
|
||||
message: 'وضعیت کلید با موفقیت بهروزرسانی شد',
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف کلید دسترسی" })
|
||||
async delete(@Param("id") id: string) {
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'حذف کلید دسترسی' })
|
||||
async delete(@Param('id') id: string) {
|
||||
await this.apiKeysService.delete(id);
|
||||
return {
|
||||
success: true,
|
||||
message: "کلید دسترسی با موفقیت حذف شد",
|
||||
message: 'کلید دسترسی با موفقیت حذف شد',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import passport from 'passport';
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import { sign } from 'jsonwebtoken';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ApiKeysController } from './api-keys.controller';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
|
||||
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||
? describe
|
||||
: describe.skip;
|
||||
integration(
|
||||
'human-only key administration / real key authentication and PostgreSQL',
|
||||
() => {
|
||||
let app: INestApplication, db: PrismaService, service: ApiKeysService;
|
||||
let rawKey: string, target: string;
|
||||
const secret = 'isolated-test-jwt';
|
||||
beforeAll(async () => {
|
||||
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||
throw new Error('Disposable DB required');
|
||||
db = new PrismaClient({
|
||||
datasources: { db: { url: url.toString() } },
|
||||
}) as PrismaService;
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: secret,
|
||||
},
|
||||
(p, done) => done(null, { id: p.sub, role: p.role }),
|
||||
),
|
||||
);
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [ApiKeysController],
|
||||
providers: [ApiKeysService, { provide: PrismaService, useValue: db }],
|
||||
}).compile();
|
||||
service = module.get(ApiKeysService);
|
||||
app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
rawKey = (
|
||||
await service.create({
|
||||
name: 'security-fixture-admin',
|
||||
scopes: ['admin'],
|
||||
})
|
||||
).rawKey;
|
||||
target = (
|
||||
await service.create({
|
||||
name: 'security-fixture-target',
|
||||
scopes: ['read'],
|
||||
})
|
||||
).apiKey.id;
|
||||
});
|
||||
afterAll(async () => {
|
||||
await db?.apiKey.deleteMany({
|
||||
where: { name: { startsWith: 'security-fixture' } },
|
||||
});
|
||||
await app?.close();
|
||||
await db?.$disconnect();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
it.each(['get', 'post', 'patch', 'delete'] as const)(
|
||||
'denies %s to authenticated admin API key without mutating keys',
|
||||
async (method) => {
|
||||
const before = await db.apiKey.count();
|
||||
const path =
|
||||
'/admin/api-keys' +
|
||||
(method === 'patch'
|
||||
? `/${target}/toggle`
|
||||
: method === 'delete'
|
||||
? `/${target}`
|
||||
: '');
|
||||
await request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set('x-api-key', rawKey)
|
||||
.send(
|
||||
method === 'post'
|
||||
? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] }
|
||||
: {},
|
||||
)
|
||||
.expect(403);
|
||||
expect(await db.apiKey.count()).toBe(before);
|
||||
expect(
|
||||
(await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status,
|
||||
).toBe('ACTIVE');
|
||||
},
|
||||
);
|
||||
it('retains human admin CRUD and rejects nonadmin humans and wildcard keys', async () => {
|
||||
const auth =
|
||||
'Bearer ' + sign({ sub: 'fixture-human', role: 'Admin' }, secret);
|
||||
const created = await request(app.getHttpServer())
|
||||
.post('/admin/api-keys')
|
||||
.set('Authorization', auth)
|
||||
.send({ name: 'security-fixture-human', scopes: ['read'] })
|
||||
.expect(201);
|
||||
const id = created.body.data.apiKey.id;
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/api-keys')
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/admin/api-keys/${id}/toggle`)
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.delete(`/admin/api-keys/${id}`)
|
||||
.set('Authorization', auth)
|
||||
.expect(200);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/api-keys')
|
||||
.set(
|
||||
'Authorization',
|
||||
'Bearer ' + sign({ sub: 'fixture-user', role: 'USER' }, secret),
|
||||
)
|
||||
.expect(403);
|
||||
const wildcard = await service.create({
|
||||
name: 'security-fixture-wildcard',
|
||||
scopes: ['*'],
|
||||
});
|
||||
expect((await service.validateKey(wildcard.rawKey)).role).toBe('USER');
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,219 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} 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) {
|
||||
const item = await (this.prisma as any).approvalRequest.create({
|
||||
data: {
|
||||
department: dto.department,
|
||||
category: dto.category,
|
||||
title: dto.title,
|
||||
payload: dto.payload,
|
||||
testContext: dto.testContext || {},
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@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) {
|
||||
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
|
||||
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
|
||||
}
|
||||
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
if (dto.decision === "REJECTED") {
|
||||
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل میشوند
|
||||
await (this.prisma as any).departmentTask.deleteMany({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
await (this.prisma as any).approvalRequest.delete({
|
||||
where: { id },
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
|
||||
};
|
||||
}
|
||||
|
||||
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر مییابد
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
executedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
||||
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
|
||||
if (existingTask) {
|
||||
await (this.prisma as any).departmentTask.update({
|
||||
where: { id: existingTask.id },
|
||||
data: {
|
||||
status: "TODO",
|
||||
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code: "TSK-" + Date.now().toString().slice(-6),
|
||||
department: item.department,
|
||||
title: item.title,
|
||||
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).approvalRequest.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: createdBlog });
|
||||
});
|
||||
|
||||
it("propagates create validation failures", async () => {
|
||||
const req = { user: { id: "admin-user-id" } };
|
||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
||||
});
|
||||
|
||||
it("updateBlog should update blog details and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
const body = {
|
||||
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||
});
|
||||
|
||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
||||
});
|
||||
|
||||
it("deleteBlog should delete blog and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||
|
||||
@@ -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,54 @@ 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 () => {
|
||||
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
|
||||
|
||||
await service.createBlog(
|
||||
{
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
id: "client-id",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
updatedAt: "2000-01-01T00:00:00.000Z",
|
||||
viewCount: 999999,
|
||||
serverOwned: "must-not-pass",
|
||||
},
|
||||
"user-admin-1",
|
||||
);
|
||||
|
||||
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
|
||||
expect(payload).toEqual(expect.objectContaining({
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
}));
|
||||
expect(payload).not.toHaveProperty("id");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("updatedAt");
|
||||
expect(payload).not.toHaveProperty("viewCount");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
|
||||
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
|
||||
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
|
||||
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
|
||||
await expect(
|
||||
service.createBlog(
|
||||
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
|
||||
"user-admin-1",
|
||||
),
|
||||
).rejects.toThrow(message);
|
||||
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
||||
@@ -228,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", () => {
|
||||
@@ -270,7 +379,136 @@ 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",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("material freshness and scheduled publishing", () => {
|
||||
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
expect(payload).not.toHaveProperty("markContentUpdated");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
});
|
||||
it("automatically marks freshness when material article content changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { content: "Meaningfully revised content" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
it("does not mark freshness for attribution-only changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
|
||||
});
|
||||
it("allows explicitly clearing contentUpdatedAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
});
|
||||
it("publishes due posts without rewriting createdAt", async () => {
|
||||
const scheduledAt = new Date("2025-02-01T10:00:00Z");
|
||||
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
|
||||
mockPrisma.blog.update.mockResolvedValue({});
|
||||
await service.publishDueScheduledBlogs();
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog security and freshness validation", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
});
|
||||
|
||||
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
|
||||
await service.updateBlog("blog-1", {
|
||||
title: "Allowed title",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
serverOwned: "must-not-pass",
|
||||
});
|
||||
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.title).toBe("Allowed title");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it("rejects an invalid explicit contentUpdatedAt", async () => {
|
||||
await expect(
|
||||
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
|
||||
).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
|
||||
await service.updateBlog("blog-1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
|
||||
await service.updateBlog("blog-1", {
|
||||
contentUpdatedAt: "not-a-date",
|
||||
markContentUpdated: true,
|
||||
});
|
||||
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -468,7 +706,6 @@ describe("Admin BlogsService", () => {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: scheduledDate,
|
||||
createdAt: scheduledDate,
|
||||
},
|
||||
});
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -141,16 +143,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async createBlog(data: any, currentUserId: string) {
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const parsed = new Date(value as string | number | Date);
|
||||
if (!Number.isFinite(parsed.getTime())) {
|
||||
throw new BadRequestException(`Invalid ${field}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
||||
const parsedContentUpdatedAt = markContentUpdated
|
||||
? new Date()
|
||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
||||
|
||||
// Connect or create tags
|
||||
const tagConnectOrCreate = [];
|
||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||
@@ -171,13 +188,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || "PUBLISHED";
|
||||
let finalStatus = data.status || "PUBLISHED";
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
data.isPublished !== undefined ? data.isPublished : true;
|
||||
let finalPublishedAt = parsedPublishedAt;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = "SCHEDULED";
|
||||
@@ -191,19 +207,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
const createPayload = {
|
||||
title: data.title,
|
||||
slug: data.slug,
|
||||
content: data.content,
|
||||
excerpt: data.excerpt,
|
||||
authorTeam: data.authorTeam,
|
||||
authorRole: data.authorRole,
|
||||
imageUrl: data.imageUrl,
|
||||
imageAlt: data.imageAlt,
|
||||
imageCaption: data.imageCaption,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
focusKeywords: data.focusKeywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
noIndex: data.noIndex,
|
||||
noFollow: data.noFollow,
|
||||
schemaType: data.schemaType,
|
||||
ogTitle: data.ogTitle,
|
||||
ogDescription: data.ogDescription,
|
||||
ogImage: data.ogImage,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
featured: data.featured,
|
||||
allowComments: data.allowComments,
|
||||
showOnHome: data.showOnHome,
|
||||
homeDisplayMode: data.homeDisplayMode,
|
||||
relatedProductIds: data.relatedProductIds,
|
||||
relatedBlogIds: data.relatedBlogIds,
|
||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
contentUpdatedAt: parsedContentUpdatedAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||
: {}),
|
||||
};
|
||||
} satisfies Prisma.BlogCreateInput;
|
||||
|
||||
const created = await this.prisma.blog.create({
|
||||
data: createPayload,
|
||||
@@ -214,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) {
|
||||
@@ -223,19 +278,105 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
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",
|
||||
"content",
|
||||
"excerpt",
|
||||
"authorTeam",
|
||||
"authorRole",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
"metaTitle",
|
||||
"metaDescription",
|
||||
"keywords",
|
||||
"focusKeywords",
|
||||
"canonicalUrl",
|
||||
"noIndex",
|
||||
"noFollow",
|
||||
"schemaType",
|
||||
"ogTitle",
|
||||
"ogDescription",
|
||||
"ogImage",
|
||||
"status",
|
||||
"isPublished",
|
||||
"featured",
|
||||
"allowComments",
|
||||
"showOnHome",
|
||||
"homeDisplayMode",
|
||||
"relatedProductIds",
|
||||
"relatedBlogIds",
|
||||
] as const;
|
||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
||||
for (const field of mutableScalarFields) {
|
||||
if (data[field] !== undefined) {
|
||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
const materialContentFields = [
|
||||
"title",
|
||||
"content",
|
||||
"excerpt",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
] as const;
|
||||
const hasMaterialContentChange = materialContentFields.some(
|
||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
||||
);
|
||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(updatePayload, {
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
@@ -245,7 +386,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
? { category: { connect: { id: categoryId } } }
|
||||
: { category: { disconnect: true } }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
@@ -259,7 +400,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
updatePayload.status = "PUBLISHED";
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
@@ -286,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;
|
||||
}
|
||||
|
||||
@@ -472,7 +655,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
} 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) {
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code,
|
||||
department: body.department,
|
||||
title: body.title,
|
||||
description: body.description || null,
|
||||
status: body.status || "TODO",
|
||||
priority: body.priority || "MEDIUM",
|
||||
assignee: body.assignee || "AI_AGENT",
|
||||
acceptanceCriteria: body.acceptanceCriteria || null,
|
||||
executionLogs: body.executionLogs || [],
|
||||
deliverableUrl: body.deliverableUrl || null,
|
||||
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه لاگها
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: task.id,
|
||||
action: "CREATE",
|
||||
department: task.department,
|
||||
actor: task.assignee || "SYSTEM",
|
||||
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
|
||||
newValues: task,
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: task };
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
|
||||
async updateStatus(
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
const existing = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
logs.push({
|
||||
timestamp: new Date().toISOString(),
|
||||
status: body.status,
|
||||
note: body.logNote,
|
||||
});
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
status: body.status,
|
||||
executionLogs: logs,
|
||||
};
|
||||
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
||||
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
||||
if (body.status === "DONE") updateData.completedAt = new Date();
|
||||
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه میشود
|
||||
if (body.status === "TODO" && body.logNote) {
|
||||
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).departmentTask.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: updated.id,
|
||||
action: "UPDATE",
|
||||
department: updated.department,
|
||||
actor: "SYSTEM",
|
||||
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
|
||||
oldValues: { status: existing.status },
|
||||
newValues: { status: updated.status, note: body.logNote },
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: updated };
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف تسک" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).departmentTask.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -1,58 +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;
|
||||
}
|
||||
|
||||
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 })
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { normalizeSearch, pagination, taskInput } from './corporate-policy';
|
||||
describe('corporate contract policy', () => {
|
||||
it('normalizes Persian letters, digits and separators', () => {
|
||||
expect(normalizeSearch('كيك ۱۲۳ (ة)')).toBe('کیک 123 ه');
|
||||
});
|
||||
it('bounds pagination and sort keys', () => {
|
||||
expect(pagination({ limit: '100' }).limit).toBe(100);
|
||||
expect(() => pagination({ limit: '101' })).toThrow();
|
||||
expect(() => pagination({ page: '-1' })).toThrow();
|
||||
expect(() => pagination({ sortBy: 'password' })).toThrow();
|
||||
});
|
||||
it('defaults CEO priority and rejects status/command injection', () => {
|
||||
expect(
|
||||
taskInput({
|
||||
title: 'عنوان',
|
||||
description: 'کار',
|
||||
department: 'CONTENT_SEO',
|
||||
}).priority,
|
||||
).toBe('CEO_EXPEDITE');
|
||||
expect(() =>
|
||||
taskInput({
|
||||
title: 'x',
|
||||
description: 'x',
|
||||
department: 'CONTENT_SEO',
|
||||
status: 'DONE',
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
export const departments = [
|
||||
'CONTENT_SEO',
|
||||
'CATALOG_COMMERCE',
|
||||
'WIKI_SCIENTIFIC',
|
||||
'TECH_DEVOPS',
|
||||
'MARKET_INTELLIGENCE',
|
||||
];
|
||||
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||
export const statuses = [
|
||||
'TODO',
|
||||
'IN_PROGRESS',
|
||||
'TEST',
|
||||
'DONE',
|
||||
'BLOCKED',
|
||||
'REJECTED',
|
||||
'CANCELLED',
|
||||
];
|
||||
export function object(value: unknown, keys: string[]): Record<string, any> {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
Object.keys(value).some((k) => !keys.includes(k))
|
||||
)
|
||||
throw new BadRequestException('Invalid fields');
|
||||
return value as Record<string, any>;
|
||||
}
|
||||
export function text(value: unknown, max = 10000): string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
||||
throw new BadRequestException('Invalid text');
|
||||
return value.trim();
|
||||
}
|
||||
export function uuid(value: unknown): string {
|
||||
const id = text(value, 36);
|
||||
if (
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
id,
|
||||
)
|
||||
)
|
||||
throw new BadRequestException('Invalid UUID');
|
||||
return id;
|
||||
}
|
||||
export function choice(value: unknown, values: string[]): string {
|
||||
if (typeof value !== 'string' || !values.includes(value))
|
||||
throw new BadRequestException('Invalid enum');
|
||||
return value;
|
||||
}
|
||||
export function normalizeSearch(value: string): string {
|
||||
return value
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/[يى]/g, 'ی')
|
||||
.replace(/ك/g, 'ک')
|
||||
.replace(/ة/g, 'ه')
|
||||
.replace(/[۰-۹٠-٩]/g, (c) =>
|
||||
String(
|
||||
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
|
||||
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
|
||||
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
|
||||
),
|
||||
)
|
||||
.replace(/[\u200c\u200d()()]/g, ' ')
|
||||
.replace(/[\u064b-\u065f]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
export function pagination(q: Record<string, any>) {
|
||||
const page = Number(q.page ?? 1),
|
||||
limit = Number(q.limit ?? 20);
|
||||
if (
|
||||
!Number.isSafeInteger(page) ||
|
||||
page < 1 ||
|
||||
page > 1000000 ||
|
||||
!Number.isInteger(limit) ||
|
||||
limit < 1 ||
|
||||
limit > 100
|
||||
)
|
||||
throw new BadRequestException('Invalid pagination');
|
||||
const sortBy = choice(q.sortBy ?? 'createdAt', [
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'title',
|
||||
'taskCode',
|
||||
'priority',
|
||||
'status',
|
||||
]);
|
||||
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
|
||||
| 'asc'
|
||||
| 'desc';
|
||||
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
|
||||
}
|
||||
export function meta(total: number, page: number, limit: number) {
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
return {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
hasNextPage: page < totalPages,
|
||||
hasPrevPage: page > 1,
|
||||
};
|
||||
}
|
||||
export function taskInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'department',
|
||||
'description',
|
||||
'priority',
|
||||
'parentId',
|
||||
'goalId',
|
||||
'actionType',
|
||||
'dueCycle',
|
||||
]);
|
||||
return {
|
||||
title: text(b.title, 300),
|
||||
description: text(b.description),
|
||||
department: choice(b.department, departments),
|
||||
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
|
||||
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
|
||||
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
|
||||
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
|
||||
'CEO_DIRECTIVE',
|
||||
'BLOG_NEW',
|
||||
'BLOG_UPDATE',
|
||||
'CATALOG_ENRICH',
|
||||
'RESEARCH',
|
||||
'ENGINEERING',
|
||||
]),
|
||||
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
|
||||
};
|
||||
}
|
||||
export function canonical(value: any): string {
|
||||
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
||||
if (value && typeof value === 'object')
|
||||
return (
|
||||
'{' +
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
|
||||
.join(',') +
|
||||
'}'
|
||||
);
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
/** Public projection must also cover nested evidence and child records. */
|
||||
export function publicData(value: any): any {
|
||||
if (value instanceof Date) return value;
|
||||
if (Array.isArray(value)) return value.map(publicData);
|
||||
if (value && typeof value === 'object')
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => key !== 'claimToken')
|
||||
.map(([key, item]) => [key, publicData(item)]),
|
||||
);
|
||||
return value;
|
||||
}
|
||||
export function httpsUrl(value: unknown): string {
|
||||
const raw = text(value, 2000);
|
||||
try {
|
||||
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw)) throw new Error();
|
||||
const u = new URL(raw);
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (
|
||||
u.protocol !== 'https:' ||
|
||||
u.username ||
|
||||
u.password ||
|
||||
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
|
||||
host === 'localhost' ||
|
||||
host.endsWith('.localhost') ||
|
||||
/(^|\.)example\.(com|org|net)$/.test(host)
|
||||
)
|
||||
throw new Error();
|
||||
return raw;
|
||||
} catch {
|
||||
throw new BadRequestException('Valid HTTPS host URL required');
|
||||
}
|
||||
}
|
||||
export function timestamp(value: unknown, message: string): Date {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
const date = new Date(value);
|
||||
if (
|
||||
!Number.isFinite(date.getTime()) ||
|
||||
date.getTime() > Date.now() ||
|
||||
date.toISOString().slice(0, 19) !== value.slice(0, 19)
|
||||
)
|
||||
throw new BadRequestException(message);
|
||||
return date;
|
||||
}
|
||||
export function evidenceInput(input: unknown) {
|
||||
const b = object(input, [
|
||||
'claimToken',
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'summary',
|
||||
'tool',
|
||||
'result',
|
||||
]);
|
||||
const uri = text(b.artifactUri, 2000);
|
||||
|
||||
const sha = text(b.sha256, 64);
|
||||
if (!/^[a-f0-9]{64}$/.test(sha))
|
||||
throw new BadRequestException('Invalid digest');
|
||||
if (uri.startsWith('urn:')) {
|
||||
if (uri !== 'urn:sha256:' + sha)
|
||||
throw new BadRequestException('Digest locator mismatch');
|
||||
} else httpsUrl(uri);
|
||||
return {
|
||||
claimToken: uuid(b.claimToken),
|
||||
artifactUri: uri,
|
||||
sha256: sha,
|
||||
summary: text(b.summary),
|
||||
tool: text(b.tool, 100),
|
||||
result: text(b.result),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../common/guards/roles.guard';
|
||||
import { Roles } from '../../common/decorators/roles.decorator';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { text } from './corporate-policy';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/hermes')
|
||||
export class CorporateController {
|
||||
constructor(private readonly service: CorporateService) {}
|
||||
private actor(req: any) {
|
||||
// API keys must use their authenticated key identity, not an editable worker label.
|
||||
const user = req.user;
|
||||
const id = user?.id ?? user?.sub;
|
||||
if (!id) throw new UnauthorizedException('Authenticated subject required');
|
||||
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
|
||||
}
|
||||
private key(key?: string) {
|
||||
return text(key, 200);
|
||||
}
|
||||
@Get('runtime') runtime() {
|
||||
return {
|
||||
mode: 'MANUAL_DORMANT',
|
||||
schedulesEnabled: false,
|
||||
externalExecutionEnabled: false,
|
||||
};
|
||||
}
|
||||
@Get('tasks') tasks(@Query() query: Record<string, any>) {
|
||||
return this.service.tasks(query);
|
||||
}
|
||||
@Get('tasks/:id') detail(@Param('id') id: string) {
|
||||
return this.service.detail(id);
|
||||
}
|
||||
@Post('tasks') create(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.create(this.actor(req), key ?? randomUUID(), body);
|
||||
}
|
||||
@Post('claims') claim(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.claim(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Post('tasks/:id/evidence') evidence(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.submitEvidence(
|
||||
this.actor(req),
|
||||
this.key(key),
|
||||
id,
|
||||
body,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/reviews') review(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.review(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Post('tasks/:id/effects') effect(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.effect(this.actor(req), this.key(key), id, body);
|
||||
}
|
||||
@Get('market-insights') insights(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('market-insights', q);
|
||||
}
|
||||
@Post('market-insights') research(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.research(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('monthly-roadmap', q);
|
||||
}
|
||||
@Post('monthly-roadmap') roadmap(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.roadmap(this.actor(req), this.key(key), body);
|
||||
}
|
||||
@Get('reports') reports(@Query() q: Record<string, any>) {
|
||||
return this.service.collection('reports', q);
|
||||
}
|
||||
@Post('reports') report(
|
||||
@Req() req: any,
|
||||
@Headers('idempotency-key') key: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return this.service.report(this.actor(req), this.key(key), body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
import passport from 'passport';
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CorporateController } from './corporate.controller';
|
||||
import { CorporateService } from './corporate.service';
|
||||
import { ApiKeysService } from '../api-keys.service';
|
||||
|
||||
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||
? describe
|
||||
: describe.skip;
|
||||
integration('corporate API / disposable PostgreSQL', () => {
|
||||
let app: INestApplication, db: PrismaService;
|
||||
const key = () => randomUUID();
|
||||
const post = (path: string, body: any, actor = 'executor', op = key()) =>
|
||||
request(app.getHttpServer())
|
||||
.post('/admin/hermes/' + path)
|
||||
.set('x-api-key', actor)
|
||||
.set('Idempotency-Key', op)
|
||||
.send(body);
|
||||
const input = {
|
||||
title: 'كيك ۱۲۳',
|
||||
description: 'integration fixture',
|
||||
department: 'CONTENT_SEO',
|
||||
};
|
||||
beforeAll(async () => {
|
||||
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
|
||||
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||
throw new Error('Disposable loopback corporate_test DB required');
|
||||
passport.use(
|
||||
'jwt',
|
||||
new Strategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'test-only-not-runtime',
|
||||
},
|
||||
(_payload, done) => done(null, false),
|
||||
),
|
||||
);
|
||||
db = new PrismaClient({
|
||||
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
|
||||
}) as PrismaService;
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [CorporateController],
|
||||
providers: [
|
||||
CorporateService,
|
||||
{ provide: PrismaService, useValue: db },
|
||||
{
|
||||
provide: ApiKeysService,
|
||||
useValue: {
|
||||
validateKey: async (id: string) => ({
|
||||
id,
|
||||
isApiKey: true,
|
||||
role: 'Admin',
|
||||
scopes: id === 'unscoped' ? [] : ['admin'],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (db)
|
||||
await db.$executeRawUnsafe(
|
||||
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||
);
|
||||
await app?.close();
|
||||
await db?.$disconnect();
|
||||
passport.unuse('jwt');
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.$executeRawUnsafe(
|
||||
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||
);
|
||||
});
|
||||
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
let release!: () => void, locked!: () => void;
|
||||
const ready = new Promise<void>((r) => (locked = r));
|
||||
const hold = new Promise<void>((r) => (release = r));
|
||||
const claiming = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
|
||||
await tx.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: {
|
||||
status: 'IN_PROGRESS',
|
||||
claimToken: key(),
|
||||
assignedAgent: 'executor',
|
||||
leasedUntil: new Date(Date.now() + 60000),
|
||||
},
|
||||
});
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
const pending = post('tasks', { ...input, parentId: parent.id }).then(
|
||||
(r) => r,
|
||||
);
|
||||
try {
|
||||
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
|
||||
let waiting = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const rows = await db.$queryRaw<
|
||||
any[]
|
||||
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
} finally {
|
||||
release();
|
||||
await claiming;
|
||||
}
|
||||
expect((await pending).status).toBe(409);
|
||||
expect(
|
||||
await db.corporateTask.count({ where: { parentId: parent.id } }),
|
||||
).toBe(0);
|
||||
});
|
||||
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||
for (const status of ['TODO', 'BLOCKED'] as const) {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateTask.update({
|
||||
where: { id: parent.id },
|
||||
data: { status },
|
||||
});
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||
child.id,
|
||||
);
|
||||
}
|
||||
});
|
||||
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
const body = {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
for (const artifactUri of [
|
||||
'https://',
|
||||
'https://?x',
|
||||
'https:///pubmed.ncbi.nlm.nih.gov/x',
|
||||
'https://pubmed.ncbi.nlm.nih.gov./x',
|
||||
'https://bad host/x',
|
||||
'https://user:pass@host.org/a',
|
||||
'https://localhost/a',
|
||||
'https://127.1/a',
|
||||
'https://[::1]/a',
|
||||
'urn:sha256:',
|
||||
'urn:sha256:' + 'b'.repeat(64),
|
||||
]) {
|
||||
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||
400,
|
||||
);
|
||||
}
|
||||
expect(await db.corporateEvidence.count()).toBe(0);
|
||||
await post(`tasks/${task.id}/evidence`, {
|
||||
...body,
|
||||
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
|
||||
}).expect(201);
|
||||
});
|
||||
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
|
||||
const service = app.get(CorporateService);
|
||||
const research = {
|
||||
title: 'research',
|
||||
category: 'TREND',
|
||||
source: 'receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'source',
|
||||
excerpt: 'receipt',
|
||||
retrievedAt: '',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
};
|
||||
for (const time of [
|
||||
null,
|
||||
0,
|
||||
false,
|
||||
[],
|
||||
'2026-01-01',
|
||||
'2026-02-30T00:00:00Z',
|
||||
]) {
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [{ ...research.sources[0], retrievedAt: time }],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.effect('fixture', key(), key(), {
|
||||
metric: 'views',
|
||||
availability: 'UNAVAILABLE',
|
||||
source: 'none',
|
||||
observedAt: time,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow('Invalid observation time');
|
||||
}
|
||||
for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||
await expect(
|
||||
Promise.resolve().then(() =>
|
||||
service.research('fixture', key(), {
|
||||
...research,
|
||||
sources: [
|
||||
{
|
||||
...research.sources[0],
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
url,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(await db.corporateResearch.count()).toBe(0);
|
||||
});
|
||||
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const op = key();
|
||||
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
|
||||
.task;
|
||||
expect(claim.claimToken).toBeTruthy();
|
||||
expect(
|
||||
(await post('claims', {}, 'executor', op).expect(201)).body.task
|
||||
.claimToken,
|
||||
).toBe(claim.claimToken);
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
}).expect(201);
|
||||
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'competitor')
|
||||
.expect(200);
|
||||
expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||
}
|
||||
});
|
||||
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
await db.corporateEvent.createMany({
|
||||
data: Array.from({ length: 105 }, () => ({
|
||||
taskId: task.id,
|
||||
speaker: 'SYSTEM',
|
||||
speakerName: 'fixture',
|
||||
step: 'FIXTURE',
|
||||
content: 'x'.repeat(10000),
|
||||
payload: { nested: ['x'.repeat(10000)] },
|
||||
})),
|
||||
});
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(detail.body.logs).toHaveLength(100);
|
||||
expect(detail.body.relationsMeta.logs).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
const op = key(),
|
||||
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||
const report = (await post('reports', body, 'executor', op).expect(201))
|
||||
.body;
|
||||
expect(report.snapshot.events).toHaveLength(100);
|
||||
expect(report.snapshot.meta.events).toEqual({
|
||||
total: 106,
|
||||
returned: 100,
|
||||
limit: 100,
|
||||
truncated: true,
|
||||
});
|
||||
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
|
||||
expect(
|
||||
Buffer.byteLength(JSON.stringify(report.body ?? report)),
|
||||
).toBeLessThan(1000000);
|
||||
await db.corporateEvent.deleteMany();
|
||||
expect(
|
||||
(await post('reports', body, 'executor', op).expect(201)).body,
|
||||
).toEqual(report);
|
||||
});
|
||||
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
|
||||
const service = app.get(CorporateService) as any;
|
||||
const before = await db.corporateTask.count();
|
||||
await expect(
|
||||
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||
await tx.corporateTask.create({
|
||||
data: {
|
||||
title: 'rollback',
|
||||
description: 'fixture',
|
||||
taskCode: key(),
|
||||
normalizedTitle: 'rollback',
|
||||
normalizedCode: key(),
|
||||
department: 'CONTENT_SEO',
|
||||
createdBy: 'fixture',
|
||||
},
|
||||
});
|
||||
return { value: 'x'.repeat(1100000) };
|
||||
}),
|
||||
).rejects.toThrow('Operation response exceeds limit');
|
||||
expect(await db.corporateTask.count()).toBe(before);
|
||||
expect(await db.corporateOperation.count()).toBe(0);
|
||||
});
|
||||
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
|
||||
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
|
||||
await post('tasks', input, 'unscoped').expect(403);
|
||||
const op = key(),
|
||||
a = await post('tasks', input, 'executor', op).expect(201);
|
||||
const b = await post('tasks', input, 'executor', op).expect(201);
|
||||
expect(b.body.id).toBe(a.body.id);
|
||||
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
|
||||
409,
|
||||
);
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(list.body.meta).toEqual({
|
||||
total: 1,
|
||||
page: 1,
|
||||
limit: 1,
|
||||
totalPages: 1,
|
||||
hasNextPage: false,
|
||||
hasPrevPage: false,
|
||||
});
|
||||
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?limit=101')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks?sortBy=password')
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(400);
|
||||
});
|
||||
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
|
||||
const task = (await post('tasks', input).expect(201)).body;
|
||||
const claims = await Promise.all([
|
||||
post('claims', {}, 'executor'),
|
||||
post('claims', {}, 'competitor'),
|
||||
]);
|
||||
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
|
||||
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
|
||||
const oldActor = claimed.assignedAgent.replace('apikey:', '');
|
||||
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
|
||||
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
|
||||
.task;
|
||||
expect(renewed.claimToken).not.toBe(claimed.claimToken);
|
||||
const evidence = {
|
||||
claimToken: claimed.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||
sha256: 'a'.repeat(64),
|
||||
summary: 'receipt',
|
||||
tool: 'jest',
|
||||
result: 'passed',
|
||||
};
|
||||
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
|
||||
const e = (
|
||||
await post(
|
||||
`tasks/${task.id}/evidence`,
|
||||
{ ...evidence, claimToken: renewed.claimToken },
|
||||
'new-executor',
|
||||
).expect(201)
|
||||
).body;
|
||||
const review = {
|
||||
evidenceId: e.id,
|
||||
passed: true,
|
||||
findings: 'verified',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'digest readback',
|
||||
result: 'match',
|
||||
},
|
||||
};
|
||||
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
|
||||
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/tasks/' + task.id)
|
||||
.set('x-api-key', 'reviewer')
|
||||
.expect(200);
|
||||
expect(detail.body.status).toBe('DONE');
|
||||
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
|
||||
await post(`tasks/${task.id}/effects`, {
|
||||
metric: 'engagement',
|
||||
availability: 'UNAVAILABLE',
|
||||
observed: 0,
|
||||
source: 'provider unavailable',
|
||||
observedAt: new Date().toISOString(),
|
||||
}).expect(400);
|
||||
});
|
||||
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
|
||||
const urgent = (await post('tasks', input).expect(201)).body;
|
||||
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
|
||||
.body;
|
||||
let release!: () => void, locked!: () => void;
|
||||
const ready = new Promise<void>((r) => (locked = r)),
|
||||
hold = new Promise<void>((r) => (release = r));
|
||||
const locking = db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
|
||||
locked();
|
||||
await hold;
|
||||
});
|
||||
await ready;
|
||||
try {
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(low.id);
|
||||
} finally {
|
||||
release();
|
||||
await locking;
|
||||
}
|
||||
const next = (await post('claims', {}, 'other').expect(201)).body.task;
|
||||
expect(next.id).toBe(urgent.id);
|
||||
});
|
||||
it('serializes simultaneous duplicate mutations into one durable record', async () => {
|
||||
const op = key();
|
||||
const responses = await Promise.all([
|
||||
post('tasks', input, 'executor', op),
|
||||
post('tasks', input, 'executor', op),
|
||||
]);
|
||||
expect(responses.map((r) => r.status)).toEqual([201, 201]);
|
||||
expect(responses[0].body.id).toBe(responses[1].body.id);
|
||||
expect(await db.corporateTask.count()).toBe(1);
|
||||
});
|
||||
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
|
||||
const parent = (await post('tasks', input).expect(201)).body;
|
||||
const child = (
|
||||
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||
).body;
|
||||
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||
expect(claim.id).toBe(child.id);
|
||||
const e = (
|
||||
await post(`tasks/${child.id}/evidence`, {
|
||||
claimToken: claim.claimToken,
|
||||
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
|
||||
sha256: 'b'.repeat(64),
|
||||
summary: 'child artifact',
|
||||
tool: 'jest',
|
||||
result: 'receipt',
|
||||
}).expect(201)
|
||||
).body;
|
||||
await post(
|
||||
`tasks/${child.id}/reviews`,
|
||||
{
|
||||
evidenceId: e.id,
|
||||
passed: false,
|
||||
findings: 'needs correction',
|
||||
verification: {
|
||||
artifactUri: e.artifactUri,
|
||||
sha256: e.sha256,
|
||||
method: 'readback',
|
||||
result: 'failed',
|
||||
},
|
||||
},
|
||||
'reviewer',
|
||||
).expect(201);
|
||||
expect(
|
||||
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
|
||||
.status,
|
||||
).toBe('BLOCKED');
|
||||
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
|
||||
const research = (
|
||||
await post('market-insights', {
|
||||
title: 'fixture research',
|
||||
category: 'TREND',
|
||||
source: 'study receipt',
|
||||
opportunity: 'investigate',
|
||||
impact: 'LOW',
|
||||
recommendedAction: 'measure',
|
||||
cadence: 'MONTHLY',
|
||||
provenance: {
|
||||
method: 'test fixture',
|
||||
collector: 'integration',
|
||||
context: 'disposable',
|
||||
},
|
||||
sources: [
|
||||
{
|
||||
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||
title: 'fixture',
|
||||
excerpt: 'test-only',
|
||||
retrievedAt: '2026-01-01T00:00:00Z',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
const roadmap = (
|
||||
await post('monthly-roadmap', {
|
||||
researchId: research.id,
|
||||
cycleName: 'test',
|
||||
month: '2026-10',
|
||||
seasonalTheme: 'evidence pending seasonal analysis',
|
||||
strategicGoals: ['measure'],
|
||||
plannedArticlesCount: 31,
|
||||
plannedRefreshesCount: 0,
|
||||
plannedCatalogEnrichments: 0,
|
||||
goals: [
|
||||
{
|
||||
title: 'goal',
|
||||
department: 'CONTENT_SEO',
|
||||
acceptanceCriteria: 'QA',
|
||||
metric: 'engagement',
|
||||
},
|
||||
],
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(roadmap.goals).toHaveLength(1);
|
||||
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
|
||||
for (const path of ['market-insights', 'monthly-roadmap']) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/hermes/' + path)
|
||||
.set('x-api-key', 'executor')
|
||||
.expect(200);
|
||||
expect(r.body.meta.total).toBe(1);
|
||||
}
|
||||
const report = (
|
||||
await post('reports', {
|
||||
day: new Date().toISOString().slice(0, 10),
|
||||
summary: 'test fixture daily report',
|
||||
}).expect(201)
|
||||
).body;
|
||||
expect(report.snapshot.tasks).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,704 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma, CorporatePriority } from '@prisma/client';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import {
|
||||
canonical,
|
||||
publicData,
|
||||
choice,
|
||||
departments,
|
||||
evidenceInput,
|
||||
httpsUrl,
|
||||
timestamp,
|
||||
meta,
|
||||
normalizeSearch,
|
||||
object,
|
||||
pagination,
|
||||
priorities,
|
||||
statuses,
|
||||
taskInput,
|
||||
text,
|
||||
uuid,
|
||||
} from './corporate-policy';
|
||||
type Tx = Prisma.TransactionClient;
|
||||
@Injectable()
|
||||
export class CorporateService {
|
||||
constructor(private readonly db: PrismaService) {}
|
||||
private async operation(
|
||||
actor: string,
|
||||
op: string,
|
||||
key: string,
|
||||
body: unknown,
|
||||
fn: (tx: Tx) => Promise<any>,
|
||||
) {
|
||||
text(key, 200);
|
||||
const scoped = createHash('sha256')
|
||||
.update(canonical([actor, op, key]))
|
||||
.digest('hex');
|
||||
const hash = createHash('sha256').update(canonical(body)).digest('hex');
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
|
||||
const prior = await tx.corporateOperation.findUnique({
|
||||
where: { key: scoped },
|
||||
});
|
||||
if (prior) {
|
||||
if (prior.payloadHash !== hash)
|
||||
throw new ConflictException('Idempotency key payload mismatch');
|
||||
return prior.response;
|
||||
}
|
||||
const result = await fn(tx);
|
||||
const serialized = JSON.stringify(result);
|
||||
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
|
||||
throw new BadRequestException('Operation response exceeds limit');
|
||||
const response = JSON.parse(serialized);
|
||||
await tx.corporateOperation.create({
|
||||
data: { key: scoped, payloadHash: hash, response },
|
||||
});
|
||||
return response;
|
||||
},
|
||||
{ maxWait: 10000, timeout: 20000 },
|
||||
);
|
||||
}
|
||||
private event(
|
||||
tx: Tx,
|
||||
taskId: string,
|
||||
actor: string,
|
||||
step: string,
|
||||
content: string,
|
||||
speaker = 'SYSTEM',
|
||||
payload?: any,
|
||||
) {
|
||||
return tx.corporateEvent.create({
|
||||
data: { taskId, speaker, speakerName: actor, step, content, payload },
|
||||
});
|
||||
}
|
||||
private async lock(tx: Tx, id: string) {
|
||||
uuid(id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
|
||||
if (!rows.length) throw new NotFoundException('Task not found');
|
||||
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
|
||||
}
|
||||
private async fenced(tx: Tx, id: string, token: string, actor: string) {
|
||||
const t = await this.lock(tx, id);
|
||||
const rows = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
|
||||
if (!rows.length) throw new ConflictException('Stale lease or owner');
|
||||
return t;
|
||||
}
|
||||
async tasks(q: Record<string, any>) {
|
||||
const p = pagination(q),
|
||||
where: Prisma.CorporateTaskWhereInput = {};
|
||||
if (q.department) where.department = choice(q.department, departments);
|
||||
if (q.priority)
|
||||
where.priority = choice(q.priority, priorities) as CorporatePriority;
|
||||
if (q.status) where.status = choice(q.status, statuses) as any;
|
||||
if (q.search) {
|
||||
const search = normalizeSearch(text(q.search, 300));
|
||||
where.OR = [
|
||||
{ normalizedTitle: { contains: search } },
|
||||
{ normalizedCode: { contains: search } },
|
||||
];
|
||||
}
|
||||
if (q.goalId) where.goalId = uuid(q.goalId);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const total = await tx.corporateTask.count({ where });
|
||||
const data = await tx.corporateTask.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
|
||||
});
|
||||
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
async detail(id: string) {
|
||||
uuid(id);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const order = { id: 'asc' as const };
|
||||
const task = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
|
||||
evidence: { take: 100, orderBy: order },
|
||||
reviews: { take: 100, orderBy: order },
|
||||
effects: { take: 100, orderBy: order },
|
||||
children: { take: 100, orderBy: order },
|
||||
_count: {
|
||||
select: {
|
||||
logs: true,
|
||||
evidence: true,
|
||||
reviews: true,
|
||||
effects: true,
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!task) throw new NotFoundException('Task not found');
|
||||
const { _count, ...data } = task;
|
||||
const relationsMeta = Object.fromEntries(
|
||||
Object.entries(_count).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
return publicData({ ...data, relationsMeta });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
create(actor: string, key: string, input: unknown) {
|
||||
const b = taskInput(input);
|
||||
return this.operation(actor, 'create-task', key, b, async (tx) => {
|
||||
if (b.parentId) {
|
||||
const parent = await this.lock(tx, b.parentId);
|
||||
if (!['TODO', 'BLOCKED'].includes(parent.status))
|
||||
throw new ConflictException('Parent no longer accepts children');
|
||||
}
|
||||
const code = 'TSK-' + randomUUID();
|
||||
const task = await tx.corporateTask.create({
|
||||
data: {
|
||||
...b,
|
||||
priority: b.priority as CorporatePriority,
|
||||
taskCode: code,
|
||||
normalizedCode: normalizeSearch(code),
|
||||
normalizedTitle: normalizeSearch(b.title),
|
||||
createdBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
|
||||
return task;
|
||||
});
|
||||
}
|
||||
claim(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, ['department', 'leaseSeconds']);
|
||||
const department =
|
||||
b.department === undefined ? null : choice(b.department, departments);
|
||||
const seconds = Number(b.leaseSeconds ?? 300);
|
||||
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
|
||||
throw new BadRequestException('Lease must be 30..900 seconds');
|
||||
return this.operation(
|
||||
actor,
|
||||
'claim',
|
||||
key,
|
||||
{ department, seconds },
|
||||
async (tx) => {
|
||||
const candidates = await tx.$queryRaw<
|
||||
{ id: string }[]
|
||||
>`SELECT t.id FROM corporate_tasks t
|
||||
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
|
||||
AND (${department}::text IS NULL OR t.department=${department})
|
||||
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
|
||||
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
|
||||
if (!candidates.length) return { task: null };
|
||||
const id = candidates[0].id,
|
||||
token = randomUUID();
|
||||
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
|
||||
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
|
||||
return {
|
||||
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
submitEvidence(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = evidenceInput(input);
|
||||
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
|
||||
await this.fenced(tx, id, b.claimToken, actor);
|
||||
const e = await tx.corporateEvidence.create({
|
||||
data: { ...b, taskId: id, executor: actor },
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: { status: 'TEST', leasedUntil: null },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
'EVIDENCE_SUBMITTED',
|
||||
b.summary,
|
||||
'AGENT',
|
||||
{ evidenceId: e.id },
|
||||
);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
review(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'evidenceId',
|
||||
'passed',
|
||||
'findings',
|
||||
'verification',
|
||||
]);
|
||||
const evidenceId = uuid(b.evidenceId),
|
||||
findings = text(b.findings);
|
||||
if (typeof b.passed !== 'boolean')
|
||||
throw new BadRequestException('passed must be boolean');
|
||||
const v = object(b.verification, [
|
||||
'artifactUri',
|
||||
'sha256',
|
||||
'method',
|
||||
'result',
|
||||
]);
|
||||
const verification = {
|
||||
artifactUri: text(v.artifactUri, 2000),
|
||||
sha256: text(v.sha256, 64),
|
||||
method: text(v.method, 1000),
|
||||
result: text(v.result),
|
||||
};
|
||||
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
|
||||
uuid(id);
|
||||
const relation = await tx.corporateTask.findUnique({
|
||||
where: { id },
|
||||
select: { parentId: true },
|
||||
});
|
||||
if (relation?.parentId) await this.lock(tx, relation.parentId);
|
||||
const task = await this.lock(tx, id);
|
||||
const evidence = await tx.corporateEvidence.findUnique({
|
||||
where: { id: evidenceId },
|
||||
});
|
||||
if (
|
||||
task.status !== 'TEST' ||
|
||||
!evidence ||
|
||||
evidence.taskId !== id ||
|
||||
evidence.claimToken !== task.claimToken
|
||||
)
|
||||
throw new ConflictException('Current execution evidence required');
|
||||
if (evidence.executor === actor)
|
||||
throw new ConflictException('Independent reviewer required');
|
||||
if (
|
||||
verification.sha256 !== evidence.sha256 ||
|
||||
verification.artifactUri !== evidence.artifactUri
|
||||
)
|
||||
throw new ConflictException('QA must verify exact artifact');
|
||||
if (
|
||||
b.passed &&
|
||||
(await tx.corporateTask.count({
|
||||
where: { parentId: id, status: { not: 'DONE' } },
|
||||
}))
|
||||
)
|
||||
throw new ConflictException('Unfinished children');
|
||||
const r = await tx.corporateReview.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
evidenceId,
|
||||
reviewer: actor,
|
||||
passed: b.passed,
|
||||
findings,
|
||||
verification,
|
||||
},
|
||||
});
|
||||
await tx.corporateTask.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: b.passed ? 'DONE' : 'TODO',
|
||||
claimToken: null,
|
||||
leasedUntil: null,
|
||||
qaCount: { increment: 1 },
|
||||
rejectionCount: { increment: b.passed ? 0 : 1 },
|
||||
},
|
||||
});
|
||||
if (!b.passed && task.parentId) {
|
||||
await tx.corporateTask.update({
|
||||
where: { id: task.parentId },
|
||||
data: { status: 'BLOCKED' },
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
task.parentId,
|
||||
actor,
|
||||
'CHILD_QA_REJECTED',
|
||||
'Parent blocked pending child correction',
|
||||
'QA',
|
||||
{ childId: id },
|
||||
);
|
||||
}
|
||||
await this.event(
|
||||
tx,
|
||||
id,
|
||||
actor,
|
||||
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
|
||||
findings,
|
||||
'QA',
|
||||
{ reviewId: r.id },
|
||||
);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
async collection(
|
||||
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
|
||||
q: Record<string, any>,
|
||||
) {
|
||||
const p = pagination(q);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const model =
|
||||
kind === 'market-insights'
|
||||
? tx.corporateResearch
|
||||
: kind === 'monthly-roadmap'
|
||||
? tx.corporateRoadmap
|
||||
: tx.corporateReport;
|
||||
const where: any = {};
|
||||
if (kind === 'market-insights' && q.category)
|
||||
where.category = choice(q.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]);
|
||||
if (kind === 'monthly-roadmap' && q.month)
|
||||
where.month = text(q.month, 40);
|
||||
const delegate = model as any;
|
||||
const total = await delegate.count({ where });
|
||||
const data = await delegate.findMany({
|
||||
where,
|
||||
skip: p.skip,
|
||||
take: p.limit,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||
...(kind === 'market-insights'
|
||||
? { include: { sources: true } }
|
||||
: kind === 'monthly-roadmap'
|
||||
? { include: { goals: true } }
|
||||
: {}),
|
||||
});
|
||||
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
research(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'title',
|
||||
'category',
|
||||
'source',
|
||||
'opportunity',
|
||||
'impact',
|
||||
'recommendedAction',
|
||||
'cadence',
|
||||
'provenance',
|
||||
'sources',
|
||||
]);
|
||||
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
|
||||
throw new BadRequestException('1..30 sources required');
|
||||
const sources = b.sources.map((raw) => {
|
||||
const s = object(raw, [
|
||||
'url',
|
||||
'title',
|
||||
'excerpt',
|
||||
'retrievedAt',
|
||||
'sha256',
|
||||
]);
|
||||
const url = httpsUrl(s.url),
|
||||
sha256 = text(s.sha256, 64),
|
||||
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
|
||||
if (
|
||||
!url.startsWith('https://') ||
|
||||
!/^[a-f0-9]{64}$/.test(sha256) ||
|
||||
!Number.isFinite(retrievedAt.getTime()) ||
|
||||
retrievedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid source');
|
||||
return {
|
||||
url,
|
||||
sha256,
|
||||
retrievedAt,
|
||||
title: text(s.title, 300),
|
||||
excerpt: text(s.excerpt),
|
||||
};
|
||||
});
|
||||
const provenance = object(b.provenance, ['method', 'collector', 'context']);
|
||||
const data = {
|
||||
title: text(b.title, 300),
|
||||
category: choice(b.category, [
|
||||
'TREND',
|
||||
'COMPETITOR',
|
||||
'NEW_CHANNEL',
|
||||
'CATALOG_GAP',
|
||||
]),
|
||||
source: text(b.source, 2000),
|
||||
opportunity: text(b.opportunity),
|
||||
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
|
||||
recommendedAction: text(b.recommendedAction),
|
||||
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
|
||||
provenance: {
|
||||
method: text(provenance.method),
|
||||
collector: text(provenance.collector, 300),
|
||||
context: text(provenance.context),
|
||||
},
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'research', key, b, (tx) =>
|
||||
tx.corporateResearch.create({
|
||||
data: { ...data, sources: { create: sources } },
|
||||
include: { sources: true },
|
||||
}),
|
||||
);
|
||||
}
|
||||
roadmap(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'researchId',
|
||||
'cycleName',
|
||||
'month',
|
||||
'seasonalTheme',
|
||||
'strategicGoals',
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
'isActive',
|
||||
'goals',
|
||||
]);
|
||||
if (
|
||||
!Array.isArray(b.strategicGoals) ||
|
||||
!b.strategicGoals.length ||
|
||||
b.strategicGoals.length > 30 ||
|
||||
!Array.isArray(b.goals) ||
|
||||
!b.goals.length ||
|
||||
b.goals.length > 100
|
||||
)
|
||||
throw new BadRequestException('Goals required');
|
||||
for (const k of [
|
||||
'plannedArticlesCount',
|
||||
'plannedRefreshesCount',
|
||||
'plannedCatalogEnrichments',
|
||||
])
|
||||
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
|
||||
throw new BadRequestException('Invalid counts');
|
||||
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
|
||||
throw new BadRequestException('Invalid active flag');
|
||||
const goals = b.goals.map((raw) => {
|
||||
const g = object(raw, [
|
||||
'title',
|
||||
'department',
|
||||
'acceptanceCriteria',
|
||||
'metric',
|
||||
'target',
|
||||
]);
|
||||
if (
|
||||
g.target !== undefined &&
|
||||
(typeof g.target !== 'number' || !Number.isFinite(g.target))
|
||||
)
|
||||
throw new BadRequestException('Invalid target');
|
||||
return {
|
||||
title: text(g.title, 300),
|
||||
department: choice(g.department, departments),
|
||||
acceptanceCriteria: text(g.acceptanceCriteria),
|
||||
metric: text(g.metric, 300),
|
||||
target: g.target,
|
||||
};
|
||||
});
|
||||
const data = {
|
||||
researchId: uuid(b.researchId),
|
||||
cycleName: text(b.cycleName, 300),
|
||||
month: text(b.month, 40),
|
||||
seasonalTheme: text(b.seasonalTheme),
|
||||
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
|
||||
plannedArticlesCount: b.plannedArticlesCount,
|
||||
plannedRefreshesCount: b.plannedRefreshesCount,
|
||||
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
|
||||
isActive: b.isActive ?? false,
|
||||
createdBy: actor,
|
||||
};
|
||||
return this.operation(actor, 'roadmap', key, b, async (tx) => {
|
||||
const research = await tx.corporateResearch.findUnique({
|
||||
where: { id: data.researchId },
|
||||
include: { sources: true },
|
||||
});
|
||||
if (!research || !research.sources.length)
|
||||
throw new ConflictException('Evidence-backed research required');
|
||||
const result = await tx.corporateRoadmap.create({
|
||||
data: { ...data, goals: { create: goals } },
|
||||
include: { goals: true },
|
||||
});
|
||||
await tx.corporateResearch.update({
|
||||
where: { id: research.id },
|
||||
data: { status: 'IN_BACKLOG' },
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
effect(actor: string, key: string, id: string, input: unknown) {
|
||||
const b = object(input, [
|
||||
'metric',
|
||||
'availability',
|
||||
'baseline',
|
||||
'observed',
|
||||
'source',
|
||||
'observedAt',
|
||||
]);
|
||||
const availability = choice(b.availability, [
|
||||
'MEASURED',
|
||||
'UNAVAILABLE',
|
||||
'UNINSTRUMENTED',
|
||||
'BUSINESS_DISABLED',
|
||||
]);
|
||||
for (const k of ['baseline', 'observed'])
|
||||
if (
|
||||
b[k] !== undefined &&
|
||||
b[k] !== null &&
|
||||
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
|
||||
)
|
||||
throw new BadRequestException('Invalid metric');
|
||||
if (availability === 'MEASURED' && typeof b.observed !== 'number')
|
||||
throw new BadRequestException('Measured value required');
|
||||
if (
|
||||
availability !== 'MEASURED' &&
|
||||
(b.observed != null || b.baseline != null)
|
||||
)
|
||||
throw new BadRequestException('Unavailable is not zero');
|
||||
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
|
||||
if (
|
||||
!Number.isFinite(observedAt.getTime()) ||
|
||||
observedAt.getTime() > Date.now()
|
||||
)
|
||||
throw new BadRequestException('Invalid observation time');
|
||||
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
|
||||
const task = await this.lock(tx, id);
|
||||
if (task.status !== 'DONE')
|
||||
throw new ConflictException('Effects require completed QA');
|
||||
const e = await tx.corporateEffect.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
metric: text(b.metric, 300),
|
||||
availability,
|
||||
baseline: b.baseline,
|
||||
observed: b.observed,
|
||||
source: text(b.source, 2000),
|
||||
observedAt,
|
||||
recordedBy: actor,
|
||||
},
|
||||
});
|
||||
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
|
||||
effectId: e.id,
|
||||
});
|
||||
return e;
|
||||
});
|
||||
}
|
||||
report(actor: string, key: string, input: unknown) {
|
||||
const b = object(input, ['day', 'summary']);
|
||||
const day = text(b.day, 10),
|
||||
summary = text(b.summary);
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
||||
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
|
||||
)
|
||||
throw new BadRequestException('ISO day required');
|
||||
return this.operation(actor, 'report', key, b, async (tx) => {
|
||||
const start = new Date(day + 'T00:00:00Z'),
|
||||
end = new Date(start.getTime() + 86400000);
|
||||
const taskWhere = { updatedAt: { gte: start, lt: end } };
|
||||
const eventWhere = { timestamp: { gte: start, lt: end } };
|
||||
const effectWhere = { createdAt: { gte: start, lt: end } };
|
||||
const totals = {
|
||||
tasks: await tx.corporateTask.count({ where: taskWhere }),
|
||||
events: await tx.corporateEvent.count({ where: eventWhere }),
|
||||
effects: await tx.corporateEffect.count({ where: effectWhere }),
|
||||
};
|
||||
const tasks = await tx.corporateTask.findMany({
|
||||
where: taskWhere,
|
||||
take: 100,
|
||||
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskCode: true,
|
||||
title: true,
|
||||
status: true,
|
||||
department: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
const events = await tx.corporateEvent.findMany({
|
||||
where: eventWhere,
|
||||
take: 100,
|
||||
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
timestamp: true,
|
||||
speaker: true,
|
||||
speakerName: true,
|
||||
step: true,
|
||||
content: true,
|
||||
},
|
||||
});
|
||||
const effects = await tx.corporateEffect.findMany({
|
||||
where: effectWhere,
|
||||
take: 100,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
taskId: true,
|
||||
metric: true,
|
||||
availability: true,
|
||||
baseline: true,
|
||||
observed: true,
|
||||
source: true,
|
||||
observedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
let fieldsTruncated = false;
|
||||
const project = (rows: any[]) =>
|
||||
rows.map((row) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(row).map(([name, value]) => {
|
||||
if (typeof value === 'string' && value.length > 1000) {
|
||||
fieldsTruncated = true;
|
||||
return [name, value.slice(0, 1000)];
|
||||
}
|
||||
return [name, value];
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bounded = {
|
||||
tasks: project(tasks),
|
||||
events: project(events),
|
||||
effects: project(effects),
|
||||
};
|
||||
const counts = Object.fromEntries(
|
||||
Object.entries(totals).map(([name, total]) => [
|
||||
name,
|
||||
{
|
||||
total,
|
||||
returned: Math.min(total, 100),
|
||||
limit: 100,
|
||||
truncated: total > 100,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const snapshot = JSON.parse(
|
||||
JSON.stringify({
|
||||
timezone: 'UTC',
|
||||
...bounded,
|
||||
meta: {
|
||||
...counts,
|
||||
fieldsTruncated,
|
||||
stringLimit: 1000,
|
||||
eventPayloadsOmitted: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return tx.corporateReport.create({
|
||||
data: { day, summary, snapshot, createdBy: actor },
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ describe("MediaService", () => {
|
||||
|
||||
const validFile = {
|
||||
originalname: "product-cover.webp",
|
||||
buffer: Buffer.from("dummy-image-bytes"),
|
||||
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
|
||||
mimetype: "image/webp",
|
||||
size: 5000,
|
||||
} as any;
|
||||
|
||||
@@ -79,6 +79,28 @@ export class MediaService {
|
||||
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
||||
);
|
||||
}
|
||||
|
||||
// SEC-01: Magic number verification for uploaded binary content
|
||||
const buf = file.buffer;
|
||||
if (!buf || buf.length < 4) {
|
||||
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
||||
}
|
||||
|
||||
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
||||
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
||||
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
||||
const isWebp =
|
||||
buf.length >= 12 &&
|
||||
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
||||
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
||||
|
||||
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
||||
throw new BadRequestException(
|
||||
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
||||
);
|
||||
}
|
||||
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
StageAuthorRestorationService,
|
||||
GENUINE_STAGE_AUTHORS,
|
||||
STAGE_AUTHOR_ROLE,
|
||||
assertStageScope,
|
||||
} from "./stage-author-restoration.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
let service: StageAuthorRestorationService;
|
||||
let mockPrisma: any;
|
||||
let mockTx: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockTx = {
|
||||
$queryRaw: jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) }))),
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
};
|
||||
mockPrisma = {
|
||||
$transaction: jest.fn(async (cb) => cb(mockTx)),
|
||||
};
|
||||
service = new StageAuthorRestorationService(mockPrisma as any);
|
||||
});
|
||||
|
||||
describe("assertStageScope environment gating", () => {
|
||||
it("denies execution in default production environment", () => {
|
||||
expect(() =>
|
||||
assertStageScope({ NODE_ENV: "production", APP_ENV: "production" }),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution when neither APP_ENV nor STAGE flag is set", () => {
|
||||
expect(() => assertStageScope({})).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only APP_ENV is stage", () => {
|
||||
expect(() => assertStageScope({ APP_ENV: "stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
|
||||
expect(() =>
|
||||
assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("denies execution with only DATABASE_URL points to caninodb_stage", () => {
|
||||
expect(() =>
|
||||
assertStageScope({
|
||||
DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage",
|
||||
}),
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("restoreStageAuthors TDD lifecycle", () => {
|
||||
const stageEnv = { APP_ENV: "stage", STAGE_AUTHOR_RESTORATION_ENABLED: "true", STAGE_AUTHOR_RESTORATION_MODE: "maintenance", DATABASE_URL: "postgresql://user@canino_db_stage:5432/caninodb_stage" };
|
||||
|
||||
it("rejects a partial existing set before any writes", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValueOnce({ ...GENUINE_STAGE_AUTHORS[0], role: STAGE_AUTHOR_ROLE });
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not allow enabled production scope", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, APP_ENV: "production" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a stage-looking substring in the database identity", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@evil/caninodb_stage_prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires explicit mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects unsafe replay even with identical names", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: "Admin" }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a Serializable transaction", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
try { await service.restoreStageAuthors(stageEnv); } catch {}
|
||||
expect(mockPrisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
});
|
||||
|
||||
it("rejects unexpected orphan distribution without writing", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 52n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects replay with remaining orphans", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, mobile: null, email: null, password: null, authExpiresAt: null, walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(0), stageTestGeneration: null, stageTestSession: null }));
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 1n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it("accepts a loopback rehearsal database only in rehearsal mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: "rehearsal", DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects rehearsal database in maintenance mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires both stage identity and enable flag", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_ENABLED: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a URL with conflicting host override", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@canino_db_stage/caninodb_stage?host=prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires the public-author marker on replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, mobile: null, email: null, password: null, isPublicAuthor: false }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects malformed URL without database work", async () => {
|
||||
await expect(service.restoreStageAuthors({ ...stageEnv, DATABASE_URL: "not-a-url" })).rejects.toThrow(ForbiddenException);
|
||||
expect(mockPrisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unexpected scheme", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "https://canino_db_stage/caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("does not allow a production database with a stage query string", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@db/prod?stage=caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a credential-bearing replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, password: "hash", mobile: null, email: null }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects no-orphan initial state", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes the public-author marker", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => data);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) })));
|
||||
await service.restoreStageAuthors(stageEnv);
|
||||
for (const [call] of mockTx.user.create.mock.calls) expect(call.data.isPublicAuthor).toBe(true);
|
||||
});
|
||||
|
||||
// Legacy lifecycle assertions below also exercise the stricter preflight.
|
||||
|
||||
it("restores all 5 genuine authors when none exist in Stage", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
|
||||
id: data.id,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
role: data.role,
|
||||
}));
|
||||
|
||||
const res = await service.restoreStageAuthors(stageEnv);
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.totalConfigured).toBe(5);
|
||||
expect(res.restoredCount).toBe(5);
|
||||
expect(res.existingCount).toBe(0);
|
||||
expect(mockTx.user.create).toHaveBeenCalledTimes(5);
|
||||
|
||||
// Verify safe non-login fields: no credentials, no contact, no elevated role
|
||||
for (const call of mockTx.user.create.mock.calls) {
|
||||
const payload = call[0].data;
|
||||
expect(payload.role).toBe(STAGE_AUTHOR_ROLE);
|
||||
expect(payload.mobile).toBeNull();
|
||||
expect(payload.email).toBeNull();
|
||||
expect(payload.password).toBeNull();
|
||||
expect(payload.walletBalance).toEqual(new Prisma.Decimal(0));
|
||||
// Verify genuine author ID is preserved
|
||||
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === payload.id);
|
||||
expect(match).toBeDefined();
|
||||
expect(payload.firstName).toBe(match!.firstName);
|
||||
expect(payload.lastName).toBe(match!.lastName);
|
||||
}
|
||||
});
|
||||
|
||||
it("is strictly idempotent: repeated calls report existing and perform no creates", async () => {
|
||||
mockTx.$queryRaw.mockResolvedValue([]);
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id);
|
||||
if (!match) return null;
|
||||
return {
|
||||
id: match.id,
|
||||
firstName: match.firstName,
|
||||
lastName: match.lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
isPublicAuthor: true,
|
||||
authExpiresAt: null,
|
||||
stageTestGeneration: null,
|
||||
stageTestSession: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
charityDonationTotal: new Prisma.Decimal(0),
|
||||
};
|
||||
});
|
||||
|
||||
const res = await service.restoreStageAuthors(stageEnv);
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.totalConfigured).toBe(5);
|
||||
expect(res.restoredCount).toBe(0);
|
||||
expect(res.existingCount).toBe(5);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed with 409 Conflict when existing record has conflicting name", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
|
||||
return {
|
||||
id: where.id,
|
||||
firstName: "Fake",
|
||||
lastName: "Impersonator",
|
||||
role: "Admin",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(
|
||||
ConflictException,
|
||||
);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handles partial restoration: restores only missing authors and retains existing identical ones", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
|
||||
return {
|
||||
id: where.id,
|
||||
firstName: GENUINE_STAGE_AUTHORS[0].firstName,
|
||||
lastName: GENUINE_STAGE_AUTHORS[0].lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
|
||||
id: data.id,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
role: data.role,
|
||||
}));
|
||||
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
export const GENUINE_STAGE_AUTHORS = [
|
||||
{
|
||||
id: "14490d36-52fc-40be-8637-b7b04b8302f8",
|
||||
firstName: "کارشناس",
|
||||
lastName: "تغذیه تیم کنینا",
|
||||
},
|
||||
{
|
||||
id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7",
|
||||
firstName: "آرزو",
|
||||
lastName: "فراشیانی",
|
||||
},
|
||||
{
|
||||
id: "63d38117-f864-4af6-afa0-ae5b05255f57",
|
||||
firstName: "کارشناس",
|
||||
lastName: "تحقیقات و کنترل کیفیت کنینا",
|
||||
},
|
||||
{
|
||||
id: "7b1e51d1-8c32-4a3c-804f-948d706aef36",
|
||||
firstName: "کارشناس",
|
||||
lastName: "رفتار و نگهداری تیم کنینا",
|
||||
},
|
||||
{
|
||||
id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4",
|
||||
firstName: "دکتر",
|
||||
lastName: "دامپزشک تیم کنینا",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const STAGE_AUTHOR_ROLE = "User_PetOwner";
|
||||
|
||||
export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void {
|
||||
let identityAllowed = false;
|
||||
try {
|
||||
const url = new URL(env.DATABASE_URL || "");
|
||||
const mode = env.STAGE_AUTHOR_RESTORATION_MODE;
|
||||
identityAllowed =
|
||||
["postgresql:", "postgres:"].includes(url.protocol) &&
|
||||
!url.search && !url.hash &&
|
||||
((mode === "maintenance" && (!url.port || url.port === "5432") && url.hostname === "canino_db_stage" && url.pathname === "/caninodb_stage") ||
|
||||
(mode === "rehearsal" && url.hostname === "127.0.0.1" && url.pathname === "/rehearsal"));
|
||||
} catch {
|
||||
// Malformed and absent URLs are denied without exposing credentials.
|
||||
}
|
||||
if (env.APP_ENV !== "stage" || env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true" || !identityAllowed) {
|
||||
throw new ForbiddenException(
|
||||
"Stage author restoration is strictly restricted to authorized Stage environments",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface StageAuthorRestoreResult {
|
||||
success: boolean;
|
||||
totalConfigured: number;
|
||||
restoredCount: number;
|
||||
existingCount: number;
|
||||
authors: Array<{
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
status: "restored" | "already_present";
|
||||
}>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StageAuthorRestorationService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async restoreStageAuthors(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Promise<StageAuthorRestoreResult> {
|
||||
assertStageScope(env);
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const results: StageAuthorRestoreResult["authors"] = [];
|
||||
let restoredCount = 0;
|
||||
let existingCount = 0;
|
||||
|
||||
// Read the entire candidate set and every dangling reference before writing.
|
||||
const candidates = await Promise.all(GENUINE_STAGE_AUTHORS.map(author => tx.user.findUnique({ where: { id: author.id } })));
|
||||
const orphans = await tx.$queryRaw<Array<{ authorId: string; count: bigint }>>`
|
||||
SELECT b.author_id AS "authorId", COUNT(*) AS count
|
||||
FROM blogs b LEFT JOIN users u ON u.id = b.author_id
|
||||
WHERE b.author_id IS NOT NULL AND u.id IS NULL
|
||||
GROUP BY b.author_id
|
||||
`;
|
||||
const present = candidates.filter(Boolean).length;
|
||||
if (present !== 0 && present !== GENUINE_STAGE_AUTHORS.length) {
|
||||
throw new ConflictException("Partial author restoration is not permitted");
|
||||
}
|
||||
if (present === 0) {
|
||||
const counts = [16, 2, 3, 14, 17];
|
||||
if (orphans.length !== 5 || !GENUINE_STAGE_AUTHORS.every((a, i) =>
|
||||
orphans.filter(o => o.authorId === a.id && Number(o.count) === counts[i]).length === 1)) {
|
||||
throw new ConflictException("Expected exactly 52 orphan blogs with the reviewed author distribution");
|
||||
}
|
||||
} else {
|
||||
if (orphans.length !== 0 || !candidates.every((row, i) => row &&
|
||||
row.id === GENUINE_STAGE_AUTHORS[i].id &&
|
||||
row.firstName === GENUINE_STAGE_AUTHORS[i].firstName &&
|
||||
row.lastName === GENUINE_STAGE_AUTHORS[i].lastName &&
|
||||
row.role === STAGE_AUTHOR_ROLE && row.isPublicAuthor === true &&
|
||||
row.mobile === null && row.email === null && row.password === null &&
|
||||
row.authExpiresAt === null && row.stageTestGeneration === null && row.stageTestSession === null &&
|
||||
row.walletBalance.equals(0) && row.charityDonationTotal.equals(0))) {
|
||||
throw new ConflictException("Replay requires all five exact safe author rows and zero orphan blogs");
|
||||
}
|
||||
}
|
||||
|
||||
for (const [index, author] of GENUINE_STAGE_AUTHORS.entries()) {
|
||||
const existing = candidates[index];
|
||||
// Candidate identity was validated atomically above.
|
||||
|
||||
if (existing) {
|
||||
if (
|
||||
existing.firstName !== author.firstName ||
|
||||
existing.lastName !== author.lastName
|
||||
) {
|
||||
throw new ConflictException(
|
||||
`Identity conflict for author UUID ${author.id}: existing name '${existing.firstName} ${existing.lastName}' conflicts with genuine name '${author.firstName} ${author.lastName}'`,
|
||||
);
|
||||
}
|
||||
|
||||
results.push({
|
||||
id: existing.id,
|
||||
firstName: existing.firstName,
|
||||
lastName: existing.lastName,
|
||||
role: existing.role,
|
||||
status: "already_present",
|
||||
});
|
||||
existingCount++;
|
||||
} else {
|
||||
// Create author with safe non-login profile fields only
|
||||
// No synthetic mobile, no synthetic email, no password, no admin privileges
|
||||
const created = await tx.user.create({
|
||||
data: {
|
||||
id: author.id,
|
||||
firstName: author.firstName,
|
||||
lastName: author.lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
isPublicAuthor: true,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
results.push({
|
||||
id: created.id,
|
||||
firstName: created.firstName,
|
||||
lastName: created.lastName,
|
||||
role: created.role,
|
||||
status: "restored",
|
||||
});
|
||||
restoredCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
totalConfigured: GENUINE_STAGE_AUTHORS.length,
|
||||
restoredCount,
|
||||
existingCount,
|
||||
authors: results,
|
||||
};
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get, Query, UseGuards } from "@nestjs/common";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/support-chat")
|
||||
export class SupportChatAnalyticsController {
|
||||
constructor(private readonly analytics: SupportChatAnalyticsService) {}
|
||||
@Get("stats") stats(@Query("startDate") startDate?: string, @Query("endDate") endDate?: string) { return this.analytics.stats(startDate, endDate).then(data => ({ success: true, data })); }
|
||||
@Get("conversations") conversations(@Query("page") page?: string, @Query("limit") limit?: string, @Query("startDate") startDate?: string, @Query("endDate") endDate?: string, @Query("onlyUnanswered") onlyUnanswered?: string) { return this.analytics.conversations(Number(page), Number(limit), startDate, endDate, onlyUnanswered === "true").then(data => ({ success: true, ...data })); }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@Injectable()
|
||||
export class SupportChatAnalyticsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async stats(startDate?: string, endDate?: string) {
|
||||
const where = this.range(startDate, endDate);
|
||||
const [conversations, messages, authenticated, unanswered, followup, escalated, topics] = await Promise.all([
|
||||
this.prisma.supportConversation.count({ where }),
|
||||
this.prisma.supportConversationMessage.count({ where: { conversation: where } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, userId: { not: null } } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, unanswered: true } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, needsFollowup: true } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, escalationSignal: true } }),
|
||||
this.prisma.supportConversation.findMany({ where, select: { topics: true }, take: 5000 }),
|
||||
]);
|
||||
const topicCounts: Record<string, number> = {};
|
||||
for (const row of topics) for (const topic of Array.isArray(row.topics) ? row.topics : []) if (typeof topic === "string") topicCounts[topic] = (topicCounts[topic] || 0) + 1;
|
||||
return { conversations, messages, authenticated, anonymous: conversations - authenticated, unanswered, followup, escalated, topics: topicCounts };
|
||||
}
|
||||
|
||||
async conversations(page = 1, limit = 25, startDate?: string, endDate?: string, onlyUnanswered = false) {
|
||||
const safePage = Math.max(1, Math.min(10000, Number(page) || 1));
|
||||
const safeLimit = Math.max(1, Math.min(100, Number(limit) || 25));
|
||||
const where = { ...this.range(startDate, endDate), ...(onlyUnanswered ? { unanswered: true } : {}) };
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.supportConversation.findMany({ where, orderBy: { updatedAt: "desc" }, skip: (safePage - 1) * safeLimit, take: safeLimit, include: { user: { select: { id: true, firstName: true, lastName: true, mobile: true, email: true } }, messages: { orderBy: { sequence: "asc" }, take: 40 } } }),
|
||||
this.prisma.supportConversation.count({ where }),
|
||||
]);
|
||||
return { data, meta: { total, page: safePage, limit: safeLimit, lastPage: Math.ceil(total / safeLimit) } };
|
||||
}
|
||||
|
||||
private range(startDate?: string, endDate?: string) {
|
||||
const createdAt: any = {};
|
||||
if (startDate && /^\d{4}-\d{2}-\d{2}$/.test(startDate)) createdAt.gte = new Date(`${startDate}T00:00:00.000Z`);
|
||||
if (endDate && /^\d{4}-\d{2}-\d{2}$/.test(endDate)) { const end = new Date(`${endDate}T00:00:00.000Z`); end.setUTCDate(end.getUTCDate() + 1); createdAt.lt = end; }
|
||||
return Object.keys(createdAt).length ? { createdAt } : {};
|
||||
}
|
||||
}
|
||||
@@ -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,3 +1,4 @@
|
||||
import { TasksModule } from './common/services/tasks.module';
|
||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||
import { PrismaModule } from "./prisma/prisma.module";
|
||||
import { SupportChatModule } from './support-chat/support-chat.module';
|
||||
@@ -37,10 +38,12 @@ import { FaqModule } from "./faq/faq.module";
|
||||
import { MenuModule } from "./menu/menu.module";
|
||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||
|
||||
import { SeoTrackingModule } from "./seo-tracking/seo-tracking.module";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
SeoTrackingModule,
|
||||
SupportChatModule,
|
||||
RevalidationModule,
|
||||
SmsModule,
|
||||
@@ -79,6 +82,7 @@ import { Request, Response, NextFunction } from "express";
|
||||
B2BModule,
|
||||
FaqModule,
|
||||
MenuModule,
|
||||
TasksModule,
|
||||
],
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
|
||||
@@ -233,7 +233,7 @@ export class AuthController {
|
||||
async refresh(
|
||||
@Req()
|
||||
req: {
|
||||
user: { id: string; email?: string; role?: string; mobile?: string };
|
||||
user: { id: string; email?: string; role?: string; mobile?: string | null };
|
||||
},
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
|
||||
@@ -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 {
|
||||
@@ -68,6 +69,8 @@ export class AuthService {
|
||||
|
||||
async sendOtp(sendOtpDto: SendOtpDto) {
|
||||
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
|
||||
const user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
|
||||
if (user) assertPrincipalActive(user);
|
||||
|
||||
// 1. Check 60-second cooldown per phone number
|
||||
const cooldownKey = `otp:cooldown:${phoneNumber}`;
|
||||
@@ -200,7 +203,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;
|
||||
@@ -218,6 +222,7 @@ export class AuthService {
|
||||
const firstName = registerDto.firstName.trim();
|
||||
const lastName = registerDto.lastName.trim();
|
||||
const mobile = normalizeMobile(registerDto.mobile);
|
||||
if (!mobile) throw new BadRequestException("شماره موبایل الزامی است");
|
||||
const email = registerDto.email
|
||||
? registerDto.email.trim().toLowerCase()
|
||||
: null;
|
||||
@@ -257,7 +262,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 +306,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;
|
||||
@@ -315,21 +322,23 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async adminLogin(body: AdminLoginInput) {
|
||||
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
|
||||
// Resolve email before checking roles so public authors cannot enter the env fallback.
|
||||
const dbAdmin = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
email: body.email,
|
||||
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
|
||||
},
|
||||
where: { email: body.email },
|
||||
});
|
||||
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
// Reject before credential/fallback evaluation, including accidentally assigned admin roles.
|
||||
if (dbAdmin) assertPrincipalActive(dbAdmin);
|
||||
|
||||
if (dbAdmin && ["Admin", "SUPER_ADMIN", "ADMIN"].includes(dbAdmin.role) && 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 +452,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;
|
||||
@@ -484,15 +496,27 @@ export class AuthService {
|
||||
|
||||
async refresh(user: {
|
||||
id: string;
|
||||
email?: string;
|
||||
email?: string | null;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
mobile?: string | null;
|
||||
isPublicAuthor?: boolean;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
// Re-resolve rather than trusting a stale or partially projected request principal.
|
||||
const current = await this.prisma.user.findUnique({ where: { id: user.id } });
|
||||
if (!current) throw new UnauthorizedException("کاربر یافت نشد");
|
||||
assertPrincipalActive(current);
|
||||
assertPrincipalActive(user);
|
||||
if (current.stageTestSession && (!current.stageTestGeneration || user.stageTestGeneration !== current.stageTestGeneration || user.stageTestSession !== current.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
const { password: _password, ...safeUser } = current;
|
||||
user = safeUser;
|
||||
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']);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
forwardRef,
|
||||
} from "@nestjs/common";
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { ApiKeysService } from "../admin/api-keys.service";
|
||||
|
||||
@Injectable()
|
||||
@@ -28,6 +29,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
|
||||
if (apiKeyHeader && this.apiKeysService) {
|
||||
try {
|
||||
const apiKeyUser = await this.apiKeysService.validateKey(apiKeyHeader);
|
||||
assertPrincipalActive(apiKeyUser as { isPublicAuthor?: boolean });
|
||||
request.user = apiKeyUser;
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
@@ -52,6 +54,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
|
||||
)
|
||||
);
|
||||
}
|
||||
assertPrincipalActive(user as { isPublicAuthor?: boolean });
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -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 unavailable"); }
|
||||
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,133 @@
|
||||
import { UnauthorizedException, ForbiddenException } from '@nestjs/common';
|
||||
import { validate } from 'class-validator';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
import { assertPrincipalActive } from './stage-test-principal';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
describe('Public authors are attribution only, never principals', () => {
|
||||
const password = 'test-password';
|
||||
const author = { id: 'author-id', mobile: '09123456789', email: 'author@example.invalid', password: bcrypt.hashSync(password, 4), role: 'SUPER_ADMIN', isPublicAuthor: true };
|
||||
let prisma: any, jwt: any, redis: any, sms: any, service: AuthService;
|
||||
const env = { ...process.env };
|
||||
beforeEach(() => {
|
||||
process.env.JWT_SECRET = 'isolated-public-author-test-secret';
|
||||
process.env.JWT_REFRESH_SECRET = 'isolated-public-author-refresh-secret';
|
||||
prisma = { user: { findUnique: jest.fn().mockResolvedValue(author), findFirst: jest.fn().mockResolvedValue(author), create: jest.fn() } };
|
||||
jwt = { sign: jest.fn().mockReturnValue('token'), verify: jest.fn().mockReturnValue({ sub: author.id, jti: 'old-token' }) };
|
||||
redis = { get: jest.fn(async (key: string) => key.startsWith('otp_attempts:') ? null : key === `otp:${author.mobile}` ? '12345' : key.startsWith('refresh_token:') ? '1' : null), set: jest.fn(), del: jest.fn(), incr: jest.fn().mockResolvedValue(1) };
|
||||
sms = { sendOtp: jest.fn().mockResolvedValue(true) };
|
||||
service = new AuthService(prisma, jwt, redis, sms);
|
||||
});
|
||||
afterEach(() => { process.env = { ...env }; });
|
||||
|
||||
it('shared principal assertion rejects the marker independent of role/mobile', () => {
|
||||
expect(() => assertPrincipalActive(author)).toThrow(UnauthorizedException);
|
||||
const withoutMobile = { ...author, mobile: null };
|
||||
expect(() => assertPrincipalActive(withoutMobile)).toThrow(UnauthorizedException);
|
||||
});
|
||||
it.each(['User_PetOwner', 'Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks password login even with role %s', async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ ...author, role });
|
||||
await expect(service.login({ mobile: author.mobile, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('does not send or store an OTP for a public author', async () => {
|
||||
await expect(service.sendOtp({ phoneNumber: author.mobile })).rejects.toThrow(UnauthorizedException);
|
||||
expect(sms.sendOtp).not.toHaveBeenCalled();
|
||||
expect(redis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks a previously issued valid OTP without creating an alternate account', async () => {
|
||||
await expect(service.verifyOtp({ phoneNumber: author.mobile, code: '12345' })).rejects.toThrow(UnauthorizedException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks email/admin login including nonproduction fallback for %s', async role => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.ADMIN_EMAIL = author.email;
|
||||
process.env.ADMIN_PASSWORD = password;
|
||||
prisma.user.findFirst.mockResolvedValue({ ...author, role, password: null });
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks email/admin login with a valid stored password', async () => {
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('email lookup cannot hide a public author behind a non-admin role and enter fallback', async () => {
|
||||
process.env.ADMIN_EMAIL = author.email;
|
||||
process.env.ADMIN_PASSWORD = password;
|
||||
prisma.user.findFirst.mockResolvedValue({ ...author, role: 'User_PetOwner' });
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(prisma.user.findFirst).toHaveBeenCalledWith({ where: { email: author.email } });
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks refresh-token rotation for an existing author account', async () => {
|
||||
await expect(service.refreshToken('previous-token')).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks legacy refresh even when supplied principal omits the marker', async () => {
|
||||
await expect(service.refresh({ id: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['Bearer old-token', 'cookie'])('rejects existing JWT via %s using database marker, not token claims', async transport => {
|
||||
const strategy = new JwtStrategy({ findById: jest.fn().mockResolvedValue(author) } as any, redis);
|
||||
const headers = transport === 'cookie' ? { cookie: 'accessToken=old-token' } : { authorization: transport };
|
||||
await expect(strategy.validate({ headers } as any, { sub: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
it('JWT guard rejects an accidentally supplied author principal', () => {
|
||||
expect(() => new JwtAuthGuard().handleRequest(null, author)).toThrow(UnauthorizedException);
|
||||
});
|
||||
it('API-key guard rejects an accidentally marked principal', async () => {
|
||||
const guard = new JwtAuthGuard({ validateKey: jest.fn().mockResolvedValue({ ...author, isApiKey: true, scopes: ['admin'] }) } as any);
|
||||
const request = { headers: { 'x-api-key': 'test-key' } };
|
||||
await expect(guard.canActivate({ switchToHttp: () => ({ getRequest: () => request }) } as any)).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
it.each([{ roles: ['Admin'] }, { roles: [] }])('role guard rejects author even for roles %j', ({ roles }) => {
|
||||
const guard = new RolesGuard({ getAllAndOverride: () => roles } as any);
|
||||
const ctx = { getHandler: () => null, getClass: () => null, switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
|
||||
expect(() => guard.canActivate(ctx)).toThrow(ForbiddenException);
|
||||
});
|
||||
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('human admin guard accepts actual human role %s', role => {
|
||||
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
|
||||
expect(new HumanAdminGuard().canActivate(ctx)).toBe(true);
|
||||
});
|
||||
it.each(['User_PetOwner', 'adminsuper', '', undefined])('human admin guard denies nonallowlisted role %s', role => {
|
||||
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
|
||||
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
|
||||
});
|
||||
it('human admin guard rejects author with admin role', () => {
|
||||
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
|
||||
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
|
||||
});
|
||||
it.each([undefined, null, '', ' '])('registration still requires mobile %j before any database write', async mobile => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
prisma.user.create.mockResolvedValue({ ...author, mobile, isPublicAuthor: false });
|
||||
await expect(service.register({ firstName: 'Real', lastName: 'User', mobile } as any)).rejects.toThrow();
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([RegisterDto, LoginDto])('real-user DTO retains required mobile validation', async Dto => {
|
||||
const dto = Object.assign(new Dto(), { firstName: 'Real', lastName: 'User', password });
|
||||
expect((await validate(dto)).some(error => error.property === 'mobile')).toBe(true);
|
||||
});
|
||||
it('real users can still login, verify OTP and refresh', async () => {
|
||||
const real = { ...author, isPublicAuthor: false };
|
||||
prisma.user.findUnique.mockResolvedValue(real);
|
||||
await expect(service.login({ mobile: real.mobile, password })).resolves.toMatchObject({ success: true });
|
||||
await expect(service.verifyOtp({ phoneNumber: real.mobile, code: '12345' })).resolves.toMatchObject({ success: true });
|
||||
await expect(service.refreshToken('previous-token')).resolves.toMatchObject({ success: true });
|
||||
await expect(service.refresh({ id: real.id })).resolves.toMatchObject({ success: true });
|
||||
});
|
||||
it('Prisma author storage permits absent mobile and defaults marker false', () => {
|
||||
const schema = readFileSync(join(__dirname, '../../prisma/schema.prisma'), 'utf8');
|
||||
const user = schema.match(/model User \{([\s\S]*?)\n\}/)![1];
|
||||
expect(user).toMatch(/mobile\s+String\?\s+@unique/);
|
||||
expect(user).toMatch(/isPublicAuthor\s+Boolean\s+@default\(false\)\s+@map\("is_public_author"\)/);
|
||||
});
|
||||
});
|
||||
@@ -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,16 @@
|
||||
import { UnauthorizedException } from "@nestjs/common";
|
||||
|
||||
// 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; isPublicAuthor?: boolean }, now = Date.now()) {
|
||||
if (user.isPublicAuthor) throw new UnauthorizedException("Public authors cannot authenticate");
|
||||
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({user:{findUnique:async()=>current}} 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');
|
||||
});
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
|
||||
describe("findAll", () => {
|
||||
it("should query published blogs with pagination", async () => {
|
||||
const blogs = [
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null },
|
||||
];
|
||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||
mockPrisma.blog.count.mockResolvedValue(1);
|
||||
@@ -49,6 +49,9 @@ describe("BlogsService", () => {
|
||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||
expect(result.data).toEqual(blogs);
|
||||
expect(result.meta.total).toBe(1);
|
||||
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
||||
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
|
||||
});
|
||||
|
||||
it("should filter by categorySlug and search term", async () => {
|
||||
@@ -67,7 +70,19 @@ describe("BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the minimal public author identity for list results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
||||
await service.findAll({});
|
||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("selects the minimal public author identity for homepage results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
await service.findHomepage();
|
||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
@@ -90,6 +105,12 @@ describe("BlogsService", () => {
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("selects the minimal public author identity for detail results", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
|
||||
@@ -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,19 +68,24 @@ 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),
|
||||
orderBy: {
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
{ id: "asc" },
|
||||
],
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
@@ -85,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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -108,9 +140,11 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -125,9 +159,11 @@ export class BlogsService {
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -163,9 +199,7 @@ export class BlogsService {
|
||||
],
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
},
|
||||
author: { select: { id: true, firstName: true, lastName: true } },
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
/** Key management is a human-only control plane, never delegated by API scope. */
|
||||
@Injectable()
|
||||
export class HumanAdminGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const user = context.switchToHttp().getRequest().user;
|
||||
if (!user || user.isPublicAuthor || user.isApiKey || !['Admin', 'ADMIN', 'SUPER_ADMIN'].includes(user.role))
|
||||
throw new ForbiddenException('Human administrator required');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ interface RequestWithUser {
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
scopes?: string[];
|
||||
isPublicAuthor?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,12 +26,14 @@ export class RolesGuard implements CanActivate {
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (user?.isPublicAuthor) throw new ForbiddenException("Public authors have no permissions");
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (!user || !user.role) {
|
||||
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -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({
|
||||
@@ -110,4 +120,64 @@ describe("RevalidationService", () => {
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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(/\/+$/, "");
|
||||
}
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
@@ -109,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"),
|
||||
@@ -123,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,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TasksService } from './tasks.service';
|
||||
import { OrdersModule } from '../../orders/orders.module';
|
||||
import { PaymentModule } from '../../payment/payment.module';
|
||||
import { RedisModule } from '../../redis/redis.module';
|
||||
|
||||
@Module({
|
||||
imports: [OrdersModule, PaymentModule, RedisModule],
|
||||
providers: [TasksService],
|
||||
exports: [TasksService],
|
||||
})
|
||||
export class TasksModule {}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
||||
import { OrdersService } from '../../orders/orders.service';
|
||||
import { RedisService } from '../../redis/redis.service';
|
||||
import { PaymentService } from '../../payment/payment.service';
|
||||
|
||||
@Injectable()
|
||||
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(TasksService.name);
|
||||
private reservationTimer: NodeJS.Timeout | null = null;
|
||||
private reconciliationTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly ordersService: OrdersService,
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly redisService: RedisService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap() {
|
||||
this.logger.log('Starting background maintenance tasks...');
|
||||
|
||||
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
|
||||
this.reservationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.ordersService.releaseExpiredInventoryReservations();
|
||||
if (result.releasedCount > 0) {
|
||||
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:inventory_release');
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
|
||||
this.reconciliationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.paymentService.reconcilePendingTransactions();
|
||||
if (result.total > 0) {
|
||||
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:payment_reconciliation');
|
||||
}
|
||||
}, 10 * 60 * 1000);
|
||||
|
||||
// Initial check on startup after 30 seconds
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.ordersService.releaseExpiredInventoryReservations();
|
||||
} catch (err) {
|
||||
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
|
||||
}
|
||||
}, 30 * 1000);
|
||||
}
|
||||
|
||||
onApplicationShutdown() {
|
||||
this.logger.log('Stopping background maintenance tasks...');
|
||||
if (this.reservationTimer) {
|
||||
clearInterval(this.reservationTimer);
|
||||
this.reservationTimer = null;
|
||||
}
|
||||
if (this.reconciliationTimer) {
|
||||
clearInterval(this.reconciliationTimer);
|
||||
this.reconciliationTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -13,9 +13,8 @@ describe("ContactService", () => {
|
||||
count: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
contactInfo: {
|
||||
setting: {
|
||||
findMany: jest.fn(),
|
||||
upsert: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -82,26 +81,27 @@ describe("ContactService", () => {
|
||||
});
|
||||
|
||||
describe("getContactInfo", () => {
|
||||
it("should return contact items if they already exist", async () => {
|
||||
const items = [
|
||||
{ id: "1", key: "branch_info", title: "تلفن", value: "021" },
|
||||
];
|
||||
mockPrisma.contactInfo.findMany.mockResolvedValue(items);
|
||||
it("should return contact items from canonical settings", async () => {
|
||||
mockPrisma.setting.findMany.mockResolvedValue([
|
||||
{ key: "CONTACT_PHONE", value: "021-12345678" },
|
||||
{ key: "CONTACT_EMAIL", value: "support@example.test" },
|
||||
{ key: "CONTACT_ADDRESS", value: "آدرس تنظیمشده" },
|
||||
]);
|
||||
|
||||
const result = await service.getContactInfo();
|
||||
expect(result).toEqual(items);
|
||||
expect(mockPrisma.contactInfo.upsert).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([
|
||||
{ key: "phone", title: "تلفنهای تماس", value: "021-12345678", icon: "phone", order: 1 },
|
||||
{ key: "email", title: "پست الکترونیک", value: "support@example.test", icon: "mail", order: 2 },
|
||||
{ key: "address", title: "نشانی دفتر مرکزی", value: "آدرس تنظیمشده", icon: "map-pin", order: 3 },
|
||||
]);
|
||||
expect(mockPrisma.setting.findMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should seed default items if empty", async () => {
|
||||
mockPrisma.contactInfo.findMany
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([{ key: "branch_info" }]);
|
||||
|
||||
const result = await service.getContactInfo();
|
||||
expect(mockPrisma.contactInfo.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(result).toHaveLength(1);
|
||||
it("does not return hardcoded contact values when settings are empty", async () => {
|
||||
mockPrisma.setting.findMany.mockResolvedValue([]);
|
||||
expect(await service.getContactInfo()).toEqual([]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("getAllSubmissions", () => {
|
||||
|
||||
@@ -65,51 +65,20 @@ export class ContactService {
|
||||
}
|
||||
|
||||
async getContactInfo() {
|
||||
let items = await this.prisma.contactInfo.findMany({
|
||||
orderBy: { order: "asc" },
|
||||
const settings = await this.prisma.setting.findMany({
|
||||
where: { key: { in: ["CONTACT_PHONE", "contact_phone", "CONTACT_EMAIL", "contact_email", "CONTACT_ADDRESS", "contact_address"] } },
|
||||
select: { key: true, value: true },
|
||||
});
|
||||
|
||||
if (items.length === 0) {
|
||||
// Seed default items if empty
|
||||
const defaultItems = [
|
||||
{
|
||||
key: "branch_info",
|
||||
title: "اطلاعات نمایندگی",
|
||||
value:
|
||||
"تلفنهای تماس\n۰۲۱-۸۸۸۸ ۴۴۴۴\n\nشنبه تا چهارشنبه ۹:۰۰ الی ۱۸:۰۰",
|
||||
icon: "phone",
|
||||
order: 1,
|
||||
},
|
||||
{
|
||||
key: "email_info",
|
||||
title: "پست الکترونیک",
|
||||
value: "info@canina.ir\n\nپاسخگویی در کمتر از ۲۴ ساعت کاری",
|
||||
icon: "mail",
|
||||
order: 2,
|
||||
},
|
||||
{
|
||||
key: "address_info",
|
||||
title: "نشانی دفتر مرکزی",
|
||||
value: "تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹",
|
||||
icon: "map-pin",
|
||||
order: 3,
|
||||
},
|
||||
];
|
||||
|
||||
for (const item of defaultItems) {
|
||||
await this.prisma.contactInfo.upsert({
|
||||
where: { key: item.key },
|
||||
update: {},
|
||||
create: item,
|
||||
});
|
||||
}
|
||||
|
||||
items = await this.prisma.contactInfo.findMany({
|
||||
orderBy: { order: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
const values = new Map(settings.map((item) => [item.key, String(item.value ?? "")]));
|
||||
const read = (...keys: string[]) => keys.map((key) => values.get(key)).find((value) => value?.trim()) || "";
|
||||
const phone = read("CONTACT_PHONE", "contact_phone");
|
||||
const email = read("CONTACT_EMAIL", "contact_email");
|
||||
const address = read("CONTACT_ADDRESS", "contact_address");
|
||||
return [
|
||||
{ key: "phone", title: "تلفنهای تماس", value: phone, icon: "phone", order: 1 },
|
||||
{ key: "email", title: "پست الکترونیک", value: email, icon: "mail", order: 2 },
|
||||
{ key: "address", title: "نشانی دفتر مرکزی", value: address, icon: "map-pin", order: 3 },
|
||||
].filter((item) => item.value.trim());
|
||||
}
|
||||
|
||||
async getAllSubmissions(page = 1, limit = 20, status?: string) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { MaintenanceModule } from './maintenance.module';
|
||||
import { assertStageScope } from '../admin/stage-author-restoration.service';
|
||||
|
||||
/** Exported for startup-contract testing; importing never starts a listener. */
|
||||
export async function startMaintenance(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
create = (module: typeof MaintenanceModule) => NestFactory.create(module),
|
||||
) {
|
||||
// Deny before connecting to any infrastructure.
|
||||
assertStageScope(env);
|
||||
const port = Number(env.PORT);
|
||||
if (!/^\d+$/.test(env.PORT || '') || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Explicit valid maintenance PORT required');
|
||||
}
|
||||
const app = await create(MaintenanceModule);
|
||||
app.setGlobalPrefix('api');
|
||||
app.enableShutdownHooks();
|
||||
await app.listen(port, '127.0.0.1');
|
||||
return app;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
startMaintenance().catch(() => {
|
||||
// Do not emit connection strings or credentials on startup failure.
|
||||
console.error('Maintenance startup failed');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
/** Connection lifecycle only: deliberately bypass PrismaService's startup DDL. */
|
||||
@Injectable()
|
||||
export class MaintenancePrismaService extends PrismaService {
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Controller, ForbiddenException, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
|
||||
@Controller('admin/users')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
export class MaintenanceController {
|
||||
constructor(private readonly restoration: StageAuthorRestorationService) {}
|
||||
|
||||
@Post('stage-author-restoration')
|
||||
async restoreStageAuthors(@Req() req: Request) {
|
||||
// Never trust proxy headers for this administrative operation.
|
||||
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket?.remoteAddress || '')) {
|
||||
throw new ForbiddenException('Loopback maintenance endpoint only');
|
||||
}
|
||||
return this.restoration.restoreStageAuthors();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 546 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user