diff --git a/.env.example b/.env.example index e8ff62f..275378c 100644 --- a/.env.example +++ b/.env.example @@ -16,3 +16,16 @@ CRON_SECRET="change-me" # Optional: initial admin password used by `npm run db:seed` # SEED_ADMIN_PASSWORD="change-me" + +# ── Ticket attachment storage ─────────────────────────────────────────────── +# Default: keep attachment bytes in PostgreSQL. Set to "s3" for AWS S3, +# Cloudflare R2, MinIO, Backblaze B2, or another S3-compatible private bucket. +ATTACHMENT_STORAGE="database" +# ATTACHMENT_S3_BUCKET="openhosting-private" +# ATTACHMENT_S3_REGION="us-east-1" +# ATTACHMENT_S3_ENDPOINT="https://s3.example.com" +# ATTACHMENT_S3_ACCESS_KEY_ID="" +# ATTACHMENT_S3_SECRET_ACCESS_KEY="" +# ATTACHMENT_S3_FORCE_PATH_STYLE="false" +# ATTACHMENT_S3_PREFIX="attachments" +# ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS="300" diff --git a/docs/getting-started/environment.md b/docs/getting-started/environment.md index a963e02..540702f 100644 --- a/docs/getting-started/environment.md +++ b/docs/getting-started/environment.md @@ -13,6 +13,15 @@ currency and SMTP is configured in the admin panel instead — see | `SKIP_MIGRATIONS` | | `true` skips `prisma migrate deploy` in the container entrypoint (when migrations run elsewhere). | | `SEED_ADMIN_PASSWORD` | | Admin password used by `npm run db:seed`, applied only when the account is created. Defaults to `admin12345`. | | `SEED_ADMIN_EMAIL` | | Address of the admin account the seed creates. Defaults to `admin@example.com`; the installer writes the address you chose here so re-seeding never adds a second admin. | +| `ATTACHMENT_STORAGE` | | `database` (default) or `s3` for new ticket attachments. Existing rows retain their original backend. | +| `ATTACHMENT_S3_BUCKET` | S3 only | Private bucket used for attachments. | +| `ATTACHMENT_S3_REGION` | S3 only | Bucket signing region. Defaults to `us-east-1`; R2 commonly uses `auto`. | +| `ATTACHMENT_S3_ENDPOINT` | | Custom S3-compatible endpoint. Omit for AWS S3. | +| `ATTACHMENT_S3_ACCESS_KEY_ID` | | Static access key. Set together with the secret; omit both to use the AWS credential provider chain. | +| `ATTACHMENT_S3_SECRET_ACCESS_KEY` | | Static secret key. Never expose it to the browser. | +| `ATTACHMENT_S3_FORCE_PATH_STYLE` | | `true` for providers such as a local MinIO deployment that require path-style bucket URLs. | +| `ATTACHMENT_S3_PREFIX` | | Object-key prefix. Defaults to `attachments`. | +| `ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS` | | Signed download lifetime from 60 to 604800 seconds. Defaults to 300. | | `PORT` | | Port the server listens on (default `3000`). | | `NODE_ENV` | | Set to `production` in production (the image sets this). | | `SHADOW_DATABASE_URL` | | Only for generating new migrations locally — a spare database Prisma uses as a shadow. | diff --git a/docs/guides/tickets.md b/docs/guides/tickets.md index 0cf21e5..c14c8f7 100644 --- a/docs/guides/tickets.md +++ b/docs/guides/tickets.md @@ -41,9 +41,16 @@ default and need your own model API key — see [AI support](ai-support.md). ## Attachments Both customers and staff can attach files (up to 3 per message, 5 MB each). -Allowed types include images, PDF, plain text, ZIP and JSON. Files are stored in -the database and served through an authenticated download route — only the -ticket owner and staff can fetch them. +Allowed types include images, PDF, plain text, ZIP and JSON. PostgreSQL storage +is the zero-configuration default. Operators can instead use a private AWS S3, +Cloudflare R2, MinIO, Backblaze B2, or other S3-compatible bucket by setting +`ATTACHMENT_STORAGE=s3` and the `ATTACHMENT_S3_*` variables described in the +[environment reference](../getting-started/environment.md). + +Every download first passes through OpenHosting's authenticated route. Only the +ticket owner and staff are authorized; S3-backed files then receive a short-lived +signed download URL. Existing database-backed attachments continue to work after +switching new uploads to S3. ## Notifications diff --git a/package-lock.json b/package-lock.json index 3a53a9e..0f4f6e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,8 @@ "version": "0.5.1", "dependencies": { "@anthropic-ai/sdk": "^0.115.0", + "@aws-sdk/client-s3": "^3.1119.0", + "@aws-sdk/s3-request-presigner": "^3.1119.0", "@modelcontextprotocol/sdk": "^1.29.0", "@prisma/adapter-pg": "^7.8.0", "@prisma/client": "^7.8.0", @@ -77,6 +79,312 @@ } } }, + "node_modules/@aws-sdk/checksums": { + "version": "3.1000.29", + "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1000.29.tgz", + "integrity": "sha512-Dtu0gr4dnATZAPwEYbpCsG+MpLM7OAliy2gTepEFQwl1vZ6DL3QMH2FveMa3HLvPsOdhJsPRB3KtxVhph9T75A==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.1120.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1120.0.tgz", + "integrity": "sha512-UunWgNl/U8wIlxVRyhUPqlozFkUS88UqXjAH50XfPDXaZeK9P7KVYTAh4KREVrLPQTzPxVSbQGog3gHlc/P6vg==", + "dependencies": { + "@aws-sdk/checksums": "^3.1000.29", + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/credential-provider-node": "^3.972.81", + "@aws-sdk/middleware-sdk-s3": "^3.972.75", + "@aws-sdk/signature-v4-multi-region": "^3.996.46", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.977.9", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.977.9.tgz", + "integrity": "sha512-reqPFEQrZxDZpeGj4PFMepBeR5LGYHRqq/L0motTzgFkCRBA4rFdaVXDSLYyGHhxVz7sT2PDnPN9CluGSfgyJA==", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@aws-sdk/xml-builder": "^3.972.40", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.33.3", + "@smithy/signature-v4": "^5.6.12", + "@smithy/types": "^4.17.2", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.70", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.70.tgz", + "integrity": "sha512-H404B7dJl2mCrBqahDEYsanB0xhdDp6tXnXcTUnXmmpy2Q3J0Ho0bUajZ2jr/RdwzCyS59Gi8xXIFwPLGBl6Uw==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.72", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.72.tgz", + "integrity": "sha512-X98zYOrVOeuosCX+6ktf29FC2N2GHPLia7qv6mzPzTc+RPAuHWCDS++Z6JK7eGYqb/v6uaW7bAXaOvDBfol+0w==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.973.15", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.15.tgz", + "integrity": "sha512-Rykg6s5ceBuynMOGWgoowO4N+27JfnqXAnVaSunZl0hOO1XodSrxGNz6sCEbnmS0lAfQZDKyb3fbr46gSuv6Sg==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/credential-provider-env": "^3.972.70", + "@aws-sdk/credential-provider-http": "^3.972.72", + "@aws-sdk/credential-provider-login": "^3.972.77", + "@aws-sdk/credential-provider-process": "^3.972.70", + "@aws-sdk/credential-provider-sso": "^3.973.14", + "@aws-sdk/credential-provider-web-identity": "^3.972.76", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/credential-provider-imds": "^4.4.16", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.77", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.77.tgz", + "integrity": "sha512-Jb59xfEISoN5mmbnA+HYqdtrSX3CgCtJoof+V5D8/TgUI56W63GEEd5Y58WijU3Ou6+WEgaLD1feVzaRXV5IDQ==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.81", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.81.tgz", + "integrity": "sha512-Rml+WitoFvXmv6JZ18U/xGdGDGGvB/mOin0ya0lTnTrdC0Z1lrVxTYh7iNklZBcvcRMrs4DoEf6xy1KWyrLQQw==", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.70", + "@aws-sdk/credential-provider-http": "^3.972.72", + "@aws-sdk/credential-provider-ini": "^3.973.15", + "@aws-sdk/credential-provider-process": "^3.972.70", + "@aws-sdk/credential-provider-sso": "^3.973.14", + "@aws-sdk/credential-provider-web-identity": "^3.972.76", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/credential-provider-imds": "^4.4.16", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.70", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.70.tgz", + "integrity": "sha512-2ry03fGRJr4sV3jI+ocjj5JqALnFD6ymM5KiNCDZMvq8bX2GSbE0vji4aM43TVCl2nXqqLRZaUxdq/KeWRAY4Q==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.973.14", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.14.tgz", + "integrity": "sha512-jkhg/8ocAAoc0RFyLMhCw+/zZh7gystQgd4F4hznNa8P4Cc501PQmxd+jGLiMHodPJ+7Zv/3znM62gZojyasmA==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/token-providers": "3.1116.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.76", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.76.tgz", + "integrity": "sha512-d3AGyVu759PGr35mEB2s22xxlNEA5rpdxtSPJthfPFJvoQ8dt357iVPECqWfUxXp1toJAvKmbtcIYVGigaGsCA==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.972.75", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.75.tgz", + "integrity": "sha512-wMIsNumRVKaNMKhvU/s9VrdEwE8S6gSzXp4RygFG5BEMnGkkXf8cjh8zf7cKJBpUDpqTWqwbz5isEgp9rH6Lng==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/signature-v4-multi-region": "^3.996.46", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.997.44", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.44.tgz", + "integrity": "sha512-NhEgryjlBF9w38ZXqGymQV28IhkYa1mKhlbYnqIis57AYwWGVYfUPgg/qC2rLRqOUfblxx++irvju10kVTa8Vw==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/signature-v4-multi-region": "^3.996.46", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/s3-request-presigner": { + "version": "3.1120.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.1120.0.tgz", + "integrity": "sha512-KDPKX7uFulSb6AmWloSQRmHOm1ad5c9+W76ljxDmL4rndCYX4mBDdHwdWXIVNaLn6gXrm7G/3CQyiEdPe69lwQ==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/signature-v4-multi-region": "^3.996.46", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.46", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.46.tgz", + "integrity": "sha512-L+2xZTye/2T96f3lwCws0Zw6GG2JHZW9e8FpVgGBeeExSKyeoZ6CWRpBml/7DNiK/O26jrgPM9F+Ay8VkgzUWQ==", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@smithy/signature-v4": "^5.6.12", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1116.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1116.0.tgz", + "integrity": "sha512-ygIivKqh8aHzNkucOCXHyIBgBpLPfrSI0mCqXF+vLBsPTUKqj0VSqAY0GFPe7lQl4HntjOcQ+KSyS7oUV2C54Q==", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.974.5", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.5.tgz", + "integrity": "sha512-LkwLL2BLbC6wNNm4JaH9mbEqBMdOZCct6VAYqhdN4U1xrWM+fUJQEfbHwQgDypapOWTRtlk25akb5afM0P8CIQ==", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.40", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.40.tgz", + "integrity": "sha512-wlFmCIGUlwF4zx/kncw+bmxTQh1HeSJq4mYV/V5cZUSJadDP3kXvGW8Rn21cimj/7y9ju+47oYWXi97vF7czaA==", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -2315,6 +2623,81 @@ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true }, + "node_modules/@smithy/core": { + "version": "3.33.3", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.33.3.tgz", + "integrity": "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg==", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz", + "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.7.2.tgz", + "integrity": "sha512-nZyWTmSpJEXl6VtWVMBJve/7x12DZu6sIX1z1a+ZMaHlQQRs9Zpu6NbTe/gmxYXVRpkjxyDYpZ5gx2IM6f/Wkw==", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.11.3", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.11.3.tgz", + "integrity": "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA==", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.3.tgz", + "integrity": "sha512-7ImGm+FkHRLcBaRttIAMZ6bzJZWb2cJGoYjq46F2UjycujWzrL9GEN9h4w7eQyXJYnltrUhxbbieBAIRrdqpow==", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.17.2", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.17.2.tgz", + "integrity": "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA==", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@stablelib/base64": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", @@ -3372,6 +3755,11 @@ "url": "https://opencollective.com/express" } }, + "node_modules/bowser": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", + "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==" + }, "node_modules/brace-expansion": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", diff --git a/package.json b/package.json index 247b9c3..46f53bc 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,8 @@ }, "dependencies": { "@anthropic-ai/sdk": "^0.115.0", + "@aws-sdk/client-s3": "^3.1119.0", + "@aws-sdk/s3-request-presigner": "^3.1119.0", "@modelcontextprotocol/sdk": "^1.29.0", "@prisma/adapter-pg": "^7.8.0", "@prisma/client": "^7.8.0", diff --git a/prisma/migrations/z_11_attachment_storage/migration.sql b/prisma/migrations/z_11_attachment_storage/migration.sql new file mode 100644 index 0000000..2492dec --- /dev/null +++ b/prisma/migrations/z_11_attachment_storage/migration.sql @@ -0,0 +1,9 @@ +-- Existing attachment rows remain database-backed. New S3-backed rows keep +-- only an object key, so the byte column must become nullable. +ALTER TABLE "TicketAttachment" +ADD COLUMN "storageBackend" TEXT NOT NULL DEFAULT 'database', +ADD COLUMN "storageKey" TEXT, +ALTER COLUMN "data" DROP NOT NULL; + +CREATE INDEX "TicketAttachment_storageBackend_storageKey_idx" +ON "TicketAttachment"("storageBackend", "storageKey"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 031998f..1b8a5f2 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -593,16 +593,20 @@ model TicketMessage { createdAt DateTime @default(now()) } -// Stored in the database to stay infrastructure-free (5 MB cap per file). +// Database storage remains the default; S3-compatible storage keeps only a key. model TicketAttachment { - id String @id @default(cuid()) - messageId String - message TicketMessage @relation(fields: [messageId], references: [id], onDelete: Cascade) - filename String - mimeType String - size Int - data Bytes - createdAt DateTime @default(now()) + id String @id @default(cuid()) + messageId String + message TicketMessage @relation(fields: [messageId], references: [id], onDelete: Cascade) + filename String + mimeType String + size Int + storageBackend String @default("database") + storageKey String? + data Bytes? + createdAt DateTime @default(now()) + + @@index([storageBackend, storageKey]) } // ── Platform ──────────────────────────────────────────────────────────────── diff --git a/src/app/api/attachments/[id]/route.ts b/src/app/api/attachments/[id]/route.ts index 3aabb3d..98ff2f1 100644 --- a/src/app/api/attachments/[id]/route.ts +++ b/src/app/api/attachments/[id]/route.ts @@ -1,6 +1,10 @@ import { NextRequest, NextResponse } from "next/server"; import { db } from "@/lib/db"; import { getUser } from "@/lib/auth"; +import { + attachmentContentDisposition, + getAttachmentDownload, +} from "@/lib/storage/attachment-storage"; export async function GET( _request: NextRequest, @@ -22,11 +26,19 @@ export async function GET( return NextResponse.json({ error: "Not found" }, { status: 404 }); } - return new NextResponse(Buffer.from(attachment.data), { + const download = await getAttachmentDownload(attachment); + if (download.kind === "redirect") { + return NextResponse.redirect(download.url, { + status: 307, + headers: { "Cache-Control": "private, no-store" }, + }); + } + + return new NextResponse(download.data, { headers: { "Content-Type": attachment.mimeType, "Content-Length": String(attachment.size), - "Content-Disposition": `attachment; filename="${attachment.filename.replace(/"/g, "")}"`, + "Content-Disposition": attachmentContentDisposition(attachment.filename), "Cache-Control": "private, max-age=3600", }, }); diff --git a/src/lib/services/attachments.ts b/src/lib/services/attachments.ts index 670ed3a..c24c6fa 100644 --- a/src/lib/services/attachments.ts +++ b/src/lib/services/attachments.ts @@ -1,5 +1,9 @@ import "server-only"; import { db } from "@/lib/db"; +import { + deleteAttachmentObject, + storeAttachmentObject, +} from "@/lib/storage/attachment-storage"; const MAX_FILES = 3; const MAX_SIZE = 5 * 1024 * 1024; // 5 MB @@ -28,15 +32,28 @@ export async function saveTicketAttachments( } } for (const file of usable) { - await db.ticketAttachment.create({ - data: { - messageId, - filename: file.name, - mimeType: file.type, - size: file.size, - data: Buffer.from(await file.arrayBuffer()), - }, + const stored = await storeAttachmentObject({ + messageId, + filename: file.name, + mimeType: file.type, + data: Buffer.from(await file.arrayBuffer()), }); + try { + await db.ticketAttachment.create({ + data: { + messageId, + filename: file.name, + mimeType: file.type, + size: file.size, + ...stored, + }, + }); + } catch (error) { + if (stored.storageBackend === "s3" && stored.storageKey) { + await deleteAttachmentObject(stored.storageKey).catch(() => undefined); + } + throw error; + } } return null; } diff --git a/src/lib/storage/attachment-storage.test.ts b/src/lib/storage/attachment-storage.test.ts new file mode 100644 index 0000000..dca0b44 --- /dev/null +++ b/src/lib/storage/attachment-storage.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, test } from "vitest"; +import { + attachmentContentDisposition, + buildAttachmentStorageKey, + getAttachmentStorageConfig, +} from "@/lib/storage/attachment-storage"; + +describe("attachment storage configuration", () => { + test("uses database storage by default", () => { + expect(getAttachmentStorageConfig({})).toEqual({ backend: "database" }); + }); + + test("builds an S3-compatible client configuration", () => { + expect( + getAttachmentStorageConfig({ + ATTACHMENT_STORAGE: "s3", + ATTACHMENT_S3_BUCKET: "private-files", + ATTACHMENT_S3_REGION: "auto", + ATTACHMENT_S3_ENDPOINT: "https://objects.example.test", + ATTACHMENT_S3_ACCESS_KEY_ID: "key", + ATTACHMENT_S3_SECRET_ACCESS_KEY: "secret", + ATTACHMENT_S3_FORCE_PATH_STYLE: "true", + ATTACHMENT_S3_PREFIX: "/tenant-a/", + ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS: "120", + }), + ).toEqual({ + backend: "s3", + bucket: "private-files", + prefix: "tenant-a", + downloadUrlTtlSeconds: 120, + client: { + region: "auto", + endpoint: "https://objects.example.test", + forcePathStyle: true, + credentials: { accessKeyId: "key", secretAccessKey: "secret" }, + }, + }); + }); + + test("rejects incomplete or unsafe S3 configuration", () => { + expect(() => + getAttachmentStorageConfig({ ATTACHMENT_STORAGE: "filesystem" }), + ).toThrow("database or s3"); + expect(() => + getAttachmentStorageConfig({ + ATTACHMENT_STORAGE: "s3", + ATTACHMENT_S3_BUCKET: "files", + ATTACHMENT_S3_ACCESS_KEY_ID: "key-only", + }), + ).toThrow("must be set together"); + expect(() => + getAttachmentStorageConfig({ + ATTACHMENT_STORAGE: "s3", + ATTACHMENT_S3_BUCKET: "files", + ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS: "10", + }), + ).toThrow("60 to 604800"); + }); +}); + +describe("attachment object metadata", () => { + test("builds tenant-safe object keys without using the original filename", () => { + expect(buildAttachmentStorageKey("message/id", "attachments", "object-id")).toBe( + "attachments/tickets/message%2Fid/object-id", + ); + }); + + test("sanitizes content-disposition headers and preserves UTF-8 names", () => { + expect(attachmentContentDisposition('invoice\r\n"é.pdf')).toBe( + "attachment; filename=\"invoice____.pdf\"; filename*=UTF-8''invoice%22%C3%A9.pdf", + ); + }); +}); diff --git a/src/lib/storage/attachment-storage.ts b/src/lib/storage/attachment-storage.ts new file mode 100644 index 0000000..5b15584 --- /dev/null +++ b/src/lib/storage/attachment-storage.ts @@ -0,0 +1,191 @@ +import "server-only"; + +import { randomUUID } from "node:crypto"; +import { + DeleteObjectCommand, + GetObjectCommand, + PutObjectCommand, + S3Client, + type S3ClientConfig, +} from "@aws-sdk/client-s3"; +import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; + +export type AttachmentStorageBackend = "database" | "s3"; + +type AttachmentStorageConfig = + | { backend: "database" } + | { + backend: "s3"; + bucket: string; + prefix: string; + downloadUrlTtlSeconds: number; + client: S3ClientConfig; + }; + +type AttachmentRecord = { + filename: string; + mimeType: string; + size: number; + storageBackend: string; + storageKey: string | null; + data: Uint8Array | null; +}; + +export type AttachmentDownload = + | { kind: "data"; data: Uint8Array } + | { kind: "redirect"; url: string }; + +let cachedS3Client: S3Client | undefined; + +function required(value: string | undefined, name: string): string { + if (!value?.trim()) { + throw new Error(`${name} is required when ATTACHMENT_STORAGE=s3.`); + } + return value.trim(); +} + +function parseTtl(value: string | undefined): number { + const parsed = Number(value ?? "300"); + if (!Number.isInteger(parsed) || parsed < 60 || parsed > 604_800) { + throw new Error( + "ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS must be an integer from 60 to 604800.", + ); + } + return parsed; +} + +export function getAttachmentStorageConfig( + environment: Record = process.env, +): AttachmentStorageConfig { + const backend = environment.ATTACHMENT_STORAGE?.trim().toLowerCase() || + "database"; + if (backend === "database") return { backend }; + if (backend !== "s3") { + throw new Error("ATTACHMENT_STORAGE must be either database or s3."); + } + + const accessKeyId = environment.ATTACHMENT_S3_ACCESS_KEY_ID?.trim(); + const secretAccessKey = environment.ATTACHMENT_S3_SECRET_ACCESS_KEY?.trim(); + if (Boolean(accessKeyId) !== Boolean(secretAccessKey)) { + throw new Error( + "ATTACHMENT_S3_ACCESS_KEY_ID and ATTACHMENT_S3_SECRET_ACCESS_KEY must be set together.", + ); + } + + const prefix = (environment.ATTACHMENT_S3_PREFIX ?? "attachments") + .trim() + .replace(/^\/+|\/+$/g, ""); + const endpoint = environment.ATTACHMENT_S3_ENDPOINT?.trim(); + + return { + backend, + bucket: required(environment.ATTACHMENT_S3_BUCKET, "ATTACHMENT_S3_BUCKET"), + prefix, + downloadUrlTtlSeconds: parseTtl( + environment.ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS, + ), + client: { + region: environment.ATTACHMENT_S3_REGION?.trim() || "us-east-1", + ...(endpoint ? { endpoint } : {}), + forcePathStyle: + environment.ATTACHMENT_S3_FORCE_PATH_STYLE?.toLowerCase() === "true", + ...(accessKeyId && secretAccessKey + ? { credentials: { accessKeyId, secretAccessKey } } + : {}), + }, + }; +} + +export function buildAttachmentStorageKey( + messageId: string, + prefix: string, + objectId: string = randomUUID(), +): string { + return [prefix, "tickets", encodeURIComponent(messageId), objectId] + .filter(Boolean) + .join("/"); +} + +export function attachmentContentDisposition(filename: string): string { + const safeAscii = filename + .replace(/[\r\n"\\]/g, "_") + .replace(/[^\x20-\x7E]/g, "_") || "attachment"; + const encoded = encodeURIComponent(filename.replace(/[\r\n]/g, "")); + return `attachment; filename="${safeAscii}"; filename*=UTF-8''${encoded}`; +} + +function s3Client(config: Extract) { + cachedS3Client ??= new S3Client(config.client); + return cachedS3Client; +} + +export async function storeAttachmentObject(input: { + messageId: string; + filename: string; + mimeType: string; + data: Buffer; +}): Promise<{ + storageBackend: AttachmentStorageBackend; + storageKey: string | null; + data: Uint8Array | null; +}> { + const config = getAttachmentStorageConfig(); + if (config.backend === "database") { + return { + storageBackend: "database", + storageKey: null, + data: Uint8Array.from(input.data), + }; + } + + const storageKey = buildAttachmentStorageKey(input.messageId, config.prefix); + await s3Client(config).send( + new PutObjectCommand({ + Bucket: config.bucket, + Key: storageKey, + Body: input.data, + ContentType: input.mimeType, + ContentLength: input.data.length, + }), + ); + return { storageBackend: "s3", storageKey, data: null }; +} + +export async function deleteAttachmentObject(storageKey: string): Promise { + const config = getAttachmentStorageConfig(); + if (config.backend !== "s3") return; + await s3Client(config).send( + new DeleteObjectCommand({ Bucket: config.bucket, Key: storageKey }), + ); +} + +export async function getAttachmentDownload( + attachment: AttachmentRecord, +): Promise { + if (attachment.storageBackend === "database") { + if (!attachment.data) throw new Error("Database attachment data is missing."); + return { kind: "data", data: Uint8Array.from(attachment.data) }; + } + if (attachment.storageBackend !== "s3" || !attachment.storageKey) { + throw new Error("Attachment storage metadata is invalid."); + } + + const config = getAttachmentStorageConfig(); + if (config.backend !== "s3") { + throw new Error("S3 attachment storage is not configured."); + } + const command = new GetObjectCommand({ + Bucket: config.bucket, + Key: attachment.storageKey, + ResponseContentType: attachment.mimeType, + ResponseContentDisposition: attachmentContentDisposition( + attachment.filename, + ), + }); + return { + kind: "redirect", + url: await getSignedUrl(s3Client(config), command, { + expiresIn: config.downloadUrlTtlSeconds, + }), + }; +} diff --git a/tests/integration/attachments.test.ts b/tests/integration/attachments.test.ts new file mode 100644 index 0000000..883ff38 --- /dev/null +++ b/tests/integration/attachments.test.ts @@ -0,0 +1,57 @@ +import { afterAll, beforeEach, expect, test } from "vitest"; +import { db } from "@/lib/db"; +import { saveTicketAttachments } from "@/lib/services/attachments"; +import { getAttachmentDownload } from "@/lib/storage/attachment-storage"; + +beforeEach(async () => { + process.env.ATTACHMENT_STORAGE = "database"; + await db.user.deleteMany(); +}); + +afterAll(async () => { + await db.$disconnect(); +}); + +test("keeps database attachments backward compatible through storage abstraction", async () => { + const user = await db.user.create({ + data: { + email: "attachment-test@example.test", + password: "not-used-in-tests", + firstName: "Attachment", + lastName: "Test", + }, + }); + const ticket = await db.ticket.create({ + data: { + userId: user.id, + subject: "Attachment test", + messages: { + create: { userId: user.id, message: "Testing a text attachment." }, + }, + }, + include: { messages: true }, + }); + const file = new File(["diagnostic output"], "diagnostic.txt", { + type: "text/plain", + }); + + expect(await saveTicketAttachments(ticket.messages[0].id, [file])).toBeNull(); + + const attachment = await db.ticketAttachment.findFirstOrThrow(); + expect(attachment).toEqual( + expect.objectContaining({ + filename: "diagnostic.txt", + mimeType: "text/plain", + size: 17, + storageBackend: "database", + storageKey: null, + }), + ); + const download = await getAttachmentDownload(attachment); + expect(download.kind).toBe("data"); + if (download.kind === "data") { + expect(Buffer.from(download.data).toString("utf8")).toBe( + "diagnostic output", + ); + } +});