fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
SUPPORT_ATTACHMENT_ACCEPT,
|
||||
SUPPORT_MAX_ATTACHMENTS,
|
||||
SUPPORT_MAX_ATTACHMENT_TOTAL_BYTES,
|
||||
SUPPORT_MAX_ATTACHMENT_TOTAL_MB,
|
||||
isSupportedAttachmentType,
|
||||
sanitizeAttachmentFilename,
|
||||
supportAttachmentFilename,
|
||||
} from '@/lib/support/attachments'
|
||||
import { HOSTED_REQUEST_BODY_LIMIT_BYTES } from '@/lib/documents/upload-size'
|
||||
|
||||
describe('support attachments', () => {
|
||||
it('accepts the types a support reader can open', () => {
|
||||
expect(isSupportedAttachmentType('image/png')).toBe(true)
|
||||
expect(isSupportedAttachmentType('IMAGE/JPEG')).toBe(true)
|
||||
expect(isSupportedAttachmentType('application/pdf')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects everything else, including a missing type', () => {
|
||||
expect(isSupportedAttachmentType('application/x-sh')).toBe(false)
|
||||
expect(isSupportedAttachmentType('image/heic')).toBe(false)
|
||||
expect(isSupportedAttachmentType(undefined)).toBe(false)
|
||||
expect(isSupportedAttachmentType('')).toBe(false)
|
||||
})
|
||||
|
||||
it('offers the same list to the file picker', () => {
|
||||
expect(SUPPORT_ATTACHMENT_ACCEPT).toBe('image/jpeg,image/png,image/webp,application/pdf')
|
||||
})
|
||||
|
||||
it('allows five files with a four megabyte combined budget', () => {
|
||||
expect(SUPPORT_MAX_ATTACHMENTS).toBe(5)
|
||||
expect(SUPPORT_MAX_ATTACHMENT_TOTAL_MB).toBe(4)
|
||||
expect(SUPPORT_MAX_ATTACHMENT_TOTAL_BYTES).toBe(4 * 1024 * 1024)
|
||||
})
|
||||
|
||||
// Vercel kills the request before the route runs if the body is over its own
|
||||
// ceiling, so the budget has to leave room for the multipart envelope.
|
||||
it('stays under the platform request-body ceiling', () => {
|
||||
expect(SUPPORT_MAX_ATTACHMENT_TOTAL_BYTES).toBeLessThan(HOSTED_REQUEST_BODY_LIMIT_BYTES)
|
||||
})
|
||||
|
||||
describe('sanitizeAttachmentFilename', () => {
|
||||
it('keeps an ordinary name', () => {
|
||||
expect(sanitizeAttachmentFilename('skarmbild.png')).toBe('skarmbild.png')
|
||||
})
|
||||
|
||||
it('drops path segments from both separators', () => {
|
||||
expect(sanitizeAttachmentFilename('../../etc/passwd.png')).toBe('passwd.png')
|
||||
expect(sanitizeAttachmentFilename('C:\\Users\\emil\\bild.png')).toBe('bild.png')
|
||||
})
|
||||
|
||||
it('strips control characters that would break a mail header', () => {
|
||||
const withNewline = `bild${String.fromCharCode(13)}${String.fromCharCode(10)}.png`
|
||||
expect(sanitizeAttachmentFilename(withNewline)).toBe('bild.png')
|
||||
})
|
||||
|
||||
it('falls back when nothing usable is left', () => {
|
||||
expect(sanitizeAttachmentFilename('')).toBe('bilaga')
|
||||
expect(sanitizeAttachmentFilename(null)).toBe('bilaga')
|
||||
expect(sanitizeAttachmentFilename(String.fromCharCode(0))).toBe('bilaga')
|
||||
})
|
||||
|
||||
it('bounds a very long name but keeps the extension', () => {
|
||||
const long = `${'a'.repeat(300)}.png`
|
||||
const result = sanitizeAttachmentFilename(long)
|
||||
expect(result.length).toBeLessThanOrEqual(100)
|
||||
expect(result.endsWith('.png')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('supportAttachmentFilename', () => {
|
||||
it('forces the extension to agree with the verified MIME type', () => {
|
||||
expect(supportAttachmentFilename('update.exe', 'application/pdf')).toBe('update.pdf')
|
||||
expect(supportAttachmentFilename('photo.png', 'image/jpeg')).toBe('photo.jpg')
|
||||
})
|
||||
|
||||
it('keeps the final filename within the mail-header bound', () => {
|
||||
const filename = supportAttachmentFilename('a'.repeat(150), 'application/pdf')
|
||||
expect(filename.length).toBeLessThanOrEqual(100)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not expose attachment names in session-replay attributes', () => {
|
||||
const source = readFileSync(
|
||||
join(process.cwd(), 'components', 'ui', 'support-link.tsx'),
|
||||
'utf8'
|
||||
)
|
||||
expect(source).toContain('ph-no-capture')
|
||||
expect(source).not.toContain('title={file.name}')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,333 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { submitFeedback } from '@/lib/support/submit-feedback'
|
||||
|
||||
// posthog-js is browser-only and irrelevant to delivery: stub it so the
|
||||
// analytics breadcrumb can be asserted without initialising the real SDK.
|
||||
const captureMock = vi.fn()
|
||||
const sendMessageMock = vi.fn()
|
||||
const isAvailableMock = vi.fn(() => true)
|
||||
vi.mock('posthog-js', () => ({
|
||||
default: {
|
||||
capture: (...a: unknown[]) => captureMock(...a),
|
||||
conversations: {
|
||||
isAvailable: () => isAvailableMock(),
|
||||
sendMessage: (...a: unknown[]) => sendMessageMock(...a),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('submitFeedback', () => {
|
||||
beforeEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
captureMock.mockClear()
|
||||
sendMessageMock.mockClear()
|
||||
isAvailableMock.mockReturnValue(true)
|
||||
// Analytics on by default so the breadcrumb path is exercised.
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
|
||||
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', 'phc_test')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
function stubFetchOk() {
|
||||
const fetchSpy = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
vi.stubGlobal('fetch', fetchSpy)
|
||||
return fetchSpy
|
||||
}
|
||||
|
||||
it('delivers over email and reports the email channel', async () => {
|
||||
const fetchSpy = stubFetchOk()
|
||||
|
||||
const result = await submitFeedback({ subject: 'Hjälpsida', message: 'Hjälp tack' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.channels).toEqual(['email', 'ticket'])
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'/api/support/contact',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ subject: 'Hjälpsida', message: 'Hjälp tack' }),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
// Recapt used to mask a failing email endpoint by reporting success on its
|
||||
// own channel. Email is now the only delivery path, so its failure must
|
||||
// surface to the user instead of being swallowed.
|
||||
it('reports failure when the email endpoint rejects', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Mailtjänsten är inte konfigurerad' }),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
|
||||
// A ticket may still open, but delivery failed, so ok stays false.
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.channels).not.toContain('email')
|
||||
expect(result.error).toBe('Mailtjänsten är inte konfigurerad')
|
||||
})
|
||||
|
||||
it('reports failure when fetch itself throws', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network down')))
|
||||
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.channels).not.toContain('email')
|
||||
expect(result.error).toBe('Network down')
|
||||
})
|
||||
|
||||
it('records a PostHog breadcrumb WITHOUT the message body', async () => {
|
||||
stubFetchOk()
|
||||
|
||||
await submitFeedback({ subject: 'Hjälpsida', message: 'känslig text om mitt bolag' })
|
||||
|
||||
expect(captureMock).toHaveBeenCalledWith('support_feedback_submitted', {
|
||||
subject: 'Hjälpsida',
|
||||
delivered: true,
|
||||
email: 'ok',
|
||||
ticket: 'ok',
|
||||
lost: false,
|
||||
})
|
||||
// Free text is user content: it must never ride along as an event property.
|
||||
expect(JSON.stringify(captureMock.mock.calls)).not.toContain('känslig text')
|
||||
})
|
||||
|
||||
it('marks the breadcrumb undelivered when email failed', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) }))
|
||||
|
||||
await submitFeedback({ message: 'msg' })
|
||||
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ delivered: false })
|
||||
)
|
||||
})
|
||||
|
||||
it('skips the breadcrumb entirely when analytics is off (self-hosted)', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
|
||||
stubFetchOk()
|
||||
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(captureMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not let a throwing analytics SDK break delivery', async () => {
|
||||
captureMock.mockImplementationOnce(() => {
|
||||
throw new Error('posthog boom')
|
||||
})
|
||||
stubFetchOk()
|
||||
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.channels).toContain('email')
|
||||
})
|
||||
|
||||
describe('PostHog Support ticket channel', () => {
|
||||
it('opens a ticket carrying the message body, unlike the analytics breadcrumb', async () => {
|
||||
stubFetchOk()
|
||||
await submitFeedback({ subject: 'Moms', message: 'Jag fastnar på ruta 05' })
|
||||
expect(sendMessageMock).toHaveBeenCalledWith('[Moms]\n\nJag fastnar på ruta 05')
|
||||
})
|
||||
|
||||
it('omits the subject prefix when there is no subject', async () => {
|
||||
stubFetchOk()
|
||||
await submitFeedback({ message: 'bara text' })
|
||||
expect(sendMessageMock).toHaveBeenCalledWith('bara text')
|
||||
})
|
||||
|
||||
// A ticket alone is NOT delivery: nobody is watching PostHog at 02:00, and
|
||||
// Recapt masking a dead email endpoint is the exact bug we removed.
|
||||
it('does not report success when only the ticket worked', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({ error: 'down' }) }))
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.channels).toEqual(['ticket'])
|
||||
expect(result.error).toBe('down')
|
||||
})
|
||||
|
||||
it('still delivers by email when conversations are unavailable', async () => {
|
||||
isAvailableMock.mockReturnValue(false)
|
||||
stubFetchOk()
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.channels).toEqual(['email'])
|
||||
expect(sendMessageMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still delivers by email when sendMessage throws', async () => {
|
||||
sendMessageMock.mockRejectedValueOnce(new Error('conversations boom'))
|
||||
stubFetchOk()
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.channels).toEqual(['email'])
|
||||
})
|
||||
|
||||
it('opens no ticket when analytics is off (self-hosted)', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
|
||||
stubFetchOk()
|
||||
const result = await submitFeedback({ message: 'msg' })
|
||||
expect(result.channels).toEqual(['email'])
|
||||
expect(sendMessageMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('breadcrumb channel outcomes', () => {
|
||||
it('reports ticket: ok when the ticket opened', async () => {
|
||||
stubFetchOk()
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ ticket: 'ok', lost: false })
|
||||
)
|
||||
})
|
||||
|
||||
// 'unavailable' is the expected steady state (Support off, analytics off);
|
||||
// 'failed' means conversations were live and the call still did not land.
|
||||
// Only the second deserves an alert, so they must not collapse.
|
||||
it("reports ticket: unavailable when conversations are not available", async () => {
|
||||
isAvailableMock.mockReturnValue(false)
|
||||
stubFetchOk()
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ ticket: 'unavailable' })
|
||||
)
|
||||
})
|
||||
|
||||
it('reports ticket: failed when sendMessage throws', async () => {
|
||||
sendMessageMock.mockRejectedValueOnce(new Error('boom'))
|
||||
stubFetchOk()
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ ticket: 'failed' })
|
||||
)
|
||||
})
|
||||
|
||||
it('reports email: failed but not lost when the ticket still opened', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) }))
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ email: 'failed', ticket: 'ok', lost: false })
|
||||
)
|
||||
})
|
||||
|
||||
// The alerting signal: the user's message reached nobody at all.
|
||||
it('sets lost when email failed and the ticket was unavailable', async () => {
|
||||
isAvailableMock.mockReturnValue(false)
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('down')))
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ email: 'failed', ticket: 'unavailable', lost: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('sets lost when email failed and the ticket genuinely errored', async () => {
|
||||
sendMessageMock.mockRejectedValueOnce(new Error('boom'))
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('down')))
|
||||
await submitFeedback({ message: 'msg' })
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ email: 'failed', ticket: 'failed', lost: true })
|
||||
)
|
||||
})
|
||||
|
||||
// A hung sendMessage must not hold the confirmation dialog open: the ticket
|
||||
// is capped and reported as 'timeout', while email still decides ok.
|
||||
it('does not let a hanging ticket call block the user', async () => {
|
||||
vi.useFakeTimers()
|
||||
sendMessageMock.mockImplementationOnce(() => new Promise(() => {}))
|
||||
stubFetchOk()
|
||||
const pending = submitFeedback({ message: 'msg' })
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
const result = await pending
|
||||
vi.useRealTimers()
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.channels).toEqual(['email'])
|
||||
expect(captureMock).toHaveBeenCalledWith(
|
||||
'support_feedback_submitted',
|
||||
expect.objectContaining({ email: 'ok', ticket: 'timeout', lost: false })
|
||||
)
|
||||
})
|
||||
|
||||
it('still carries no message body', async () => {
|
||||
stubFetchOk()
|
||||
await submitFeedback({ subject: 'Moms', message: 'hemlig fritext om bolaget' })
|
||||
expect(JSON.stringify(captureMock.mock.calls)).not.toContain('hemlig fritext')
|
||||
})
|
||||
|
||||
it('does not add attachment metadata to analytics', async () => {
|
||||
stubFetchOk()
|
||||
await submitFeedback({
|
||||
message: 'Se bilagan',
|
||||
files: [new File(['x'], 'kontoutdrag-privat.png', { type: 'image/png' })],
|
||||
})
|
||||
const props = captureMock.mock.calls[0][1] as Record<string, unknown>
|
||||
expect(props).not.toHaveProperty('attachment_count')
|
||||
expect(JSON.stringify(captureMock.mock.calls)).not.toContain('kontoutdrag-privat')
|
||||
})
|
||||
})
|
||||
|
||||
describe('attachments', () => {
|
||||
it('sends multipart with the files when there are any', async () => {
|
||||
const fetchSpy = stubFetchOk()
|
||||
const file = new File(['x'], 'skarmbild.png', { type: 'image/png' })
|
||||
|
||||
await submitFeedback({ subject: 'Trasig vy', message: 'Ser ut så här', files: [file] })
|
||||
|
||||
const init = fetchSpy.mock.calls[0][1]
|
||||
expect(init.body).toBeInstanceOf(FormData)
|
||||
// The browser has to set the multipart boundary itself.
|
||||
expect(init.headers).toBeUndefined()
|
||||
const form = init.body as FormData
|
||||
expect(form.get('subject')).toBe('Trasig vy')
|
||||
expect(form.get('message')).toBe('Ser ut så här')
|
||||
expect(form.getAll('files')).toHaveLength(1)
|
||||
expect((form.get('files') as File).name).toBe('skarmbild.png')
|
||||
})
|
||||
|
||||
it('keeps the JSON body when the file list is empty', async () => {
|
||||
const fetchSpy = stubFetchOk()
|
||||
|
||||
await submitFeedback({ subject: 'Moms', message: 'Jag fastnar', files: [] })
|
||||
|
||||
expect(fetchSpy.mock.calls[0][1].body).toBe(
|
||||
JSON.stringify({ subject: 'Moms', message: 'Jag fastnar' })
|
||||
)
|
||||
})
|
||||
|
||||
it('surfaces the route error when an attachment is rejected', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Du kan bifoga max 5 filer' }),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await submitFeedback({
|
||||
message: 'För många bilder',
|
||||
files: [new File(['x'], 'a.png', { type: 'image/png' })],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBe('Du kan bifoga max 5 filer')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Support attachment rules, shared by the dialog and the /api/support/contact
|
||||
* route so the client never offers to send something the server will reject.
|
||||
*
|
||||
* Attachments ride along on the existing support email. This module only
|
||||
* defines the transport limits and does not add a storage path.
|
||||
*/
|
||||
|
||||
/** What a support reader can actually open without extra tooling. */
|
||||
export const SUPPORT_ATTACHMENT_TYPES = [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
'application/pdf',
|
||||
] as const
|
||||
|
||||
const SUPPORT_ATTACHMENT_EXTENSIONS: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
'application/pdf': '.pdf',
|
||||
}
|
||||
|
||||
export const SUPPORT_MAX_ATTACHMENTS = 5
|
||||
|
||||
/**
|
||||
* Total bytes across all attachments in one message.
|
||||
*
|
||||
* Vercel rejects a request body over 4.5 MB before the function runs (see
|
||||
* lib/documents/upload-size.ts), so the ceiling has to leave room for the
|
||||
* multipart envelope and the message text on top of the files themselves.
|
||||
* Self-hosted has no such proxy limit, but the same cap applies there: a
|
||||
* support mailbox is not a file transfer service.
|
||||
*/
|
||||
export const SUPPORT_MAX_ATTACHMENT_TOTAL_MB = 4
|
||||
export const SUPPORT_MAX_ATTACHMENT_TOTAL_BYTES = SUPPORT_MAX_ATTACHMENT_TOTAL_MB * 1024 * 1024
|
||||
|
||||
export function isSupportedAttachmentType(type: string | null | undefined): boolean {
|
||||
return (SUPPORT_ATTACHMENT_TYPES as readonly string[]).includes(String(type ?? '').toLowerCase())
|
||||
}
|
||||
|
||||
/** The `accept` attribute for the file picker: same list, one source of truth. */
|
||||
export const SUPPORT_ATTACHMENT_ACCEPT = SUPPORT_ATTACHMENT_TYPES.join(',')
|
||||
|
||||
/**
|
||||
* Make a client-supplied name safe to put in a mail header: no path
|
||||
* separators, no control characters, bounded length. The extension is kept
|
||||
* when there is one so the attachment still opens with the right app.
|
||||
*
|
||||
* Control characters are stripped by code point rather than by a regex class:
|
||||
* a literal control character in a source file is invisible in review and has
|
||||
* corrupted this repo's files before.
|
||||
*/
|
||||
export function sanitizeAttachmentFilename(raw: string | undefined | null): string {
|
||||
const base = (String(raw ?? '').split(/[\\/]/).pop() ?? '')
|
||||
.split('')
|
||||
.filter((ch) => {
|
||||
const code = ch.charCodeAt(0)
|
||||
return code >= 0x20 && code !== 0x7f
|
||||
})
|
||||
.join('')
|
||||
.trim()
|
||||
|
||||
if (!base) return 'bilaga'
|
||||
return base.length > 100 ? `${base.slice(0, 80)}-${base.slice(-16)}` : base
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the mail attachment an extension that agrees with the verified MIME
|
||||
* type. A browser-supplied name must not make a PDF look executable.
|
||||
*/
|
||||
export function supportAttachmentFilename(
|
||||
raw: string | undefined | null,
|
||||
type: string
|
||||
): string {
|
||||
const safe = sanitizeAttachmentFilename(raw)
|
||||
const extension = SUPPORT_ATTACHMENT_EXTENSIONS[type.toLowerCase()] ?? '.bin'
|
||||
const lastDot = safe.lastIndexOf('.')
|
||||
const stem = (lastDot > 0 ? safe.slice(0, lastDot) : safe) || 'bilaga'
|
||||
return `${stem.slice(0, 100 - extension.length)}${extension}`
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import posthog from 'posthog-js'
|
||||
import { isAnalyticsEnabled } from '@/lib/analytics/enabled'
|
||||
|
||||
export interface SubmitFeedbackInput {
|
||||
message: string
|
||||
subject?: string
|
||||
/** Screenshots or PDFs relayed on the support email only. */
|
||||
files?: File[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery channels.
|
||||
*
|
||||
* 'email' - Resend to the support inbox. The guarantee: it works with no
|
||||
* third party beyond the mail provider and needs no analytics.
|
||||
* 'ticket' - PostHog Support conversation, linked to the person and their
|
||||
* session replay so we can see what they were doing.
|
||||
*
|
||||
* Recapt used to be the second channel and would report success on its own,
|
||||
* masking a failing /api/support/contact. This does NOT repeat that: the
|
||||
* result is `ok` only when email actually delivered. A ticket alone is not
|
||||
* treated as delivery, because nobody is watching PostHog at 02:00.
|
||||
*/
|
||||
export type SupportChannel = 'email' | 'ticket'
|
||||
|
||||
export interface SubmitFeedbackResult {
|
||||
ok: boolean
|
||||
channels: SupportChannel[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON when there is nothing to attach, multipart when there is. The JSON path
|
||||
* is kept byte-identical rather than always sending multipart: it is the shape
|
||||
* every existing message uses, and a plain body is the one that still works if
|
||||
* multipart parsing is ever the thing that broke.
|
||||
*/
|
||||
function buildEmailRequest({ message, subject, files }: SubmitFeedbackInput): RequestInit {
|
||||
if (!files?.length) {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ subject, message }),
|
||||
}
|
||||
}
|
||||
|
||||
const form = new FormData()
|
||||
if (subject) form.append('subject', subject)
|
||||
form.append('message', message)
|
||||
for (const file of files) form.append('files', file, file.name)
|
||||
// No Content-Type header: the browser has to set the multipart boundary.
|
||||
return { method: 'POST', body: form }
|
||||
}
|
||||
|
||||
async function submitViaEmail(
|
||||
input: SubmitFeedbackInput
|
||||
): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
try {
|
||||
const res = await fetch('/api/support/contact', buildEmailRequest(input))
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
return { ok: false, error: data.error || 'Kunde inte skicka meddelandet' }
|
||||
}
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : 'Nätverksfel' }
|
||||
}
|
||||
}
|
||||
|
||||
/** Outcome of each channel, for the analytics breadcrumb. */
|
||||
type ChannelOutcome = 'ok' | 'failed' | 'unavailable' | 'timeout'
|
||||
|
||||
/** How long the ticket call may run before we stop waiting on it. The user is
|
||||
* waiting on this dialog, and the ticket is a complement, not the delivery. */
|
||||
const TICKET_TIMEOUT_MS = 4000
|
||||
|
||||
/**
|
||||
* Breadcrumb on the user's PostHog timeline so a support message is visible
|
||||
* next to the session replay that led to it: the genuinely useful half of what
|
||||
* the Recapt channel provided. NOT a delivery channel, and deliberately
|
||||
* carries no message body: free text is user content and would be PII in an
|
||||
* event property. Email remains the only thing that actually delivers.
|
||||
*
|
||||
* Both channels are reported, because both fail silently from the user's side.
|
||||
* A ticket that never opened is invisible in the UI (email is the guarantee,
|
||||
* so the user still sees success) and invisible in PostHog Support (no ticket
|
||||
* exists to look at). Without `ticket` here, the only way to answer "did the
|
||||
* ticket open?" is to reproduce it with devtools open, which is what happened
|
||||
* the first time this shipped.
|
||||
*
|
||||
* 'unavailable' is kept distinct from 'failed' on purpose: unavailable is the
|
||||
* expected steady state when Support is off or analytics is disabled, whereas
|
||||
* failed means conversations were live and the call still did not land. Only
|
||||
* the second is worth alerting on.
|
||||
*/
|
||||
function noteInAnalytics(
|
||||
{ subject }: SubmitFeedbackInput,
|
||||
outcomes: { email: boolean; ticket: ChannelOutcome }
|
||||
): void {
|
||||
if (!isAnalyticsEnabled()) return
|
||||
try {
|
||||
posthog.capture('support_feedback_submitted', {
|
||||
subject: subject ?? null,
|
||||
// Kept for continuity: existing insights filter on `delivered`.
|
||||
delivered: outcomes.email,
|
||||
email: outcomes.email ? 'ok' : 'failed',
|
||||
ticket: outcomes.ticket,
|
||||
// True only when the user's message reached neither channel. This is the
|
||||
// one that deserves an alert.
|
||||
lost: !outcomes.email && outcomes.ticket !== 'ok',
|
||||
})
|
||||
} catch {
|
||||
// Telemetry must never affect whether the user's message went out.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a PostHog Support ticket alongside the email.
|
||||
*
|
||||
* Unlike the analytics breadcrumb this DOES carry the message body: a support
|
||||
* ticket the user deliberately wrote is the one place their words are the
|
||||
* point. That makes tickets a distinct processing purpose from analytics, so
|
||||
* it is declared separately in .compliance/ropa.yaml and on the privacy page.
|
||||
*
|
||||
* Never throws and never blocks: if conversations are unavailable (support
|
||||
* disabled, no analytics, older SDK) the user still gets the email path.
|
||||
*/
|
||||
async function submitViaTicket({ message, subject }: SubmitFeedbackInput): Promise<ChannelOutcome> {
|
||||
if (!isAnalyticsEnabled()) return 'unavailable'
|
||||
try {
|
||||
const conversations = posthog.conversations
|
||||
if (!conversations?.isAvailable?.()) return 'unavailable'
|
||||
await conversations.sendMessage(composeTicketBody(message, subject))
|
||||
return 'ok'
|
||||
} catch {
|
||||
return 'failed'
|
||||
}
|
||||
}
|
||||
|
||||
function composeTicketBody(message: string, subject?: string): string {
|
||||
return subject ? `[${subject}]\n\n${message}` : message
|
||||
}
|
||||
|
||||
/** Resolve to `fallback` if the promise has not settled in time. Never rejects:
|
||||
* submitViaTicket already swallows its own errors. */
|
||||
function withTimeout(
|
||||
promise: Promise<ChannelOutcome>,
|
||||
ms: number,
|
||||
fallback: ChannelOutcome
|
||||
): Promise<ChannelOutcome> {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => resolve(fallback), ms)
|
||||
void promise.then((value) => {
|
||||
clearTimeout(timer)
|
||||
resolve(value)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function submitFeedback(input: SubmitFeedbackInput): Promise<SubmitFeedbackResult> {
|
||||
// Both channels start together, so the user waits max(email, ticket) rather
|
||||
// than the sum. Email is the delivery guarantee and decides `ok`; the ticket
|
||||
// is a complement, so it is additionally capped: a hung sendMessage must
|
||||
// never hold the confirmation dialog open. It resolves to 'timeout' instead,
|
||||
// which is reported rather than silently rounded to 'failed'.
|
||||
const ticketPromise = submitViaTicket(input)
|
||||
const emailResult = await submitViaEmail(input)
|
||||
const ticket = await withTimeout(ticketPromise, TICKET_TIMEOUT_MS, 'timeout')
|
||||
|
||||
noteInAnalytics(input, { email: emailResult.ok, ticket })
|
||||
|
||||
if (emailResult.ok) {
|
||||
return { ok: true, channels: ticket === 'ok' ? ['email', 'ticket'] : ['email'] }
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
channels: ticket === 'ok' ? ['ticket'] : [],
|
||||
error: emailResult.error,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user