chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockResolveActiveShareByToken,
|
||||
mockEnforceRateLimit,
|
||||
mockValidateDeploymentAuth,
|
||||
mockDownloadFile,
|
||||
mockResolveServableDoc,
|
||||
} = vi.hoisted(() => ({
|
||||
mockResolveActiveShareByToken: vi.fn(),
|
||||
mockEnforceRateLimit: vi.fn(),
|
||||
mockValidateDeploymentAuth: vi.fn(),
|
||||
mockDownloadFile: vi.fn(),
|
||||
mockResolveServableDoc: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/share-manager', () => ({
|
||||
resolveActiveShareByToken: mockResolveActiveShareByToken,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/rate-limit', () => ({
|
||||
enforcePublicFileRateLimit: mockEnforceRateLimit,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/security/deployment-auth', () => ({
|
||||
validateDeploymentAuth: mockValidateDeploymentAuth,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/uploads/core/storage-service', () => ({
|
||||
downloadFile: mockDownloadFile,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/tools/server/files/doc-compile', () => ({
|
||||
resolveServableDoc: mockResolveServableDoc,
|
||||
}))
|
||||
|
||||
import { GET } from '@/app/api/files/public/[token]/content/route'
|
||||
|
||||
const params = (token = 'tok_1') => ({ params: Promise.resolve({ token }) })
|
||||
const request = (token = 'tok_1') =>
|
||||
new NextRequest(`http://localhost/api/files/public/${token}/content`)
|
||||
|
||||
const passwordShare = {
|
||||
share: { id: 'sh_1', token: 'tok_1', authType: 'password', password: 'enc:secret' },
|
||||
file: {
|
||||
id: 'wf_1',
|
||||
key: 'workspace/ws/secret-key.pdf',
|
||||
workspaceId: 'ws-1',
|
||||
originalName: 'report.pdf',
|
||||
contentType: 'application/pdf',
|
||||
size: 4,
|
||||
},
|
||||
workspaceName: 'Acme',
|
||||
ownerName: 'Jane',
|
||||
}
|
||||
|
||||
describe('GET /api/files/public/[token]/content', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockEnforceRateLimit.mockResolvedValue(null)
|
||||
mockResolveActiveShareByToken.mockResolvedValue(passwordShare)
|
||||
mockDownloadFile.mockResolvedValue(Buffer.from('data'))
|
||||
mockResolveServableDoc.mockResolvedValue({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('returns 401 and never reads storage when a password share is unauthorized', async () => {
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({
|
||||
authorized: false,
|
||||
error: 'auth_required_password',
|
||||
})
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(401)
|
||||
expect((await res.json()).error).toBe('auth_required_password')
|
||||
expect(mockDownloadFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('serves the bytes once authorized', async () => {
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({ authorized: true })
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockDownloadFile).toHaveBeenCalledWith({
|
||||
key: passwordShare.file.key,
|
||||
context: 'workspace',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPublicFileContentContract } from '@/lib/api/contracts/public-shares'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { resolveServableDoc } from '@/lib/copilot/tools/server/files/doc-compile'
|
||||
import { validateDeploymentAuth } from '@/lib/core/security/deployment-auth'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit'
|
||||
import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager'
|
||||
import { downloadFile } from '@/lib/uploads/core/storage-service'
|
||||
import { createErrorResponse, createFileResponse, FileNotFoundError } from '@/app/api/files/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('PublicFileContentAPI')
|
||||
|
||||
/**
|
||||
* GET /api/files/public/[token]/content
|
||||
* Public, unauthenticated bytes for a shared file. Authorized solely by an active
|
||||
* share token — never by workspace membership. 404 for unknown/inactive/deleted
|
||||
* shares. Disposition (inline vs attachment) is resolved from the file type by
|
||||
* {@link createFileResponse}; the public page's Download button uses `<a download>`.
|
||||
*
|
||||
* Generated office docs are stored as source; {@link resolveServableDoc} swaps in
|
||||
* their prebuilt compiled binary (read-only, never compiles). Uploaded binaries
|
||||
* pass through untouched. A generated doc whose compiled artifact isn't built yet
|
||||
* returns 409 rather than serving raw source under a binary content type.
|
||||
*/
|
||||
export const GET = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const limited = await enforcePublicFileRateLimit(request, 'content')
|
||||
if (limited) return limited
|
||||
|
||||
const parsed = await parseRequest(getPublicFileContentContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
throw new FileNotFoundError('Not found')
|
||||
}
|
||||
|
||||
const auth = await validateDeploymentAuth(
|
||||
requestId,
|
||||
resolved.share,
|
||||
request,
|
||||
undefined,
|
||||
'file'
|
||||
)
|
||||
if (!auth.authorized) {
|
||||
return NextResponse.json({ error: auth.error ?? 'auth_required_password' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { file } = resolved
|
||||
const raw = await downloadFile({ key: file.key, context: 'workspace' })
|
||||
|
||||
const servable = file.workspaceId
|
||||
? await resolveServableDoc(file.workspaceId, raw, file.originalName)
|
||||
: ({ kind: 'passthrough' } as const)
|
||||
|
||||
if (servable.kind === 'unavailable') {
|
||||
logger.info('Public shared doc not yet compiled', { token, key: file.key })
|
||||
return NextResponse.json(
|
||||
{ error: 'This document is still being prepared. Please try again shortly.' },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
const buffer = servable.kind === 'artifact' ? servable.buffer : raw
|
||||
const contentType = servable.kind === 'artifact' ? servable.contentType : file.contentType
|
||||
|
||||
logger.info('Public shared file served', { token, key: file.key, size: buffer.length })
|
||||
|
||||
// Anonymous access: null actor (owner-as-actor would misread as a self-download).
|
||||
recordAudit({
|
||||
workspaceId: file.workspaceId ?? null,
|
||||
actorId: null,
|
||||
action: AuditAction.FILE_DOWNLOADED,
|
||||
resourceType: AuditResourceType.FILE,
|
||||
resourceId: file.id,
|
||||
resourceName: file.originalName,
|
||||
description: `Public share download of "${file.originalName}"`,
|
||||
metadata: {
|
||||
access: 'public_share',
|
||||
anonymous: true,
|
||||
sharedByUserId: file.userId,
|
||||
fileName: file.originalName,
|
||||
bytes: buffer.length,
|
||||
},
|
||||
request,
|
||||
})
|
||||
|
||||
// Revalidate every request: a shared file can be unshared, edited, or deleted,
|
||||
// so the fixed token URL must never serve stale bytes from a long-lived cache.
|
||||
return createFileResponse({
|
||||
buffer,
|
||||
contentType,
|
||||
filename: file.originalName,
|
||||
cacheControl: 'private, no-cache, must-revalidate',
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error serving public shared file:', error)
|
||||
if (error instanceof FileNotFoundError) {
|
||||
return createErrorResponse(error)
|
||||
}
|
||||
return createErrorResponse(error instanceof Error ? error : new Error('Failed to serve file'))
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockResolveShare, mockRateLimit, mockValidateAuth, mockDownloadFile, mockResolveImage } =
|
||||
vi.hoisted(() => ({
|
||||
mockResolveShare: vi.fn(),
|
||||
mockRateLimit: vi.fn(),
|
||||
mockValidateAuth: vi.fn(),
|
||||
mockDownloadFile: vi.fn(),
|
||||
mockResolveImage: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/share-manager', () => ({
|
||||
resolveActiveShareByToken: mockResolveShare,
|
||||
}))
|
||||
vi.mock('@/lib/public-shares/rate-limit', () => ({ enforcePublicFileRateLimit: mockRateLimit }))
|
||||
vi.mock('@/lib/core/security/deployment-auth', () => ({ validateDeploymentAuth: mockValidateAuth }))
|
||||
vi.mock('@/lib/uploads/core/storage-service', () => ({ downloadFile: mockDownloadFile }))
|
||||
vi.mock('@/lib/uploads/server/inline-image', () => ({
|
||||
resolveWorkspaceInlineImage: mockResolveImage,
|
||||
}))
|
||||
|
||||
import { GET } from '@/app/api/files/public/[token]/inline/route'
|
||||
|
||||
const TOKEN = 'tok_share_123456'
|
||||
const DOC_KEY = 'workspace/ws-1/doc.md'
|
||||
const IMG_KEY = 'workspace/ws-1/photo.png'
|
||||
const FILE_ID = 'wf_YwDXi8eWOkTxn0sbgChlB'
|
||||
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00])
|
||||
|
||||
const params = { params: Promise.resolve({ token: TOKEN }) }
|
||||
const req = (q: string) => new NextRequest(`http://localhost/api/files/public/${TOKEN}/inline?${q}`)
|
||||
|
||||
const share = {
|
||||
share: { id: 'sh_1', token: TOKEN, authType: 'public' },
|
||||
file: { id: 'wf_doc', key: DOC_KEY, workspaceId: 'ws-1', originalName: 'doc.md' },
|
||||
workspaceName: 'Acme',
|
||||
ownerName: 'Jane',
|
||||
}
|
||||
|
||||
/** doc bytes embed the image via the view form; image bytes are a real PNG */
|
||||
function downloadByKey(docContent = ``) {
|
||||
return ({ key }: { key: string }) =>
|
||||
Promise.resolve(key === DOC_KEY ? Buffer.from(docContent, 'utf-8') : PNG)
|
||||
}
|
||||
|
||||
describe('GET /api/files/public/[token]/inline', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockRateLimit.mockResolvedValue(null)
|
||||
mockResolveShare.mockResolvedValue(share)
|
||||
mockValidateAuth.mockResolvedValue({ authorized: true })
|
||||
mockResolveImage.mockResolvedValue({
|
||||
key: IMG_KEY,
|
||||
contentType: 'image/png',
|
||||
filename: 'photo.png',
|
||||
})
|
||||
mockDownloadFile.mockImplementation(downloadByKey())
|
||||
})
|
||||
|
||||
it('serves a same-workspace image referenced by the doc, typed from its bytes', async () => {
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('image/png')
|
||||
})
|
||||
|
||||
it('serves a key-referenced image', async () => {
|
||||
mockDownloadFile.mockImplementation(
|
||||
downloadByKey(`}?context=workspace)`)
|
||||
)
|
||||
const res = await GET(req(`key=${encodeURIComponent(IMG_KEY)}`), params)
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('404s when the reference is not embedded in the shared document', async () => {
|
||||
mockDownloadFile.mockImplementation(downloadByKey('no images here'))
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(404)
|
||||
expect(mockResolveImage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s when the referenced file is not in the document workspace', async () => {
|
||||
mockResolveImage.mockResolvedValue(null)
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('404s when the bytes are not a renderable image', async () => {
|
||||
mockDownloadFile.mockImplementation(({ key }: { key: string }) =>
|
||||
Promise.resolve(
|
||||
key === DOC_KEY
|
||||
? Buffer.from(``, 'utf-8')
|
||||
: Buffer.from('<svg/>', 'utf-8')
|
||||
)
|
||||
)
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('401s and never reads storage when the share is unauthorized', async () => {
|
||||
mockValidateAuth.mockResolvedValue({ authorized: false, error: 'auth_required_password' })
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(401)
|
||||
expect(mockDownloadFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s for an unknown or inactive token', async () => {
|
||||
mockResolveShare.mockResolvedValue(null)
|
||||
const res = await GET(req(`fileId=${FILE_ID}`), params)
|
||||
expect(res.status).toBe(404)
|
||||
expect(mockDownloadFile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPublicInlineFileContract } from '@/lib/api/contracts/public-shares'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import {
|
||||
extractEmbeddedImageIds,
|
||||
extractEmbeddedImageKeys,
|
||||
} from '@/lib/copilot/tools/server/files/embedded-image-refs'
|
||||
import { validateDeploymentAuth } from '@/lib/core/security/deployment-auth'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit'
|
||||
import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager'
|
||||
import { downloadFile } from '@/lib/uploads/core/storage-service'
|
||||
import { resolveWorkspaceInlineImage } from '@/lib/uploads/server/inline-image'
|
||||
import { serveInlineImage } from '@/app/api/files/serve-inline-image'
|
||||
import { createErrorResponse, FileNotFoundError } from '@/app/api/files/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('PublicInlineFileAPI')
|
||||
|
||||
/**
|
||||
* GET /api/files/public/[token]/inline?key=<cloudKey>|fileId=<id>
|
||||
*
|
||||
* Cascades a markdown document's public share to the images it embeds, so a logged-out viewer sees them
|
||||
* instead of broken icons. The share grants the document bytes; this route extends that grant to the
|
||||
* document's referenced images only, behind three gates that together hold the security boundary:
|
||||
*
|
||||
* 1. Referenced-by-doc — the requested key/id must appear in the shared document's current bytes. The
|
||||
* token is a capability for the document and its embeds, never an arbitrary workspace file.
|
||||
* 2. Same-workspace — the referenced file must be a `workspace` file in the document's own workspace
|
||||
* ({@link resolveWorkspaceInlineImage}). This blocks any cross-workspace reference (which an author
|
||||
* can write but must never resolve) from loading.
|
||||
* 3. Content-truth — the served content type is sniffed from the bytes, not the client-declared type,
|
||||
* and only genuine raster images are served. A file spoofing `image/png` while holding HTML/SVG is
|
||||
* refused rather than rendered inline.
|
||||
*/
|
||||
export const GET = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const limited = await enforcePublicFileRateLimit(request, 'content')
|
||||
if (limited) return limited
|
||||
|
||||
const parsed = await parseRequest(getPublicInlineFileContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
const ref = parsed.data.query
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
throw new FileNotFoundError('Not found')
|
||||
}
|
||||
|
||||
const auth = await validateDeploymentAuth(
|
||||
requestId,
|
||||
resolved.share,
|
||||
request,
|
||||
undefined,
|
||||
'file'
|
||||
)
|
||||
if (!auth.authorized) {
|
||||
return NextResponse.json({ error: auth.error ?? 'auth_required_password' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { file: doc } = resolved
|
||||
if (!doc.workspaceId) {
|
||||
throw new FileNotFoundError('Not found')
|
||||
}
|
||||
|
||||
// Referenced-by-doc gate: the share grants exactly the images the document embeds.
|
||||
const docText = (await downloadFile({ key: doc.key, context: 'workspace' })).toString('utf-8')
|
||||
const referenced = ref.fileId
|
||||
? extractEmbeddedImageIds(docText).includes(ref.fileId)
|
||||
: extractEmbeddedImageKeys(docText).includes(ref.key as string)
|
||||
if (!referenced) {
|
||||
throw new FileNotFoundError('Not found')
|
||||
}
|
||||
|
||||
// Same-workspace gate: resolve scoped to the document's own workspace.
|
||||
const image = await resolveWorkspaceInlineImage(doc.workspaceId, ref)
|
||||
if (!image) {
|
||||
throw new FileNotFoundError('Not found')
|
||||
}
|
||||
|
||||
// Content-truth gate (`sniff`): render only genuine raster image bytes; audit after.
|
||||
const response = await serveInlineImage(image, { sniff: true })
|
||||
|
||||
// Anonymous access: null actor (owner-as-actor would misread as a self-download).
|
||||
recordAudit({
|
||||
workspaceId: doc.workspaceId,
|
||||
actorId: null,
|
||||
action: AuditAction.FILE_DOWNLOADED,
|
||||
resourceType: AuditResourceType.FILE,
|
||||
resourceName: image.filename,
|
||||
description: `Public share inline image "${image.filename}"`,
|
||||
metadata: {
|
||||
access: 'public_share',
|
||||
anonymous: true,
|
||||
inline: true,
|
||||
sharedByUserId: doc.userId,
|
||||
},
|
||||
request,
|
||||
})
|
||||
|
||||
return response
|
||||
} catch (error) {
|
||||
if (error instanceof FileNotFoundError) {
|
||||
return createErrorResponse(error)
|
||||
}
|
||||
logger.error('Error serving public inline image:', error)
|
||||
return createErrorResponse(error instanceof Error ? error : new Error('Failed to serve file'))
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockResolveActiveShareByToken,
|
||||
mockIsEmailAllowed,
|
||||
mockSetDeploymentAuthCookie,
|
||||
mockGenerateOTP,
|
||||
mockStoreOTP,
|
||||
mockGetOTP,
|
||||
mockDeleteOTP,
|
||||
mockIncrementOTPAttempts,
|
||||
mockDecodeOTPValue,
|
||||
mockRenderOTPEmail,
|
||||
mockSendEmail,
|
||||
mockCheckRateLimitDirect,
|
||||
} = vi.hoisted(() => ({
|
||||
mockResolveActiveShareByToken: vi.fn(),
|
||||
mockIsEmailAllowed: vi.fn(),
|
||||
mockSetDeploymentAuthCookie: vi.fn(),
|
||||
mockGenerateOTP: vi.fn(),
|
||||
mockStoreOTP: vi.fn(),
|
||||
mockGetOTP: vi.fn(),
|
||||
mockDeleteOTP: vi.fn(),
|
||||
mockIncrementOTPAttempts: vi.fn(),
|
||||
mockDecodeOTPValue: vi.fn(),
|
||||
mockRenderOTPEmail: vi.fn(),
|
||||
mockSendEmail: vi.fn(),
|
||||
mockCheckRateLimitDirect: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/share-manager', () => ({
|
||||
resolveActiveShareByToken: mockResolveActiveShareByToken,
|
||||
}))
|
||||
vi.mock('@/lib/core/security/deployment', () => ({
|
||||
isEmailAllowed: mockIsEmailAllowed,
|
||||
setDeploymentAuthCookie: mockSetDeploymentAuthCookie,
|
||||
}))
|
||||
vi.mock('@/lib/core/security/otp', () => ({
|
||||
generateOTP: mockGenerateOTP,
|
||||
storeOTP: mockStoreOTP,
|
||||
getOTP: mockGetOTP,
|
||||
deleteOTP: mockDeleteOTP,
|
||||
incrementOTPAttempts: mockIncrementOTPAttempts,
|
||||
decodeOTPValue: mockDecodeOTPValue,
|
||||
MAX_OTP_ATTEMPTS: 5,
|
||||
OTP_IP_RATE_LIMIT: { maxTokens: 10, refillRate: 10, refillIntervalMs: 1000 },
|
||||
OTP_EMAIL_RATE_LIMIT: { maxTokens: 3, refillRate: 3, refillIntervalMs: 1000 },
|
||||
}))
|
||||
vi.mock('@/components/emails', () => ({ renderOTPEmail: mockRenderOTPEmail }))
|
||||
vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: mockSendEmail }))
|
||||
vi.mock('@/lib/core/rate-limiter', () => ({
|
||||
RateLimiter: class {
|
||||
checkRateLimitDirect = mockCheckRateLimitDirect
|
||||
},
|
||||
}))
|
||||
|
||||
import { POST, PUT } from '@/app/api/files/public/[token]/otp/route'
|
||||
|
||||
const params = (token = 'tok_1') => ({ params: Promise.resolve({ token }) })
|
||||
const post = (email: string, token = 'tok_1') =>
|
||||
new NextRequest(`http://localhost/api/files/public/${token}/otp`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
})
|
||||
const put = (email: string, otp: string, token = 'tok_1') =>
|
||||
new NextRequest(`http://localhost/api/files/public/${token}/otp`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ email, otp }),
|
||||
})
|
||||
|
||||
const emailShare = {
|
||||
share: { id: 'sh_1', authType: 'email', password: null, allowedEmails: ['@acme.com'] },
|
||||
file: { originalName: 'report.pdf' },
|
||||
}
|
||||
|
||||
describe('POST /api/files/public/[token]/otp', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimitDirect.mockResolvedValue({ allowed: true })
|
||||
mockResolveActiveShareByToken.mockResolvedValue(emailShare)
|
||||
mockIsEmailAllowed.mockReturnValue(true)
|
||||
mockGenerateOTP.mockReturnValue('123456')
|
||||
mockRenderOTPEmail.mockResolvedValue('<html/>')
|
||||
mockSendEmail.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('sends a code to an allow-listed email', async () => {
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockStoreOTP).toHaveBeenCalledWith('file', 'sh_1', 'user@acme.com', '123456')
|
||||
expect(mockSendEmail).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an email not on the allow-list with 403', async () => {
|
||||
mockIsEmailAllowed.mockReturnValueOnce(false)
|
||||
const res = await POST(post('user@evil.com'), params())
|
||||
expect(res.status).toBe(403)
|
||||
expect(mockStoreOTP).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lowercases the email for allow-list matching and OTP storage', async () => {
|
||||
await POST(post('User@ACME.com'), params())
|
||||
expect(mockIsEmailAllowed).toHaveBeenCalledWith('user@acme.com', expect.anything())
|
||||
expect(mockStoreOTP).toHaveBeenCalledWith('file', 'sh_1', 'user@acme.com', '123456')
|
||||
})
|
||||
|
||||
it('rejects a non-email share with 400', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce({
|
||||
...emailShare,
|
||||
share: { ...emailShare.share, authType: 'password' },
|
||||
})
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 429 when the IP rate limit is exceeded', async () => {
|
||||
mockCheckRateLimitDirect.mockResolvedValueOnce({ allowed: false, retryAfterMs: 1000 })
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/files/public/[token]/otp', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockResolveActiveShareByToken.mockResolvedValue(emailShare)
|
||||
mockGetOTP.mockResolvedValue('123456:0')
|
||||
mockDecodeOTPValue.mockReturnValue({ otp: '123456', attempts: 0 })
|
||||
})
|
||||
|
||||
it('verifies a correct code, sets the cookie, returns authType', async () => {
|
||||
const res = await PUT(put('user@acme.com', '123456'), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ authType: 'email' })
|
||||
expect(mockDeleteOTP).toHaveBeenCalledWith('file', 'sh_1', 'user@acme.com')
|
||||
expect(mockSetDeploymentAuthCookie).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'file',
|
||||
'sh_1',
|
||||
'email',
|
||||
null
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a wrong code with 400 and increments attempts', async () => {
|
||||
mockIncrementOTPAttempts.mockResolvedValueOnce('incremented')
|
||||
const res = await PUT(put('user@acme.com', '000000'), params())
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockIncrementOTPAttempts).toHaveBeenCalled()
|
||||
expect(mockSetDeploymentAuthCookie).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 429 when attempts are exhausted on a wrong code', async () => {
|
||||
mockIncrementOTPAttempts.mockResolvedValueOnce('locked')
|
||||
const res = await PUT(put('user@acme.com', '000000'), params())
|
||||
expect(res.status).toBe(429)
|
||||
})
|
||||
|
||||
it('returns 400 when no code was issued', async () => {
|
||||
mockGetOTP.mockResolvedValueOnce(null)
|
||||
const res = await PUT(put('user@acme.com', '123456'), params())
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,195 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { normalizeEmail } from '@sim/utils/string'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderOTPEmail } from '@/components/emails'
|
||||
import {
|
||||
requestPublicFileOtpContract,
|
||||
verifyPublicFileOtpContract,
|
||||
} from '@/lib/api/contracts/public-shares'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { RateLimiter } from '@/lib/core/rate-limiter'
|
||||
import { isEmailAllowed, setDeploymentAuthCookie } from '@/lib/core/security/deployment'
|
||||
import {
|
||||
decodeOTPValue,
|
||||
deleteOTP,
|
||||
generateOTP,
|
||||
getOTP,
|
||||
incrementOTPAttempts,
|
||||
MAX_OTP_ATTEMPTS,
|
||||
OTP_EMAIL_RATE_LIMIT,
|
||||
OTP_IP_RATE_LIMIT,
|
||||
storeOTP,
|
||||
} from '@/lib/core/security/otp'
|
||||
import { generateRequestId, getClientIp } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { sendEmail } from '@/lib/messaging/email/mailer'
|
||||
import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('PublicFileOtpAPI')
|
||||
|
||||
const rateLimiter = new RateLimiter()
|
||||
|
||||
const SHARE_EMAIL_LABEL = 'a shared file'
|
||||
|
||||
/** Allow-list for an email-gated share, read off the resolved row. */
|
||||
function shareAllowedEmails(allowedEmails: unknown): string[] {
|
||||
return Array.isArray(allowedEmails) ? (allowedEmails as string[]) : []
|
||||
}
|
||||
|
||||
function rateLimited(retryAfterMs: number | undefined, fallbackMs: number): NextResponse {
|
||||
const response = NextResponse.json(
|
||||
{ error: 'Too many requests. Please try again later.' },
|
||||
{ status: 429 }
|
||||
)
|
||||
response.headers.set('Retry-After', String(Math.ceil((retryAfterMs ?? fallbackMs) / 1000)))
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/files/public/[token]/otp
|
||||
* Sends a 6-digit verification code to an allow-listed email for an email-gated share.
|
||||
*/
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const ip = getClientIp(request)
|
||||
const ipRateLimit = await rateLimiter.checkRateLimitDirect(
|
||||
`file-otp:ip:${ip}`,
|
||||
OTP_IP_RATE_LIMIT
|
||||
)
|
||||
if (!ipRateLimit.allowed) {
|
||||
logger.warn(`[${requestId}] OTP IP rate limit exceeded from ${ip}`)
|
||||
return rateLimited(ipRateLimit.retryAfterMs, OTP_IP_RATE_LIMIT.refillIntervalMs)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(requestPublicFileOtpContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
// Normalize once so allow-list matching, OTP storage, and the verify lookup
|
||||
// all key off the same value (allow-list entries are stored lowercase).
|
||||
const email = normalizeEmail(parsed.data.body.email)
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
if (resolved.share.authType !== 'email') {
|
||||
return NextResponse.json(
|
||||
{ error: 'This file does not use email authentication' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!isEmailAllowed(email, shareAllowedEmails(resolved.share.allowedEmails))) {
|
||||
return NextResponse.json({ error: 'Email not authorized for this file' }, { status: 403 })
|
||||
}
|
||||
|
||||
const emailRateLimit = await rateLimiter.checkRateLimitDirect(
|
||||
`file-otp:email:${resolved.share.id}:${email}`,
|
||||
OTP_EMAIL_RATE_LIMIT
|
||||
)
|
||||
if (!emailRateLimit.allowed) {
|
||||
logger.warn(`[${requestId}] OTP email rate limit exceeded for ${email}`)
|
||||
return rateLimited(emailRateLimit.retryAfterMs, OTP_EMAIL_RATE_LIMIT.refillIntervalMs)
|
||||
}
|
||||
|
||||
const otp = generateOTP()
|
||||
await storeOTP('file', resolved.share.id, email, otp)
|
||||
|
||||
const emailHtml = await renderOTPEmail(otp, email, 'email-verification', SHARE_EMAIL_LABEL)
|
||||
const emailResult = await sendEmail({
|
||||
to: email,
|
||||
subject: `Verification code for ${SHARE_EMAIL_LABEL}`,
|
||||
html: emailHtml,
|
||||
})
|
||||
if (!emailResult.success) {
|
||||
logger.error(`[${requestId}] Failed to send OTP email:`, emailResult.message)
|
||||
return NextResponse.json({ error: 'Failed to send verification email' }, { status: 500 })
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] OTP sent for share ${resolved.share.id}`)
|
||||
return NextResponse.json({ message: 'Verification code sent' })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error processing OTP request:`, error)
|
||||
return NextResponse.json({ error: 'Failed to process request' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* PUT /api/files/public/[token]/otp
|
||||
* Verifies the code and, on success, sets the `file_auth_{shareId}` cookie.
|
||||
*/
|
||||
export const PUT = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(verifyPublicFileOtpContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
const { otp } = parsed.data.body
|
||||
const email = normalizeEmail(parsed.data.body.email)
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
if (resolved.share.authType !== 'email') {
|
||||
return NextResponse.json(
|
||||
{ error: 'This file does not use email authentication' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const storedValue = await getOTP('file', resolved.share.id, email)
|
||||
if (!storedValue) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No verification code found, request a new one' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const { otp: storedOTP, attempts } = decodeOTPValue(storedValue)
|
||||
if (attempts >= MAX_OTP_ATTEMPTS) {
|
||||
await deleteOTP('file', resolved.share.id, email)
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many failed attempts. Please request a new code.' },
|
||||
{ status: 429 }
|
||||
)
|
||||
}
|
||||
|
||||
if (storedOTP !== otp) {
|
||||
const result = await incrementOTPAttempts('file', resolved.share.id, email, storedValue)
|
||||
if (result === 'locked') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many failed attempts. Please request a new code.' },
|
||||
{ status: 429 }
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ error: 'Invalid verification code' }, { status: 400 })
|
||||
}
|
||||
|
||||
await deleteOTP('file', resolved.share.id, email)
|
||||
|
||||
const response = NextResponse.json({ authType: resolved.share.authType })
|
||||
setDeploymentAuthCookie(
|
||||
response,
|
||||
'file',
|
||||
resolved.share.id,
|
||||
resolved.share.authType,
|
||||
resolved.share.password
|
||||
)
|
||||
logger.info(`[${requestId}] OTP verified for share ${resolved.share.id}`)
|
||||
return response
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error verifying OTP:`, error)
|
||||
return NextResponse.json({ error: 'Failed to process request' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockResolveActiveShareByToken,
|
||||
mockEnforceRateLimit,
|
||||
mockValidateDeploymentAuth,
|
||||
mockSetDeploymentAuthCookie,
|
||||
} = vi.hoisted(() => ({
|
||||
mockResolveActiveShareByToken: vi.fn(),
|
||||
mockEnforceRateLimit: vi.fn(),
|
||||
mockValidateDeploymentAuth: vi.fn(),
|
||||
mockSetDeploymentAuthCookie: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/share-manager', () => ({
|
||||
resolveActiveShareByToken: mockResolveActiveShareByToken,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/public-shares/rate-limit', () => ({
|
||||
enforcePublicFileRateLimit: mockEnforceRateLimit,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/security/deployment-auth', () => ({
|
||||
validateDeploymentAuth: mockValidateDeploymentAuth,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/security/deployment', () => ({
|
||||
setDeploymentAuthCookie: mockSetDeploymentAuthCookie,
|
||||
}))
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { GET, POST } from '@/app/api/files/public/[token]/route'
|
||||
|
||||
const params = (token = 'tok_1') => ({ params: Promise.resolve({ token }) })
|
||||
const request = (token = 'tok_1') => new NextRequest(`http://localhost/api/files/public/${token}`)
|
||||
const postRequest = (password: string, token = 'tok_1') =>
|
||||
new NextRequest(`http://localhost/api/files/public/${token}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
})
|
||||
|
||||
const publicShare = {
|
||||
share: { id: 'sh_1', token: 'tok_1', authType: 'public', password: null },
|
||||
file: {
|
||||
id: 'wf_1',
|
||||
key: 'workspace/ws/secret-key.pdf',
|
||||
workspaceId: 'ws-secret',
|
||||
originalName: 'report.pdf',
|
||||
contentType: 'application/pdf',
|
||||
size: 2048,
|
||||
},
|
||||
workspaceName: 'Acme Workspace',
|
||||
ownerName: 'Jane Doe',
|
||||
}
|
||||
|
||||
const passwordShare = {
|
||||
...publicShare,
|
||||
share: { id: 'sh_1', token: 'tok_1', authType: 'password', password: 'enc:secret' },
|
||||
}
|
||||
|
||||
describe('GET /api/files/public/[token]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockEnforceRateLimit.mockResolvedValue(null) // allow by default
|
||||
mockValidateDeploymentAuth.mockResolvedValue({ authorized: true }) // public by default
|
||||
})
|
||||
|
||||
it('returns 429 when the per-IP rate limit is exceeded', async () => {
|
||||
mockEnforceRateLimit.mockResolvedValueOnce(
|
||||
NextResponse.json({ error: 'Too many requests. Please try again later.' }, { status: 429 })
|
||||
)
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(429)
|
||||
expect(mockResolveActiveShareByToken).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown or inactive token', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(null)
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns public-safe metadata without leaking the key or workspace id', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(publicShare)
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body).toEqual({
|
||||
token: 'tok_1',
|
||||
name: 'report.pdf',
|
||||
type: 'application/pdf',
|
||||
size: 2048,
|
||||
workspaceName: 'Acme Workspace',
|
||||
ownerName: 'Jane Doe',
|
||||
})
|
||||
expect(JSON.stringify(body)).not.toContain('secret-key')
|
||||
expect(JSON.stringify(body)).not.toContain('ws-secret')
|
||||
})
|
||||
|
||||
it('returns 401 auth_required_password for a password share without a valid cookie', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(passwordShare)
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({
|
||||
authorized: false,
|
||||
error: 'auth_required_password',
|
||||
})
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(401)
|
||||
expect((await res.json()).error).toBe('auth_required_password')
|
||||
expect(mockValidateDeploymentAuth).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
passwordShare.share,
|
||||
expect.anything(),
|
||||
undefined,
|
||||
'file'
|
||||
)
|
||||
})
|
||||
|
||||
it('serves metadata for a password share once authorized by cookie', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(passwordShare)
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({ authorized: true })
|
||||
const res = await GET(request(), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).name).toBe('report.pdf')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/files/public/[token]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockResolveActiveShareByToken.mockResolvedValue(passwordShare)
|
||||
})
|
||||
|
||||
it('sets the file_auth cookie and returns the authType on a correct password', async () => {
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({ authorized: true })
|
||||
const res = await POST(postRequest('hunter2'), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ authType: 'password' })
|
||||
expect(mockSetDeploymentAuthCookie).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'file',
|
||||
'sh_1',
|
||||
'password',
|
||||
'enc:secret'
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses to mint a cookie for a non-password (e.g. public) share', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce({
|
||||
...passwordShare,
|
||||
share: { id: 'sh_1', token: 'tok_1', authType: 'public', password: null },
|
||||
})
|
||||
const res = await POST(postRequest('whatever'), params())
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockValidateDeploymentAuth).not.toHaveBeenCalled()
|
||||
expect(mockSetDeploymentAuthCookie).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 401 Invalid password on mismatch without setting a cookie', async () => {
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({
|
||||
authorized: false,
|
||||
error: 'Invalid password',
|
||||
})
|
||||
const res = await POST(postRequest('wrong'), params())
|
||||
expect(res.status).toBe(401)
|
||||
expect((await res.json()).error).toBe('Invalid password')
|
||||
expect(mockSetDeploymentAuthCookie).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 429 with Retry-After when password attempts are rate-limited', async () => {
|
||||
mockValidateDeploymentAuth.mockResolvedValueOnce({
|
||||
authorized: false,
|
||||
error: 'Too many attempts. Please try again later.',
|
||||
status: 429,
|
||||
retryAfterMs: 60_000,
|
||||
})
|
||||
const res = await POST(postRequest('wrong'), params())
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('60')
|
||||
expect(mockSetDeploymentAuthCookie).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown token', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(null)
|
||||
const res = await POST(postRequest('hunter2'), params())
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
authenticatePublicFileContract,
|
||||
getPublicFileContract,
|
||||
} from '@/lib/api/contracts/public-shares'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { setDeploymentAuthCookie } from '@/lib/core/security/deployment'
|
||||
import { validateDeploymentAuth } from '@/lib/core/security/deployment-auth'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit'
|
||||
import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('PublicFileMetadataAPI')
|
||||
|
||||
/**
|
||||
* GET /api/files/public/[token]
|
||||
* Public, unauthenticated metadata for a shared file. Returns 404 for unknown,
|
||||
* inactive, or deleted shares — the existence of a file is never leaked. A
|
||||
* password-protected share returns 401 `auth_required_password` until a valid
|
||||
* `file_auth_{shareId}` cookie is present.
|
||||
*/
|
||||
export const GET = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const limited = await enforcePublicFileRateLimit(request, 'metadata')
|
||||
if (limited) return limited
|
||||
|
||||
const parsed = await parseRequest(getPublicFileContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const auth = await validateDeploymentAuth(
|
||||
requestId,
|
||||
resolved.share,
|
||||
request,
|
||||
undefined,
|
||||
'file'
|
||||
)
|
||||
if (!auth.authorized) {
|
||||
return NextResponse.json({ error: auth.error ?? 'auth_required_password' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { file, workspaceName, ownerName } = resolved
|
||||
return NextResponse.json({
|
||||
token,
|
||||
name: file.originalName,
|
||||
type: file.contentType,
|
||||
size: file.size,
|
||||
workspaceName,
|
||||
ownerName,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error fetching public file metadata:', error)
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(error, 'Failed to fetch file') },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* POST /api/files/public/[token]
|
||||
* Exchanges a share password for a `file_auth_{shareId}` cookie. IP rate-limited
|
||||
* via the shared deployment-auth gate; returns 401 (`Invalid password`) on
|
||||
* mismatch and 429 (with `Retry-After`) when throttled.
|
||||
*/
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(authenticatePublicFileContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
const { password } = parsed.data.body
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// This endpoint authenticates password shares only. Refusing other modes
|
||||
// here prevents minting a `file_auth` cookie for a `public` share (which
|
||||
// `validateDeploymentAuth` would otherwise authorize), which could later
|
||||
// satisfy the gate if the share is switched to `email`/`sso`.
|
||||
if (resolved.share.authType !== 'password') {
|
||||
return NextResponse.json(
|
||||
{ error: 'This file does not use password authentication' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const auth = await validateDeploymentAuth(
|
||||
requestId,
|
||||
resolved.share,
|
||||
request,
|
||||
{ password },
|
||||
'file'
|
||||
)
|
||||
if (!auth.authorized) {
|
||||
const response = NextResponse.json(
|
||||
{ error: auth.error ?? 'Invalid password' },
|
||||
{ status: auth.status ?? 401 }
|
||||
)
|
||||
if (auth.status === 429 && auth.retryAfterMs !== undefined) {
|
||||
response.headers.set('Retry-After', String(Math.ceil(auth.retryAfterMs / 1000)))
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
const response = NextResponse.json({ authType: resolved.share.authType })
|
||||
setDeploymentAuthCookie(
|
||||
response,
|
||||
'file',
|
||||
resolved.share.id,
|
||||
resolved.share.authType,
|
||||
resolved.share.password
|
||||
)
|
||||
logger.info('Public file share password accepted', { token, shareId: resolved.share.id })
|
||||
return response
|
||||
} catch (error) {
|
||||
logger.error('Error authenticating public file share:', error)
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(error, 'Failed to authenticate') },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockResolveActiveShareByToken, mockIsEmailAllowed, mockCheckRateLimitDirect } = vi.hoisted(
|
||||
() => ({
|
||||
mockResolveActiveShareByToken: vi.fn(),
|
||||
mockIsEmailAllowed: vi.fn(),
|
||||
mockCheckRateLimitDirect: vi.fn(),
|
||||
})
|
||||
)
|
||||
|
||||
vi.mock('@/lib/public-shares/share-manager', () => ({
|
||||
resolveActiveShareByToken: mockResolveActiveShareByToken,
|
||||
}))
|
||||
vi.mock('@/lib/core/security/deployment', () => ({ isEmailAllowed: mockIsEmailAllowed }))
|
||||
vi.mock('@/lib/core/rate-limiter', () => ({
|
||||
RateLimiter: class {
|
||||
checkRateLimitDirect = mockCheckRateLimitDirect
|
||||
},
|
||||
}))
|
||||
|
||||
import { POST } from '@/app/api/files/public/[token]/sso/route'
|
||||
|
||||
const params = (token = 'tok_1') => ({ params: Promise.resolve({ token }) })
|
||||
const post = (email: string, token = 'tok_1') =>
|
||||
new NextRequest(`http://localhost/api/files/public/${token}/sso`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
})
|
||||
|
||||
const ssoShare = {
|
||||
share: { id: 'sh_1', authType: 'sso', password: null, allowedEmails: ['@acme.com'] },
|
||||
file: { originalName: 'report.pdf' },
|
||||
}
|
||||
|
||||
describe('POST /api/files/public/[token]/sso', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimitDirect.mockResolvedValue({ allowed: true })
|
||||
mockResolveActiveShareByToken.mockResolvedValue(ssoShare)
|
||||
})
|
||||
|
||||
it('returns eligible:true for an allow-listed email', async () => {
|
||||
mockIsEmailAllowed.mockReturnValueOnce(true)
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ eligible: true })
|
||||
})
|
||||
|
||||
it('returns eligible:false for a non-listed email', async () => {
|
||||
mockIsEmailAllowed.mockReturnValueOnce(false)
|
||||
const res = await POST(post('user@evil.com'), params())
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ eligible: false })
|
||||
})
|
||||
|
||||
it('rejects a non-sso share with 400', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce({
|
||||
...ssoShare,
|
||||
share: { ...ssoShare.share, authType: 'email' },
|
||||
})
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown token', async () => {
|
||||
mockResolveActiveShareByToken.mockResolvedValueOnce(null)
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 429 when rate-limited', async () => {
|
||||
mockCheckRateLimitDirect.mockResolvedValueOnce({ allowed: false, retryAfterMs: 2000 })
|
||||
const res = await POST(post('user@acme.com'), params())
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { normalizeEmail } from '@sim/utils/string'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { publicFileSSOContract } from '@/lib/api/contracts/public-shares'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import type { TokenBucketConfig } from '@/lib/core/rate-limiter'
|
||||
import { RateLimiter } from '@/lib/core/rate-limiter'
|
||||
import { isEmailAllowed } from '@/lib/core/security/deployment'
|
||||
import { generateRequestId, getClientIp } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
const logger = createLogger('PublicFileSSOAPI')
|
||||
|
||||
const rateLimiter = new RateLimiter()
|
||||
|
||||
const SSO_IP_RATE_LIMIT: TokenBucketConfig = {
|
||||
maxTokens: 20,
|
||||
refillRate: 20,
|
||||
refillIntervalMs: 15 * 60_000,
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/files/public/[token]/sso
|
||||
* Reports whether an email is on the allow-list for an SSO-gated share. The actual
|
||||
* authentication is the global Sim session (checked at the page/route gate).
|
||||
*/
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ token: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
const ip = getClientIp(request)
|
||||
const ipRateLimit = await rateLimiter.checkRateLimitDirect(
|
||||
`file-sso:ip:${ip}`,
|
||||
SSO_IP_RATE_LIMIT
|
||||
)
|
||||
if (!ipRateLimit.allowed) {
|
||||
logger.warn(`[${requestId}] SSO eligibility rate limit exceeded from ${ip}`)
|
||||
const response = NextResponse.json(
|
||||
{ error: 'Too many requests. Please try again later.' },
|
||||
{ status: 429 }
|
||||
)
|
||||
response.headers.set(
|
||||
'Retry-After',
|
||||
String(Math.ceil((ipRateLimit.retryAfterMs ?? SSO_IP_RATE_LIMIT.refillIntervalMs) / 1000))
|
||||
)
|
||||
return response
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(publicFileSSOContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { token } = parsed.data.params
|
||||
const email = normalizeEmail(parsed.data.body.email)
|
||||
|
||||
const resolved = await resolveActiveShareByToken(token)
|
||||
if (!resolved) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
if (resolved.share.authType !== 'sso') {
|
||||
return NextResponse.json({ error: 'This file is not configured for SSO' }, { status: 400 })
|
||||
}
|
||||
|
||||
const allowedEmails = Array.isArray(resolved.share.allowedEmails)
|
||||
? (resolved.share.allowedEmails as string[])
|
||||
: []
|
||||
return NextResponse.json({ eligible: isEmailAllowed(email, allowedEmails) })
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user