An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(storage): sign file URLs from a fixed window so attachments stay cached (#941)
Yoshiki Miura9c9fd1c1d2fe
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex f723085f..8fa1b769 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -278,6 +278,10 @@ R2_ACCOUNT_ID=[YOUR_ACCOUNT_ID] # For Cloudflare R2R2_BUCKET_NAME=[YOUR_BUCKET_NAME]# Optional: signed GET URL lifetime in seconds (default: 3600)R2_SIGNED_URL_EXPIRES_SECONDS=3600+# Optional: reuse one signature per window so a file signs to the same URL+# across requests, which keeps replayed attachments in the prompt cache.+# Capped at half the lifetime above; set to 0 to sign every request (default: 900)+R2_SIGNED_URL_STABILITY_WINDOW_SECONDS=900```If storage variables are not configured, `/api/upload` returns `400` and uploads are disabled.diff --git a/lib/storage/__tests__/r2-client.test.ts b/lib/storage/__tests__/r2-client.test.tsindex 4856759d..c568a1ea 100644--- a/lib/storage/__tests__/r2-client.test.ts+++ b/lib/storage/__tests__/r2-client.test.ts@@ -57,6 +57,8 @@ const originalEnv = {R2_BUCKET_NAME: process.env.R2_BUCKET_NAME,R2_PUBLIC_URL: process.env.R2_PUBLIC_URL,R2_SIGNED_URL_EXPIRES_SECONDS: process.env.R2_SIGNED_URL_EXPIRES_SECONDS,+ R2_SIGNED_URL_STABILITY_WINDOW_SECONDS:+ process.env.R2_SIGNED_URL_STABILITY_WINDOW_SECONDS,R2_SECRET_ACCESS_KEY: process.env.R2_SECRET_ACCESS_KEY,S3_ENDPOINT: process.env.S3_ENDPOINT}@@ -77,6 +79,7 @@ describe('R2 client', () => {process.env.R2_BUCKET_NAME = 'test-bucket'process.env.R2_PUBLIC_URL = 'https://uploads.example.com'process.env.R2_SIGNED_URL_EXPIRES_SECONDS = '3600'+ delete process.env.R2_SIGNED_URL_STABILITY_WINDOW_SECONDSprocess.env.S3_ENDPOINT = 'https://r2.example.com'delete process.env.R2_ACCOUNT_ID})@@ -157,7 +160,7 @@ describe('R2 client', () => {expect(s3Mocks.getSignedUrl).toHaveBeenCalledWith(expect.any(Object),expect.any(s3Mocks.GetObjectCommand),- { expiresIn: 3600 }+ { expiresIn: 3600, signingDate: expect.any(Date) })expect((s3Mocks.getSignedUrl.mock.calls[0][1] as any).input).toEqual({Bucket: 'test-bucket',@@ -165,6 +168,71 @@ describe('R2 client', () => {})})+ describe('signing date stability', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ s3Mocks.getSignedUrl.mockResolvedValue('https://signed.example.com/file')+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ const signingDateOf = (call: number) =>+ (s3Mocks.getSignedUrl.mock.calls[call][2] as { signingDate?: Date })+ .signingDate++ it('reuses one signing date for every request inside the same window', async () => {+ const { getSignedFileUrl } = await importR2Client()++ vi.setSystemTime(new Date('2026-08-05T14:24:33.000Z'))+ await getSignedFileUrl('user-id/file.png')+ vi.setSystemTime(new Date('2026-08-05T14:29:09.000Z'))+ await getSignedFileUrl('user-id/file.png')++ // Same signing date + same key + same expiry is what makes the presigned+ // URL byte-identical across turns, so the attachment stays cached.+ expect(signingDateOf(0)).toEqual(new Date('2026-08-05T14:15:00.000Z'))+ expect(signingDateOf(1)).toEqual(signingDateOf(0))+ })++ it('advances the signing date once the window rolls over', async () => {+ const { getSignedFileUrl } = await importR2Client()++ vi.setSystemTime(new Date('2026-08-05T14:29:59.000Z'))+ await getSignedFileUrl('user-id/file.png')+ vi.setSystemTime(new Date('2026-08-05T14:30:00.000Z'))+ await getSignedFileUrl('user-id/file.png')++ expect(signingDateOf(0)).toEqual(new Date('2026-08-05T14:15:00.000Z'))+ expect(signingDateOf(1)).toEqual(new Date('2026-08-05T14:30:00.000Z'))+ })++ it('caps the window at half the expiry so a URL keeps a usable lifetime', async () => {+ process.env.R2_SIGNED_URL_EXPIRES_SECONDS = '60'++ const { getSignedFileUrl } = await importR2Client()++ vi.setSystemTime(new Date('2026-08-05T14:24:59.000Z'))+ await getSignedFileUrl('user-id/file.png')++ // 30s window, not the configured 900s: the URL signed at :24:30 is still+ // valid for 30 of its 60 seconds when handed out at :24:59.+ expect(signingDateOf(0)).toEqual(new Date('2026-08-05T14:24:30.000Z'))+ })++ it('signs with the current time when the window is disabled', async () => {+ process.env.R2_SIGNED_URL_STABILITY_WINDOW_SECONDS = '0'++ const { getSignedFileUrl } = await importR2Client()++ vi.setSystemTime(new Date('2026-08-05T14:24:33.000Z'))+ await getSignedFileUrl('user-id/file.png')++ expect(s3Mocks.getSignedUrl.mock.calls[0][2]).toEqual({ expiresIn: 3600 })+ })+ })+it('preserves existing file URLs when no object key is available', async () => {const { signFilePartUrls } = await importR2Client()diff --git a/lib/storage/r2-client.ts b/lib/storage/r2-client.tsindex e46f0985..d884d0b1 100644--- a/lib/storage/r2-client.ts+++ b/lib/storage/r2-client.ts@@ -18,6 +18,17 @@ export const R2_SIGNED_URL_EXPIRES_SECONDS =? configuredSignedUrlExpiresSeconds: DEFAULT_SIGNED_URL_EXPIRES_SECONDS+const DEFAULT_SIGNED_URL_STABILITY_WINDOW_SECONDS = 15 * 60+const configuredSignedUrlStabilityWindowSeconds = Number(+ process.env.R2_SIGNED_URL_STABILITY_WINDOW_SECONDS+)+// Set to 0 to go back to signing every request with the current time.+export const R2_SIGNED_URL_STABILITY_WINDOW_SECONDS =+ Number.isFinite(configuredSignedUrlStabilityWindowSeconds) &&+ configuredSignedUrlStabilityWindowSeconds >= 0+ ? configuredSignedUrlStabilityWindowSeconds+ : DEFAULT_SIGNED_URL_STABILITY_WINDOW_SECONDS+let _r2Client: S3Client | null = nulltype SignFilePartUrlsOptions = {@@ -90,6 +101,31 @@ function isObjectKeyWithinPrefix(key: string, prefix: string) {)}+/**+ * Rounds the signing time down to a fixed window so the same object key signs+ * to a byte-identical URL for the whole window.+ *+ * Attachments are replayed on every turn of a conversation, and a URL whose+ * signature changes per request changes the prompt prefix with it, so the+ * provider re-reads every replayed attachment instead of serving it from the+ * prompt cache.+ *+ * The window is capped at half the expiry so a URL handed out at the end of a+ * window still keeps at least half its configured lifetime.+ */+function getStableSigningDate(expiresIn: number): Date | undefined {+ const windowSeconds = Math.min(+ R2_SIGNED_URL_STABILITY_WINDOW_SECONDS,+ Math.floor(expiresIn / 2)+ )+ if (windowSeconds < 1) {+ return undefined+ }++ const windowMs = windowSeconds * 1000+ return new Date(Math.floor(Date.now() / windowMs) * windowMs)+}+export async function getSignedFileUrl(key: string,expiresIn = R2_SIGNED_URL_EXPIRES_SECONDS@@ -99,13 +135,15 @@ export async function getSignedFileUrl(throw new Error('Cannot sign an empty object key')}+ const signingDate = getStableSigningDate(expiresIn)+return getSignedUrl(getR2Client(),new GetObjectCommand({Bucket: R2_BUCKET_NAME,Key: normalizedKey}),- { expiresIn }+ signingDate ? { expiresIn, signingDate } : { expiresIn })}