Compare commits

..

No commits in common. "main" and "feat/order-expiry-workflow" have entirely different histories.

38 changed files with 83 additions and 1001 deletions

View File

@ -23,16 +23,15 @@ steps:
- name: Deploy - name: Deploy
image: appleboy/drone-ssh image: appleboy/drone-ssh
settings: settings:
host: manicandles-backend.midastix.com host: api.midastix.com
username: manicandle-backend username: manicandle-backend
key: key:
from_secret: server_ssh_pkey from_secret: server_ssh_pkey
port: 22 port: 22
command_timeout: 3m command_timeout: 3m
script: script:
- set -e
- echo "Deploying manicandle-backend" - echo "Deploying manicandle-backend"
- sudo -n /opt/deployable/manicandle-backend/docker/deploy.sh - sudo /opt/deployable/manicandle-backend/docker/deploy.sh
- echo "Deployment completed" - echo "Deployment completed"
when: when:
branch: branch:

View File

@ -14,10 +14,5 @@ RECOVERY_TTL_MINUTES=15
# RECOVERY_URL=https://shop.example.com/reset # RECOVERY_URL=https://shop.example.com/reset
DATABASE_POOL_SIZE=10 DATABASE_POOL_SIZE=10
# Reverse proxies whose X-Forwarded-For is trusted for client IPs (rate limits).
# Comma-separated IPs, CIDRs, or loopback/linklocal/uniquelocal. Empty = trust none.
# Behind the local Nginx plus the frontend server's Nginx, list both hops, e.g.:
# TRUST_PROXY=loopback,172.17.0.0/16,<frontend server IP>
# Optional; defaults to true only in development. # Optional; defaults to true only in development.
# SWAGGER_ENABLED=true # SWAGGER_ENABLED=true

View File

@ -7,47 +7,27 @@ on:
jobs: jobs:
quality: quality:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: node:24.15-bookworm
timeout-minutes: 30
env:
DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
TEST_DATABASE_URL: ''
steps:
- uses: https://github.com/actions/checkout@v4
- name: Install locked dependencies
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile
- name: Audit production dependencies
run: pnpm security:audit
- name: Generate Prisma client
run: pnpm db:generate
- name: Validate embedded migration upgrade and schema drift
run: pnpm db:test
- name: Formatting, types, tooling, coverage and build
run: pnpm check
native-postgres:
runs-on: ubuntu-latest
container: node:24.15-bookworm
timeout-minutes: 15
services: services:
postgres: postgres:
image: postgres:17 image: postgres:17
env: env:
POSTGRES_USER: mani POSTGRES_USER: mani
POSTGRES_PASSWORD: ${{ secrets.CI_POSTGRES_PASSWORD }} POSTGRES_PASSWORD: ci_only_password
POSTGRES_DB: mani_ci POSTGRES_DB: mani_ci
options: >- options: >-
--health-cmd "pg_isready -U mani -d mani_ci" --health-cmd "pg_isready -U mani -d mani_ci"
--health-interval 5s --health-timeout 5s --health-retries 10 --health-interval 5s --health-timeout 5s --health-retries 10
env: env:
DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
TEST_DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci TEST_DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
steps: steps:
- uses: https://github.com/actions/checkout@v4 - uses: actions/checkout@v4
- name: Install locked dependencies - uses: actions/setup-node@v4
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile with:
- name: Generate Prisma client node-version: '24'
run: pnpm db:generate - run: npm install --global pnpm@11.19.0
- name: Validate native migration upgrade and schema drift - run: pnpm install --frozen-lockfile
run: node scripts/verify-migrations.mjs - run: pnpm security:audit
- name: Require native concurrency tests without skips - run: pnpm db:generate
run: pnpm test:native - run: node scripts/verify-migrations.mjs
- run: pnpm check

View File

@ -98,5 +98,3 @@ Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-a
Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md). Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md).
Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md). Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md).
Production verification gates and launch procedure: see [Phase 6A runbook](docs/production-readiness.md).

View File

@ -25,13 +25,3 @@ Stock quantities are integers. Opening stock is an adjustment. Adjustments requi
Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes. Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes.
Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2. Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2.
## Product photos
| Method | Path | Permission | Request / result |
| ------ | -------------------------------------------------------- | ----------------- | -------------------------------------------------------------------- |
| POST | /products/:id/images | catalog.manage | multipart `file`: JPEG, PNG or WebP up to 2 MiB → id, mimeType, size |
| DELETE | /products/:id/images/:imageId | catalog.manage | 204; 404 if missing or out of scope |
| GET | /storefront/:organizationId/products/:id/images/:imageId | Public; throttled | Image bytes for published products only; cached publicly for one day |
The file signature must match the declared type, so renamed scripts or SVGs are rejected. A product holds at most 8 photos, ordered by upload; the first is the main photo. Storefront lists include `images` with the main photo ID; storefront and admin product details include all photos. Images are immutable rows; replace one by deleting and uploading again. Archived products cannot change photos.

View File

@ -1,27 +1,26 @@
# Phase 1B: identity and access API # Phase 1B: identity and access API
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. Customers create their own accounts with `/auth/register`; there is no public owner-creation endpoint. Staff accounts are provisioned by authorized administrators. Email verification is not yet implemented. All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. There are no public account-creation or owner-creation endpoints. Staff account provisioning is available to authorized administrators; storefront self-registration and verified email onboarding can be added with the customer milestone.
## Endpoints ## Endpoints
| Method | Path | Permission | Request / result | | Method | Path | Permission | Request / result |
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------ | | ------ | ---------------------- | ------------------ | ------------------------------------------------------------------- |
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt | | POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
| POST | /auth/register | Public; throttled | organizationId, email, name, password → active customer + session; 409 duplicate; 10/hour per IP | | GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions | | POST | /auth/logout | Authenticated | Revoke current session; 204 |
| POST | /auth/logout | Authenticated | Revoke current session; 204 | | POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 | | POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured | | POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once | | GET | /users | users.read | Paginated safe user records |
| GET | /users | users.read | Paginated safe user records | | POST | /users | users.create | name, email, password → PENDING account |
| POST | /users | users.create | name, email, password → PENDING account | | PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED | | PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments | | GET | /roles/permissions | roles.read | Current permission catalogue |
| GET | /roles/permissions | roles.read | Current permission catalogue | | GET | /roles | roles.read | Paginated roles |
| GET | /roles | roles.read | Paginated roles | | POST | /roles | roles.manage | name, permissions |
| POST | /roles | roles.manage | name, permissions | | PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions | | GET | /audit-events | audit.read | Paginated append-only organization audit history |
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
List queries accept `limit` (1–100, default 25) and `offset` (0–10000, default 0). Unknown fields, malformed UUIDs, duplicate role assignments/permissions and unknown permissions are rejected. Errors use Nest's JSON error contract: 400 invalid input, 401 unauthenticated, 403 denied, 404 missing/out-of-scope target, 409 duplicate record, 429 throttled, 503 unavailable. List queries accept `limit` (1–100, default 25) and `offset` (0–10000, default 0). Unknown fields, malformed UUIDs, duplicate role assignments/permissions and unknown permissions are rejected. Errors use Nest's JSON error contract: 400 invalid input, 401 unauthenticated, 403 denied, 404 missing/out-of-scope target, 409 duplicate record, 429 throttled, 503 unavailable.
@ -37,7 +36,7 @@ Example login:
## Access rules ## Access rules
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. Staff-created accounts have no roles and cannot sign in until approved. Self-registered customers are active immediately with no roles: they can use their own cart, checkout, addresses, orders and wishlist, and nothing that requires a permission. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions. Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. New accounts have no roles and cannot sign in until approved. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them. Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them.

View File

@ -1,42 +0,0 @@
# Phase 6A: release gates and production readiness
This milestone prepares repeatable verification and the launch procedure. It does not deploy the service or establish that the production environment is ready.
## Required merge checks
The `Backend quality` workflow runs on feature/fix pushes, main pushes and pull requests targeting main. Two independent jobs must pass:
| Job | Evidence |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `quality` | Frozen dependency installation, production dependency audit, embedded migration deployment/status/drift, immutable migration hashes, formatting, Prisma validation, TypeScript, tooling tests, coverage and compilation. |
| `native-postgres` | PostgreSQL 17 migration deployment/status/drift and the existing checkout, inventory, recovery and outbox concurrency tests. The gate fails on missing configuration, failures, empty results or any skipped/todo test. |
Configure a Docker-capable Gitea runner with the existing `ubuntu-latest` label, able to pull Node/PostgreSQL images, GitHub checkout and npm packages. Both jobs explicitly run in `node:24.15-bookworm`; the native job reaches its database by the `postgres` service hostname. Absolute action URLs avoid dependence on the instance's default action host; see [Gitea action compatibility](https://docs.gitea.com/usage/actions/comparison/).
Enable Actions for the repository and instance if it is disabled. An unavailable Actions page does not establish whether execution is disabled or the viewer lacks permission; inspect the authenticated settings and runner status before claiming the gates are active.
Add repository Actions secret `CI_POSTGRES_PASSWORD`: a random alphanumeric password used only for the disposable CI PostgreSQL service. Alphanumeric characters keep the connection URL valid without URL encoding. CI tests create and drop isolated databases, so the CI role needs `CREATEDB`. Never supply a production database URL or credentials. No service port is published to the runner host.
Express's transitive `proxy-addr` is pinned to 2.0.8 through the existing workspace override mechanism to address [GHSA-jqcg-44mw-7w3h](https://github.com/advisories/GHSA-jqcg-44mw-7w3h). Keep the production audit gate enabled; remove the override when the upstream dependency graph resolves a patched version itself.
In Gitea branch protection for `main`, require both job statuses using their exact names from the first successful run, require review, and disable force pushes. These repository settings are operational prerequisites; committing YAML does not enable branch protection or register a runner.
The existing `.drone.yml` is a separate build/deploy pipeline: a push to `main` publishes `git.midastix.com/ci-docker-repo-user/manicandle-backend:latest` and then invokes the server deployment script. It does not wait for the new Gitea jobs. Require the reviewed commit's checks before merging and avoid direct main pushes; otherwise deployment can run before validation completes. Its registry secrets are Drone repository secrets `docker_username` and `docker_password`, not `CI_POSTGRES_PASSWORD`. For `unauthorized: reqPackageAccess`, verify that the credentials belong to the target package owner or an authorized publisher, and use a Gitea token with package write access. Retrying a successful main build also runs deployment; server credentials and settings are managed manually by the operator.
Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only tests and the surrounding regression cases, provide `TEST_DATABASE_URL` for a disposable native PostgreSQL administrator connection, then run `pnpm test:native`. The native command uses the normal test helper to create separate randomly named databases and remove them afterward. Embedded PostgreSQL is useful for ordinary tests but does not prove multi-connection locking behavior.
## Staging and launch procedure
1. Select a reviewed commit whose two CI jobs pass. Record its SHA, the previous release SHA and migration manifest. Agree on the launch feature cut: payments, carriers, live marketing and automated scheduler invocation remain deferred.
2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). Rate limits key on the client IP: set `TRUST_PROXY` to exactly the proxy hops in front of the service (for example the backend host's Nginx or Docker bridge, plus the frontend server whose Nginx forwards `/api`), and make every hop append `X-Forwarded-For $proxy_add_x_forwarded_for`. Without it, all visitors share one proxy IP and one rate-limit bucket. Never trust all addresses; a direct caller could then spoof its IP.
3. Build the existing image or compiled application from that exact commit. For a source installation: `pnpm install --frozen-lockfile`, `pnpm db:generate`, `pnpm build`. The current Dockerfile is a development-derived build; non-root runtime, graceful shutdown verification, image scanning and a tested deployment definition remain launch work, not proven by this CI milestone.
4. Take a database backup and restore it into isolated staging. Verify representative immutable audit, order, supplier-payment and inventory records after restore. Keep production secrets and outbound provider access out of the staging restore.
5. Run `pnpm migrations:check`, then `pnpm db:deploy` and `pnpm db:status` against staging with migration credentials. Start the built service with restricted application credentials. Verify `/api/v1/health/live` and `/api/v1/health/ready`; readiness must fail when PostgreSQL is unavailable.
6. Smoke-test login, denied/foreign-organization access, checkout and cancellation/hold release, procurement and stock reads, and expiry replay using staging identities. Confirm errors/logs omit credentials, tokens, addresses and document bodies. Exercise the deployment's shutdown/restart behavior before enabling traffic.
7. After the restore drill and staging checks pass, take a fresh production backup, apply reviewed additive migrations, deploy the same artifact and verify readiness before routing traffic. Keep a named operator monitoring health, errors, latency, database connections and integrity-sensitive flows during the first hour. Define alert destinations and acceptable baselines for the actual environment before launch.
## Rollback and remaining decisions
Stop scheduler invocation and route traffic back to the previous compatible application artifact if readiness, authentication, stock integrity or error/latency checks regress. Preserve additive tables, audit history, completed expiry runs and released holds; an application rollback cannot reopen cancelled orders. Never edit committed migration SQL or reverse financial/stock history with database deletes. A destructive schema rollback or database restore requires a separate incident decision, an assessed data-loss window and reconciliation.
Before public launch, the operator still needs to select the host/database/secret store, enable and observe both CI jobs, configure branch protection, validate backup restoration, complete monitoring and incident ownership, verify the runtime container/process lifecycle, settle tax/shipping/retention policy and perform deployed-environment security testing. Live providers and SaaS tenancy/billing remain separate decisions.

View File

@ -74,10 +74,6 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil
- 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones. - 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones.
- 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones. - 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones.
## Phase 6: Production readiness
- 6A (release gates implemented; operational activation pending): separate embedded quality and native PostgreSQL concurrency jobs, fail-closed native test evidence, and a staging/backup/rollback runbook. Runner/secret setup, required branch checks, observed remote CI, hardened runtime, deployment infrastructure, restore drills, monitoring and live launch remain operational or later milestones.
## Definition of done for every feature ## Definition of done for every feature
Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass. Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass.

View File

@ -19,9 +19,7 @@
"db:validate": "prisma validate", "db:validate": "prisma validate",
"db:migrate": "prisma migrate dev", "db:migrate": "prisma migrate dev",
"db:deploy": "prisma migrate deploy", "db:deploy": "prisma migrate deploy",
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:tooling && pnpm test:coverage && pnpm build", "check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:coverage && pnpm build",
"test:tooling": "node --test scripts/test/*.test.mjs",
"test:native": "node scripts/test-native.mjs",
"start:watch": "node --watch dist/main.js", "start:watch": "node --watch dist/main.js",
"db:status": "prisma migrate status", "db:status": "prisma migrate status",
"bootstrap:owner": "node dist/cli/bootstrap-owner.js", "bootstrap:owner": "node dist/cli/bootstrap-owner.js",
@ -41,10 +39,10 @@
"@prisma/client": "^7.0.0", "@prisma/client": "^7.0.0",
"dotenv": "^17.0.0", "dotenv": "^17.0.0",
"helmet": "^8.0.0", "helmet": "^8.0.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.0.2",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2", "rxjs": "^7.8.2",
"zod": "^4.6.7" "zod": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@electric-sql/pglite": "^0.5.8", "@electric-sql/pglite": "^0.5.8",

View File

@ -6,12 +6,10 @@ settings:
overrides: overrides:
'@prisma/config>deepmerge-ts': 8.0.0 '@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
prisma>mysql2: 3.23.1 prisma>mysql2: 3.23.1
'@nestjs/platform-express>multer': 2.5.0 '@nestjs/platform-express>multer': 2.4.0
'@nestjs/swagger>js-yaml': 5.4.1 '@nestjs/swagger>js-yaml': 5.4.1
ajv>fast-uri: 3.1.9 ajv>fast-uri: 3.1.8
express>proxy-addr: 2.0.8
importers: importers:
@ -42,8 +40,8 @@ importers:
specifier: ^8.0.0 specifier: ^8.0.0
version: 8.3.0 version: 8.3.0
nodemailer: nodemailer:
specifier: ^10.6.1 specifier: ^10.0.2
version: 10.6.1 version: 10.0.11
reflect-metadata: reflect-metadata:
specifier: ^0.2.2 specifier: ^0.2.2
version: 0.2.2 version: 0.2.2
@ -51,8 +49,8 @@ importers:
specifier: ^7.8.2 specifier: ^7.8.2
version: 7.8.2 version: 7.8.2
zod: zod:
specifier: ^4.6.7 specifier: ^4.0.0
version: 4.6.7 version: 4.5.4
devDependencies: devDependencies:
'@electric-sql/pglite': '@electric-sql/pglite':
specifier: ^0.5.8 specifier: ^0.5.8
@ -1341,8 +1339,8 @@ packages:
better-result@2.10.0: better-result@2.10.0:
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==} resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
body-parser@2.4.0: body-parser@2.3.0:
resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
engines: {node: '>=18'} engines: {node: '>=18'}
brace-expansion@2.1.4: brace-expansion@2.1.4:
@ -1612,8 +1610,8 @@ packages:
ee-first@1.1.1: ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
effect@3.22.5: effect@3.20.0:
resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==} resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==}
electron-to-chromium@1.5.422: electron-to-chromium@1.5.422:
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==} resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
@ -1728,8 +1726,8 @@ packages:
fast-safe-stringify@2.1.1: fast-safe-stringify@2.1.1:
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
fast-uri@3.1.9: fast-uri@3.1.8:
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
fb-watchman@2.0.2: fb-watchman@2.0.2:
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
@ -2221,8 +2219,8 @@ packages:
ms@2.1.3: ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
multer@2.5.0: multer@2.4.0:
resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==} resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==}
engines: {node: '>= 10.16.0'} engines: {node: '>= 10.16.0'}
mysql2@3.23.1: mysql2@3.23.1:
@ -2260,8 +2258,8 @@ packages:
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==} resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
nodemailer@10.6.1: nodemailer@10.0.11:
resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==} resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==}
engines: {node: '>=20.0.0'} engines: {node: '>=20.0.0'}
normalize-path@3.0.0: normalize-path@3.0.0:
@ -2451,8 +2449,8 @@ packages:
proper-lockfile@4.1.2: proper-lockfile@4.1.2:
resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==} resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
proxy-addr@2.0.8: proxy-addr@2.0.7:
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
engines: {node: '>= 0.10'} engines: {node: '>= 0.10'}
pure-rand@6.1.0: pure-rand@6.1.0:
@ -2461,8 +2459,8 @@ packages:
pure-rand@7.0.1: pure-rand@7.0.1:
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==} resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
qs@6.17.1: qs@6.16.0:
resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}
engines: {node: '>=0.6'} engines: {node: '>=0.6'}
range-parser@1.3.0: range-parser@1.3.0:
@ -2850,8 +2848,8 @@ packages:
zeptomatch@2.1.0: zeptomatch@2.1.0:
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==} resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
zod@4.6.7: zod@4.5.4:
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==}
snapshots: snapshots:
@ -3455,7 +3453,7 @@ snapshots:
'@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
cors: 2.8.6 cors: 2.8.6
express: 5.2.1(supports-color@8.1.1) express: 5.2.1(supports-color@8.1.1)
multer: 2.5.0 multer: 2.4.0
path-to-regexp: 8.4.2 path-to-regexp: 8.4.2
tslib: 2.8.1 tslib: 2.8.1
transitivePeerDependencies: transitivePeerDependencies:
@ -3570,7 +3568,7 @@ snapshots:
dependencies: dependencies:
c12: 3.3.4 c12: 3.3.4
deepmerge-ts: 8.0.0 deepmerge-ts: 8.0.0
effect: 3.22.5 effect: 3.20.0
empathic: 2.0.0 empathic: 2.0.0
transitivePeerDependencies: transitivePeerDependencies:
- magicast - magicast
@ -4042,7 +4040,7 @@ snapshots:
ajv@8.20.0: ajv@8.20.0:
dependencies: dependencies:
fast-deep-equal: 3.1.3 fast-deep-equal: 3.1.3
fast-uri: 3.1.9 fast-uri: 3.1.8
json-schema-traverse: 1.0.0 json-schema-traverse: 1.0.0
require-from-string: 2.0.2 require-from-string: 2.0.2
@ -4141,7 +4139,7 @@ snapshots:
better-result@2.10.0: {} better-result@2.10.0: {}
body-parser@2.4.0(supports-color@8.1.1): body-parser@2.3.0(supports-color@8.1.1):
dependencies: dependencies:
bytes: 3.1.2 bytes: 3.1.2
content-type: 2.1.0 content-type: 2.1.0
@ -4149,7 +4147,7 @@ snapshots:
http-errors: 2.0.1 http-errors: 2.0.1
iconv-lite: 0.7.3 iconv-lite: 0.7.3
on-finished: 2.4.1 on-finished: 2.4.1
qs: 6.17.1 qs: 6.16.0
raw-body: 3.0.2 raw-body: 3.0.2
type-is: 2.1.0 type-is: 2.1.0
transitivePeerDependencies: transitivePeerDependencies:
@ -4381,7 +4379,7 @@ snapshots:
ee-first@1.1.1: {} ee-first@1.1.1: {}
effect@3.22.5: effect@3.20.0:
dependencies: dependencies:
'@standard-schema/spec': 1.1.0 '@standard-schema/spec': 1.1.0
fast-check: 3.23.2 fast-check: 3.23.2
@ -4489,7 +4487,7 @@ snapshots:
express@5.2.1(supports-color@8.1.1): express@5.2.1(supports-color@8.1.1):
dependencies: dependencies:
accepts: 2.0.0 accepts: 2.0.0
body-parser: 2.4.0(supports-color@8.1.1) body-parser: 2.3.0(supports-color@8.1.1)
content-disposition: 1.1.0 content-disposition: 1.1.0
content-type: 1.0.5 content-type: 1.0.5
cookie: 0.7.2 cookie: 0.7.2
@ -4507,8 +4505,8 @@ snapshots:
on-finished: 2.4.1 on-finished: 2.4.1
once: 1.4.0 once: 1.4.0
parseurl: 1.3.3 parseurl: 1.3.3
proxy-addr: 2.0.8 proxy-addr: 2.0.7
qs: 6.17.1 qs: 6.16.0
range-parser: 1.3.0 range-parser: 1.3.0
router: 2.2.0(supports-color@8.1.1) router: 2.2.0(supports-color@8.1.1)
send: 1.2.1(supports-color@8.1.1) send: 1.2.1(supports-color@8.1.1)
@ -4537,7 +4535,7 @@ snapshots:
fast-safe-stringify@2.1.1: {} fast-safe-stringify@2.1.1: {}
fast-uri@3.1.9: {} fast-uri@3.1.8: {}
fb-watchman@2.0.2: fb-watchman@2.0.2:
dependencies: dependencies:
@ -5175,7 +5173,7 @@ snapshots:
ms@2.1.3: {} ms@2.1.3: {}
multer@2.5.0: multer@2.4.0:
dependencies: dependencies:
append-field: 1.0.0 append-field: 1.0.0
busboy: 1.6.0 busboy: 1.6.0
@ -5213,7 +5211,7 @@ snapshots:
node-releases@2.0.54: {} node-releases@2.0.54: {}
nodemailer@10.6.1: {} nodemailer@10.0.11: {}
normalize-path@3.0.0: {} normalize-path@3.0.0: {}
@ -5384,7 +5382,7 @@ snapshots:
retry: 0.12.0 retry: 0.12.0
signal-exit: 3.0.7 signal-exit: 3.0.7
proxy-addr@2.0.8: proxy-addr@2.0.7:
dependencies: dependencies:
forwarded: 0.2.0 forwarded: 0.2.0
ipaddr.js: 1.9.1 ipaddr.js: 1.9.1
@ -5393,7 +5391,7 @@ snapshots:
pure-rand@7.0.1: {} pure-rand@7.0.1: {}
qs@6.17.1: qs@6.16.0:
dependencies: dependencies:
es-define-property: 1.0.1 es-define-property: 1.0.1
side-channel: 1.1.1 side-channel: 1.1.1
@ -5601,7 +5599,7 @@ snapshots:
formidable: 3.5.4 formidable: 3.5.4
methods: 1.1.2 methods: 1.1.2
mime: 2.6.0 mime: 2.6.0
qs: 6.17.1 qs: 6.16.0
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@ -5793,4 +5791,4 @@ snapshots:
grammex: 3.1.13 grammex: 3.1.13
graphmatch: 1.1.1 graphmatch: 1.1.1
zod@4.6.7: {} zod@4.5.4: {}

View File

@ -7,9 +7,7 @@ allowBuilds:
unrs-resolver: true unrs-resolver: true
overrides: overrides:
'@prisma/config>deepmerge-ts': 8.0.0 '@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
'prisma>mysql2': 3.23.1 'prisma>mysql2': 3.23.1
'@nestjs/platform-express>multer': 2.5.0 '@nestjs/platform-express>multer': 2.4.0
'@nestjs/swagger>js-yaml': 5.4.1 '@nestjs/swagger>js-yaml': 5.4.1
'ajv>fast-uri': 3.1.9 'ajv>fast-uri': 3.1.8
'express>proxy-addr': 2.0.8

View File

@ -19,7 +19,6 @@ model Product {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
variants ProductVariant[] variants ProductVariant[]
groups ProductGroup[] groups ProductGroup[]
images ProductImage[]
@@unique([organizationId, slug]) @@unique([organizationId, slug])
@@unique([id, organizationId]) @@unique([id, organizationId])
@@index([organizationId, status, createdAt, id]) @@index([organizationId, status, createdAt, id])

View File

@ -56,6 +56,5 @@
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043", "20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396", "20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471", "20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471",
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff", "20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff"
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb"
} }

View File

@ -1,9 +0,0 @@
CREATE TABLE product_images (
id UUID NOT NULL, product_id UUID NOT NULL, organization_id UUID NOT NULL,
mime_type VARCHAR(32) NOT NULL, sha256 CHAR(64) NOT NULL, size INTEGER NOT NULL,
content BYTEA NOT NULL, created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT product_images_pkey PRIMARY KEY (id),
CONSTRAINT product_images_product_id_organization_id_fkey FOREIGN KEY (product_id, organization_id) REFERENCES products(id, organization_id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT product_image_valid CHECK (mime_type IN ('image/jpeg', 'image/png', 'image/webp') AND size BETWEEN 1 AND 2097152 AND octet_length(content) = size AND sha256 ~ '^[a-f0-9]{64}$')
);
CREATE INDEX product_images_product_id_created_at_id_idx ON product_images (product_id, created_at, id);

View File

@ -1,13 +0,0 @@
model ProductImage {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
mimeType String @map("mime_type") @db.VarChar(32)
sha256 String @db.Char(64)
size Int
content Bytes @db.ByteA
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Cascade)
@@index([productId, createdAt, id])
@@map("product_images")
}

View File

@ -1,83 +0,0 @@
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
export function assertNativeReport(report) {
const nativeTests = (report.testResults ?? []).flatMap((suite) =>
(suite.assertionResults ?? []).filter((test) =>
test.fullName.includes('native PostgreSQL'),
),
);
if (
report.success !== true ||
nativeTests.length < 6 ||
!(report.numTotalTests > 0) ||
report.numPassedTests !== report.numTotalTests ||
report.numPendingTests !== 0 ||
report.numTodoTests !== 0 ||
report.numRuntimeErrorTestSuites !== 0
) {
throw new Error(
'Native PostgreSQL gate requires all six concurrency checks and no skipped tests',
);
}
}
function run() {
const value = process.env.TEST_DATABASE_URL;
if (
!value ||
!URL.canParse(value) ||
!['postgres:', 'postgresql:'].includes(new URL(value).protocol)
) {
throw new Error(
'TEST_DATABASE_URL must identify a disposable native PostgreSQL database',
);
}
const directory = mkdtempSync(join(tmpdir(), 'mani-native-'));
try {
const reportPath = join(directory, 'report.json');
const child = spawnSync(
process.execPath,
[
'--experimental-vm-modules',
'node_modules/jest/bin/jest.js',
'--runInBand',
'--runTestsByPath',
'test/checkout-concurrency.spec.ts',
'test/events-concurrency.spec.ts',
'test/inventory.spec.ts',
'test/migration-integrity.spec.ts',
'--json',
'--outputFile',
reportPath,
],
{ stdio: 'inherit', env: process.env },
);
if (child.error) throw new Error('Could not start native PostgreSQL tests');
if (child.status !== 0) throw new Error('Native PostgreSQL tests failed');
assertNativeReport(JSON.parse(readFileSync(reportPath, 'utf8')));
console.log('Native PostgreSQL gate passed: no selected tests skipped');
} finally {
rmSync(directory, { recursive: true, force: true });
}
}
if (
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
try {
run();
} catch (error) {
// Database credentials and provider errors must not appear in gate diagnostics.
console.error(
error instanceof Error && error.message.startsWith('Native PostgreSQL')
? error.message
: 'Native gate failed; check TEST_DATABASE_URL and test output',
);
process.exitCode = 1;
}
}

View File

@ -1,55 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { assertNativeReport } from '../test-native.mjs';
const passing = {
success: true,
numTotalTests: 6,
numPassedTests: 6,
numPendingTests: 0,
numTodoTests: 0,
numRuntimeErrorTestSuites: 0,
testResults: [
{
assertionResults: Array.from({ length: 6 }, () => ({
fullName: 'native PostgreSQL concurrency check',
})),
},
],
};
test('requires complete passing evidence, including zero skipped tests', () => {
assert.doesNotThrow(() => assertNativeReport(passing));
for (const changed of [
{ success: false },
{ numTotalTests: 0, numPassedTests: 0 },
{ numPassedTests: 5 },
{ numPendingTests: 1 },
{ numTodoTests: 1 },
{ numRuntimeErrorTestSuites: 1 },
{ testResults: [] },
{
testResults: [
{ assertionResults: [{ fullName: 'ordinary embedded test' }] },
],
},
])
assert.throws(() => assertNativeReport({ ...passing, ...changed }));
});
test('rejects absent or invalid database configuration without leaking it', () => {
for (const value of [
'',
'https://user:private-password@localhost/db',
'invalid',
]) {
const child = spawnSync(process.execPath, ['scripts/test-native.mjs'], {
env: { ...process.env, TEST_DATABASE_URL: value },
encoding: 'utf8',
});
assert.equal(child.status, 1);
assert.match(child.stderr, /Native gate failed/);
assert.doesNotMatch(child.stderr, /private-password/);
}
});

View File

@ -1,16 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
test('Express rejects IPv4 peers outside the configured trust subnet', () => {
const require = createRequire(import.meta.url);
const platformRequire = createRequire(
require.resolve('@nestjs/platform-express'),
);
const expressRequire = createRequire(platformRequire.resolve('express'));
const proxyaddr = expressRequire('proxy-addr');
assert.equal(proxyaddr.compile('::ffff:10.0.0.0/8')('203.0.113.10'), false);
const trust = proxyaddr.compile('10.0.0.0/8');
assert.equal(trust('10.1.2.3'), true);
assert.equal(trust('203.0.113.10'), false);
});

View File

@ -9,11 +9,6 @@ import { ProductsController } from './products.controller';
import { GroupsController } from './groups.controller'; import { GroupsController } from './groups.controller';
import { StorefrontController } from './storefront.controller'; import { StorefrontController } from './storefront.controller';
import { StorefrontGuard } from './storefront.guard'; import { StorefrontGuard } from './storefront.guard';
import { ProductImageStore } from './product-image.store';
import {
ProductImagesController,
StorefrontImagesController,
} from './product-images.controller';
@Module({ @Module({
imports: [DatabaseModule, IdentityModule], imports: [DatabaseModule, IdentityModule],
@ -23,14 +18,7 @@ import {
GroupStore, GroupStore,
StorefrontStore, StorefrontStore,
StorefrontGuard, StorefrontGuard,
ProductImageStore,
],
controllers: [
ProductsController,
GroupsController,
StorefrontController,
ProductImagesController,
StorefrontImagesController,
], ],
controllers: [ProductsController, GroupsController, StorefrontController],
}) })
export class CatalogModule {} export class CatalogModule {}

View File

@ -1,38 +0,0 @@
import { AppError } from '../common/errors/app-error';
import { fileDigest } from '../common/file-digest';
import type { UploadedDocument } from '../procurement/supplier-document-file';
export const MAX_PRODUCT_IMAGE_BYTES = 2 * 1024 * 1024;
export const MAX_PRODUCT_IMAGES = 8;
// The declared type must match the file's own signature, so a renamed script or SVG is rejected.
function signature(bytes: Buffer) {
if (bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')))
return 'image/png';
if (bytes.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')))
return 'image/jpeg';
if (
bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&
bytes.subarray(8, 12).toString('latin1') === 'WEBP'
)
return 'image/webp';
return null;
}
export function inspectProductImage(file?: UploadedDocument) {
const bytes = file?.buffer;
if (
!file ||
!bytes?.length ||
bytes.length > MAX_PRODUCT_IMAGE_BYTES ||
file.size !== bytes.length ||
signature(bytes) !== file.mimetype
)
throw new AppError('PRODUCT_IMAGE_INVALID');
return {
mimeType: file.mimetype,
sha256: fileDigest(bytes),
size: bytes.length,
content: Uint8Array.from(bytes),
};
}

View File

@ -1,87 +0,0 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { AppError } from '../common/errors/app-error';
import type { UploadedDocument } from '../procurement/supplier-document-file';
import { editableProduct } from './catalog.helpers';
import { inspectProductImage, MAX_PRODUCT_IMAGES } from './product-image-file';
export const imageSummary = {
id: true,
mimeType: true,
size: true,
createdAt: true,
} as const;
export const imageOrder = [
{ createdAt: 'asc' as const },
{ id: 'asc' as const },
];
@Injectable()
export class ProductImageStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
add(actor: Principal, productId: string, file?: UploadedDocument) {
const image = inspectProductImage(file);
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
await editableProduct(tx, actor.organizationId, productId);
// The product row lock serializes concurrent uploads against the quota.
await tx.$queryRaw`SELECT id FROM products WHERE id = ${productId}::uuid FOR UPDATE`;
if (
(await tx.productImage.count({ where: { productId } })) >=
MAX_PRODUCT_IMAGES
)
throw new AppError('PRODUCT_IMAGE_LIMIT');
const saved = await tx.productImage.create({
data: { ...image, productId, organizationId: actor.organizationId },
select: imageSummary,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'product.image_added',
productId,
);
return saved;
});
}
remove(actor: Principal, productId: string, imageId: string) {
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
await editableProduct(tx, actor.organizationId, productId);
const { count } = await tx.productImage.deleteMany({
where: { id: imageId, productId, organizationId: actor.organizationId },
});
if (!count) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'product.image_removed',
productId,
);
});
}
// Public: only images of published products in the requested organization.
async publicImage(
organizationId: string,
productId: string,
imageId: string,
) {
const image = await this.db.productImage.findFirst({
where: {
id: imageId,
productId,
organizationId,
product: { status: 'PUBLISHED' },
},
select: { mimeType: true, content: true },
});
if (!image) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
return image;
}
}

View File

@ -1,86 +0,0 @@
import {
Controller,
Delete,
Get,
HttpCode,
Param,
ParseUUIDPipe,
Post,
Res,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiProduces } from '@nestjs/swagger';
import type { Response } from 'express';
import {
CurrentPrincipal,
Public,
RequirePermission,
} from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import type { UploadedDocument } from '../procurement/supplier-document-file';
import { MAX_PRODUCT_IMAGE_BYTES } from './product-image-file';
import { ProductImageStore } from './product-image.store';
import { StorefrontGuard } from './storefront.guard';
@Controller('products/:id/images')
export class ProductImagesController {
constructor(private readonly images: ProductImageStore) {}
@Post()
@RequirePermission('catalog.manage')
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
required: ['file'],
properties: { file: { type: 'string', format: 'binary' } },
},
})
@UseInterceptors(
FileInterceptor('file', {
limits: { fileSize: MAX_PRODUCT_IMAGE_BYTES + 1, files: 1, fields: 0 },
}),
)
add(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@UploadedFile() file?: UploadedDocument,
) {
return this.images.add(actor, id, file);
}
@Delete(':imageId')
@RequirePermission('catalog.manage')
@HttpCode(204)
remove(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Param('imageId', ParseUUIDPipe) imageId: string,
) {
return this.images.remove(actor, id, imageId);
}
}
@Public()
@UseGuards(StorefrontGuard)
@Controller('storefront/:organizationId/products/:id/images')
export class StorefrontImagesController {
constructor(private readonly images: ProductImageStore) {}
@Get(':imageId')
@ApiProduces('image/jpeg', 'image/png', 'image/webp')
async get(
@Param('organizationId', ParseUUIDPipe) organizationId: string,
@Param('id', ParseUUIDPipe) id: string,
@Param('imageId', ParseUUIDPipe) imageId: string,
@Res() response: Response,
) {
const image = await this.images.publicImage(organizationId, id, imageId);
response.setHeader('Content-Type', image.mimeType);
response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Content-Security-Policy', 'sandbox');
// Image rows are never edited, so an ID always names the same bytes.
response.setHeader('Cache-Control', 'public, max-age=86400, immutable');
response.send(Buffer.from(image.content));
}
}

View File

@ -11,7 +11,6 @@ import {
validateGroups, validateGroups,
} from './catalog.helpers'; } from './catalog.helpers';
import type { CatalogQuery, ProductInput } from './catalog.schemas'; import type { CatalogQuery, ProductInput } from './catalog.schemas';
import { imageOrder, imageSummary } from './product-image.store';
@Injectable() @Injectable()
export class ProductStore { export class ProductStore {
@ -35,7 +34,6 @@ export class ProductStore {
include: { include: {
variants: { orderBy: { id: 'asc' } }, variants: { orderBy: { id: 'asc' } },
groups: { include: { group: true } }, groups: { include: { group: true } },
images: { orderBy: imageOrder, select: imageSummary },
}, },
}); });
} }

View File

@ -3,7 +3,6 @@ import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service'; import { DatabaseService } from '../database/database.service';
import { AppError } from '../common/errors/app-error'; import { AppError } from '../common/errors/app-error';
import type { CatalogQuery } from './catalog.schemas'; import type { CatalogQuery } from './catalog.schemas';
import { imageOrder } from './product-image.store';
const storefrontView = { const storefrontView = {
id: true, id: true,
@ -22,7 +21,6 @@ const storefrontView = {
attributes: true, attributes: true,
}, },
}, },
images: { orderBy: imageOrder, select: { id: true } },
groups: { groups: {
select: { select: {
group: { select: { id: true, name: true, slug: true, kind: true } }, group: { select: { id: true, name: true, slug: true, kind: true } },
@ -35,12 +33,7 @@ export class StorefrontStore {
list(organizationId: string, query: CatalogQuery) { list(organizationId: string, query: CatalogQuery) {
return this.db.product.findMany({ return this.db.product.findMany({
where: catalogWhere(organizationId, query, true), where: catalogWhere(organizationId, query, true),
select: { select: { id: true, name: true, slug: true },
id: true,
name: true,
slug: true,
images: { orderBy: imageOrder, take: 1, select: { id: true } },
},
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit, take: query.limit,
skip: query.offset, skip: query.offset,

View File

@ -10,21 +10,6 @@ export const COMMERCE_ERRORS = {
'Archived products cannot be edited', 'Archived products cannot be edited',
'Archived product mutation rejected', 'Archived product mutation rejected',
], ],
PRODUCT_IMAGE_NOT_FOUND: [
404,
'Product image not found',
'Scoped product image lookup failed',
],
PRODUCT_IMAGE_LIMIT: [
409,
'Product image limit reached',
'Product image quota exceeded',
],
PRODUCT_IMAGE_INVALID: [
400,
'Image must be a JPEG, PNG or WebP file up to 2 MiB',
'Product image upload bytes, size or type rejected',
],
VARIANT_NOT_FOUND: [ VARIANT_NOT_FOUND: [
404, 404,
'Product variant not found', 'Product variant not found',

View File

@ -1,5 +1,4 @@
import { identityEnvironmentShape, validateSmtp } from './identity-environment'; import { identityEnvironmentShape, validateSmtp } from './identity-environment';
import { isIP } from 'node:net';
import { z } from 'zod'; import { z } from 'zod';
const schema = z const schema = z
@ -13,17 +12,6 @@ const schema = z
.enum(['true', 'false']) .enum(['true', 'false'])
.transform((value) => value === 'true') .transform((value) => value === 'true')
.optional(), .optional(),
// Proxies whose X-Forwarded-For is believed. Never "true": any client could spoof its IP.
TRUST_PROXY: z
.string()
.default('')
.transform((value) =>
value
.split(',')
.map((entry) => entry.trim())
.filter(Boolean),
)
.pipe(z.array(z.string().refine(isTrustedProxy))),
DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10), DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10),
DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)), DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)),
CORS_ORIGINS: z CORS_ORIGINS: z
@ -51,18 +39,6 @@ const schema = z
export type Environment = z.infer<typeof schema>; export type Environment = z.infer<typeof schema>;
const PROXY_NAMES = ['loopback', 'linklocal', 'uniquelocal'];
function isTrustedProxy(entry: string): boolean {
if (PROXY_NAMES.includes(entry)) return true;
const [address, prefix, extra] = entry.split('/');
const family = isIP(address);
if (!family || extra !== undefined) return false;
if (prefix === undefined) return true;
return (
/^\d{1,3}$/.test(prefix) && Number(prefix) <= (family === 4 ? 32 : 128)
);
}
export function parseEnvironment(input: NodeJS.ProcessEnv): Environment { export function parseEnvironment(input: NodeJS.ProcessEnv): Environment {
const result = schema.safeParse(input); const result = schema.safeParse(input);
if (!result.success) { if (!result.success) {

View File

@ -10,8 +10,6 @@ export function configureApp(
app: INestApplication, app: INestApplication,
environment: Environment, environment: Environment,
): void { ): void {
if (environment.TRUST_PROXY.length)
(app as NestExpressApplication).set('trust proxy', environment.TRUST_PROXY);
app.setGlobalPrefix('api/v1'); app.setGlobalPrefix('api/v1');
app.use(helmet()); app.use(helmet());
app.use((_request: Request, response: Response, next: NextFunction) => { app.use((_request: Request, response: Response, next: NextFunction) => {

View File

@ -7,7 +7,7 @@ export class AuthRateGuard implements CanActivate {
constructor(private readonly limits: RateLimitService) {} constructor(private readonly limits: RateLimitService) {}
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>(); const request = context.switchToHttp().getRequest<Request>();
// request.ip honours X-Forwarded-For only from TRUST_PROXY hops; never arbitrary clients. // Express proxy trust remains disabled; never trust arbitrary forwarded IP headers.
await this.limits.consume(`auth-ip:${request.ip}`, 30, 60); await this.limits.consume(`auth-ip:${request.ip}`, 30, 60);
return true; return true;
} }

View File

@ -4,7 +4,6 @@ import {
Get, Get,
Header, Header,
HttpCode, HttpCode,
Ip,
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
@ -13,12 +12,7 @@ import { AuthService } from './auth.service';
import { AuthStore } from './auth.store'; import { AuthStore } from './auth.store';
import { AuthRateGuard } from './auth-rate.guard'; import { AuthRateGuard } from './auth-rate.guard';
import { CurrentPrincipal, Public } from './access.decorator'; import { CurrentPrincipal, Public } from './access.decorator';
import { import { loginSchema, type LoginInput } from './identity.schemas';
loginSchema,
registerSchema,
type LoginInput,
type RegisterInput,
} from './identity.schemas';
import type { Principal } from './identity.types'; import type { Principal } from './identity.types';
@Controller('auth') @Controller('auth')
@ -36,17 +30,6 @@ export class AuthController {
return this.auth.login(input); return this.auth.login(input);
} }
@Public()
@Post('register')
@HttpCode(201)
@Header('Cache-Control', 'no-store')
register(
@Body(new SchemaPipe(registerSchema)) input: RegisterInput,
@Ip() ip: string,
) {
return this.auth.register(input, ip);
}
@Get('me') @Get('me')
@Header('Cache-Control', 'no-store') @Header('Cache-Control', 'no-store')
me(@CurrentPrincipal() principal: Principal) { me(@CurrentPrincipal() principal: Principal) {

View File

@ -6,7 +6,7 @@ import { AuthStore } from './auth.store';
import { PasswordService } from './password.service'; import { PasswordService } from './password.service';
import { RateLimitService } from './rate-limit.service'; import { RateLimitService } from './rate-limit.service';
import { issueToken } from './tokens'; import { issueToken } from './tokens';
import type { LoginInput, RegisterInput } from './identity.schemas'; import type { LoginInput } from './identity.schemas';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
@ -36,19 +36,6 @@ export class AuthService {
: 'ACCOUNT_INACTIVE'; : 'ACCOUNT_INACTIVE';
throw new AppError('AUTH_INVALID_CREDENTIALS', reason); throw new AppError('AUTH_INVALID_CREDENTIALS', reason);
} }
return this.startSession(user);
}
// Customers get an active account with no roles: cart, checkout, addresses and orders need only a session.
async register(input: RegisterInput, ip: string) {
await this.limits.consume(`register-ip:${ip}`, 10, 3600);
const { password, ...profile } = input;
const user = await this.store.createCustomer({
...profile,
passwordHash: await this.passwords.hash(password),
});
return this.startSession(user);
}
private async startSession(user: { id: string; passwordHash: string }) {
const { token, tokenHash } = issueToken(); const { token, tokenHash } = issueToken();
const expiresAt = new Date( const expiresAt = new Date(
Date.now() + this.env.SESSION_TTL_MINUTES * 60_000, Date.now() + this.env.SESSION_TTL_MINUTES * 60_000,

View File

@ -12,26 +12,6 @@ export class AuthStore {
where: { organizationId_email: { organizationId, email } }, where: { organizationId_email: { organizationId, email } },
}); });
} }
createCustomer(input: {
organizationId: string;
email: string;
name: string;
passwordHash: string;
}) {
return this.db.$transaction(async (tx) => {
const user = await tx.user.create({
data: { ...input, status: 'ACTIVE' },
});
await recordAudit(
tx,
user.organizationId,
user.id,
'user.registered',
user.id,
);
return user;
});
}
async createSession( async createSession(
userId: string, userId: string,
expectedHash: string, expectedHash: string,

View File

@ -14,9 +14,6 @@ export const loginSchema = z
password: z.string().min(1).max(128), password: z.string().min(1).max(128),
}) })
.strict(); .strict();
export const registerSchema = z
.object({ organizationId: z.uuid(), email, name, password })
.strict();
export const recoveryRequestSchema = loginSchema.omit({ password: true }); export const recoveryRequestSchema = loginSchema.omit({ password: true });
export const recoveryResetSchema = z export const recoveryResetSchema = z
.object({ .object({
@ -52,7 +49,6 @@ export const pageSchema = z
}) })
.strict(); .strict();
export type LoginInput = z.infer<typeof loginSchema>; export type LoginInput = z.infer<typeof loginSchema>;
export type RegisterInput = z.infer<typeof registerSchema>;
export type RecoveryInput = z.infer<typeof recoveryRequestSchema>; export type RecoveryInput = z.infer<typeof recoveryRequestSchema>;
export type CreateUserInput = z.infer<typeof createUserSchema>; export type CreateUserInput = z.infer<typeof createUserSchema>;
export type RoleInput = z.infer<typeof roleSchema>; export type RoleInput = z.infer<typeof roleSchema>;

View File

@ -19,10 +19,6 @@ export class RateLimitService {
THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END
RETURNING hits, expires_at AS "expiresAt" RETURNING hits, expires_at AS "expiresAt"
`; `;
// shortcut: ~1% of calls sweep expired windows; move to the scheduler once one runs in production.
if (Math.random() < 0.01)
await this.db
.$executeRaw`DELETE FROM rate_limits WHERE expires_at < NOW() - INTERVAL '1 hour'`;
if (row.hits > limit) if (row.hits > limit)
throw new AppError( throw new AppError(
'RATE_LIMITED', 'RATE_LIMITED',

View File

@ -1,95 +0,0 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
describe('customer self-registration', () => {
let ctx: IdentityApp;
const customer = {
email: 'Buyer@Example.com',
name: 'Asha Buyer',
password: 'a long enough customer password',
};
const register = (body: object) =>
ctx.api().post('/api/v1/auth/register').send(body);
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('creates an active role-less customer with a working session', async () => {
const response = await register({
organizationId: ctx.owner.organizationId,
...customer,
}).expect(201);
expect(response.body).toMatchObject({ tokenType: 'Bearer' });
expect(JSON.stringify(response.body)).not.toContain(customer.password);
const me = await ctx
.api()
.get('/api/v1/auth/me')
.auth(response.body.accessToken, { type: 'bearer' })
.expect(200);
expect(me.body.permissions).toEqual([]);
await ctx
.api()
.get('/api/v1/cart')
.auth(response.body.accessToken, { type: 'bearer' })
.expect(200);
await ctx
.api()
.get('/api/v1/users')
.auth(response.body.accessToken, { type: 'bearer' })
.expect(403);
const user = await ctx.db.user.findFirstOrThrow({
where: { email: 'buyer@example.com' },
include: { roles: true },
});
expect(user).toMatchObject({ status: 'ACTIVE', isOwner: false, roles: [] });
expect(
await ctx.db.auditEvent.count({
where: { action: 'user.registered', targetId: user.id },
}),
).toBe(1);
expect(
(await ctx.login('buyer@example.com', customer.password)).status,
).toBe(200);
});
it('rejects duplicates, weak passwords, unknown organizations and extra fields', async () => {
const organizationId = ctx.owner.organizationId;
await register({ organizationId, ...customer, email: 'dup@example.com' });
await register({
organizationId,
...customer,
email: 'DUP@example.com',
}).expect(409);
await register({ organizationId, ...customer, password: 'short' }).expect(
400,
);
await register({ ...customer, organizationId: randomUUID() }).expect(
(response) => expect(response.status).toBeGreaterThanOrEqual(400),
);
await register({ organizationId, ...customer, isOwner: true }).expect(400);
expect(
await ctx.db.user.count({ where: { email: 'dup@example.com' } }),
).toBe(1);
});
it('limits registrations per client address', async () => {
const organizationId = ctx.owner.organizationId;
for (let index = 0; index < 10; index++)
await register({
organizationId,
...customer,
email: `bulk${index}@example.com`,
}).expect(201);
await register({
organizationId,
...customer,
email: 'bulk-over@example.com',
}).expect(429);
});
});

View File

@ -27,28 +27,12 @@ describe('environment configuration', () => {
{ NODE_ENV: 'staging' }, { NODE_ENV: 'staging' },
{ CORS_ORIGINS: '*' }, { CORS_ORIGINS: '*' },
{ CORS_ORIGINS: 'https://shop.example.com/path' }, { CORS_ORIGINS: 'https://shop.example.com/path' },
{ TRUST_PROXY: 'true' },
{ TRUST_PROXY: '*' },
{ TRUST_PROXY: '2' },
{ TRUST_PROXY: '10.0.0.0/33' },
{ TRUST_PROXY: '10.0.0.1/8/1' },
{ TRUST_PROXY: 'proxy.example.com' },
])('rejects invalid configuration %j', (override) => { ])('rejects invalid configuration %j', (override) => {
expect(() => parseEnvironment({ ...valid, ...override })).toThrow( expect(() => parseEnvironment({ ...valid, ...override })).toThrow(
'Invalid environment', 'Invalid environment',
); );
}); });
it('parses trusted proxy addresses, subnets and named ranges', () => {
expect(parseEnvironment(valid).TRUST_PROXY).toEqual([]);
expect(
parseEnvironment({
...valid,
TRUST_PROXY: ' loopback, 172.17.0.0/16 ,203.0.113.7,::1/128',
}).TRUST_PROXY,
).toEqual(['loopback', '172.17.0.0/16', '203.0.113.7', '::1/128']);
});
it('does not leak credentials in validation errors', () => { it('does not leak credentials in validation errors', () => {
expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow( expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow(
'DATABASE_URL', 'DATABASE_URL',

View File

@ -90,23 +90,6 @@ describe('identity transactional failure paths', () => {
}); });
await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined(); await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined();
}); });
it('sweeps long-expired rate-limit windows', async () => {
const limits = ctx.app.get(RateLimitService);
await ctx.db.rateLimit.create({
data: { key: hashToken('stale-bucket'), hits: 1, expiresAt: new Date(0) },
});
const random = jest.spyOn(Math, 'random').mockReturnValue(0);
try {
await limits.consume('sweep-trigger', 100, 60);
} finally {
random.mockRestore();
}
expect(
await ctx.db.rateLimit.findUnique({
where: { key: hashToken('stale-bucket') },
}),
).toBeNull();
});
it('rechecks current permissions inside administration transactions', async () => { it('rechecks current permissions inside administration transactions', async () => {
const actor = await ctx.app.get(SessionStore).authenticate(ctx.token); const actor = await ctx.app.get(SessionStore).authenticate(ctx.token);
const ownerRole = await ctx.db.role.findFirstOrThrow({ const ownerRole = await ctx.db.role.findFirstOrThrow({

View File

@ -1,132 +0,0 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor, seedProduct } from './helpers/commerce';
const png = Buffer.concat([
Buffer.from('89504e470d0a1a0a', 'hex'),
Buffer.from('fake image body'),
]);
const webp = Buffer.concat([
Buffer.from('RIFF'),
Buffer.alloc(4),
Buffer.from('WEBPVP8 body'),
]);
describe('product images', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const upload = (
productId: string,
bytes = png,
contentType = 'image/png',
token = ctx.token,
) =>
ctx
.api()
.post(`/api/v1/products/${productId}/images`)
.auth(token, auth)
.attach('file', bytes, { filename: 'photo', contentType });
const storefront = (path: string) =>
ctx
.api()
.get(`/api/v1/storefront/${ctx.owner.organizationId}/products${path}`);
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('stores images and serves them publicly only for published products', async () => {
const { product } = await seedProduct(ctx);
const first = await upload(product.id).expect(201);
expect(first.body).toMatchObject({
mimeType: 'image/png',
size: png.length,
});
expect(first.body).not.toHaveProperty('content');
await upload(product.id, webp, 'image/webp').expect(201);
const path = `/${product.id}/images/${first.body.id}`;
await storefront(path).expect(404);
await ctx
.api()
.patch(`/api/v1/products/${product.id}/status`)
.auth(ctx.token, auth)
.send({ status: 'PUBLISHED' })
.expect(200);
const served = await storefront(path)
.buffer(true)
.parse((response, done) => {
const chunks: Buffer[] = [];
response.on('data', (chunk: Buffer) => chunks.push(chunk));
response.on('end', () => done(null, Buffer.concat(chunks)));
})
.expect(200);
expect(served.headers['content-type']).toBe('image/png');
expect(served.headers['cache-control']).toContain('public');
expect(Buffer.compare(served.body as Buffer, png)).toBe(0);
const detail = await storefront(`/${product.id}`).expect(200);
expect(detail.body.images).toHaveLength(2);
expect(detail.body.images[0]).toEqual({ id: first.body.id });
const list = await storefront('?limit=100').expect(200);
expect(
list.body.find((item: { id: string }) => item.id === product.id).images,
).toEqual([{ id: first.body.id }]);
await ctx
.api()
.get(`/api/v1/storefront/${randomUUID()}/products${path}`)
.expect(404);
});
it('rejects disguised, oversized and over-quota uploads', async () => {
const { product } = await seedProduct(ctx);
for (const [bytes, type] of [
[Buffer.from('<svg onload=alert(1)>'), 'image/png'],
[png, 'image/jpeg'],
[Buffer.from('<svg/>'), 'image/svg+xml'],
] as const)
expect(
(await upload(product.id, bytes, type).expect(400)).body.code,
).toBe('PRODUCT_IMAGE_INVALID');
const big = Buffer.concat([png, Buffer.alloc(2 * 1024 * 1024)]);
expect((await upload(product.id, big)).status).toBeGreaterThanOrEqual(400);
for (let index = 0; index < 8; index++)
await upload(product.id).expect(201);
expect((await upload(product.id).expect(409)).body.code).toBe(
'PRODUCT_IMAGE_LIMIT',
);
});
it('requires catalog.manage and organization scope to add or remove', async () => {
const { product } = await seedProduct(ctx);
const image = await upload(product.id).expect(201);
const customer = await secondActor(ctx);
await upload(product.id, png, 'image/png', customer.token).expect(403);
const foreign = await secondActor(ctx, false, ['catalog.manage']);
await upload(product.id, png, 'image/png', foreign.token).expect(404);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(foreign.token, auth)
.expect(404);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(ctx.token, auth)
.expect(204);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(ctx.token, auth)
.expect(404);
const admin = await ctx
.api()
.get(`/api/v1/products/${product.id}`)
.auth(ctx.token, auth)
.expect(200);
expect(admin.body.images).toEqual([]);
});
});

View File

@ -1,58 +0,0 @@
import 'reflect-metadata';
import { Controller, Get, Module, Req } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import type { Request } from 'express';
import request from 'supertest';
import { configureApp } from '../src/configure-app';
import { parseEnvironment } from '../src/config/environment';
@Controller('ip')
class IpController {
@Get()
ip(@Req() req: Request) {
return { ip: req.ip };
}
}
@Module({ controllers: [IpController] })
class IpModule {}
async function appWith(TRUST_PROXY?: string): Promise<INestApplication> {
const module = await Test.createTestingModule({
imports: [IpModule],
}).compile();
const app = module.createNestApplication();
configureApp(
app,
parseEnvironment({
DATABASE_URL: 'postgresql://localhost/mani',
TRUST_PROXY,
}),
);
await app.init();
return app;
}
const ipOf = async (app: INestApplication, forwarded: string) =>
(
await request(app.getHttpServer())
.get('/api/v1/ip')
.set('X-Forwarded-For', forwarded)
.expect(200)
).body.ip as string;
describe('client IP behind reverse proxies', () => {
it('ignores forwarded headers when no proxy is trusted', async () => {
const app = await appWith();
expect(await ipOf(app, '198.51.100.4')).not.toBe('198.51.100.4');
await app.close();
});
it('uses the forwarded client address from trusted hops only', async () => {
// supertest connects over loopback, standing in for the local Nginx.
const app = await appWith('loopback,203.0.113.7');
expect(await ipOf(app, '198.51.100.4, 203.0.113.7')).toBe('198.51.100.4');
// A client that skips the trusted frontend proxy cannot spoof an address.
expect(await ipOf(app, '198.51.100.4, 192.0.2.66')).toBe('192.0.2.66');
await app.close();
});
});