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

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -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'))
}
}
)