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,354 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
vi.mock('next/server', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('next/server')>()
|
||||
return { ...actual, after: vi.fn() }
|
||||
})
|
||||
|
||||
import { cloudBackupExtension } from '../index'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { CloudBackupStatus } from '../types'
|
||||
import { createOAuthState } from '../lib/crypto'
|
||||
import { googleDriveProvider } from '../lib/google-provider'
|
||||
|
||||
const BASE = 'https://test.local/api/extensions/ext/cloud-backup'
|
||||
|
||||
function findRoute(method: string, path: string) {
|
||||
const route = cloudBackupExtension.apiRoutes?.find(
|
||||
(r) => r.method === method && r.path === path
|
||||
)
|
||||
expect(route, `${method} ${path} must be registered`).toBeDefined()
|
||||
return route!
|
||||
}
|
||||
|
||||
function makeRequest(path: string, method = 'POST', body?: unknown): Request {
|
||||
return new Request(`${BASE}${path}`, {
|
||||
method,
|
||||
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
/** Settings backed by a map, so a test can assert which keys were touched. */
|
||||
function makeContext(seed: Record<string, unknown> = {}) {
|
||||
const store = new Map<string, unknown>(Object.entries(seed))
|
||||
const set = vi.fn().mockImplementation(async (key: string, value: unknown) => {
|
||||
store.set(key, value)
|
||||
})
|
||||
const clear = vi.fn().mockImplementation(async (key: string) => {
|
||||
store.delete(key)
|
||||
})
|
||||
const ctx = {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'cloud-backup',
|
||||
requestId: 'req_test',
|
||||
supabase: {},
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
settings: {
|
||||
get: vi.fn().mockImplementation(async (key: string) => store.get(key) ?? null),
|
||||
set,
|
||||
clear,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any as ExtensionContext
|
||||
return { ctx, store, set, clear }
|
||||
}
|
||||
|
||||
function makeConnection(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
refresh_token_encrypted: 'enc',
|
||||
account_email: '[email protected]',
|
||||
connected_at: '2026-01-01T00:00:00.000Z',
|
||||
root_folder_id: null,
|
||||
company_folder_id: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const ENV_KEYS = [
|
||||
'GOOGLE_CLIENT_ID',
|
||||
'GOOGLE_CLIENT_SECRET',
|
||||
'DROPBOX_APP_KEY',
|
||||
'DROPBOX_APP_SECRET',
|
||||
// The OAuth state parameter is encrypted with a key derived from this.
|
||||
'SUPABASE_SERVICE_ROLE_KEY',
|
||||
// Canonical app origin. Cleared so request-origin fallback tests remain
|
||||
// deterministic regardless of the runner's environment.
|
||||
'NEXT_PUBLIC_APP_URL',
|
||||
] as const
|
||||
const originalEnv: Record<string, string | undefined> = {}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
for (const key of ENV_KEYS) originalEnv[key] = process.env[key]
|
||||
process.env.GOOGLE_CLIENT_ID = 'google-id'
|
||||
process.env.GOOGLE_CLIENT_SECRET = 'google-secret'
|
||||
process.env.DROPBOX_APP_KEY = 'dropbox-key'
|
||||
process.env.DROPBOX_APP_SECRET = 'dropbox-secret'
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
|
||||
delete process.env.NEXT_PUBLIC_APP_URL
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const key of ENV_KEYS) {
|
||||
if (originalEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = originalEnv[key]
|
||||
}
|
||||
})
|
||||
|
||||
describe('provider routing', () => {
|
||||
it('rejects an unknown provider rather than defaulting to a destination', async () => {
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect?provider=onedrive'), ctx)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
await expect(res.json()).resolves.toEqual({ error: 'unknown_provider' })
|
||||
})
|
||||
|
||||
it('treats a missing provider as Google Drive, as pre-Dropbox clients meant', async () => {
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const { url } = (await res.json()) as { url: string }
|
||||
expect(url).toContain('accounts.google.com')
|
||||
})
|
||||
|
||||
it('sends the user to Dropbox with an app-folder scope set', async () => {
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect?provider=dropbox'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const { url } = (await res.json()) as { url: string }
|
||||
const parsed = new URL(url)
|
||||
expect(parsed.origin + parsed.pathname).toBe('https://www.dropbox.com/oauth2/authorize')
|
||||
// Without offline access Dropbox issues no refresh token and the nightly
|
||||
// cron dies a few hours after connecting.
|
||||
expect(parsed.searchParams.get('token_access_type')).toBe('offline')
|
||||
expect(parsed.searchParams.get('scope')).toBe(
|
||||
'files.content.write files.content.read account_info.read'
|
||||
)
|
||||
expect(parsed.searchParams.get('redirect_uri')).toBe(
|
||||
'https://test.local/api/extensions/ext/cloud-backup/oauth/dropbox/callback'
|
||||
)
|
||||
expect(parsed.searchParams.get('state')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('refuses to start a flow the deployment has no credentials for', async () => {
|
||||
delete process.env.DROPBOX_APP_KEY
|
||||
delete process.env.DROPBOX_APP_SECRET
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect?provider=dropbox'), ctx)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
await expect(res.json()).resolves.toEqual({ error: 'provider_not_configured' })
|
||||
})
|
||||
|
||||
it('registers a separate OAuth callback per provider', () => {
|
||||
expect(findRoute('GET', '/oauth/callback')).toBeDefined()
|
||||
expect(findRoute('GET', '/oauth/dropbox/callback')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('canonical redirect URI', () => {
|
||||
it('builds the Google callback from NEXT_PUBLIC_APP_URL, not the request host', async () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect?provider=google_drive'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const { url } = (await res.json()) as { url: string }
|
||||
expect(new URL(url).searchParams.get('redirect_uri')).toBe(
|
||||
'https://app.accounted.se/api/extensions/ext/cloud-backup/oauth/callback'
|
||||
)
|
||||
})
|
||||
|
||||
it('builds the Dropbox callback from NEXT_PUBLIC_APP_URL, not the request host', async () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
|
||||
const route = findRoute('POST', '/connect')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/connect?provider=dropbox'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const { url } = (await res.json()) as { url: string }
|
||||
expect(new URL(url).searchParams.get('redirect_uri')).toBe(
|
||||
'https://app.accounted.se/api/extensions/ext/cloud-backup/oauth/dropbox/callback'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the same canonical origin for the callback token exchange', async () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
|
||||
const route = findRoute('GET', '/oauth/callback')
|
||||
const { ctx } = makeContext()
|
||||
const exchange = vi.spyOn(googleDriveProvider, 'exchangeCode').mockResolvedValue({
|
||||
refreshToken: 'refresh-token',
|
||||
accountLabel: '[email protected]',
|
||||
})
|
||||
const callbackUrl = new URL(`${BASE}/oauth/callback`)
|
||||
callbackUrl.searchParams.set('code', 'provider-code')
|
||||
callbackUrl.searchParams.set('state', createOAuthState(ctx.userId, ctx.companyId))
|
||||
|
||||
const res = await route.handler(new Request(callbackUrl), ctx)
|
||||
|
||||
expect(exchange).toHaveBeenCalledWith('https://app.accounted.se', 'provider-code')
|
||||
const location = new URL(res.headers.get('location')!)
|
||||
expect(location.origin).toBe('https://app.accounted.se')
|
||||
expect(location.pathname).toBe('/settings/backup')
|
||||
expect(location.searchParams.get('cloud_backup')).toBe('connected_first')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /status', () => {
|
||||
it('reports every provider independently', async () => {
|
||||
const route = findRoute('GET', '/status')
|
||||
const { ctx } = makeContext({
|
||||
google_drive_connection: makeConnection({ account_email: '[email protected]' }),
|
||||
dropbox_connection: makeConnection({
|
||||
account_email: '[email protected]',
|
||||
status: 'needs_reauth',
|
||||
}),
|
||||
})
|
||||
|
||||
const res = await route.handler(makeRequest('/status', 'GET'), ctx)
|
||||
const { data } = (await res.json()) as { data: CloudBackupStatus }
|
||||
|
||||
expect(data.providers.map((p) => p.provider)).toEqual(['google_drive', 'dropbox'])
|
||||
const google = data.providers[0]
|
||||
const dropbox = data.providers[1]
|
||||
expect(google).toMatchObject({
|
||||
connected: true,
|
||||
needs_reauth: false,
|
||||
account_email: '[email protected]',
|
||||
})
|
||||
expect(dropbox).toMatchObject({
|
||||
connected: true,
|
||||
needs_reauth: true,
|
||||
account_email: '[email protected]',
|
||||
})
|
||||
})
|
||||
|
||||
it('flags a provider the deployment cannot use so the UI can disable the row', async () => {
|
||||
delete process.env.DROPBOX_APP_KEY
|
||||
delete process.env.DROPBOX_APP_SECRET
|
||||
const route = findRoute('GET', '/status')
|
||||
const { ctx } = makeContext()
|
||||
|
||||
const res = await route.handler(makeRequest('/status', 'GET'), ctx)
|
||||
const { data } = (await res.json()) as { data: CloudBackupStatus }
|
||||
|
||||
expect(data.providers.find((p) => p.provider === 'google_drive')?.configured).toBe(true)
|
||||
expect(data.providers.find((p) => p.provider === 'dropbox')?.configured).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps mirroring Google Drive at the top level for pre-Dropbox clients', async () => {
|
||||
const route = findRoute('GET', '/status')
|
||||
const { ctx } = makeContext({
|
||||
google_drive_connection: makeConnection({ account_email: '[email protected]' }),
|
||||
})
|
||||
|
||||
const res = await route.handler(makeRequest('/status', 'GET'), ctx)
|
||||
const { data } = (await res.json()) as { data: CloudBackupStatus }
|
||||
|
||||
expect(data.connected).toBe(true)
|
||||
expect(data.account_email).toBe('[email protected]')
|
||||
})
|
||||
|
||||
it('does not report a Dropbox connection as a Google one at the top level', async () => {
|
||||
const route = findRoute('GET', '/status')
|
||||
const { ctx } = makeContext({ dropbox_connection: makeConnection() })
|
||||
|
||||
const res = await route.handler(makeRequest('/status', 'GET'), ctx)
|
||||
const { data } = (await res.json()) as { data: CloudBackupStatus }
|
||||
|
||||
// The legacy fields describe Google Drive alone: a dashboard banner reading
|
||||
// them must not claim the Drive backup is healthy because Dropbox is.
|
||||
expect(data.connected).toBe(false)
|
||||
expect(data.account_email).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /disconnect', () => {
|
||||
it('clears only the targeted provider records', async () => {
|
||||
const route = findRoute('POST', '/disconnect')
|
||||
const { ctx, store } = makeContext({
|
||||
google_drive_connection: makeConnection(),
|
||||
google_drive_last_sync: { at: 'x', folder_id: 'f' },
|
||||
google_drive_schedule: { enabled: true },
|
||||
dropbox_connection: makeConnection(),
|
||||
dropbox_last_sync: { at: 'y', folder_id: '/g' },
|
||||
dropbox_schedule: { enabled: true },
|
||||
})
|
||||
|
||||
const res = await route.handler(makeRequest('/disconnect?provider=dropbox'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect([...store.keys()].sort()).toEqual([
|
||||
'google_drive_connection',
|
||||
'google_drive_last_sync',
|
||||
'google_drive_schedule',
|
||||
])
|
||||
})
|
||||
|
||||
it('still works when the deployment lost its credentials', async () => {
|
||||
// A user must never be trapped with a connection they cannot remove.
|
||||
delete process.env.DROPBOX_APP_KEY
|
||||
delete process.env.DROPBOX_APP_SECRET
|
||||
const route = findRoute('POST', '/disconnect')
|
||||
const { ctx, store } = makeContext({ dropbox_connection: makeConnection() })
|
||||
|
||||
const res = await route.handler(makeRequest('/disconnect?provider=dropbox'), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(store.has('dropbox_connection')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('schedule routes are per provider', () => {
|
||||
it('writes the schedule under the targeted provider key', async () => {
|
||||
const route = findRoute('PUT', '/schedule')
|
||||
const { ctx, store } = makeContext()
|
||||
|
||||
const res = await route.handler(
|
||||
makeRequest('/schedule?provider=dropbox', 'PUT', { enabled: true, hour_local: 4 }),
|
||||
ctx
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(store.has('dropbox_schedule')).toBe(true)
|
||||
expect(store.has('google_drive_schedule')).toBe(false)
|
||||
})
|
||||
|
||||
it('reads each provider schedule separately', async () => {
|
||||
const route = findRoute('GET', '/schedule')
|
||||
const { ctx } = makeContext({
|
||||
google_drive_schedule: { enabled: true, hour_utc: 3, hour_local: 5 },
|
||||
dropbox_schedule: { enabled: false, hour_utc: 9, hour_local: 11 },
|
||||
})
|
||||
|
||||
const google = await route.handler(makeRequest('/schedule', 'GET'), ctx)
|
||||
const dropbox = await route.handler(
|
||||
makeRequest('/schedule?provider=dropbox', 'GET'),
|
||||
ctx
|
||||
)
|
||||
|
||||
await expect(google.json()).resolves.toMatchObject({
|
||||
data: { enabled: true, hour_local: 5 },
|
||||
})
|
||||
await expect(dropbox.json()).resolves.toMatchObject({
|
||||
data: { enabled: false, hour_local: 11 },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { cloudBackupExtension } from '../index'
|
||||
import { isScheduleDue } from '../lib/schedule'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { GoogleDriveSchedule } from '../types'
|
||||
|
||||
function findRoute(method: string, path: string) {
|
||||
const route = cloudBackupExtension.apiRoutes?.find(
|
||||
(r) => r.method === method && r.path === path
|
||||
)
|
||||
expect(route, `${method} ${path} must be registered`).toBeDefined()
|
||||
return route!
|
||||
}
|
||||
|
||||
function makeRequest(body: unknown): Request {
|
||||
return new Request('https://test.local/api/extensions/ext/cloud-backup/schedule', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
function makeContext(existing: GoogleDriveSchedule | null): {
|
||||
ctx: ExtensionContext
|
||||
set: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const set = vi.fn().mockResolvedValue(undefined)
|
||||
const ctx = {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'cloud-backup',
|
||||
requestId: 'req_test',
|
||||
supabase: {},
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
settings: {
|
||||
get: vi.fn().mockResolvedValue(existing),
|
||||
set,
|
||||
clear: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any as ExtensionContext
|
||||
return { ctx, set }
|
||||
}
|
||||
|
||||
describe('PUT /schedule', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('clears a stale hour_local on an hour_utc-only update so the UTC hour wins', async () => {
|
||||
// Existing schedule fires at 05:00 Stockholm (03:00 UTC in summer).
|
||||
const existing: GoogleDriveSchedule = {
|
||||
enabled: true,
|
||||
hour_utc: 3,
|
||||
hour_local: 5,
|
||||
last_auto_sync_at: null,
|
||||
last_auto_sync_status: null,
|
||||
last_auto_sync_error: null,
|
||||
}
|
||||
const { ctx, set } = makeContext(existing)
|
||||
|
||||
// Legacy UTC-only client moves the schedule to 14:00 UTC.
|
||||
const res = await findRoute('PUT', '/schedule').handler(
|
||||
makeRequest({ enabled: true, hour_utc: 14 }),
|
||||
ctx
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(set).toHaveBeenCalledTimes(1)
|
||||
const stored = set.mock.calls[0][1] as GoogleDriveSchedule
|
||||
expect(stored.hour_utc).toBe(14)
|
||||
// The stale local hour must not survive: the scheduler prefers
|
||||
// hour_local, so keeping 5 would make the schedule ignore 14:00 UTC.
|
||||
expect(stored.hour_local).toBeUndefined()
|
||||
|
||||
// The stored schedule no longer resolves to the stale 05:00 Stockholm
|
||||
// slot (03:00 UTC in summer): not due before 14:00 UTC, due after.
|
||||
expect(isScheduleDue(stored, new Date('2026-07-12T03:30:00.000Z'))).toBe(false)
|
||||
expect(isScheduleDue(stored, new Date('2026-07-12T14:01:00.000Z'))).toBe(true)
|
||||
})
|
||||
|
||||
it('stores hour_local and mirrors hour_utc on an hour_local update', async () => {
|
||||
const { ctx, set } = makeContext(null)
|
||||
const res = await findRoute('PUT', '/schedule').handler(
|
||||
makeRequest({ enabled: true, hour_local: 5 }),
|
||||
ctx
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const stored = set.mock.calls[0][1] as GoogleDriveSchedule
|
||||
expect(stored.hour_local).toBe(5)
|
||||
expect([3, 4]).toContain(stored.hour_utc) // CEST vs CET mirror
|
||||
})
|
||||
|
||||
it('rejects a request without a valid hour', async () => {
|
||||
const { ctx, set } = makeContext(null)
|
||||
const res = await findRoute('PUT', '/schedule').handler(
|
||||
makeRequest({ enabled: true }),
|
||||
ctx
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
expect(set).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,439 @@
|
||||
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
|
||||
import { NextResponse, after } from 'next/server'
|
||||
import {
|
||||
createOAuthState,
|
||||
decryptToken,
|
||||
encryptToken,
|
||||
verifyOAuthState,
|
||||
} from './lib/crypto'
|
||||
import { performSync } from './lib/sync'
|
||||
import { resolveCallbackOrigin } from './lib/callback-origin'
|
||||
import { stockholmHourToUtcHour } from './lib/schedule'
|
||||
import { CLOUD_PROVIDERS, providerFromRequest } from './lib/provider-registry'
|
||||
import { googleDriveProvider } from './lib/google-provider'
|
||||
import { dropboxProvider } from './lib/dropbox-provider'
|
||||
import type { CloudStorageProvider } from './lib/cloud-provider'
|
||||
import type {
|
||||
CloudBackupStatus,
|
||||
CloudConnection,
|
||||
CloudLastSync,
|
||||
CloudProviderStatus,
|
||||
CloudSchedule,
|
||||
} from './types'
|
||||
|
||||
function jsonError(message: string, status = 500): Response {
|
||||
return NextResponse.json({ error: message }, { status })
|
||||
}
|
||||
|
||||
const DEFAULT_SCHEDULE: CloudSchedule = {
|
||||
enabled: false,
|
||||
hour_utc: 3,
|
||||
hour_local: 5, // 05:00 Swedish time, DST-stable: low-traffic default
|
||||
last_auto_sync_at: null,
|
||||
last_auto_sync_status: null,
|
||||
last_auto_sync_error: null,
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the destination a request targets. An unknown `?provider=` value is
|
||||
* an error rather than a silent fallback: writing a company's backup to the
|
||||
* wrong destination because of a typo must never happen quietly.
|
||||
*
|
||||
* `requireConfigured` is for `/connect` alone, which cannot succeed without
|
||||
* OAuth credentials. Every other route stays open even when a deployment loses
|
||||
* its credentials: a user must always be able to disconnect an account or
|
||||
* switch off a schedule, and locking those behind an env var would trap them.
|
||||
*/
|
||||
function resolveProvider(
|
||||
request: Request,
|
||||
options: { requireConfigured?: boolean } = {}
|
||||
): { provider: CloudStorageProvider } | { error: Response } {
|
||||
const provider = providerFromRequest(request)
|
||||
if (!provider) {
|
||||
return { error: jsonError('unknown_provider', 400) }
|
||||
}
|
||||
if (options.requireConfigured && !provider.isConfigured()) {
|
||||
return { error: jsonError('provider_not_configured', 400) }
|
||||
}
|
||||
return { provider }
|
||||
}
|
||||
|
||||
async function readProviderStatus(
|
||||
ctx: ExtensionContext,
|
||||
provider: CloudStorageProvider
|
||||
): Promise<CloudProviderStatus> {
|
||||
const connection = await ctx.settings.get<CloudConnection>(provider.keys.connection)
|
||||
const lastSync = await ctx.settings.get<CloudLastSync>(provider.keys.lastSync)
|
||||
const schedule = await ctx.settings.get<CloudSchedule>(provider.keys.schedule)
|
||||
return {
|
||||
provider: provider.id,
|
||||
configured: provider.isConfigured(),
|
||||
connected: !!connection,
|
||||
needs_reauth: connection?.status === 'needs_reauth',
|
||||
account_email: connection?.account_email ?? null,
|
||||
connected_at: connection?.connected_at ?? null,
|
||||
last_sync: lastSync ?? null,
|
||||
schedule: schedule ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared OAuth callback body. Each provider needs its own route because the
|
||||
* redirect URI is registered with the provider, but the exchange, the state
|
||||
* check and the first-backup kickoff are identical.
|
||||
*/
|
||||
async function handleOAuthCallback(
|
||||
request: Request,
|
||||
ctx: ExtensionContext | undefined,
|
||||
provider: CloudStorageProvider
|
||||
): Promise<Response> {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const url = new URL(request.url)
|
||||
const code = url.searchParams.get('code')
|
||||
const state = url.searchParams.get('state')
|
||||
const errorParam = url.searchParams.get('error')
|
||||
// Resolve exactly as /connect did: the token exchange repeats the
|
||||
// redirect_uri from the authorization request.
|
||||
const origin = resolveCallbackOrigin(url.origin)
|
||||
const redirect = (status: string, reason?: string) => {
|
||||
const target = new URL('/settings/backup', origin)
|
||||
target.searchParams.set('cloud_backup', status)
|
||||
target.searchParams.set('provider', provider.id)
|
||||
if (reason) target.searchParams.set('reason', reason)
|
||||
return NextResponse.redirect(target)
|
||||
}
|
||||
|
||||
if (errorParam) {
|
||||
return redirect('error', errorParam)
|
||||
}
|
||||
if (!code || !state) {
|
||||
return redirect('error', 'missing_params')
|
||||
}
|
||||
|
||||
const verified = verifyOAuthState(state)
|
||||
if (!verified) {
|
||||
return redirect('error', 'invalid_state')
|
||||
}
|
||||
if (verified.userId !== ctx.userId || verified.companyId !== ctx.companyId) {
|
||||
return redirect('error', 'state_mismatch')
|
||||
}
|
||||
|
||||
try {
|
||||
const { refreshToken, accountLabel } = await provider.exchangeCode(origin, code)
|
||||
|
||||
const connection: CloudConnection = {
|
||||
refresh_token_encrypted: encryptToken(refreshToken),
|
||||
account_email: accountLabel,
|
||||
connected_at: new Date().toISOString(),
|
||||
root_folder_id: null,
|
||||
company_folder_id: null,
|
||||
company_folder_path: null,
|
||||
}
|
||||
await ctx.settings.set(provider.keys.connection, connection)
|
||||
|
||||
// First-time connections get daily auto-sync on by default: a
|
||||
// backup that defaults to off protects nobody. Reconnects keep
|
||||
// whatever schedule the user had. Each provider is scheduled
|
||||
// independently, so connecting a second one does not disturb the first.
|
||||
const existingSchedule = await ctx.settings.get<CloudSchedule>(
|
||||
provider.keys.schedule
|
||||
)
|
||||
const firstConnect = !existingSchedule
|
||||
if (firstConnect) {
|
||||
await ctx.settings.set(provider.keys.schedule, {
|
||||
...DEFAULT_SCHEDULE,
|
||||
enabled: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Kick off the first backup after the redirect response is sent, so
|
||||
// the user lands back on the card immediately while the archive
|
||||
// builds in the background.
|
||||
after(async () => {
|
||||
try {
|
||||
await performSync({
|
||||
supabase: ctx.supabase,
|
||||
companyId: ctx.companyId,
|
||||
userId: ctx.userId,
|
||||
origin,
|
||||
includeDocuments: true,
|
||||
allowDocumentFallback: true,
|
||||
provider,
|
||||
})
|
||||
} catch (err) {
|
||||
ctx.log.error(`initial ${provider.id} sync after connect failed`, err)
|
||||
}
|
||||
})
|
||||
|
||||
return redirect(firstConnect ? 'connected_first' : 'connected')
|
||||
} catch (err) {
|
||||
ctx.log.error(`${provider.id} oauth callback failed`, err)
|
||||
return redirect(
|
||||
'error',
|
||||
err instanceof Error ? err.message.slice(0, 80) : 'exchange_failed'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const cloudBackupExtension: Extension = {
|
||||
id: 'cloud-backup',
|
||||
name: 'Molnsynkronisering',
|
||||
version: '1.1.0',
|
||||
sector: 'general',
|
||||
|
||||
// The canonical entry point for cloud-backup is now `/import#cloud-backup`
|
||||
// (under "Importera/Exportera"). `/settings/backup` is preserved as a
|
||||
// permanent redirect to that anchor so legacy bookmarks and OAuth callbacks
|
||||
// keep working: see `app/(dashboard)/settings/backup/page.tsx`.
|
||||
settingsPanel: {
|
||||
label: 'Molnsynkronisering',
|
||||
path: '/settings/backup',
|
||||
},
|
||||
|
||||
apiRoutes: [
|
||||
// Kick off OAuth: return the provider's consent URL.
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/connect',
|
||||
handler: async (request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const resolved = resolveProvider(request, { requireConfigured: true })
|
||||
if ('error' in resolved) return resolved.error
|
||||
try {
|
||||
const origin = resolveCallbackOrigin(new URL(request.url).origin)
|
||||
const state = createOAuthState(ctx.userId, ctx.companyId)
|
||||
const url = resolved.provider.buildAuthorizationUrl(origin, state)
|
||||
return NextResponse.json({ url })
|
||||
} catch (err) {
|
||||
ctx.log.error('connect failed', err)
|
||||
return jsonError(
|
||||
err instanceof Error ? err.message : 'Could not start OAuth',
|
||||
500
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// Google redirects here after the user consents. The path is registered
|
||||
// with Google as an authorised redirect URI: never rename it.
|
||||
{
|
||||
method: 'GET',
|
||||
path: googleDriveProvider.callbackPath,
|
||||
handler: (request, ctx) => handleOAuthCallback(request, ctx, googleDriveProvider),
|
||||
},
|
||||
|
||||
// Dropbox equivalent, on its own registered redirect URI.
|
||||
{
|
||||
method: 'GET',
|
||||
path: dropboxProvider.callbackPath,
|
||||
handler: (request, ctx) => handleOAuthCallback(request, ctx, dropboxProvider),
|
||||
},
|
||||
|
||||
// Revoke the refresh token and clear the stored connection + schedule for
|
||||
// one provider. The other provider's records are untouched.
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/disconnect',
|
||||
handler: async (request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const resolved = resolveProvider(request)
|
||||
if ('error' in resolved) return resolved.error
|
||||
const { provider } = resolved
|
||||
try {
|
||||
const connection = await ctx.settings.get<CloudConnection>(
|
||||
provider.keys.connection
|
||||
)
|
||||
if (connection) {
|
||||
try {
|
||||
const refreshToken = decryptToken(connection.refresh_token_encrypted)
|
||||
await provider.revoke(
|
||||
refreshToken,
|
||||
resolveCallbackOrigin(new URL(request.url).origin)
|
||||
)
|
||||
} catch (err) {
|
||||
ctx.log.warn('token revoke failed (continuing)', err)
|
||||
}
|
||||
}
|
||||
await ctx.settings.clear(provider.keys.connection)
|
||||
await ctx.settings.clear(provider.keys.lastSync)
|
||||
await ctx.settings.clear(provider.keys.schedule)
|
||||
return NextResponse.json({ ok: true })
|
||||
} catch (err) {
|
||||
ctx.log.error('disconnect failed', err)
|
||||
return jsonError(
|
||||
err instanceof Error ? err.message : 'Disconnect failed',
|
||||
500
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// Read-only status used by the UI to show connected/last-sync info for
|
||||
// every provider. The top-level fields mirror Google Drive so clients
|
||||
// written before Dropbox existed keep working.
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/status',
|
||||
handler: async (_request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const providers: CloudProviderStatus[] = []
|
||||
for (const provider of CLOUD_PROVIDERS) {
|
||||
providers.push(await readProviderStatus(ctx, provider))
|
||||
}
|
||||
const google =
|
||||
providers.find((p) => p.provider === googleDriveProvider.id) ?? null
|
||||
const status: CloudBackupStatus = {
|
||||
providers,
|
||||
connected: google?.connected ?? false,
|
||||
needs_reauth: google?.needs_reauth ?? false,
|
||||
account_email: google?.account_email ?? null,
|
||||
connected_at: google?.connected_at ?? null,
|
||||
last_sync: google?.last_sync ?? null,
|
||||
schedule: google?.schedule ?? null,
|
||||
}
|
||||
return NextResponse.json({ data: status })
|
||||
},
|
||||
},
|
||||
|
||||
// Read one provider's auto-sync schedule. Returns the default (disabled)
|
||||
// shape if the user has never configured one.
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/schedule',
|
||||
handler: async (request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const resolved = resolveProvider(request)
|
||||
if ('error' in resolved) return resolved.error
|
||||
const schedule = await ctx.settings.get<CloudSchedule>(
|
||||
resolved.provider.keys.schedule
|
||||
)
|
||||
return NextResponse.json({ data: schedule ?? DEFAULT_SCHEDULE })
|
||||
},
|
||||
},
|
||||
|
||||
// Update one provider's auto-sync schedule. Preserves the fields the cron
|
||||
// writes (`last_auto_sync_*`, failure counter, alert throttle): those are
|
||||
// not user-editable.
|
||||
{
|
||||
method: 'PUT',
|
||||
path: '/schedule',
|
||||
handler: async (request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const resolved = resolveProvider(request)
|
||||
if ('error' in resolved) return resolved.error
|
||||
try {
|
||||
const body = (await request.json()) as {
|
||||
enabled?: boolean
|
||||
hour_local?: number
|
||||
hour_utc?: number
|
||||
}
|
||||
if (typeof body.enabled !== 'boolean') {
|
||||
return jsonError('enabled must be a boolean', 400)
|
||||
}
|
||||
const validHour = (h: unknown): h is number =>
|
||||
typeof h === 'number' && Number.isInteger(h) && h >= 0 && h <= 23
|
||||
|
||||
let hourLocal: number | undefined
|
||||
let hourUtc: number
|
||||
if (validHour(body.hour_local)) {
|
||||
// Preferred: Stockholm wall-clock hour, DST-stable. hour_utc is
|
||||
// mirrored (today's offset) so legacy readers keep a sane value.
|
||||
hourLocal = body.hour_local
|
||||
hourUtc = stockholmHourToUtcHour(body.hour_local)
|
||||
} else if (validHour(body.hour_utc)) {
|
||||
// Legacy UTC-only request: leave hourLocal undefined so any
|
||||
// stored hour_local is cleared below. The scheduler prefers
|
||||
// hour_local, so keeping a stale value would make the schedule
|
||||
// ignore the requested UTC hour.
|
||||
hourUtc = body.hour_utc
|
||||
} else {
|
||||
return jsonError('hour_local must be an integer between 0 and 23', 400)
|
||||
}
|
||||
|
||||
const key = resolved.provider.keys.schedule
|
||||
const existing = await ctx.settings.get<CloudSchedule>(key)
|
||||
const updated: CloudSchedule = {
|
||||
...existing,
|
||||
enabled: body.enabled,
|
||||
hour_utc: hourUtc,
|
||||
hour_local: hourLocal,
|
||||
last_auto_sync_at: existing?.last_auto_sync_at ?? null,
|
||||
last_auto_sync_status: existing?.last_auto_sync_status ?? null,
|
||||
last_auto_sync_error: existing?.last_auto_sync_error ?? null,
|
||||
}
|
||||
await ctx.settings.set(key, updated)
|
||||
return NextResponse.json({ data: updated })
|
||||
} catch (err) {
|
||||
ctx.log.error('update schedule failed', err)
|
||||
return jsonError(
|
||||
err instanceof Error ? err.message : 'Invalid request body',
|
||||
400
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// Generate the archive set and sync it to one provider. Returns the sync
|
||||
// summary.
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/sync',
|
||||
handler: async (request, ctx) => {
|
||||
if (!ctx) return jsonError('Missing context', 500)
|
||||
const resolved = resolveProvider(request)
|
||||
if ('error' in resolved) return resolved.error
|
||||
try {
|
||||
const body = (await request.json().catch(() => ({}))) as {
|
||||
include_documents?: boolean
|
||||
allow_document_fallback?: boolean
|
||||
}
|
||||
const origin = resolveCallbackOrigin(new URL(request.url).origin)
|
||||
const result = await performSync({
|
||||
supabase: ctx.supabase,
|
||||
companyId: ctx.companyId,
|
||||
userId: ctx.userId,
|
||||
origin,
|
||||
includeDocuments: body.include_documents !== false,
|
||||
allowDocumentFallback: body.allow_document_fallback === true,
|
||||
provider: resolved.provider,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
if (result.reason === 'not_connected') {
|
||||
return jsonError('not_connected', 400)
|
||||
}
|
||||
if (result.reason === 'needs_reauth') {
|
||||
return jsonError('needs_reauth', 400)
|
||||
}
|
||||
if (result.reason === 'archive_too_large') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'archive_too_large',
|
||||
size_bytes: result.size_bytes,
|
||||
size_limit_bytes: result.size_limit_bytes,
|
||||
},
|
||||
{ status: 413 }
|
||||
)
|
||||
}
|
||||
return jsonError(result.message, 500)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
...result.lastSync,
|
||||
web_view_link: result.webViewLink,
|
||||
uploaded_count: result.uploadedCount,
|
||||
skipped_count: result.skippedCount,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
ctx.log.error('sync failed', err)
|
||||
return jsonError(
|
||||
err instanceof Error ? err.message : 'Sync failed',
|
||||
500
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const sendEmail = vi.fn()
|
||||
const isConfigured = vi.fn()
|
||||
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
getEmailService: () => ({ sendEmail, isConfigured }),
|
||||
}))
|
||||
|
||||
import {
|
||||
shouldSendBackupAlert,
|
||||
sendBackupFailureAlert,
|
||||
ALERT_FAILURE_THRESHOLD,
|
||||
ALERT_THROTTLE_MS,
|
||||
} from '../backup-alert'
|
||||
|
||||
const NOW = new Date('2026-07-12T04:00:00.000Z')
|
||||
|
||||
describe('shouldSendBackupAlert', () => {
|
||||
it('alerts immediately on needs_reauth regardless of failure count', () => {
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'needs_reauth',
|
||||
consecutiveFailures: 1,
|
||||
lastAlertAt: null,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('requires the failure threshold for repeated_failures', () => {
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'repeated_failures',
|
||||
consecutiveFailures: ALERT_FAILURE_THRESHOLD - 1,
|
||||
lastAlertAt: null,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'repeated_failures',
|
||||
consecutiveFailures: ALERT_FAILURE_THRESHOLD,
|
||||
lastAlertAt: null,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('throttles both kinds against last_alert_at', () => {
|
||||
const recent = new Date(NOW.getTime() - ALERT_THROTTLE_MS + 60_000).toISOString()
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'needs_reauth',
|
||||
consecutiveFailures: 0,
|
||||
lastAlertAt: recent,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'repeated_failures',
|
||||
consecutiveFailures: 10,
|
||||
lastAlertAt: recent,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(false)
|
||||
|
||||
const stale = new Date(NOW.getTime() - ALERT_THROTTLE_MS - 60_000).toISOString()
|
||||
expect(
|
||||
shouldSendBackupAlert({
|
||||
kind: 'needs_reauth',
|
||||
consecutiveFailures: 0,
|
||||
lastAlertAt: stale,
|
||||
now: NOW,
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Supabase stub: the two-step recipient lookup (company_members membership
|
||||
* check, then profiles email), and company_settings resolves a company name.
|
||||
*/
|
||||
function makeSupabase(options: { member?: unknown; companyName?: string | null } = {}) {
|
||||
const from = vi.fn().mockImplementation((table: string) => {
|
||||
const chain: any = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockImplementation(() => {
|
||||
if (table === 'company_members') {
|
||||
return Promise.resolve({
|
||||
data: options.member !== undefined ? options.member : { user_id: 'u-1' },
|
||||
error: null,
|
||||
})
|
||||
}
|
||||
if (table === 'profiles') {
|
||||
return Promise.resolve({ data: { email: '[email protected]' }, error: null })
|
||||
}
|
||||
return Promise.resolve({
|
||||
data: { company_name: options.companyName ?? 'Testbolag AB' },
|
||||
error: null,
|
||||
})
|
||||
}),
|
||||
}
|
||||
return chain
|
||||
})
|
||||
return { from } as any
|
||||
}
|
||||
|
||||
const baseInput = {
|
||||
companyId: 'c-1',
|
||||
userId: 'u-1',
|
||||
consecutiveFailures: 3,
|
||||
errorMessage: 'Drive quota exceeded',
|
||||
origin: 'https://app.test',
|
||||
} as const
|
||||
|
||||
describe('sendBackupFailureAlert', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isConfigured.mockReturnValue(true)
|
||||
sendEmail.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('does nothing when the email service is not configured', async () => {
|
||||
isConfigured.mockReturnValue(false)
|
||||
const result = await sendBackupFailureAlert(makeSupabase(), {
|
||||
...baseInput,
|
||||
kind: 'repeated_failures',
|
||||
})
|
||||
expect(result).toEqual({ sent: false, reason: 'email_not_configured' })
|
||||
expect(sendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not email a user who is no longer a company member', async () => {
|
||||
const result = await sendBackupFailureAlert(makeSupabase({ member: null }), {
|
||||
...baseInput,
|
||||
kind: 'repeated_failures',
|
||||
})
|
||||
expect(result).toEqual({ sent: false, reason: 'no_recipient' })
|
||||
expect(sendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends a repeated-failures email with count, error and link', async () => {
|
||||
const result = await sendBackupFailureAlert(makeSupabase(), {
|
||||
...baseInput,
|
||||
kind: 'repeated_failures',
|
||||
})
|
||||
expect(result).toEqual({ sent: true })
|
||||
expect(sendEmail).toHaveBeenCalledTimes(1)
|
||||
const options = sendEmail.mock.calls[0][0]
|
||||
expect(options.to).toBe('[email protected]')
|
||||
expect(options.subject).toContain('misslyckas')
|
||||
expect(options.text).toContain('3 nätter i rad')
|
||||
expect(options.text).toContain('Drive quota exceeded')
|
||||
expect(options.text).toContain('https://app.test/import#cloud-backup')
|
||||
expect(options.html).toContain('Testbolag AB')
|
||||
})
|
||||
|
||||
it('sends a needs_reauth email pointing at the reconnect flow', async () => {
|
||||
const result = await sendBackupFailureAlert(makeSupabase(), {
|
||||
...baseInput,
|
||||
kind: 'needs_reauth',
|
||||
errorMessage: null,
|
||||
})
|
||||
expect(result).toEqual({ sent: true })
|
||||
const options = sendEmail.mock.calls[0][0]
|
||||
expect(options.subject).toContain('pausad')
|
||||
expect(options.text).toContain('Koppla om Google Drive')
|
||||
expect(options.text).toContain('https://app.test/import#cloud-backup')
|
||||
})
|
||||
|
||||
it('reports send failures without throwing', async () => {
|
||||
sendEmail.mockResolvedValue({ success: false, error: 'smtp down' })
|
||||
const result = await sendBackupFailureAlert(makeSupabase(), {
|
||||
...baseInput,
|
||||
kind: 'repeated_failures',
|
||||
})
|
||||
expect(result).toEqual({ sent: false, reason: 'send_failed' })
|
||||
})
|
||||
|
||||
it('escapes HTML in the error message', async () => {
|
||||
await sendBackupFailureAlert(makeSupabase(), {
|
||||
...baseInput,
|
||||
kind: 'repeated_failures',
|
||||
errorMessage: '<script>alert(1)</script>',
|
||||
})
|
||||
const options = sendEmail.mock.calls[0][0]
|
||||
expect(options.html).not.toContain('<script>')
|
||||
expect(options.html).toContain('<script>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { resolveCallbackOrigin } from '../callback-origin'
|
||||
|
||||
const originalAppUrl = process.env.NEXT_PUBLIC_APP_URL
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.NEXT_PUBLIC_APP_URL
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalAppUrl === undefined) delete process.env.NEXT_PUBLIC_APP_URL
|
||||
else process.env.NEXT_PUBLIC_APP_URL = originalAppUrl
|
||||
})
|
||||
|
||||
describe('resolveCallbackOrigin', () => {
|
||||
it('falls back to the request origin when no canonical URL is configured', () => {
|
||||
expect(resolveCallbackOrigin('https://self-hosted.example')).toBe(
|
||||
'https://self-hosted.example'
|
||||
)
|
||||
})
|
||||
|
||||
it('prefers the canonical app origin over the request origin', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
|
||||
expect(resolveCallbackOrigin('https://app.gnubok.se')).toBe(
|
||||
'https://app.accounted.se'
|
||||
)
|
||||
})
|
||||
|
||||
it('normalizes a trailing slash so the redirect URI stays byte-identical', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se/'
|
||||
expect(resolveCallbackOrigin('https://other.example')).toBe(
|
||||
'https://app.accounted.se'
|
||||
)
|
||||
})
|
||||
|
||||
it('strips any path from the configured URL', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se/dashboard'
|
||||
expect(resolveCallbackOrigin('https://other.example')).toBe(
|
||||
'https://app.accounted.se'
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores a blank value', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = ' '
|
||||
expect(resolveCallbackOrigin('https://other.example')).toBe(
|
||||
'https://other.example'
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the request origin when the configured URL is malformed', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'not a url'
|
||||
expect(resolveCallbackOrigin('https://other.example')).toBe(
|
||||
'https://other.example'
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the request origin for a non-web URL scheme', () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'mailto:[email protected]'
|
||||
expect(resolveCallbackOrigin('https://other.example')).toBe(
|
||||
'https://other.example'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import {
|
||||
encryptToken,
|
||||
decryptToken,
|
||||
createOAuthState,
|
||||
verifyOAuthState,
|
||||
} from '../crypto'
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-role-key-that-is-long-enough'
|
||||
})
|
||||
|
||||
describe('token encryption', () => {
|
||||
it('round-trips a refresh token', () => {
|
||||
const token = '1//0abcdef_refresh_token_value'
|
||||
const encrypted = encryptToken(token)
|
||||
expect(encrypted).not.toContain(token)
|
||||
expect(decryptToken(encrypted)).toBe(token)
|
||||
})
|
||||
|
||||
it('produces different ciphertext for the same plaintext (IV is random)', () => {
|
||||
const token = 'same-token'
|
||||
const a = encryptToken(token)
|
||||
const b = encryptToken(token)
|
||||
expect(a).not.toBe(b)
|
||||
expect(decryptToken(a)).toBe(token)
|
||||
expect(decryptToken(b)).toBe(token)
|
||||
})
|
||||
|
||||
it('fails to decrypt tampered ciphertext', () => {
|
||||
const encrypted = encryptToken('secret')
|
||||
// Flip a byte in the middle of the ciphertext.
|
||||
const buf = Buffer.from(encrypted, 'base64url')
|
||||
buf[30] ^= 0xff
|
||||
const tampered = buf.toString('base64url')
|
||||
expect(() => decryptToken(tampered)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('OAuth state', () => {
|
||||
it('round-trips userId and companyId', () => {
|
||||
const state = createOAuthState('user-1', 'company-1')
|
||||
expect(verifyOAuthState(state)).toEqual({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null for garbage state', () => {
|
||||
expect(verifyOAuthState('not-a-valid-state')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for expired state', () => {
|
||||
const state = createOAuthState('user-1', 'company-1')
|
||||
// Fast-forward past the 10-minute TTL.
|
||||
const realNow = Date.now
|
||||
Date.now = () => realNow() + 11 * 60 * 1000
|
||||
try {
|
||||
expect(verifyOAuthState(state)).toBeNull()
|
||||
} finally {
|
||||
Date.now = realNow
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import {
|
||||
asciiJson,
|
||||
dropboxContentHash,
|
||||
sanitizeDropboxName,
|
||||
uploadDropboxFile,
|
||||
} from '../dropbox-client'
|
||||
|
||||
const CHUNK = 8 * 1024 * 1024
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
/** Dropbox's content_hash, computed independently of the implementation. */
|
||||
function expectedHash(bytes: Uint8Array): string {
|
||||
const blocks: Buffer[] = []
|
||||
for (let i = 0; i < bytes.length; i += 4 * 1024 * 1024) {
|
||||
blocks.push(
|
||||
createHash('sha256')
|
||||
.update(Buffer.from(bytes.subarray(i, Math.min(i + 4 * 1024 * 1024, bytes.length))))
|
||||
.digest()
|
||||
)
|
||||
}
|
||||
return createHash('sha256').update(Buffer.concat(blocks)).digest('hex')
|
||||
}
|
||||
|
||||
function makeBuffer(size: number, fill = 7): ArrayBuffer {
|
||||
return new Uint8Array(size).fill(fill).buffer
|
||||
}
|
||||
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('dropboxContentHash', () => {
|
||||
it('matches the block-wise definition for a multi-block payload', () => {
|
||||
const bytes = new Uint8Array(9 * 1024 * 1024).fill(3)
|
||||
expect(dropboxContentHash(bytes.buffer)).toBe(expectedHash(bytes))
|
||||
})
|
||||
|
||||
it('hashes an empty file as the hash of an empty concatenation', () => {
|
||||
expect(dropboxContentHash(new ArrayBuffer(0))).toBe(
|
||||
createHash('sha256').update(Buffer.alloc(0)).digest('hex')
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('asciiJson', () => {
|
||||
it('escapes Swedish characters so the header stays ASCII', () => {
|
||||
const encoded = asciiJson({ path: '/Bolag/LÄSMIG.txt' })
|
||||
expect([...encoded].every((c) => c.codePointAt(0)! < 128)).toBe(true)
|
||||
expect(JSON.parse(encoded)).toEqual({ path: '/Bolag/LÄSMIG.txt' })
|
||||
})
|
||||
|
||||
it('escapes astral characters as surrogate pairs', () => {
|
||||
const encoded = asciiJson({ n: '🚀' })
|
||||
expect(encoded).toContain('\\ud83d')
|
||||
expect(encoded).toContain('\\ude80')
|
||||
expect(JSON.parse(encoded)).toEqual({ n: '🚀' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeDropboxName', () => {
|
||||
it('replaces characters Dropbox rejects in a path component', () => {
|
||||
expect(sanitizeDropboxName('Bolaget AB / Filial: X?')).toBe('Bolaget AB - Filial- X-')
|
||||
})
|
||||
|
||||
it('neutralises a backslash so a name cannot escape its folder', () => {
|
||||
expect(sanitizeDropboxName(`a${String.fromCharCode(92)}b`)).toBe('a-b')
|
||||
})
|
||||
|
||||
it('strips trailing dots and spaces', () => {
|
||||
expect(sanitizeDropboxName('Firma AB. ')).toBe('Firma AB')
|
||||
})
|
||||
|
||||
it('never returns an empty component', () => {
|
||||
expect(sanitizeDropboxName('///')).toBe('---')
|
||||
expect(sanitizeDropboxName('')).toBe('foretag')
|
||||
})
|
||||
|
||||
it('keeps Swedish characters: Dropbox accepts them, the header escapes them', () => {
|
||||
expect(sanitizeDropboxName('Åkeri Ödmjuk AB')).toBe('Åkeri Ödmjuk AB')
|
||||
})
|
||||
})
|
||||
|
||||
describe('uploadDropboxFile', () => {
|
||||
it('uses a single request for a payload that fits one chunk', async () => {
|
||||
const data = makeBuffer(1024)
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
name: 'Grunddata.zip',
|
||||
path_display: '/Bolag/Grunddata.zip',
|
||||
size: 1024,
|
||||
content_hash: dropboxContentHash(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadDropboxFile('token', '/Bolag/Grunddata.zip', data)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('https://content.dropboxapi.com/2/files/upload')
|
||||
expect(JSON.parse((init.headers as Record<string, string>)['Dropbox-API-Arg'])).toEqual({
|
||||
path: '/Bolag/Grunddata.zip',
|
||||
mode: 'overwrite',
|
||||
mute: true,
|
||||
autorename: false,
|
||||
})
|
||||
expect(result).toMatchObject({ path: '/Bolag/Grunddata.zip', size_bytes: 1024 })
|
||||
})
|
||||
|
||||
it('splits a large payload into a start/append/finish session', async () => {
|
||||
const data = makeBuffer(CHUNK * 2 + 10)
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(jsonResponse({ session_id: 'sess-1' }))
|
||||
.mockResolvedValueOnce(jsonResponse({}))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
name: 'Arkiv 2024.zip',
|
||||
path_display: '/Bolag/Arkiv 2024.zip',
|
||||
size: data.byteLength,
|
||||
content_hash: dropboxContentHash(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadDropboxFile('token', '/Bolag/Arkiv 2024.zip', data)
|
||||
|
||||
const endpoints = fetchMock.mock.calls.map(([url]) => String(url).split('/2')[1])
|
||||
expect(endpoints).toEqual([
|
||||
'/files/upload_session/start',
|
||||
'/files/upload_session/append_v2',
|
||||
'/files/upload_session/finish',
|
||||
])
|
||||
// The append cursor must sit exactly one chunk in, and finish two chunks in:
|
||||
// a wrong offset silently truncates or duplicates archive bytes.
|
||||
const appendArg = JSON.parse(
|
||||
(fetchMock.mock.calls[1][1].headers as Record<string, string>)['Dropbox-API-Arg']
|
||||
)
|
||||
expect(appendArg.cursor).toEqual({ session_id: 'sess-1', offset: CHUNK })
|
||||
const finishArg = JSON.parse(
|
||||
(fetchMock.mock.calls[2][1].headers as Record<string, string>)['Dropbox-API-Arg']
|
||||
)
|
||||
expect(finishArg.cursor).toEqual({ session_id: 'sess-1', offset: CHUNK * 2 })
|
||||
expect(finishArg.commit.mode).toBe('overwrite')
|
||||
expect(result.size_bytes).toBe(data.byteLength)
|
||||
})
|
||||
|
||||
it('closes a payload that is an exact multiple of the chunk size', async () => {
|
||||
const data = makeBuffer(CHUNK * 2)
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(jsonResponse({ session_id: 'sess-2' }))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
name: 'Arkiv 2024.zip',
|
||||
path_display: '/Bolag/Arkiv 2024.zip',
|
||||
size: data.byteLength,
|
||||
content_hash: dropboxContentHash(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadDropboxFile('token', '/Bolag/Arkiv 2024.zip', data)
|
||||
|
||||
const endpoints = fetchMock.mock.calls.map(([url]) => String(url).split('/2')[1])
|
||||
expect(endpoints).toEqual([
|
||||
'/files/upload_session/start',
|
||||
'/files/upload_session/finish',
|
||||
])
|
||||
expect(result.size_bytes).toBe(data.byteLength)
|
||||
})
|
||||
|
||||
it('retries the whole upload once when the stored content hash disagrees', async () => {
|
||||
const data = makeBuffer(512)
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ name: 'x.zip', path_display: '/x.zip', size: 512, content_hash: 'wrong' })
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
name: 'x.zip',
|
||||
path_display: '/x.zip',
|
||||
size: 512,
|
||||
content_hash: dropboxContentHash(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadDropboxFile('token', '/x.zip', data)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(result.content_hash).toBe(dropboxContentHash(data))
|
||||
})
|
||||
|
||||
it('throws rather than record a corrupted backup when the hash never matches', async () => {
|
||||
const data = makeBuffer(512)
|
||||
// A fresh Response per call: a body can only be read once, and the retry
|
||||
// issues a genuinely new request.
|
||||
fetchMock.mockImplementation(async () =>
|
||||
jsonResponse({ name: 'x.zip', path_display: '/x.zip', size: 512, content_hash: 'wrong' })
|
||||
)
|
||||
|
||||
await expect(uploadDropboxFile('token', '/x.zip', data)).rejects.toThrow(
|
||||
/checksum mismatch/
|
||||
)
|
||||
})
|
||||
|
||||
it('retries a 5xx and succeeds on a later attempt', async () => {
|
||||
const data = makeBuffer(256)
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(new Response('boom', { status: 503 }))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
name: 'x.zip',
|
||||
path_display: '/x.zip',
|
||||
size: 256,
|
||||
content_hash: dropboxContentHash(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadDropboxFile('token', '/x.zip', data)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(result.size_bytes).toBe(256)
|
||||
})
|
||||
|
||||
it('does not retry a 4xx: it can only fail the same way again', async () => {
|
||||
fetchMock.mockImplementation(
|
||||
async () => new Response('{"error_summary":"path/malformed_path/"}', { status: 400 })
|
||||
)
|
||||
|
||||
await expect(uploadDropboxFile('token', '/x.zip', makeBuffer(256))).rejects.toThrow(
|
||||
/malformed_path/
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,179 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
vi.mock('../dropbox-client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../dropbox-client')>()
|
||||
return { ...actual, uploadDropboxFile: vi.fn() }
|
||||
})
|
||||
|
||||
import { dropboxProvider } from '../dropbox-provider'
|
||||
import { uploadDropboxFile } from '../dropbox-client'
|
||||
import type { CloudConnection } from '../../types'
|
||||
|
||||
const mockUpload = vi.mocked(uploadDropboxFile)
|
||||
|
||||
function makeConnection(overrides: Partial<CloudConnection> = {}): CloudConnection {
|
||||
return {
|
||||
refresh_token_encrypted: 'enc',
|
||||
account_email: '[email protected]',
|
||||
connected_at: '2026-01-01T00:00:00.000Z',
|
||||
root_folder_id: null,
|
||||
company_folder_id: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const ORIGINAL_APP_FOLDER = process.env.DROPBOX_APP_FOLDER_NAME
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
delete process.env.DROPBOX_APP_FOLDER_NAME
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_APP_FOLDER === undefined) delete process.env.DROPBOX_APP_FOLDER_NAME
|
||||
else process.env.DROPBOX_APP_FOLDER_NAME = ORIGINAL_APP_FOLDER
|
||||
})
|
||||
|
||||
describe('dropboxProvider storage keys', () => {
|
||||
it('owns keys distinct from Google Drive so the two never collide', () => {
|
||||
expect(dropboxProvider.keys).toEqual({
|
||||
connection: 'dropbox_connection',
|
||||
lastSync: 'dropbox_last_sync',
|
||||
schedule: 'dropbox_schedule',
|
||||
})
|
||||
})
|
||||
|
||||
it('uses its own OAuth callback path', () => {
|
||||
expect(dropboxProvider.callbackPath).toBe('/oauth/dropbox/callback')
|
||||
})
|
||||
})
|
||||
|
||||
describe('dropboxProvider.prepareTarget', () => {
|
||||
it('derives the company folder path without calling Dropbox', async () => {
|
||||
const { target, connectionPatch } = await dropboxProvider.prepareTarget({
|
||||
accessToken: 'token',
|
||||
connection: makeConnection(),
|
||||
companyLabel: 'Testbolag AB (556000-0000)',
|
||||
})
|
||||
|
||||
expect(target.folderId).toBe('/Testbolag AB (556000-0000)')
|
||||
expect(connectionPatch).toEqual({
|
||||
company_folder_path: '/Testbolag AB (556000-0000)',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports no change when the stored path already matches', async () => {
|
||||
const { connectionPatch } = await dropboxProvider.prepareTarget({
|
||||
accessToken: 'token',
|
||||
connection: makeConnection({ company_folder_path: '/Testbolag AB (556000-0000)' }),
|
||||
companyLabel: 'Testbolag AB (556000-0000)',
|
||||
})
|
||||
|
||||
expect(connectionPatch).toBeNull()
|
||||
})
|
||||
|
||||
it('sanitises a company name that would produce an invalid path', async () => {
|
||||
const { target } = await dropboxProvider.prepareTarget({
|
||||
accessToken: 'token',
|
||||
connection: makeConnection(),
|
||||
companyLabel: 'Bolaget AB / Filial (556000-0000)',
|
||||
})
|
||||
|
||||
// A single leading slash: the label must not be able to add path segments.
|
||||
expect(target.folderId).toBe('/Bolaget AB - Filial (556000-0000)')
|
||||
expect(target.folderId.slice(1)).not.toContain('/')
|
||||
})
|
||||
|
||||
it('links to the Apps root when the app folder name is unknown', async () => {
|
||||
const { target } = await dropboxProvider.prepareTarget({
|
||||
accessToken: 'token',
|
||||
connection: makeConnection(),
|
||||
companyLabel: 'Testbolag AB',
|
||||
})
|
||||
|
||||
expect(target.webViewLink).toBe('https://www.dropbox.com/home/Apps')
|
||||
})
|
||||
|
||||
it('deep-links into the company folder when the app folder name is configured', async () => {
|
||||
process.env.DROPBOX_APP_FOLDER_NAME = 'Accounted'
|
||||
|
||||
const { target } = await dropboxProvider.prepareTarget({
|
||||
accessToken: 'token',
|
||||
connection: makeConnection(),
|
||||
companyLabel: 'Testbolag AB',
|
||||
})
|
||||
|
||||
expect(target.webViewLink).toBe(
|
||||
'https://www.dropbox.com/home/Apps/Accounted/Testbolag%20AB'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('dropboxProvider.putFile', () => {
|
||||
it('writes under the company folder and returns the path as the handle', async () => {
|
||||
mockUpload.mockResolvedValue({
|
||||
path: '/Testbolag AB/Arkiv 2024.zip',
|
||||
name: 'Arkiv 2024.zip',
|
||||
size_bytes: 42,
|
||||
})
|
||||
|
||||
const result = await dropboxProvider.putFile({
|
||||
accessToken: 'token',
|
||||
target: {
|
||||
folderId: '/Testbolag AB',
|
||||
webViewLink: 'https://www.dropbox.com/home/Apps',
|
||||
},
|
||||
name: 'Arkiv 2024.zip',
|
||||
data: new ArrayBuffer(42),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
expect(mockUpload).toHaveBeenCalledWith(
|
||||
'token',
|
||||
'/Testbolag AB/Arkiv 2024.zip',
|
||||
expect.any(ArrayBuffer)
|
||||
)
|
||||
expect(result).toEqual({
|
||||
id: '/Testbolag AB/Arkiv 2024.zip',
|
||||
name: 'Arkiv 2024.zip',
|
||||
size_bytes: 42,
|
||||
})
|
||||
})
|
||||
|
||||
it('overwrites by path and ignores the previous handle', async () => {
|
||||
mockUpload.mockResolvedValue({
|
||||
path: '/Bolag/Grunddata.zip',
|
||||
name: 'Grunddata.zip',
|
||||
size_bytes: 8,
|
||||
})
|
||||
|
||||
await dropboxProvider.putFile({
|
||||
accessToken: 'token',
|
||||
target: { folderId: '/Bolag', webViewLink: 'https://www.dropbox.com/home/Apps' },
|
||||
name: 'Grunddata.zip',
|
||||
previousId: '/somewhere/else/Grunddata.zip',
|
||||
data: new ArrayBuffer(8),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
expect(mockUpload.mock.calls[0][1]).toBe('/Bolag/Grunddata.zip')
|
||||
})
|
||||
|
||||
it('keeps Swedish file names intact: the header encoder handles them', async () => {
|
||||
mockUpload.mockResolvedValue({
|
||||
path: '/Bolag/LÄSMIG.txt',
|
||||
name: 'LÄSMIG.txt',
|
||||
size_bytes: 11,
|
||||
})
|
||||
|
||||
await dropboxProvider.putFile({
|
||||
accessToken: 'token',
|
||||
target: { folderId: '/Bolag', webViewLink: 'https://www.dropbox.com/home/Apps' },
|
||||
name: 'LÄSMIG.txt',
|
||||
data: new ArrayBuffer(11),
|
||||
contentType: 'text/plain',
|
||||
})
|
||||
|
||||
expect(mockUpload.mock.calls[0][1]).toBe('/Bolag/LÄSMIG.txt')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,297 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import {
|
||||
DriveFileGoneError,
|
||||
ensureFolder,
|
||||
getFileMeta,
|
||||
updateFile,
|
||||
uploadFile,
|
||||
} from '../google-drive'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('ensureFolder', () => {
|
||||
it('returns existing folder when found', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ files: [{ id: 'folder-1', name: 'gnubok' }] }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
)
|
||||
const folder = await ensureFolder('at', 'gnubok', null)
|
||||
expect(folder.id).toBe('folder-1')
|
||||
// Only the search call; no create needed.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const url = fetchMock.mock.calls[0][0] as string
|
||||
expect(url).toContain('/files?q=')
|
||||
expect(decodeURIComponent(url)).toContain(`name = 'gnubok'`)
|
||||
expect(decodeURIComponent(url)).toContain(`'root' in parents`)
|
||||
})
|
||||
|
||||
it('creates a new folder when none exists', async () => {
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ files: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ id: 'new-id', name: 'gnubok' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
const folder = await ensureFolder('at', 'gnubok', null)
|
||||
expect(folder.id).toBe('new-id')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const createCall = fetchMock.mock.calls[1]
|
||||
expect((createCall[1] as RequestInit).method).toBe('POST')
|
||||
const body = JSON.parse(String((createCall[1] as RequestInit).body))
|
||||
expect(body.mimeType).toBe('application/vnd.google-apps.folder')
|
||||
expect(body.name).toBe('gnubok')
|
||||
})
|
||||
|
||||
it('escapes single quotes in folder name and scopes to parent', async () => {
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(
|
||||
// findFolderByName → match so we never hit create.
|
||||
new Response(JSON.stringify({ files: [{ id: 'x', name: "Kalle's" }] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
await ensureFolder('at', "Kalle's", 'parent-id')
|
||||
const searchUrl = decodeURIComponent(fetchMock.mock.calls[0][0] as string)
|
||||
expect(searchUrl).toContain(`name = 'Kalle\\'s'`)
|
||||
expect(searchUrl).toContain(`'parent-id' in parents`)
|
||||
})
|
||||
})
|
||||
|
||||
/** Resumable init response: 200 with a session URL in the Location header. */
|
||||
function initResponse(): Response {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: { Location: 'https://upload.session/xyz' },
|
||||
})
|
||||
}
|
||||
|
||||
function fileResponse(
|
||||
file: Record<string, unknown>,
|
||||
status = 200
|
||||
): Response {
|
||||
return new Response(JSON.stringify(file), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function md5Of(data: ArrayBuffer): string {
|
||||
return createHash('md5').update(Buffer.from(data)).digest('hex')
|
||||
}
|
||||
|
||||
describe('uploadFile (resumable)', () => {
|
||||
it('initiates a resumable session with metadata, then uploads the bytes', async () => {
|
||||
const data = new Uint8Array([1, 2, 3, 4, 5]).buffer
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({
|
||||
id: 'file-123',
|
||||
name: 'arkiv.zip',
|
||||
size: '2048',
|
||||
webViewLink: 'https://drive.google.com/file/d/file-123/view',
|
||||
md5Checksum: md5Of(data),
|
||||
})
|
||||
)
|
||||
|
||||
const result = await uploadFile('access-tok', 'folder-1', 'arkiv.zip', data)
|
||||
|
||||
expect(result.id).toBe('file-123')
|
||||
expect(result.size_bytes).toBe(2048)
|
||||
expect(result.md5_checksum).toBe(md5Of(data))
|
||||
|
||||
const [initUrl, initInit] = fetchMock.mock.calls[0]
|
||||
expect(initUrl).toContain('uploadType=resumable')
|
||||
expect((initInit as RequestInit).method).toBe('POST')
|
||||
const initHeaders = (initInit as RequestInit).headers as Record<string, string>
|
||||
expect(initHeaders.Authorization).toBe('Bearer access-tok')
|
||||
expect(initHeaders['X-Upload-Content-Length']).toBe('5')
|
||||
const metadata = JSON.parse(String((initInit as RequestInit).body))
|
||||
expect(metadata.name).toBe('arkiv.zip')
|
||||
expect(metadata.parents).toEqual(['folder-1'])
|
||||
|
||||
const [chunkUrl, chunkInit] = fetchMock.mock.calls[1]
|
||||
expect(chunkUrl).toBe('https://upload.session/xyz')
|
||||
expect((chunkInit as RequestInit).method).toBe('PUT')
|
||||
const chunkHeaders = (chunkInit as RequestInit).headers as Record<string, string>
|
||||
expect(chunkHeaders['Content-Range']).toBe('bytes 0-4/5')
|
||||
})
|
||||
|
||||
it('splits large payloads into chunks and follows 308 continuations', async () => {
|
||||
const CHUNK = 8 * 1024 * 1024
|
||||
const data = new Uint8Array(CHUNK + 10).buffer
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 308,
|
||||
headers: { Range: `bytes=0-${CHUNK - 1}` },
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({ id: 'f-1', name: 'big.zip', md5Checksum: md5Of(data) })
|
||||
)
|
||||
|
||||
const result = await uploadFile('at', 'folder', 'big.zip', data)
|
||||
expect(result.id).toBe('f-1')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
const firstRange = (fetchMock.mock.calls[1][1] as RequestInit)
|
||||
.headers as Record<string, string>
|
||||
expect(firstRange['Content-Range']).toBe(`bytes 0-${CHUNK - 1}/${CHUNK + 10}`)
|
||||
const secondRange = (fetchMock.mock.calls[2][1] as RequestInit)
|
||||
.headers as Record<string, string>
|
||||
expect(secondRange['Content-Range']).toBe(`bytes ${CHUNK}-${CHUNK + 9}/${CHUNK + 10}`)
|
||||
})
|
||||
|
||||
it('retries a chunk on 5xx before giving up', async () => {
|
||||
const data = new Uint8Array([7, 7]).buffer
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(new Response('flaky', { status: 502 }))
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({ id: 'f-1', name: 'a.zip', md5Checksum: md5Of(data) })
|
||||
)
|
||||
|
||||
const result = await uploadFile('at', 'folder', 'a.zip', data)
|
||||
expect(result.id).toBe('f-1')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('throws with Drive error body when the init fails', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('quota exceeded', { status: 403 })
|
||||
)
|
||||
await expect(
|
||||
uploadFile('at', 'folder', 'a.zip', new Uint8Array(1).buffer)
|
||||
).rejects.toThrow(/403/)
|
||||
})
|
||||
|
||||
it('retries the whole upload once on checksum mismatch, then succeeds', async () => {
|
||||
const data = new Uint8Array([1, 2, 3, 4, 5]).buffer
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({ id: 'f-1', name: 'a.zip', md5Checksum: 'corrupted' })
|
||||
)
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({ id: 'f-2', name: 'a.zip', md5Checksum: md5Of(data) })
|
||||
)
|
||||
|
||||
const result = await uploadFile('at', 'folder', 'a.zip', data)
|
||||
expect(result.id).toBe('f-2')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('throws after two checksum mismatches', async () => {
|
||||
let call = 0
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {
|
||||
call++
|
||||
return call % 2 === 1
|
||||
? initResponse()
|
||||
: fileResponse({ id: 'f-1', name: 'a.zip', md5Checksum: 'corrupted' })
|
||||
})
|
||||
await expect(
|
||||
uploadFile('at', 'folder', 'a.zip', new Uint8Array([9]).buffer)
|
||||
).rejects.toThrow(/checksum mismatch/)
|
||||
})
|
||||
|
||||
it('trusts the upload when Drive omits md5Checksum', async () => {
|
||||
vi.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(fileResponse({ id: 'f-1', name: 'a.zip' }))
|
||||
const result = await uploadFile('at', 'folder', 'a.zip', new Uint8Array([9]).buffer)
|
||||
expect(result.id).toBe('f-1')
|
||||
expect(result.md5_checksum).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateFile (resumable, in place)', () => {
|
||||
it('PATCHes an existing file id and uploads the new content', async () => {
|
||||
const data = new Uint8Array([4, 5, 6]).buffer
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(initResponse())
|
||||
.mockResolvedValueOnce(
|
||||
fileResponse({ id: 'file-9', name: 'Arkiv 2024.zip', md5Checksum: md5Of(data) })
|
||||
)
|
||||
|
||||
const result = await updateFile('at', 'file-9', data)
|
||||
expect(result.id).toBe('file-9')
|
||||
|
||||
const [initUrl, initInit] = fetchMock.mock.calls[0]
|
||||
expect(initUrl).toContain('/file-9?uploadType=resumable')
|
||||
expect((initInit as RequestInit).method).toBe('PATCH')
|
||||
// No metadata body on a content-only update.
|
||||
expect((initInit as RequestInit).body).toBeUndefined()
|
||||
})
|
||||
|
||||
it('throws DriveFileGoneError when the file id no longer exists', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('not found', { status: 404 })
|
||||
)
|
||||
await expect(
|
||||
updateFile('at', 'gone-id', new Uint8Array([1]).buffer)
|
||||
).rejects.toBeInstanceOf(DriveFileGoneError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileMeta', () => {
|
||||
it('returns metadata with trashed flag', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ id: 'f-1', name: 'gnubok', trashed: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
const meta = await getFileMeta('at', 'f-1')
|
||||
expect(meta).toEqual({ id: 'f-1', name: 'gnubok', trashed: true })
|
||||
const url = fetchMock.mock.calls[0][0] as string
|
||||
expect(url).toContain('/files/f-1')
|
||||
expect(url).toContain('fields=id,name,trashed')
|
||||
})
|
||||
|
||||
it('defaults trashed to false when the field is absent', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ id: 'f-1', name: 'gnubok' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
const meta = await getFileMeta('at', 'f-1')
|
||||
expect(meta?.trashed).toBe(false)
|
||||
})
|
||||
|
||||
it('returns null on 404 (deleted or invisible to the scope)', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('not found', { status: 404 })
|
||||
)
|
||||
expect(await getFileMeta('at', 'gone')).toBeNull()
|
||||
})
|
||||
|
||||
it('throws on other errors', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('server error', { status: 500 })
|
||||
)
|
||||
await expect(getFileMeta('at', 'f-1')).rejects.toThrow(/500/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import {
|
||||
buildAuthorizationUrl,
|
||||
exchangeCodeForTokens,
|
||||
refreshAccessToken,
|
||||
getOAuthEnv,
|
||||
GoogleTokenRefreshError,
|
||||
} from '../google-oauth'
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.GOOGLE_CLIENT_ID = 'test-client-id'
|
||||
process.env.GOOGLE_CLIENT_SECRET = 'test-client-secret'
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('getOAuthEnv', () => {
|
||||
it('builds redirect URI from origin', () => {
|
||||
const env = getOAuthEnv('https://app.example.com')
|
||||
expect(env.redirectUri).toBe(
|
||||
'https://app.example.com/api/extensions/ext/cloud-backup/oauth/callback'
|
||||
)
|
||||
expect(env.clientId).toBe('test-client-id')
|
||||
})
|
||||
|
||||
it('throws when env vars missing', () => {
|
||||
delete process.env.GOOGLE_CLIENT_ID
|
||||
expect(() => getOAuthEnv('http://localhost:3000')).toThrow(/GOOGLE_CLIENT_ID/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAuthorizationUrl', () => {
|
||||
it('includes scope, offline access, consent prompt, and state', () => {
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
const url = buildAuthorizationUrl(env, 'abc123state')
|
||||
const parsed = new URL(url)
|
||||
expect(parsed.origin + parsed.pathname).toBe(
|
||||
'https://accounts.google.com/o/oauth2/v2/auth'
|
||||
)
|
||||
expect(parsed.searchParams.get('access_type')).toBe('offline')
|
||||
expect(parsed.searchParams.get('prompt')).toBe('consent')
|
||||
expect(parsed.searchParams.get('state')).toBe('abc123state')
|
||||
expect(parsed.searchParams.get('scope')).toContain(
|
||||
'https://www.googleapis.com/auth/drive.file'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('exchangeCodeForTokens', () => {
|
||||
it('posts form-encoded body and parses token response', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
access_token: 'at',
|
||||
refresh_token: 'rt',
|
||||
expires_in: 3600,
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
)
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
const result = await exchangeCodeForTokens(env, 'auth-code')
|
||||
|
||||
expect(result.refresh_token).toBe('rt')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('https://oauth2.googleapis.com/token')
|
||||
expect((init as RequestInit).method).toBe('POST')
|
||||
expect(String((init as RequestInit).body)).toContain('grant_type=authorization_code')
|
||||
expect(String((init as RequestInit).body)).toContain('code=auth-code')
|
||||
})
|
||||
|
||||
it('throws a clear error when no refresh_token is returned', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ access_token: 'at', expires_in: 3600 }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
await expect(exchangeCodeForTokens(env, 'code')).rejects.toThrow(/refresh token/i)
|
||||
})
|
||||
|
||||
it('throws on non-OK response', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('Bad Request', { status: 400 })
|
||||
)
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
await expect(exchangeCodeForTokens(env, 'code')).rejects.toThrow(/400/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('refreshAccessToken', () => {
|
||||
it('returns a fresh access token', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ access_token: 'new-at', expires_in: 3600 }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
const result = await refreshAccessToken(env, 'old-refresh')
|
||||
expect(result.access_token).toBe('new-at')
|
||||
})
|
||||
|
||||
it('throws GoogleTokenRefreshError carrying status and body on non-OK response', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response('{"error":"invalid_grant"}', { status: 400 })
|
||||
)
|
||||
const env = getOAuthEnv('http://localhost:3000')
|
||||
const err = await refreshAccessToken(env, 'dead-refresh').catch((e) => e)
|
||||
expect(err).toBeInstanceOf(GoogleTokenRefreshError)
|
||||
expect(err.status).toBe(400)
|
||||
expect(err.body).toContain('invalid_grant')
|
||||
expect(err.message).toContain('400')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GoogleTokenRefreshError.isInvalidGrant', () => {
|
||||
it('is true only for a 400 whose body mentions invalid_grant', () => {
|
||||
expect(
|
||||
new GoogleTokenRefreshError(400, '{"error":"invalid_grant"}').isInvalidGrant
|
||||
).toBe(true)
|
||||
expect(
|
||||
new GoogleTokenRefreshError(400, '{"error":"invalid_request"}').isInvalidGrant
|
||||
).toBe(false)
|
||||
expect(
|
||||
new GoogleTokenRefreshError(500, '{"error":"invalid_grant"}').isInvalidGrant
|
||||
).toBe(false)
|
||||
expect(new GoogleTokenRefreshError(503, 'Service Unavailable').isInvalidGrant).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isScheduleDue, stockholmHourToUtcHour } from '../schedule'
|
||||
import type { GoogleDriveSchedule } from '../../types'
|
||||
|
||||
function makeSchedule(overrides: Partial<GoogleDriveSchedule> = {}): GoogleDriveSchedule {
|
||||
return {
|
||||
enabled: true,
|
||||
hour_utc: 3,
|
||||
last_auto_sync_at: null,
|
||||
last_auto_sync_status: null,
|
||||
last_auto_sync_error: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
// Fixed reference: 2026-07-12 12:30 UTC.
|
||||
const NOW = new Date('2026-07-12T12:30:00.000Z')
|
||||
|
||||
describe('isScheduleDue', () => {
|
||||
it('is false when the schedule is missing or disabled', () => {
|
||||
expect(isScheduleDue(null, NOW)).toBe(false)
|
||||
expect(isScheduleDue(undefined, NOW)).toBe(false)
|
||||
expect(isScheduleDue(makeSchedule({ enabled: false }), NOW)).toBe(false)
|
||||
})
|
||||
|
||||
it('is false when hour_utc is invalid', () => {
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: -1 }), NOW)).toBe(false)
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 24 }), NOW)).toBe(false)
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 3.5 }), NOW)).toBe(false)
|
||||
expect(
|
||||
isScheduleDue(makeSchedule({ hour_utc: 'x' as unknown as number }), NOW)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('is false before the daily slot has passed', () => {
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 13 }), NOW)).toBe(false)
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 23 }), NOW)).toBe(false)
|
||||
})
|
||||
|
||||
it('is true at or after the slot when never synced', () => {
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 12 }), NOW)).toBe(true)
|
||||
// Catch-up: a 03:00 company missed by an overrun batch is still due at 12:30.
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 3 }), NOW)).toBe(true)
|
||||
expect(isScheduleDue(makeSchedule({ hour_utc: 0 }), NOW)).toBe(true)
|
||||
})
|
||||
|
||||
it('is false when an attempt already ran since today\'s slot', () => {
|
||||
expect(
|
||||
isScheduleDue(
|
||||
makeSchedule({ hour_utc: 3, last_auto_sync_at: '2026-07-12T03:05:00.000Z' }),
|
||||
NOW
|
||||
)
|
||||
).toBe(false)
|
||||
expect(
|
||||
isScheduleDue(
|
||||
makeSchedule({ hour_utc: 12, last_auto_sync_at: '2026-07-12T12:10:00.000Z' }),
|
||||
NOW
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('is true when the last attempt predates today\'s slot', () => {
|
||||
// Yesterday's run.
|
||||
expect(
|
||||
isScheduleDue(
|
||||
makeSchedule({ hour_utc: 3, last_auto_sync_at: '2026-07-11T03:05:00.000Z' }),
|
||||
NOW
|
||||
)
|
||||
).toBe(true)
|
||||
// A late catch-up yesterday evening does not swallow today's slot.
|
||||
expect(
|
||||
isScheduleDue(
|
||||
makeSchedule({ hour_utc: 3, last_auto_sync_at: '2026-07-11T23:00:00.000Z' }),
|
||||
NOW
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('treats an unparsable last_auto_sync_at as never synced', () => {
|
||||
expect(
|
||||
isScheduleDue(
|
||||
makeSchedule({ hour_utc: 3, last_auto_sync_at: 'not-a-date' }),
|
||||
NOW
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isScheduleDue with hour_local (Europe/Stockholm, DST-stable)', () => {
|
||||
it('computes the slot in Stockholm time during CEST (UTC+2)', () => {
|
||||
// 05:00 Swedish summer time = 03:00 UTC.
|
||||
const schedule = makeSchedule({ hour_local: 5 })
|
||||
expect(isScheduleDue(schedule, new Date('2026-07-12T02:59:00.000Z'))).toBe(false)
|
||||
expect(isScheduleDue(schedule, new Date('2026-07-12T03:01:00.000Z'))).toBe(true)
|
||||
})
|
||||
|
||||
it('computes the slot in Stockholm time during CET (UTC+1)', () => {
|
||||
// 05:00 Swedish winter time = 04:00 UTC: same wall-clock, shifted UTC.
|
||||
const schedule = makeSchedule({ hour_local: 5 })
|
||||
expect(isScheduleDue(schedule, new Date('2026-01-12T03:30:00.000Z'))).toBe(false)
|
||||
expect(isScheduleDue(schedule, new Date('2026-01-12T04:01:00.000Z'))).toBe(true)
|
||||
})
|
||||
|
||||
it('hour_local wins over the legacy hour_utc', () => {
|
||||
// hour_utc says 23 (not yet due), hour_local says 5 (due at 12:30 UTC).
|
||||
const schedule = makeSchedule({ hour_utc: 23, hour_local: 5 })
|
||||
expect(isScheduleDue(schedule, NOW)).toBe(true)
|
||||
})
|
||||
|
||||
it('already-ran-today respects the Stockholm slot', () => {
|
||||
const ranToday = makeSchedule({
|
||||
hour_local: 5,
|
||||
last_auto_sync_at: '2026-07-12T03:05:00.000Z',
|
||||
})
|
||||
expect(isScheduleDue(ranToday, new Date('2026-07-12T12:00:00.000Z'))).toBe(false)
|
||||
|
||||
const ranYesterday = makeSchedule({
|
||||
hour_local: 5,
|
||||
last_auto_sync_at: '2026-07-11T03:05:00.000Z',
|
||||
})
|
||||
expect(isScheduleDue(ranYesterday, new Date('2026-07-12T12:00:00.000Z'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('stockholmHourToUtcHour', () => {
|
||||
it('maps 05:00 Stockholm to 03 UTC in summer and 04 UTC in winter', () => {
|
||||
expect(stockholmHourToUtcHour(5, new Date('2026-07-12T12:00:00.000Z'))).toBe(3)
|
||||
expect(stockholmHourToUtcHour(5, new Date('2026-01-12T12:00:00.000Z'))).toBe(4)
|
||||
})
|
||||
|
||||
it('handles midnight without h24 artifacts', () => {
|
||||
expect(stockholmHourToUtcHour(0, new Date('2026-07-12T12:00:00.000Z'))).toBe(22)
|
||||
expect(stockholmHourToUtcHour(0, new Date('2026-01-12T12:00:00.000Z'))).toBe(23)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,284 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/lib/reports/full-archive-export', () => ({
|
||||
generateFullArchive: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
|
||||
generateBaseDataArchive: vi.fn().mockResolvedValue(new ArrayBuffer(16)),
|
||||
ARCHIVE_OVERHEAD_BYTES: 8 * 1024 * 1024,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/reports/archive-readme', () => ({
|
||||
buildDriveFolderReadme: vi.fn().mockReturnValue('README TEXT'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn(() => ({ storage: { from: vi.fn() } })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/branding/service', () => ({
|
||||
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.test' }),
|
||||
}))
|
||||
|
||||
vi.mock('../crypto', () => ({
|
||||
decryptToken: vi.fn().mockReturnValue('plain-refresh-token'),
|
||||
}))
|
||||
|
||||
import { performSync } from '../sync'
|
||||
import { CloudTokenRefreshError, type CloudStorageProvider } from '../cloud-provider'
|
||||
import type { CloudConnection, CloudLastSync } from '../../types'
|
||||
|
||||
const PERIOD = { id: 'p-2024', period_start: '2024-01-01', period_end: '2024-12-31' }
|
||||
const ENTRY = { id: 'e-1', fiscal_period_id: 'p-2024', updated_at: '2024-06-01T00:00:00Z' }
|
||||
|
||||
function makeConnection(): CloudConnection {
|
||||
return {
|
||||
refresh_token_encrypted: 'encrypted-token',
|
||||
account_email: '[email protected]',
|
||||
connected_at: '2026-01-01T00:00:00.000Z',
|
||||
root_folder_id: null,
|
||||
company_folder_id: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Supabase stub that stores extension_data per key, so a test can assert which
|
||||
* provider's records a sync read and wrote.
|
||||
*/
|
||||
function makeSupabase(seed: Record<string, unknown> = {}) {
|
||||
const store = new Map<string, unknown>(Object.entries(seed))
|
||||
const writes: { key: string; value: unknown }[] = []
|
||||
|
||||
const upsert = vi.fn().mockImplementation((payload: any) => {
|
||||
store.set(payload.key, payload.value)
|
||||
writes.push({ key: payload.key, value: payload.value })
|
||||
return Promise.resolve({ error: null })
|
||||
})
|
||||
|
||||
const from = vi.fn().mockImplementation((table: string) => {
|
||||
let key: string | null = null
|
||||
const chain: any = {
|
||||
upsert,
|
||||
maybeSingle: vi.fn().mockImplementation(() => {
|
||||
if (table === 'extension_data') {
|
||||
const value = key ? store.get(key) : undefined
|
||||
return Promise.resolve({ data: value ? { value } : null })
|
||||
}
|
||||
if (table === 'company_settings') {
|
||||
return Promise.resolve({
|
||||
data: { company_name: 'Testbolag AB', org_number: '556000-0000' },
|
||||
})
|
||||
}
|
||||
return Promise.resolve({ data: null })
|
||||
}),
|
||||
then: (resolve: (v: unknown) => void) => {
|
||||
if (table === 'fiscal_periods') return resolve({ data: [PERIOD], error: null })
|
||||
if (table === 'journal_entries') return resolve({ data: [ENTRY], error: null })
|
||||
if (table === 'document_attachments') return resolve({ data: [], error: null })
|
||||
if (table === 'audit_log') {
|
||||
return resolve({ data: [{ created_at: '2026-07-01T00:00:00Z' }], error: null })
|
||||
}
|
||||
return resolve({ data: [], error: null })
|
||||
},
|
||||
}
|
||||
for (const method of ['select', 'eq', 'neq', 'in', 'order', 'range', 'limit']) {
|
||||
chain[method] = vi.fn().mockImplementation((col?: string, val?: string) => {
|
||||
if (method === 'eq' && col === 'key') key = val ?? null
|
||||
return chain
|
||||
})
|
||||
}
|
||||
return chain
|
||||
})
|
||||
|
||||
return { supabase: { from } as any, store, writes, upsert }
|
||||
}
|
||||
|
||||
/** A provider that records what the sync engine asked it to do. */
|
||||
function makeFakeProvider(
|
||||
id: string,
|
||||
overrides: Partial<CloudStorageProvider> = {}
|
||||
): CloudStorageProvider {
|
||||
return {
|
||||
id: id as CloudStorageProvider['id'],
|
||||
label: id,
|
||||
keys: {
|
||||
connection: `${id}_connection`,
|
||||
lastSync: `${id}_last_sync`,
|
||||
schedule: `${id}_schedule`,
|
||||
},
|
||||
callbackPath: `/oauth/${id}/callback`,
|
||||
isConfigured: () => true,
|
||||
buildAuthorizationUrl: () => 'https://auth.test',
|
||||
exchangeCode: vi.fn(),
|
||||
revoke: vi.fn(),
|
||||
refreshAccessToken: vi.fn().mockResolvedValue('fresh-token'),
|
||||
prepareTarget: vi.fn().mockResolvedValue({
|
||||
target: { folderId: `folder-${id}`, webViewLink: `https://${id}.test/folder` },
|
||||
connectionPatch: null,
|
||||
}),
|
||||
putFile: vi.fn().mockImplementation(async ({ name, data }: any) => ({
|
||||
id: `${id}:${name}`,
|
||||
name,
|
||||
size_bytes: (data as ArrayBuffer).byteLength,
|
||||
})),
|
||||
...overrides,
|
||||
} as CloudStorageProvider
|
||||
}
|
||||
|
||||
function syncParams(supabase: any, provider: CloudStorageProvider) {
|
||||
return {
|
||||
supabase,
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
origin: 'https://app.test',
|
||||
includeDocuments: true,
|
||||
provider,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('performSync provider routing', () => {
|
||||
it('reads and writes only the requested provider records', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase, writes } = makeSupabase({
|
||||
dropbox_connection: makeConnection(),
|
||||
})
|
||||
|
||||
const result = await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const touchedKeys = new Set(writes.map((w) => w.key))
|
||||
expect([...touchedKeys]).toEqual(['dropbox_last_sync'])
|
||||
// Nothing under the Google keys was written.
|
||||
expect([...touchedKeys].some((k) => k.startsWith('google_drive'))).toBe(false)
|
||||
})
|
||||
|
||||
it('returns not_connected when only the OTHER provider is connected', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase } = makeSupabase({
|
||||
google_drive_connection: makeConnection(),
|
||||
})
|
||||
|
||||
const result = await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, reason: 'not_connected' })
|
||||
expect(provider.refreshAccessToken).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uploads the full file set through the provider and reports its folder link', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
const result = await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.uploadedCount).toBe(3)
|
||||
expect(result.webViewLink).toBe('https://dropbox.test/folder')
|
||||
const names = vi.mocked(provider.putFile).mock.calls.map((c) => c[0].name)
|
||||
expect(names).toEqual(['Arkiv 2024.zip', 'Grunddata.zip', 'LÄSMIG.txt'])
|
||||
// Every upload targets the folder prepareTarget resolved.
|
||||
for (const call of vi.mocked(provider.putFile).mock.calls) {
|
||||
expect(call[0].target.folderId).toBe('folder-dropbox')
|
||||
}
|
||||
})
|
||||
|
||||
it('records the folder link on the snapshot so the UI can link without guessing', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase, store } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
await performSync(syncParams(supabase, provider))
|
||||
|
||||
const snapshot = store.get('dropbox_last_sync') as CloudLastSync
|
||||
expect(snapshot.web_view_link).toBe('https://dropbox.test/folder')
|
||||
expect(snapshot.folder_id).toBe('folder-dropbox')
|
||||
})
|
||||
|
||||
it('flags only the failing provider needs_reauth on a dead refresh token', async () => {
|
||||
const provider = makeFakeProvider('dropbox', {
|
||||
refreshAccessToken: vi
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new CloudTokenRefreshError('Dropbox', 400, '{"error":"invalid_grant"}')
|
||||
),
|
||||
})
|
||||
const { supabase, store, writes } = makeSupabase({
|
||||
dropbox_connection: makeConnection(),
|
||||
google_drive_connection: makeConnection(),
|
||||
})
|
||||
|
||||
const result = await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, reason: 'needs_reauth' })
|
||||
expect((store.get('dropbox_connection') as CloudConnection).status).toBe('needs_reauth')
|
||||
// The healthy Google connection is left exactly as it was.
|
||||
expect((store.get('google_drive_connection') as CloudConnection).status).toBeUndefined()
|
||||
expect(writes.every((w) => w.key === 'dropbox_connection')).toBe(true)
|
||||
})
|
||||
|
||||
it('rethrows a transient refresh failure without flagging the connection', async () => {
|
||||
const provider = makeFakeProvider('dropbox', {
|
||||
refreshAccessToken: vi
|
||||
.fn()
|
||||
.mockRejectedValue(new CloudTokenRefreshError('Dropbox', 500, 'Server Error')),
|
||||
})
|
||||
const { supabase, writes } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
await expect(performSync(syncParams(supabase, provider))).rejects.toThrow(/500/)
|
||||
expect(writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('persists a connection patch the provider asked for', async () => {
|
||||
const provider = makeFakeProvider('dropbox', {
|
||||
prepareTarget: vi.fn().mockResolvedValue({
|
||||
target: { folderId: '/Bolag', webViewLink: 'https://dropbox.test/folder' },
|
||||
connectionPatch: { company_folder_path: '/Bolag' },
|
||||
}),
|
||||
})
|
||||
const { supabase, store } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect((store.get('dropbox_connection') as CloudConnection).company_folder_path).toBe(
|
||||
'/Bolag'
|
||||
)
|
||||
})
|
||||
|
||||
it('skips unchanged files using that provider own last-sync record', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
await performSync(syncParams(supabase, provider))
|
||||
vi.mocked(provider.putFile).mockClear()
|
||||
|
||||
// Second run against the snapshot the first run persisted.
|
||||
const second = await performSync(syncParams(supabase, provider))
|
||||
|
||||
expect(second.ok).toBe(true)
|
||||
if (!second.ok) return
|
||||
expect(second.uploadedCount).toBe(0)
|
||||
expect(second.skippedCount).toBe(3)
|
||||
expect(provider.putFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes the previous handle only while the file name is unchanged', async () => {
|
||||
const provider = makeFakeProvider('dropbox')
|
||||
const { supabase, store } = makeSupabase({ dropbox_connection: makeConnection() })
|
||||
|
||||
await performSync(syncParams(supabase, provider))
|
||||
|
||||
// Invalidate the period fingerprint so the next run re-uploads that file.
|
||||
const snapshot = store.get('dropbox_last_sync') as CloudLastSync
|
||||
snapshot.files![0].fingerprint = 'stale'
|
||||
store.set('dropbox_last_sync', snapshot)
|
||||
vi.mocked(provider.putFile).mockClear()
|
||||
|
||||
await performSync(syncParams(supabase, provider))
|
||||
|
||||
const call = vi.mocked(provider.putFile).mock.calls[0][0]
|
||||
expect(call.name).toBe('Arkiv 2024.zip')
|
||||
expect(call.previousId).toBe('dropbox:Arkiv 2024.zip')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Failure-alert email for the cloud backup auto-sync.
|
||||
*
|
||||
* A backup that silently stops running is worse than no backup: the user
|
||||
* believes they are covered. The cron calls this when a connection goes
|
||||
* needs_reauth (retrying can never succeed) or when several consecutive
|
||||
* auto-syncs have failed. Manual syncs never alert: the user is watching.
|
||||
*
|
||||
* Best-effort by design: an alert failure must never fail the sync loop.
|
||||
* Throttling state (`last_alert_at`) lives on the schedule object and is
|
||||
* persisted by the caller. The body carries no bookkeeping data, only the
|
||||
* company name and the error summary.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { resolveMemberEmail } from '@/lib/notifications/member-email'
|
||||
import { escapeHtml } from '@/lib/email/user-text'
|
||||
|
||||
const log = createLogger('cloud-backup-alert')
|
||||
|
||||
/** At most one alert email per company per throttle window. */
|
||||
export const ALERT_THROTTLE_MS = 7 * 24 * 60 * 60 * 1000
|
||||
/** Consecutive auto-sync failures before a repeated-failures alert fires. */
|
||||
export const ALERT_FAILURE_THRESHOLD = 3
|
||||
|
||||
export type BackupAlertKind = 'needs_reauth' | 'repeated_failures'
|
||||
|
||||
export function shouldSendBackupAlert(params: {
|
||||
kind: BackupAlertKind
|
||||
consecutiveFailures: number
|
||||
lastAlertAt: string | null | undefined
|
||||
now?: Date
|
||||
}): boolean {
|
||||
const now = params.now ?? new Date()
|
||||
if (params.lastAlertAt) {
|
||||
const last = new Date(params.lastAlertAt).getTime()
|
||||
if (Number.isFinite(last) && now.getTime() - last < ALERT_THROTTLE_MS) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (params.kind === 'needs_reauth') return true
|
||||
return params.consecutiveFailures >= ALERT_FAILURE_THRESHOLD
|
||||
}
|
||||
|
||||
export interface BackupAlertInput {
|
||||
companyId: string
|
||||
/** The user who configured the schedule: recipient candidate. */
|
||||
userId: string
|
||||
kind: BackupAlertKind
|
||||
consecutiveFailures: number
|
||||
errorMessage: string | null
|
||||
/** App origin used to build the reconnect link. */
|
||||
origin: string
|
||||
/**
|
||||
* Destination that failed ("Google Drive", "Dropbox"). Named in the mail so
|
||||
* a user backing up to both knows which one to reconnect. Defaults to Google
|
||||
* Drive for callers written before the second provider existed.
|
||||
*/
|
||||
providerLabel?: string
|
||||
}
|
||||
|
||||
export async function sendBackupFailureAlert(
|
||||
supabase: SupabaseClient,
|
||||
input: BackupAlertInput
|
||||
): Promise<{ sent: boolean; reason?: string }> {
|
||||
try {
|
||||
const email = getEmailService()
|
||||
if (!email.isConfigured()) return { sent: false, reason: 'email_not_configured' }
|
||||
|
||||
const recipient = await resolveMemberEmail(supabase, input.companyId, input.userId)
|
||||
if (!recipient) {
|
||||
log.info('no authorised recipient for backup alert', { companyId: input.companyId })
|
||||
return { sent: false, reason: 'no_recipient' }
|
||||
}
|
||||
|
||||
const companyName = await fetchCompanyName(supabase, input.companyId)
|
||||
const link = `${input.origin}/import#cloud-backup`
|
||||
const providerLabel = input.providerLabel || 'Google Drive'
|
||||
|
||||
let subject: string
|
||||
let paragraphs: string[]
|
||||
if (input.kind === 'needs_reauth') {
|
||||
subject = `Säkerhetskopieringen till ${providerLabel} är pausad`
|
||||
paragraphs = [
|
||||
`Den automatiska säkerhetskopieringen för ${companyName} är pausad: åtkomsten till ditt ${providerLabel}-konto har gått ut eller återkallats.`,
|
||||
`Koppla om ${providerLabel} för att återuppta säkerhetskopieringen.`,
|
||||
]
|
||||
} else {
|
||||
subject = `Säkerhetskopieringen till ${providerLabel} misslyckas`
|
||||
paragraphs = [
|
||||
`Den automatiska säkerhetskopieringen för ${companyName} till ${providerLabel} har misslyckats ${input.consecutiveFailures} nätter i rad.`,
|
||||
input.errorMessage ? `Senaste fel: ${input.errorMessage}` : '',
|
||||
'Kontrollera anslutningen under Importera/Exportera.',
|
||||
].filter(Boolean)
|
||||
}
|
||||
|
||||
const text = [...paragraphs, '', link].join('\n\n')
|
||||
const html = [
|
||||
...paragraphs.map((p) => `<p>${escapeHtml(p)}</p>`),
|
||||
`<p><a href="${escapeHtml(link)}">Öppna säkerhetskopiering</a></p>`,
|
||||
].join('')
|
||||
|
||||
const result = await email.sendEmail({ to: recipient, subject, text, html })
|
||||
if (!result.success) {
|
||||
log.warn('backup alert send failed', { companyId: input.companyId, error: result.error })
|
||||
return { sent: false, reason: 'send_failed' }
|
||||
}
|
||||
return { sent: true }
|
||||
} catch (err) {
|
||||
log.warn('backup alert failed', {
|
||||
companyId: input.companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
return { sent: false, reason: 'error' }
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCompanyName(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string
|
||||
): Promise<string> {
|
||||
const { data } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
return (data?.company_name as string) || 'ditt företag'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Resolve the origin used to build OAuth redirect URIs.
|
||||
*
|
||||
* Both OAuth legs must send the same redirect_uri. Pinning it to the
|
||||
* deployment's canonical app URL also prevents an old domain alias or preview
|
||||
* host from generating a callback that is not registered with the provider.
|
||||
* Self-hosted deployments without NEXT_PUBLIC_APP_URL fall back to the
|
||||
* request origin.
|
||||
*/
|
||||
export function resolveCallbackOrigin(requestOrigin: string): string {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL
|
||||
if (appUrl && appUrl.trim().length > 0) {
|
||||
try {
|
||||
// Normalizes trailing slashes and strips paths so the provider receives
|
||||
// the same bare origin on the authorization and token-exchange legs.
|
||||
const configuredUrl = new URL(appUrl)
|
||||
if (
|
||||
configuredUrl.protocol !== 'http:' &&
|
||||
configuredUrl.protocol !== 'https:'
|
||||
) {
|
||||
return requestOrigin
|
||||
}
|
||||
return configuredUrl.origin
|
||||
} catch {
|
||||
return requestOrigin
|
||||
}
|
||||
}
|
||||
return requestOrigin
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Provider-agnostic contract for a cloud backup target.
|
||||
*
|
||||
* `performSync()` builds the same archive set regardless of destination and
|
||||
* talks to storage only through this interface. Everything provider-specific
|
||||
* (OAuth dialect, folder model, upload protocol, checksum verification) lives
|
||||
* behind an implementation: `google-provider.ts`, `dropbox-provider.ts`.
|
||||
*
|
||||
* Adding a provider therefore means writing one implementation and listing it
|
||||
* in `provider-registry.ts`, without touching the sync engine.
|
||||
*/
|
||||
import type { CloudConnection, CloudProviderId } from '../types'
|
||||
|
||||
/**
|
||||
* Thrown when a provider's token endpoint rejects a refresh attempt. Carries
|
||||
* the HTTP status and raw response body so callers can distinguish a
|
||||
* permanently dead refresh token (400 invalid_grant) from transient failures.
|
||||
*/
|
||||
export class CloudTokenRefreshError extends Error {
|
||||
readonly status: number
|
||||
readonly body: string
|
||||
|
||||
constructor(providerLabel: string, status: number, body: string) {
|
||||
super(`${providerLabel} token refresh failed: ${status} ${body}`)
|
||||
this.name = 'CloudTokenRefreshError'
|
||||
this.status = status
|
||||
this.body = body
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the provider reports the refresh token itself is dead (revoked,
|
||||
* expired, or the grant was invalidated). Retrying will never succeed;
|
||||
* the user must re-consent. Google and Dropbox both use OAuth 2.0's
|
||||
* `invalid_grant` for this.
|
||||
*/
|
||||
get isInvalidGrant(): boolean {
|
||||
return this.status === 400 && this.body.includes('invalid_grant')
|
||||
}
|
||||
}
|
||||
|
||||
/** The three `extension_data` keys a provider owns for a company. */
|
||||
export interface CloudStorageKeys {
|
||||
connection: string
|
||||
lastSync: string
|
||||
schedule: string
|
||||
}
|
||||
|
||||
/** Where one company's archives are written, in provider-native terms. */
|
||||
export interface CloudTarget {
|
||||
/** Drive: the company folder id. Dropbox: the company folder path. */
|
||||
folderId: string
|
||||
/** Link a human can open to reach the backup folder. */
|
||||
webViewLink: string
|
||||
}
|
||||
|
||||
export interface PreparedTarget {
|
||||
target: CloudTarget
|
||||
/**
|
||||
* Fields to merge into the stored connection because preparing the target
|
||||
* changed them (e.g. Drive re-created a folder the user trashed). Null when
|
||||
* nothing changed, so the common path writes no connection record.
|
||||
*/
|
||||
connectionPatch: Partial<CloudConnection> | null
|
||||
}
|
||||
|
||||
export interface PutFileResult {
|
||||
/** Provider-native handle: a Drive file id, or the Dropbox path. */
|
||||
id: string
|
||||
name: string
|
||||
size_bytes: number
|
||||
}
|
||||
|
||||
export interface PutFileParams {
|
||||
accessToken: string
|
||||
target: CloudTarget
|
||||
name: string
|
||||
/**
|
||||
* Handle recorded by the previous sync for this same file name. Providers
|
||||
* that address files by id use it to update in place (and to detect that
|
||||
* the user deleted the file); path-addressed providers ignore it.
|
||||
*/
|
||||
previousId?: string
|
||||
data: ArrayBuffer
|
||||
contentType: string
|
||||
}
|
||||
|
||||
export interface PrepareTargetParams {
|
||||
accessToken: string
|
||||
connection: CloudConnection
|
||||
/** `Testbolag AB (556000-0000)`: the per-company folder name. */
|
||||
companyLabel: string
|
||||
}
|
||||
|
||||
export interface CloudStorageProvider {
|
||||
readonly id: CloudProviderId
|
||||
/** Human label used in logs, errors and alert emails. */
|
||||
readonly label: string
|
||||
readonly keys: CloudStorageKeys
|
||||
/**
|
||||
* OAuth callback path relative to the extension's route root. Each provider
|
||||
* needs its own: the redirect URI is registered with the provider, so they
|
||||
* can never be merged after the fact.
|
||||
*/
|
||||
readonly callbackPath: string
|
||||
|
||||
/** False when this deployment has no OAuth credentials for the provider. */
|
||||
isConfigured(): boolean
|
||||
buildAuthorizationUrl(origin: string, state: string): string
|
||||
exchangeCode(
|
||||
origin: string,
|
||||
code: string
|
||||
): Promise<{ refreshToken: string; accountLabel: string }>
|
||||
/**
|
||||
* Best-effort: a failed revoke must not block a local disconnect.
|
||||
* `origin` resolves the same deployment credentials as the connect flow.
|
||||
*/
|
||||
revoke(refreshToken: string, origin: string): Promise<void>
|
||||
/** Throws {@link CloudTokenRefreshError} on rejection. */
|
||||
refreshAccessToken(refreshToken: string, origin: string): Promise<string>
|
||||
prepareTarget(params: PrepareTargetParams): Promise<PreparedTarget>
|
||||
/**
|
||||
* Write one file into the target, replacing any existing file of that name.
|
||||
* Implementations verify the stored bytes against the provider's own
|
||||
* checksum: a silently corrupted backup is worse than a failed one.
|
||||
*/
|
||||
putFile(params: PutFileParams): Promise<PutFileResult>
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* AES-256-GCM encryption for long-lived refresh tokens stored in
|
||||
* extension_data. Key is derived from SUPABASE_SERVICE_ROLE_KEY (same
|
||||
* trust boundary as the database itself: anyone who can exfiltrate the
|
||||
* key can already read the data).
|
||||
*/
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm'
|
||||
|
||||
function getKey(): Buffer {
|
||||
const secret = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
if (!secret) throw new Error('SUPABASE_SERVICE_ROLE_KEY is required')
|
||||
// Scope the key with a purpose string so this can't be confused with
|
||||
// oauth-codes.ts's derivation if both are ever compromised together.
|
||||
return crypto
|
||||
.createHash('sha256')
|
||||
.update('cloud-backup:v1:' + secret)
|
||||
.digest()
|
||||
}
|
||||
|
||||
export function encryptToken(plaintext: string): string {
|
||||
const key = getKey()
|
||||
const iv = crypto.randomBytes(12)
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
return Buffer.concat([iv, tag, encrypted]).toString('base64url')
|
||||
}
|
||||
|
||||
export function decryptToken(ciphertext: string): string {
|
||||
const key = getKey()
|
||||
const combined = Buffer.from(ciphertext, 'base64url')
|
||||
const iv = combined.subarray(0, 12)
|
||||
const tag = combined.subarray(12, 28)
|
||||
const encrypted = combined.subarray(28)
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
|
||||
return decrypted.toString('utf8')
|
||||
}
|
||||
|
||||
/**
|
||||
* Short-lived signed state parameter for OAuth CSRF protection.
|
||||
*
|
||||
* The state encodes `{userId, companyId, exp}` and is verified on the
|
||||
* callback. Stateless (no DB round-trip) and self-expiring.
|
||||
*/
|
||||
const STATE_TTL_MS = 10 * 60 * 1000
|
||||
|
||||
interface StatePayload {
|
||||
u: string
|
||||
c: string
|
||||
e: number
|
||||
}
|
||||
|
||||
export function createOAuthState(userId: string, companyId: string): string {
|
||||
const payload: StatePayload = {
|
||||
u: userId,
|
||||
c: companyId,
|
||||
e: Date.now() + STATE_TTL_MS,
|
||||
}
|
||||
return encryptToken(JSON.stringify(payload))
|
||||
}
|
||||
|
||||
export function verifyOAuthState(
|
||||
state: string
|
||||
): { userId: string; companyId: string } | null {
|
||||
try {
|
||||
const payload = JSON.parse(decryptToken(state)) as StatePayload
|
||||
if (Date.now() > payload.e) return null
|
||||
return { userId: payload.u, companyId: payload.c }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* Minimal Dropbox content client: just enough to write one archive into the
|
||||
* app folder and prove the stored bytes are the bytes we sent.
|
||||
*
|
||||
* Two upload paths, picked by size:
|
||||
* - files/upload for anything that fits one chunk (one round trip),
|
||||
* - files/upload_session/* in 8 MB chunks for the large archives, which
|
||||
* avoids holding a second copy of the payload for a multipart body.
|
||||
*
|
||||
* Both write with `mode: overwrite`, which makes uploads idempotent and lets
|
||||
* Dropbox keep its own version history (30 days on Basic, longer on paid
|
||||
* plans): the same rolling-history property the Drive target relies on.
|
||||
* Dropbox creates missing parent folders on write, so there is no folder
|
||||
* bootstrap step and nothing to revalidate.
|
||||
*
|
||||
* Every upload is verified against the `content_hash` Dropbox reports. A
|
||||
* silently corrupted backup is worse than a failed one.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
const CONTENT_API = 'https://content.dropboxapi.com/2'
|
||||
|
||||
/** 8 MB upload chunks: comfortably inside Dropbox's 150 MB per-request cap. */
|
||||
const UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024
|
||||
const CHUNK_MAX_ATTEMPTS = 3
|
||||
|
||||
/** Dropbox's content_hash is defined over 4 MB blocks: not our chunk size. */
|
||||
const CONTENT_HASH_BLOCK_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export interface DropboxUploadResult {
|
||||
/** App-folder-relative path, used as the file handle in sync state. */
|
||||
path: string
|
||||
name: string
|
||||
size_bytes: number
|
||||
content_hash?: string
|
||||
}
|
||||
|
||||
interface DropboxFileMetadata {
|
||||
name: string
|
||||
path_lower?: string
|
||||
path_display?: string
|
||||
size?: number
|
||||
content_hash?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Dropbox's documented content hash: SHA-256 of the concatenated SHA-256
|
||||
* digests of each 4 MB block. Computing it locally is the only way to verify
|
||||
* an upload, since Dropbox reports this and no other checksum.
|
||||
*/
|
||||
export function dropboxContentHash(data: ArrayBuffer): string {
|
||||
const buffer = Buffer.from(data)
|
||||
const blockHashes: Buffer[] = []
|
||||
for (let offset = 0; offset < buffer.length; offset += CONTENT_HASH_BLOCK_BYTES) {
|
||||
const block = buffer.subarray(
|
||||
offset,
|
||||
Math.min(offset + CONTENT_HASH_BLOCK_BYTES, buffer.length)
|
||||
)
|
||||
blockHashes.push(createHash('sha256').update(block).digest())
|
||||
}
|
||||
// An empty file hashes the empty concatenation, which is what Dropbox reports.
|
||||
return createHash('sha256').update(Buffer.concat(blockHashes)).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* Dropbox passes call arguments in the `Dropbox-API-Arg` HTTP header, which
|
||||
* must be ASCII. Swedish file and folder names (`LÄSMIG.txt`, `Testbolag AB`)
|
||||
* would otherwise produce an invalid header and a 400: escape every non-ASCII
|
||||
* code unit as a \\uXXXX sequence, which Dropbox unescapes server-side.
|
||||
*/
|
||||
/** A single backslash, spelled without an escape the tooling can mangle. */
|
||||
const BACKSLASH = String.fromCharCode(92)
|
||||
const ESCAPE_PREFIX = BACKSLASH + 'u'
|
||||
|
||||
export function asciiJson(value: unknown): string {
|
||||
let out = ''
|
||||
// Iterate by code point so an astral character (an emoji in a company
|
||||
// name) is escaped as its two surrogate halves rather than mangled.
|
||||
for (const char of JSON.stringify(value)) {
|
||||
if (char.codePointAt(0)! < 128) {
|
||||
out += char
|
||||
continue
|
||||
}
|
||||
for (let i = 0; i < char.length; i++) {
|
||||
out += ESCAPE_PREFIX + char.charCodeAt(i).toString(16).padStart(4, '0')
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Dropbox rejects `/ \ : ? * " < > |` in a path component, along with control
|
||||
* characters and trailing dots or spaces. Company names are user-supplied, so
|
||||
* a name like `Bolaget AB / Filial` must not be able to produce an invalid
|
||||
* path (or escape into a sibling folder).
|
||||
*/
|
||||
export function sanitizeDropboxName(name: string): string {
|
||||
const ILLEGAL = '/:?*"<>|' + BACKSLASH
|
||||
let out = ''
|
||||
for (const char of name) {
|
||||
const code = char.codePointAt(0)!
|
||||
if (code < 0x20 || code === 0x7f) continue
|
||||
out += ILLEGAL.includes(char) ? '-' : char
|
||||
}
|
||||
const cleaned = out.trim().replace(/[. ]+$/, '').slice(0, 180)
|
||||
return cleaned || 'foretag'
|
||||
}
|
||||
|
||||
async function readError(res: Response): Promise<string> {
|
||||
const body = await res.text().catch(() => '')
|
||||
return `${res.status} ${body.slice(0, 200)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* A response Dropbox will keep rejecting however many times we ask (bad path,
|
||||
* insufficient scope, dead token). Retrying it wastes the cron's time budget,
|
||||
* so it aborts the chunk loop immediately.
|
||||
*/
|
||||
class DropboxFatalError extends Error {}
|
||||
|
||||
/**
|
||||
* Upload `data` to `path`, replacing whatever is there.
|
||||
*
|
||||
* `path` is app-folder-relative and must start with `/`
|
||||
* (e.g. `/Testbolag AB (556000-0000)/Arkiv 2024.zip`).
|
||||
*/
|
||||
export async function uploadDropboxFile(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
data: ArrayBuffer
|
||||
): Promise<DropboxUploadResult> {
|
||||
const expected = dropboxContentHash(data)
|
||||
let lastError: Error | null = null
|
||||
|
||||
// One full retry on a hash mismatch, mirroring the Drive target: a mismatch
|
||||
// is far more likely to be a truncated transfer than a corrupted source.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const meta =
|
||||
data.byteLength <= UPLOAD_CHUNK_BYTES
|
||||
? await singleShotUpload(accessToken, path, data)
|
||||
: await sessionUpload(accessToken, path, data)
|
||||
|
||||
const result: DropboxUploadResult = {
|
||||
path: meta.path_display || meta.path_lower || path,
|
||||
name: meta.name,
|
||||
size_bytes: typeof meta.size === 'number' ? meta.size : data.byteLength,
|
||||
content_hash: meta.content_hash,
|
||||
}
|
||||
if (!result.content_hash || result.content_hash === expected) {
|
||||
return result
|
||||
}
|
||||
lastError = new Error(
|
||||
`Dropbox upload checksum mismatch: expected ${expected}, got ${result.content_hash}`
|
||||
)
|
||||
}
|
||||
throw lastError
|
||||
}
|
||||
|
||||
function commitArg(path: string) {
|
||||
return {
|
||||
path,
|
||||
mode: 'overwrite' as const,
|
||||
// No desktop notification for an automated nightly backup.
|
||||
mute: true,
|
||||
// Never let Dropbox invent `Arkiv 2024 (1).zip`: overwrite is the contract
|
||||
// the fingerprint logic depends on.
|
||||
autorename: false,
|
||||
}
|
||||
}
|
||||
|
||||
async function singleShotUpload(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
data: ArrayBuffer
|
||||
): Promise<DropboxFileMetadata> {
|
||||
const res = await contentFetch(accessToken, '/files/upload', commitArg(path), data)
|
||||
return (await res.json()) as DropboxFileMetadata
|
||||
}
|
||||
|
||||
/**
|
||||
* Chunked upload session. Transient failures are retried per chunk; the
|
||||
* session itself is not resumed across a failed run, because `performSync`
|
||||
* already persists per-file progress and simply re-uploads this one file.
|
||||
*/
|
||||
async function sessionUpload(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
data: ArrayBuffer
|
||||
): Promise<DropboxFileMetadata> {
|
||||
const total = data.byteLength
|
||||
|
||||
// Chunks are sliced off the source rather than viewed into it: a view would
|
||||
// keep the whole 300 MB archive reachable from every in-flight request body.
|
||||
const firstChunk = data.slice(0, UPLOAD_CHUNK_BYTES)
|
||||
const startRes = await contentFetch(
|
||||
accessToken,
|
||||
'/files/upload_session/start',
|
||||
{ close: false },
|
||||
firstChunk
|
||||
)
|
||||
const { session_id: sessionId } = (await startRes.json()) as { session_id: string }
|
||||
let offset = firstChunk.byteLength
|
||||
|
||||
while (offset < total) {
|
||||
const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total)
|
||||
const chunk = data.slice(offset, end)
|
||||
|
||||
if (end >= total) {
|
||||
const finishRes = await contentFetch(
|
||||
accessToken,
|
||||
'/files/upload_session/finish',
|
||||
{ cursor: { session_id: sessionId, offset }, commit: commitArg(path) },
|
||||
chunk
|
||||
)
|
||||
return (await finishRes.json()) as DropboxFileMetadata
|
||||
}
|
||||
|
||||
await contentFetch(
|
||||
accessToken,
|
||||
'/files/upload_session/append_v2',
|
||||
{ cursor: { session_id: sessionId, offset }, close: false },
|
||||
chunk
|
||||
)
|
||||
offset = end
|
||||
}
|
||||
|
||||
// Payload was an exact multiple of the chunk size: close with an empty commit.
|
||||
const finishRes = await contentFetch(
|
||||
accessToken,
|
||||
'/files/upload_session/finish',
|
||||
{ cursor: { session_id: sessionId, offset }, commit: commitArg(path) },
|
||||
new ArrayBuffer(0)
|
||||
)
|
||||
return (await finishRes.json()) as DropboxFileMetadata
|
||||
}
|
||||
|
||||
async function contentFetch(
|
||||
accessToken: string,
|
||||
endpoint: string,
|
||||
arg: unknown,
|
||||
body: ArrayBuffer
|
||||
): Promise<Response> {
|
||||
let lastErr: unknown = null
|
||||
for (let attempt = 0; attempt < CHUNK_MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
const res = await fetch(`${CONTENT_API}${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Dropbox-API-Arg': asciiJson(arg),
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
body,
|
||||
})
|
||||
if (res.ok) return res
|
||||
// 429 (rate limited) and 5xx are the documented retryable responses;
|
||||
// everything else is our fault and will fail identically on retry.
|
||||
const detail = `Dropbox ${endpoint} failed: ${await readError(res)}`
|
||||
if (res.status === 429 || res.status >= 500) {
|
||||
lastErr = new Error(detail)
|
||||
continue
|
||||
}
|
||||
throw new DropboxFatalError(detail)
|
||||
} catch (err) {
|
||||
if (err instanceof DropboxFatalError) throw err
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
throw lastErr instanceof Error
|
||||
? lastErr
|
||||
: new Error(`Dropbox ${endpoint} failed after retries`)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Minimal Dropbox OAuth 2.0 client for the cloud-backup extension.
|
||||
*
|
||||
* Access type: **App folder**. Dropbox confines the app to its own
|
||||
* `Apps/<app name>/` directory, so every path we use is relative to that
|
||||
* folder and the app can never read the rest of the user's Dropbox. This
|
||||
* mirrors the privacy posture of the Google `drive.file` scope.
|
||||
*
|
||||
* `token_access_type=offline` is what makes Dropbox return a refresh token;
|
||||
* without it the grant yields a short-lived access token only and the nightly
|
||||
* cron would stop working after a few hours.
|
||||
*/
|
||||
|
||||
import {
|
||||
fetchWithTimeout,
|
||||
OAUTH_TIMEOUT_MS,
|
||||
OAUTH_REVOKE_TIMEOUT_MS,
|
||||
} from '@/lib/http/fetch-with-timeout'
|
||||
import { CloudTokenRefreshError } from './cloud-provider'
|
||||
|
||||
const AUTH_ENDPOINT = 'https://www.dropbox.com/oauth2/authorize'
|
||||
const TOKEN_ENDPOINT = 'https://api.dropboxapi.com/oauth2/token'
|
||||
const REVOKE_ENDPOINT = 'https://api.dropboxapi.com/2/auth/token/revoke'
|
||||
const ACCOUNT_ENDPOINT = 'https://api.dropboxapi.com/2/users/get_current_account'
|
||||
|
||||
/**
|
||||
* Write + read the app folder, and read the account identity for the "connected
|
||||
* as" line in the UI. Read access is requested because a restore-side feature
|
||||
* (and support diagnosing a partial backup) needs to list what is actually
|
||||
* there; without it the app is write-only and cannot verify its own output.
|
||||
*/
|
||||
const SCOPES = ['files.content.write', 'files.content.read', 'account_info.read']
|
||||
|
||||
export interface DropboxOAuthEnv {
|
||||
appKey: string
|
||||
appSecret: string
|
||||
redirectUri: string
|
||||
}
|
||||
|
||||
/** Callback path, kept next to the URL builder so the two cannot drift. */
|
||||
export const DROPBOX_CALLBACK_PATH = '/oauth/dropbox/callback'
|
||||
|
||||
export function isDropboxOAuthConfigured(): boolean {
|
||||
return Boolean(process.env.DROPBOX_APP_KEY && process.env.DROPBOX_APP_SECRET)
|
||||
}
|
||||
|
||||
export function getDropboxOAuthEnv(origin: string): DropboxOAuthEnv {
|
||||
const appKey = process.env.DROPBOX_APP_KEY
|
||||
const appSecret = process.env.DROPBOX_APP_SECRET
|
||||
if (!appKey || !appSecret) {
|
||||
throw new Error(
|
||||
'Dropbox OAuth is not configured: set DROPBOX_APP_KEY and DROPBOX_APP_SECRET'
|
||||
)
|
||||
}
|
||||
return {
|
||||
appKey,
|
||||
appSecret,
|
||||
redirectUri: `${origin}/api/extensions/ext/cloud-backup${DROPBOX_CALLBACK_PATH}`,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDropboxAuthorizationUrl(
|
||||
env: DropboxOAuthEnv,
|
||||
state: string
|
||||
): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.appKey,
|
||||
redirect_uri: env.redirectUri,
|
||||
response_type: 'code',
|
||||
token_access_type: 'offline',
|
||||
scope: SCOPES.join(' '),
|
||||
// Re-consent on every connect so a reconnect always yields a fresh refresh
|
||||
// token, matching the Google flow's `prompt=consent`.
|
||||
force_reapprove: 'true',
|
||||
state,
|
||||
})
|
||||
return `${AUTH_ENDPOINT}?${params.toString()}`
|
||||
}
|
||||
|
||||
export interface DropboxTokenExchangeResult {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
account_id?: string
|
||||
}
|
||||
|
||||
export async function exchangeDropboxCodeForTokens(
|
||||
env: DropboxOAuthEnv,
|
||||
code: string
|
||||
): Promise<DropboxTokenExchangeResult> {
|
||||
const body = new URLSearchParams({
|
||||
code,
|
||||
grant_type: 'authorization_code',
|
||||
client_id: env.appKey,
|
||||
client_secret: env.appSecret,
|
||||
redirect_uri: env.redirectUri,
|
||||
})
|
||||
const res = await fetchWithTimeout(
|
||||
TOKEN_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Dropbox token exchange' }
|
||||
)
|
||||
if (!res.ok) {
|
||||
const errText = await res.text()
|
||||
throw new Error(`Dropbox token exchange failed: ${res.status} ${errText}`)
|
||||
}
|
||||
const json = (await res.json()) as DropboxTokenExchangeResult
|
||||
if (!json.refresh_token) {
|
||||
throw new Error(
|
||||
'No refresh token returned: the authorization request must use ' +
|
||||
'token_access_type=offline.'
|
||||
)
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when Dropbox's token endpoint rejects a refresh. Shares
|
||||
* {@link CloudTokenRefreshError}'s `invalid_grant` detection: Dropbox returns
|
||||
* `400 {"error": "invalid_grant"}` once the user disconnects the app.
|
||||
*/
|
||||
export class DropboxTokenRefreshError extends CloudTokenRefreshError {
|
||||
constructor(status: number, body: string) {
|
||||
super('Dropbox', status, body)
|
||||
this.name = 'DropboxTokenRefreshError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function refreshDropboxAccessToken(
|
||||
env: DropboxOAuthEnv,
|
||||
refreshToken: string
|
||||
): Promise<{ access_token: string; expires_in: number }> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
client_id: env.appKey,
|
||||
client_secret: env.appSecret,
|
||||
})
|
||||
const res = await fetchWithTimeout(
|
||||
TOKEN_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Dropbox token refresh' }
|
||||
)
|
||||
if (!res.ok) {
|
||||
const errText = await res.text()
|
||||
throw new DropboxTokenRefreshError(res.status, errText)
|
||||
}
|
||||
return (await res.json()) as { access_token: string; expires_in: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the grant. Dropbox revokes by *access* token (there is no
|
||||
* refresh-token revoke endpoint), so the caller mints a short-lived one first.
|
||||
* Best-effort: a failed revoke must not block the local disconnect.
|
||||
*/
|
||||
export async function revokeDropboxToken(accessToken: string): Promise<void> {
|
||||
try {
|
||||
await fetchWithTimeout(
|
||||
REVOKE_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
},
|
||||
{ timeoutMs: OAUTH_REVOKE_TIMEOUT_MS, description: 'Dropbox token revoke' }
|
||||
)
|
||||
} catch {
|
||||
// Swallow timeouts and network errors so disconnect flows still complete locally.
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchDropboxAccountEmail(accessToken: string): Promise<string> {
|
||||
// An RPC endpoint taking no arguments: send no body and no Content-Type,
|
||||
// otherwise Dropbox rejects the call as a malformed request.
|
||||
const res = await fetchWithTimeout(
|
||||
ACCOUNT_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Dropbox account fetch' }
|
||||
)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch Dropbox account info: ${res.status}`)
|
||||
}
|
||||
const json = (await res.json()) as { email?: string }
|
||||
return json.email || 'unknown@dropbox'
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Dropbox as a cloud backup target.
|
||||
*
|
||||
* The app is **app-folder** scoped, so every path here is relative to
|
||||
* `Apps/<app name>/` in the user's Dropbox and the app can never see anything
|
||||
* else they store there. That gives the same "we only touch what we created"
|
||||
* guarantee as the Google `drive.file` scope.
|
||||
*
|
||||
* Consequences for the sync engine, all handled here:
|
||||
* - There is no root folder to create: Dropbox's own app folder plays that
|
||||
* role, so company folders sit directly inside it (Drive needs the extra
|
||||
* `gnubok/` level because it writes into the user's whole Drive).
|
||||
* - Files are addressed by path, not id, and writes are `overwrite`. Nothing
|
||||
* can go stale, so `prepareTarget` makes no network call and the
|
||||
* "user deleted the file" recovery the Drive target needs has no analogue.
|
||||
*/
|
||||
import {
|
||||
buildDropboxAuthorizationUrl,
|
||||
exchangeDropboxCodeForTokens,
|
||||
fetchDropboxAccountEmail,
|
||||
getDropboxOAuthEnv,
|
||||
isDropboxOAuthConfigured,
|
||||
refreshDropboxAccessToken,
|
||||
revokeDropboxToken,
|
||||
DROPBOX_CALLBACK_PATH,
|
||||
} from './dropbox-oauth'
|
||||
import { sanitizeDropboxName, uploadDropboxFile } from './dropbox-client'
|
||||
import type {
|
||||
CloudStorageProvider,
|
||||
PreparedTarget,
|
||||
PrepareTargetParams,
|
||||
PutFileParams,
|
||||
PutFileResult,
|
||||
} from './cloud-provider'
|
||||
import type { CloudConnection } from '../types'
|
||||
|
||||
export const DROPBOX_CONNECTION_KEY = 'dropbox_connection'
|
||||
export const DROPBOX_LAST_SYNC_KEY = 'dropbox_last_sync'
|
||||
export const DROPBOX_SCHEDULE_KEY = 'dropbox_schedule'
|
||||
|
||||
/**
|
||||
* Link into the Dropbox web UI.
|
||||
*
|
||||
* App-folder scoped calls only ever see app-relative paths, so the API cannot
|
||||
* tell us where the app folder sits in the user's account. `Apps/<app name>`
|
||||
* is the answer, and the app name is chosen when the Dropbox app is
|
||||
* registered: a self-hoster registers their own. `DROPBOX_APP_FOLDER_NAME`
|
||||
* lets a deployment state it and get a deep link; without it we send the user
|
||||
* to `Apps/`, which is always correct and one click away. Never guess the
|
||||
* name: a link into the wrong folder reads as a lost backup.
|
||||
*/
|
||||
function folderLink(companyFolderPath: string): string {
|
||||
const appFolder = process.env.DROPBOX_APP_FOLDER_NAME
|
||||
const base = 'https://www.dropbox.com/home/Apps'
|
||||
if (!appFolder) return base
|
||||
return `${base}/${encodeURIComponent(appFolder)}${companyFolderPath
|
||||
.split('/')
|
||||
.map(encodeURIComponent)
|
||||
.join('/')}`
|
||||
}
|
||||
|
||||
export const dropboxProvider: CloudStorageProvider = {
|
||||
id: 'dropbox',
|
||||
label: 'Dropbox',
|
||||
keys: {
|
||||
connection: DROPBOX_CONNECTION_KEY,
|
||||
lastSync: DROPBOX_LAST_SYNC_KEY,
|
||||
schedule: DROPBOX_SCHEDULE_KEY,
|
||||
},
|
||||
callbackPath: DROPBOX_CALLBACK_PATH,
|
||||
|
||||
isConfigured: isDropboxOAuthConfigured,
|
||||
|
||||
buildAuthorizationUrl(origin, state) {
|
||||
return buildDropboxAuthorizationUrl(getDropboxOAuthEnv(origin), state)
|
||||
},
|
||||
|
||||
async exchangeCode(origin, code) {
|
||||
const tokens = await exchangeDropboxCodeForTokens(getDropboxOAuthEnv(origin), code)
|
||||
const email = await fetchDropboxAccountEmail(tokens.access_token)
|
||||
return { refreshToken: tokens.refresh_token, accountLabel: email }
|
||||
},
|
||||
|
||||
async revoke(refreshToken, origin) {
|
||||
// Dropbox revokes by access token, so mint a short-lived one first. The
|
||||
// whole thing is best-effort: a dead refresh token is already revoked.
|
||||
try {
|
||||
const env = getDropboxOAuthEnv(origin)
|
||||
const refreshed = await refreshDropboxAccessToken(env, refreshToken)
|
||||
await revokeDropboxToken(refreshed.access_token)
|
||||
} catch {
|
||||
// Swallow: the local disconnect must complete regardless.
|
||||
}
|
||||
},
|
||||
|
||||
async refreshAccessToken(refreshToken, origin) {
|
||||
const refreshed = await refreshDropboxAccessToken(
|
||||
getDropboxOAuthEnv(origin),
|
||||
refreshToken
|
||||
)
|
||||
return refreshed.access_token
|
||||
},
|
||||
|
||||
/**
|
||||
* Pure path derivation: Dropbox creates missing parent folders on upload, so
|
||||
* there is nothing to create up front and nothing that can be trashed
|
||||
* underneath us.
|
||||
*/
|
||||
async prepareTarget({
|
||||
connection,
|
||||
companyLabel,
|
||||
}: PrepareTargetParams): Promise<PreparedTarget> {
|
||||
const companyFolderPath = `/${sanitizeDropboxName(companyLabel)}`
|
||||
const patch: Partial<CloudConnection> | null =
|
||||
connection.company_folder_path === companyFolderPath
|
||||
? null
|
||||
: { company_folder_path: companyFolderPath }
|
||||
|
||||
return {
|
||||
target: {
|
||||
folderId: companyFolderPath,
|
||||
webViewLink: folderLink(companyFolderPath),
|
||||
},
|
||||
connectionPatch: patch,
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* `previousId` is ignored: the path is derived from the file name, and an
|
||||
* overwrite write is correct whether or not the file is already there. That
|
||||
* also means a file the user deleted in Dropbox simply reappears on the next
|
||||
* sync, with no recovery path needed.
|
||||
*/
|
||||
async putFile({
|
||||
accessToken,
|
||||
target,
|
||||
name,
|
||||
data,
|
||||
}: PutFileParams): Promise<PutFileResult> {
|
||||
const path = `${target.folderId}/${sanitizeDropboxName(name)}`
|
||||
const uploaded = await uploadDropboxFile(accessToken, path, data)
|
||||
return {
|
||||
id: uploaded.path,
|
||||
name: uploaded.name,
|
||||
size_bytes: uploaded.size_bytes,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Folder naming shared by the sync engine and the storage providers.
|
||||
*
|
||||
* Lives in its own module so a provider can read it without importing
|
||||
* `sync.ts`, which imports the provider registry back (import cycle).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Top-level folder created in the user's Google Drive. Wire-format identifier:
|
||||
* it names a folder that already exists in every connected user's Drive, so
|
||||
* renaming it would strand their existing backups (see the gnubok naming rule
|
||||
* in CLAUDE.md).
|
||||
*
|
||||
* Dropbox has no equivalent: the app is app-folder scoped, so Dropbox's own
|
||||
* `Apps/<app name>/` folder already plays this role and company folders sit
|
||||
* directly inside it.
|
||||
*/
|
||||
export const ROOT_FOLDER_NAME = 'gnubok'
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* Minimal Google Drive v3 client: just enough to:
|
||||
* - find or create a named folder,
|
||||
* - revalidate a cached file/folder id,
|
||||
* - upload a file (create) or update one in place, via resumable uploads.
|
||||
*
|
||||
* We operate on `drive.file` scope, so we can only see files we created.
|
||||
* Queries by name return only app-created folders with that name.
|
||||
*
|
||||
* Uploads use Drive's resumable protocol in 8 MB chunks (a multiple of the
|
||||
* required 256 KiB): no multipart body concatenation (which doubles memory
|
||||
* for large archives), per-chunk retries on transient failures, and every
|
||||
* upload is verified against the md5Checksum Drive reports. A silently
|
||||
* corrupted backup is worse than a failed one.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
const DRIVE_API = 'https://www.googleapis.com/drive/v3'
|
||||
const DRIVE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3/files'
|
||||
const FOLDER_MIME = 'application/vnd.google-apps.folder'
|
||||
|
||||
/** 8 MB: resumable chunks must be multiples of 256 KiB. */
|
||||
const UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024
|
||||
const CHUNK_MAX_ATTEMPTS = 3
|
||||
const RESULT_FIELDS = 'id,name,size,webViewLink,md5Checksum'
|
||||
|
||||
interface DriveFile {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
/** Thrown when an update targets a file that no longer exists (404). */
|
||||
export class DriveFileGoneError extends Error {
|
||||
constructor(fileId: string) {
|
||||
super(`Drive file ${fileId} no longer exists`)
|
||||
this.name = 'DriveFileGoneError'
|
||||
}
|
||||
}
|
||||
|
||||
async function driveFetch(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
init?: RequestInit
|
||||
): Promise<Response> {
|
||||
const res = await fetch(`${DRIVE_API}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.headers || {}),
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = await res.text()
|
||||
throw new Error(`Drive API ${res.status}: ${body.slice(0, 200)}`)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a folder by name under a parent (or root). Returns null if none exists.
|
||||
* Uses q= filter; drive.file scope only sees app-created folders.
|
||||
*/
|
||||
async function findFolderByName(
|
||||
accessToken: string,
|
||||
name: string,
|
||||
parentId: string | null
|
||||
): Promise<DriveFile | null> {
|
||||
const parentClause = parentId ? `'${parentId}' in parents` : `'root' in parents`
|
||||
const q = [
|
||||
`mimeType = '${FOLDER_MIME}'`,
|
||||
`name = '${escapeName(name)}'`,
|
||||
parentClause,
|
||||
'trashed = false',
|
||||
].join(' and ')
|
||||
const url = `/files?q=${encodeURIComponent(q)}&fields=files(id,name)&pageSize=1`
|
||||
const res = await driveFetch(accessToken, url)
|
||||
const json = (await res.json()) as { files: DriveFile[] }
|
||||
return json.files[0] || null
|
||||
}
|
||||
|
||||
async function createFolder(
|
||||
accessToken: string,
|
||||
name: string,
|
||||
parentId: string | null
|
||||
): Promise<DriveFile> {
|
||||
const body = {
|
||||
name,
|
||||
mimeType: FOLDER_MIME,
|
||||
parents: parentId ? [parentId] : undefined,
|
||||
}
|
||||
const res = await driveFetch(accessToken, '/files?fields=id,name', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
return (await res.json()) as DriveFile
|
||||
}
|
||||
|
||||
export async function ensureFolder(
|
||||
accessToken: string,
|
||||
name: string,
|
||||
parentId: string | null
|
||||
): Promise<DriveFile> {
|
||||
const existing = await findFolderByName(accessToken, name, parentId)
|
||||
if (existing) return existing
|
||||
return createFolder(accessToken, name, parentId)
|
||||
}
|
||||
|
||||
export interface FileMeta {
|
||||
id: string
|
||||
name: string
|
||||
/** True also when the file sits inside a trashed parent folder. */
|
||||
trashed: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch metadata for a file/folder by id. Returns null on 404 (deleted or
|
||||
* never visible to this scope). Used to revalidate cached folder ids: a file
|
||||
* created inside a trashed folder is purged with it, so uploads must never
|
||||
* target a trashed parent.
|
||||
*/
|
||||
export async function getFileMeta(
|
||||
accessToken: string,
|
||||
fileId: string
|
||||
): Promise<FileMeta | null> {
|
||||
const res = await fetch(
|
||||
`${DRIVE_API}/files/${encodeURIComponent(fileId)}?fields=id,name,trashed`,
|
||||
{ headers: { Authorization: `Bearer ${accessToken}` } }
|
||||
)
|
||||
if (res.status === 404) return null
|
||||
if (!res.ok) {
|
||||
const body = await res.text()
|
||||
throw new Error(`Drive API ${res.status}: ${body.slice(0, 200)}`)
|
||||
}
|
||||
const json = (await res.json()) as { id: string; name: string; trashed?: boolean }
|
||||
return { id: json.id, name: json.name, trashed: json.trashed === true }
|
||||
}
|
||||
|
||||
export interface UploadResult {
|
||||
id: string
|
||||
name: string
|
||||
size_bytes: number
|
||||
web_view_link: string
|
||||
/** MD5 reported by Drive; present when the API returned it. */
|
||||
md5_checksum?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new file in a folder (resumable, md5-verified, one full retry on
|
||||
* checksum mismatch).
|
||||
*/
|
||||
export async function uploadFile(
|
||||
accessToken: string,
|
||||
folderId: string,
|
||||
fileName: string,
|
||||
data: ArrayBuffer,
|
||||
contentType = 'application/zip'
|
||||
): Promise<UploadResult> {
|
||||
return verifiedUpload(data, () =>
|
||||
resumableUpload(accessToken, data, contentType, {
|
||||
method: 'POST',
|
||||
url: `${DRIVE_UPLOAD_API}?uploadType=resumable&fields=${RESULT_FIELDS}`,
|
||||
metadata: { name: fileName, parents: [folderId] },
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the content of an existing file in place (resumable, md5-verified).
|
||||
* Drive keeps prior versions of updated files for ~30 days, which gives the
|
||||
* backup rolling history without accumulating one file per day.
|
||||
* Throws DriveFileGoneError when the file id no longer exists.
|
||||
*/
|
||||
export async function updateFile(
|
||||
accessToken: string,
|
||||
fileId: string,
|
||||
data: ArrayBuffer,
|
||||
contentType = 'application/zip'
|
||||
): Promise<UploadResult> {
|
||||
return verifiedUpload(data, () =>
|
||||
resumableUpload(accessToken, data, contentType, {
|
||||
method: 'PATCH',
|
||||
url: `${DRIVE_UPLOAD_API}/${encodeURIComponent(fileId)}?uploadType=resumable&fields=${RESULT_FIELDS}`,
|
||||
fileId,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
async function verifiedUpload(
|
||||
data: ArrayBuffer,
|
||||
run: () => Promise<UploadResult>
|
||||
): Promise<UploadResult> {
|
||||
const expectedMd5 = createHash('md5').update(Buffer.from(data)).digest('hex')
|
||||
let lastError: Error | null = null
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const result = await run()
|
||||
if (!result.md5_checksum || result.md5_checksum === expectedMd5) {
|
||||
return result
|
||||
}
|
||||
lastError = new Error(
|
||||
`Drive upload checksum mismatch: expected ${expectedMd5}, got ${result.md5_checksum}`
|
||||
)
|
||||
}
|
||||
throw lastError
|
||||
}
|
||||
|
||||
interface ResumableTarget {
|
||||
method: 'POST' | 'PATCH'
|
||||
url: string
|
||||
metadata?: Record<string, unknown>
|
||||
fileId?: string
|
||||
}
|
||||
|
||||
async function resumableUpload(
|
||||
accessToken: string,
|
||||
data: ArrayBuffer,
|
||||
contentType: string,
|
||||
target: ResumableTarget
|
||||
): Promise<UploadResult> {
|
||||
// 1) Initiate the session. Metadata (name/parents) rides on the initiation
|
||||
// request; the byte chunks follow against the returned session URL.
|
||||
const initRes = await fetch(target.url, {
|
||||
method: target.method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json; charset=UTF-8',
|
||||
'X-Upload-Content-Type': contentType,
|
||||
'X-Upload-Content-Length': String(data.byteLength),
|
||||
},
|
||||
body: target.metadata ? JSON.stringify(target.metadata) : undefined,
|
||||
})
|
||||
if (initRes.status === 404 && target.fileId) {
|
||||
throw new DriveFileGoneError(target.fileId)
|
||||
}
|
||||
if (!initRes.ok) {
|
||||
const body = await initRes.text()
|
||||
throw new Error(`Drive upload init failed: ${initRes.status} ${body.slice(0, 200)}`)
|
||||
}
|
||||
const sessionUrl = initRes.headers.get('location')
|
||||
if (!sessionUrl) {
|
||||
throw new Error('Drive upload init returned no session URL')
|
||||
}
|
||||
|
||||
// 2) Send the bytes in chunks. 308 = chunk accepted, keep going;
|
||||
// 200/201 = upload complete with the file resource as body.
|
||||
const total = data.byteLength
|
||||
const buffer = Buffer.from(data)
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total)
|
||||
const chunk = buffer.subarray(offset, end)
|
||||
|
||||
let res: Response | null = null
|
||||
let lastErr: unknown = null
|
||||
for (let attempt = 0; attempt < CHUNK_MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
res = await fetch(sessionUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Length': String(chunk.length),
|
||||
'Content-Range': `bytes ${offset}-${end - 1}/${total}`,
|
||||
},
|
||||
body: chunk,
|
||||
})
|
||||
if (res.status >= 500) {
|
||||
lastErr = new Error(`Drive chunk upload ${res.status}`)
|
||||
res = null
|
||||
continue
|
||||
}
|
||||
break
|
||||
} catch (err) {
|
||||
lastErr = err
|
||||
res = null
|
||||
}
|
||||
}
|
||||
if (!res) {
|
||||
throw lastErr instanceof Error
|
||||
? lastErr
|
||||
: new Error('Drive chunk upload failed after retries')
|
||||
}
|
||||
|
||||
if (res.status === 308) {
|
||||
// Advance to wherever the session says it is (defensive: usually `end`).
|
||||
const range = res.headers.get('range')
|
||||
const match = range?.match(/bytes=0-(\d+)/)
|
||||
offset = match ? Number(match[1]) + 1 : end
|
||||
continue
|
||||
}
|
||||
if (res.ok) {
|
||||
const json = (await res.json()) as {
|
||||
id: string
|
||||
name: string
|
||||
size?: string
|
||||
webViewLink?: string
|
||||
md5Checksum?: string
|
||||
}
|
||||
return {
|
||||
id: json.id,
|
||||
name: json.name,
|
||||
size_bytes: json.size ? Number(json.size) : total,
|
||||
web_view_link:
|
||||
json.webViewLink || `https://drive.google.com/file/d/${json.id}/view`,
|
||||
md5_checksum: json.md5Checksum,
|
||||
}
|
||||
}
|
||||
const body = await res.text()
|
||||
throw new Error(`Drive upload failed: ${res.status} ${body.slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function escapeName(name: string): string {
|
||||
// Drive query string: escape single quotes and backslashes.
|
||||
return name.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* Minimal Google OAuth 2.0 client for the cloud-backup extension.
|
||||
*
|
||||
* Scope: `drive.file`: app-created files only, not the user's full Drive.
|
||||
* Access type: `offline`: returns a refresh token on first consent.
|
||||
* Prompt: `consent`: forces the consent screen so the refresh token is
|
||||
* re-issued even if the user has previously authorised the app.
|
||||
*/
|
||||
|
||||
import {
|
||||
fetchWithTimeout,
|
||||
OAUTH_TIMEOUT_MS,
|
||||
OAUTH_REVOKE_TIMEOUT_MS,
|
||||
} from '@/lib/http/fetch-with-timeout'
|
||||
import { CloudTokenRefreshError } from './cloud-provider'
|
||||
|
||||
const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file'
|
||||
const AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'
|
||||
const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
|
||||
const USERINFO_ENDPOINT = 'https://openidconnect.googleapis.com/v1/userinfo'
|
||||
|
||||
export interface OAuthEnv {
|
||||
clientId: string
|
||||
clientSecret: string
|
||||
redirectUri: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this deployment can run the Google flow at all. Checked before the
|
||||
* UI offers a connect button, so a missing credential renders as a disabled
|
||||
* row instead of a failed OAuth round-trip.
|
||||
*/
|
||||
export function isGoogleOAuthConfigured(): boolean {
|
||||
return Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET)
|
||||
}
|
||||
|
||||
export function getOAuthEnv(origin: string): OAuthEnv {
|
||||
const clientId = process.env.GOOGLE_CLIENT_ID
|
||||
const clientSecret = process.env.GOOGLE_CLIENT_SECRET
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error(
|
||||
'Google OAuth is not configured: set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET'
|
||||
)
|
||||
}
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri: `${origin}/api/extensions/ext/cloud-backup/oauth/callback`,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl(env: OAuthEnv, state: string): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.clientId,
|
||||
redirect_uri: env.redirectUri,
|
||||
response_type: 'code',
|
||||
scope: `openid email ${DRIVE_SCOPE}`,
|
||||
access_type: 'offline',
|
||||
prompt: 'consent',
|
||||
include_granted_scopes: 'true',
|
||||
state,
|
||||
})
|
||||
return `${AUTH_ENDPOINT}?${params.toString()}`
|
||||
}
|
||||
|
||||
export interface TokenExchangeResult {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
id_token?: string
|
||||
}
|
||||
|
||||
export async function exchangeCodeForTokens(
|
||||
env: OAuthEnv,
|
||||
code: string
|
||||
): Promise<TokenExchangeResult> {
|
||||
const body = new URLSearchParams({
|
||||
code,
|
||||
client_id: env.clientId,
|
||||
client_secret: env.clientSecret,
|
||||
redirect_uri: env.redirectUri,
|
||||
grant_type: 'authorization_code',
|
||||
})
|
||||
const res = await fetchWithTimeout(
|
||||
TOKEN_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google token exchange' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
const errText = await res.text()
|
||||
throw new Error(`Google token exchange failed: ${res.status} ${errText}`)
|
||||
}
|
||||
const json = (await res.json()) as TokenExchangeResult
|
||||
if (!json.refresh_token) {
|
||||
throw new Error(
|
||||
'No refresh token returned: Google only issues one on first consent. ' +
|
||||
'Revoke the app at myaccount.google.com/permissions and try again.'
|
||||
)
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
export interface AccessTokenResult {
|
||||
access_token: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when Google's token endpoint rejects a refresh attempt. Carries the
|
||||
* HTTP status and raw response body so callers can distinguish a permanently
|
||||
* dead refresh token (400 invalid_grant) from transient failures.
|
||||
*
|
||||
* Extends the provider-agnostic {@link CloudTokenRefreshError} so `performSync`
|
||||
* can handle a dead token identically whatever the destination is.
|
||||
*/
|
||||
export class GoogleTokenRefreshError extends CloudTokenRefreshError {
|
||||
constructor(status: number, body: string) {
|
||||
super('Google', status, body)
|
||||
this.name = 'GoogleTokenRefreshError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function refreshAccessToken(
|
||||
env: OAuthEnv,
|
||||
refreshToken: string
|
||||
): Promise<AccessTokenResult> {
|
||||
const body = new URLSearchParams({
|
||||
client_id: env.clientId,
|
||||
client_secret: env.clientSecret,
|
||||
refresh_token: refreshToken,
|
||||
grant_type: 'refresh_token',
|
||||
})
|
||||
const res = await fetchWithTimeout(
|
||||
TOKEN_ENDPOINT,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google token refresh' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
const errText = await res.text()
|
||||
throw new GoogleTokenRefreshError(res.status, errText)
|
||||
}
|
||||
return (await res.json()) as AccessTokenResult
|
||||
}
|
||||
|
||||
export async function revokeToken(token: string): Promise<void> {
|
||||
try {
|
||||
await fetchWithTimeout(
|
||||
`https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(token)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
},
|
||||
{ timeoutMs: OAUTH_REVOKE_TIMEOUT_MS, description: 'Google token revoke' },
|
||||
)
|
||||
} catch {
|
||||
// Best-effort revoke: swallow timeouts and network errors so disconnect flows still complete locally.
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchUserEmail(accessToken: string): Promise<string> {
|
||||
const res = await fetchWithTimeout(
|
||||
USERINFO_ENDPOINT,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
},
|
||||
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google userinfo fetch' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch Google user info: ${res.status}`)
|
||||
}
|
||||
const json = (await res.json()) as { email?: string }
|
||||
return json.email || 'unknown@google'
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Google Drive as a cloud backup target.
|
||||
*
|
||||
* Wraps the existing `google-oauth.ts` + `google-drive.ts` clients in the
|
||||
* provider contract. Behaviour is unchanged from before the contract existed:
|
||||
* the same `drive.file` scope, the same `gnubok/<company>/` folder pair with
|
||||
* trashed-folder revalidation, and the same resumable md5-verified uploads.
|
||||
*
|
||||
* The storage keys keep their original `google_drive_*` names on purpose:
|
||||
* every already-connected company has records under them.
|
||||
*/
|
||||
import { ROOT_FOLDER_NAME } from './folder-names'
|
||||
import {
|
||||
buildAuthorizationUrl,
|
||||
exchangeCodeForTokens,
|
||||
fetchUserEmail,
|
||||
getOAuthEnv,
|
||||
isGoogleOAuthConfigured,
|
||||
refreshAccessToken,
|
||||
revokeToken,
|
||||
} from './google-oauth'
|
||||
import {
|
||||
DriveFileGoneError,
|
||||
ensureFolder,
|
||||
getFileMeta,
|
||||
updateFile,
|
||||
uploadFile,
|
||||
} from './google-drive'
|
||||
import type {
|
||||
CloudStorageProvider,
|
||||
PreparedTarget,
|
||||
PrepareTargetParams,
|
||||
PutFileParams,
|
||||
PutFileResult,
|
||||
} from './cloud-provider'
|
||||
import type { CloudConnection } from '../types'
|
||||
|
||||
export const GOOGLE_CONNECTION_KEY = 'google_drive_connection'
|
||||
export const GOOGLE_LAST_SYNC_KEY = 'google_drive_last_sync'
|
||||
export const GOOGLE_SCHEDULE_KEY = 'google_drive_schedule'
|
||||
|
||||
function folderLink(folderId: string): string {
|
||||
return `https://drive.google.com/drive/folders/${folderId}`
|
||||
}
|
||||
|
||||
export const googleDriveProvider: CloudStorageProvider = {
|
||||
id: 'google_drive',
|
||||
label: 'Google Drive',
|
||||
keys: {
|
||||
connection: GOOGLE_CONNECTION_KEY,
|
||||
lastSync: GOOGLE_LAST_SYNC_KEY,
|
||||
schedule: GOOGLE_SCHEDULE_KEY,
|
||||
},
|
||||
// Registered with Google as an authorised redirect URI: never change it.
|
||||
callbackPath: '/oauth/callback',
|
||||
|
||||
isConfigured: isGoogleOAuthConfigured,
|
||||
|
||||
buildAuthorizationUrl(origin, state) {
|
||||
return buildAuthorizationUrl(getOAuthEnv(origin), state)
|
||||
},
|
||||
|
||||
async exchangeCode(origin, code) {
|
||||
const tokens = await exchangeCodeForTokens(getOAuthEnv(origin), code)
|
||||
const email = await fetchUserEmail(tokens.access_token)
|
||||
return { refreshToken: tokens.refresh_token, accountLabel: email }
|
||||
},
|
||||
|
||||
async revoke(refreshToken) {
|
||||
// Google revokes a refresh token directly: no client credentials needed.
|
||||
await revokeToken(refreshToken)
|
||||
},
|
||||
|
||||
async refreshAccessToken(refreshToken, origin) {
|
||||
const refreshed = await refreshAccessToken(getOAuthEnv(origin), refreshToken)
|
||||
return refreshed.access_token
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve the `gnubok/<company>/` folder pair, revalidating the cached ids.
|
||||
*
|
||||
* Files created inside a trashed folder are purged with it, so a folder the
|
||||
* user trashed or deleted must never receive uploads. `trashed` is inherited
|
||||
* from parents, so checking the company folder covers a trashed root too;
|
||||
* the root is only re-checked when the company folder needs recreating.
|
||||
*/
|
||||
async prepareTarget({
|
||||
accessToken,
|
||||
connection,
|
||||
companyLabel,
|
||||
}: PrepareTargetParams): Promise<PreparedTarget> {
|
||||
let rootFolderId = connection.root_folder_id
|
||||
let companyFolderId = connection.company_folder_id
|
||||
|
||||
if (companyFolderId) {
|
||||
const meta = await getFileMeta(accessToken, companyFolderId)
|
||||
if (!meta || meta.trashed) companyFolderId = null
|
||||
}
|
||||
if (!companyFolderId && rootFolderId) {
|
||||
const rootMeta = await getFileMeta(accessToken, rootFolderId)
|
||||
if (!rootMeta || rootMeta.trashed) rootFolderId = null
|
||||
}
|
||||
if (!rootFolderId) {
|
||||
const root = await ensureFolder(accessToken, ROOT_FOLDER_NAME, null)
|
||||
rootFolderId = root.id
|
||||
}
|
||||
if (!companyFolderId) {
|
||||
const companyFolder = await ensureFolder(accessToken, companyLabel, rootFolderId)
|
||||
companyFolderId = companyFolder.id
|
||||
}
|
||||
|
||||
const changed =
|
||||
rootFolderId !== connection.root_folder_id ||
|
||||
companyFolderId !== connection.company_folder_id
|
||||
const patch: Partial<CloudConnection> | null = changed
|
||||
? { root_folder_id: rootFolderId, company_folder_id: companyFolderId }
|
||||
: null
|
||||
|
||||
return {
|
||||
target: { folderId: companyFolderId, webViewLink: folderLink(companyFolderId) },
|
||||
connectionPatch: patch,
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Update the file in place when we already know its id (Drive keeps ~30 days
|
||||
* of prior versions, which gives the backup rolling history without one file
|
||||
* per day), falling back to a create when the user deleted it.
|
||||
*/
|
||||
async putFile({
|
||||
accessToken,
|
||||
target,
|
||||
name,
|
||||
previousId,
|
||||
data,
|
||||
contentType,
|
||||
}: PutFileParams): Promise<PutFileResult> {
|
||||
if (previousId) {
|
||||
try {
|
||||
return await updateFile(accessToken, previousId, data, contentType)
|
||||
} catch (err) {
|
||||
if (!(err instanceof DriveFileGoneError)) throw err
|
||||
// The user deleted the file in Drive: recreate it.
|
||||
}
|
||||
}
|
||||
return uploadFile(accessToken, target.folderId, name, data, contentType)
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* The cloud backup destinations this build knows about.
|
||||
*
|
||||
* Order matters: it is the order the providers are listed in the UI and the
|
||||
* order the cron walks them. Google Drive stays first because it shipped
|
||||
* first and every existing connection points at it.
|
||||
*/
|
||||
import { googleDriveProvider } from './google-provider'
|
||||
import { dropboxProvider } from './dropbox-provider'
|
||||
import type { CloudStorageProvider } from './cloud-provider'
|
||||
import type { CloudProviderId } from '../types'
|
||||
|
||||
export const CLOUD_PROVIDERS: readonly CloudStorageProvider[] = [
|
||||
googleDriveProvider,
|
||||
dropboxProvider,
|
||||
]
|
||||
|
||||
/** The destination assumed when a request names none: the original target. */
|
||||
export const DEFAULT_PROVIDER_ID: CloudProviderId = 'google_drive'
|
||||
|
||||
export function getProvider(id: string | null | undefined): CloudStorageProvider | null {
|
||||
if (!id) return getProvider(DEFAULT_PROVIDER_ID)
|
||||
return CLOUD_PROVIDERS.find((p) => p.id === id) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the provider named by a request's `?provider=` parameter.
|
||||
* Absent means Google Drive, so links and clients written before Dropbox
|
||||
* existed keep hitting the destination they meant.
|
||||
*/
|
||||
export function providerFromRequest(request: Request): CloudStorageProvider | null {
|
||||
return getProvider(new URL(request.url).searchParams.get('provider'))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { GoogleDriveSchedule } from '../types'
|
||||
|
||||
const STOCKHOLM_TZ = 'Europe/Stockholm'
|
||||
|
||||
function isValidHour(hour: unknown): hour is number {
|
||||
return (
|
||||
typeof hour === 'number' && Number.isInteger(hour) && hour >= 0 && hour <= 23
|
||||
)
|
||||
}
|
||||
|
||||
function stockholmDateString(now: Date): string {
|
||||
// sv-SE with a timeZone yields YYYY-MM-DD.
|
||||
return new Intl.DateTimeFormat('sv-SE', { timeZone: STOCKHOLM_TZ }).format(now)
|
||||
}
|
||||
|
||||
function stockholmHourOf(date: Date): number {
|
||||
return Number(
|
||||
new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: STOCKHOLM_TZ,
|
||||
hour: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
}).format(date)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute timestamp of today's HH:00 in Europe/Stockholm. Tries the two
|
||||
* offsets Sweden uses (CEST +02:00, CET +01:00) and keeps the one that lands
|
||||
* on the requested wall-clock hour, so DST transitions resolve correctly
|
||||
* without a timezone library.
|
||||
*/
|
||||
export function stockholmSlotForDay(now: Date, hour: number): Date {
|
||||
const dateStr = stockholmDateString(now)
|
||||
const hh = String(hour).padStart(2, '0')
|
||||
for (const offset of ['+02:00', '+01:00']) {
|
||||
const candidate = new Date(`${dateStr}T${hh}:00:00${offset}`)
|
||||
if (stockholmHourOf(candidate) === hour) return candidate
|
||||
}
|
||||
return new Date(`${dateStr}T${hh}:00:00+01:00`)
|
||||
}
|
||||
|
||||
/** UTC hour that corresponds to a Stockholm wall-clock hour today. */
|
||||
export function stockholmHourToUtcHour(hour: number, now: Date = new Date()): number {
|
||||
return stockholmSlotForDay(now, hour).getUTCHours()
|
||||
}
|
||||
|
||||
/**
|
||||
* Today's scheduled slot as an absolute timestamp, or null when the schedule
|
||||
* carries no valid hour. `hour_local` (Europe/Stockholm wall-clock, stable
|
||||
* across DST) wins over the legacy `hour_utc`.
|
||||
*/
|
||||
function scheduleSlotForDay(schedule: GoogleDriveSchedule, now: Date): Date | null {
|
||||
if (isValidHour(schedule.hour_local)) {
|
||||
return stockholmSlotForDay(now, schedule.hour_local)
|
||||
}
|
||||
if (isValidHour(schedule.hour_utc)) {
|
||||
const slot = new Date(now)
|
||||
slot.setUTCHours(schedule.hour_utc, 0, 0, 0)
|
||||
return slot
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* A schedule is due when its daily slot for today has passed and no auto-sync
|
||||
* attempt has run since that slot. Hour equality is deliberately NOT
|
||||
* required: if the popular 03:00 batch overruns the cron's time budget, the
|
||||
* leftover companies stay due and get picked up by the next hourly run
|
||||
* instead of silently losing the whole day.
|
||||
*/
|
||||
export function isScheduleDue(
|
||||
schedule: GoogleDriveSchedule | null | undefined,
|
||||
now: Date
|
||||
): boolean {
|
||||
if (!schedule?.enabled) return false
|
||||
const slot = scheduleSlotForDay(schedule, now)
|
||||
if (!slot) return false
|
||||
if (now.getTime() < slot.getTime()) return false
|
||||
|
||||
if (!schedule.last_auto_sync_at) return true
|
||||
const lastAttempt = new Date(schedule.last_auto_sync_at).getTime()
|
||||
return Number.isFinite(lastAttempt) ? lastAttempt < slot.getTime() : true
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"id": "cloud-backup",
|
||||
"sector": "general",
|
||||
"exportName": "cloudBackupExtension",
|
||||
"entryPoint": "@/extensions/general/cloud-backup",
|
||||
"workspace": "@/components/extensions/general/CloudBackupWorkspace",
|
||||
"requiredEnvVars": ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"],
|
||||
"optionalEnvVars": [
|
||||
"DROPBOX_APP_KEY",
|
||||
"DROPBOX_APP_SECRET",
|
||||
"DROPBOX_APP_FOLDER_NAME"
|
||||
],
|
||||
"npmDependencies": [],
|
||||
"definition": {
|
||||
"name": "Molnsynkronisering",
|
||||
"category": "operations",
|
||||
"icon": "Cloud",
|
||||
"dataPattern": "manual",
|
||||
"hasOwnData": true,
|
||||
"description": "Synka säkerhetsbackup till din egen molnlagring",
|
||||
"longDescription": "Koppla ditt Google Drive- eller Dropbox-konto och ladda upp en fullständig säkerhetsbackup med ett klick. Accounted skapar en ZIP med SIE-filer, kvitton och behandlingshistorik och laddar upp till en egen mapp i din molnlagring. Du kan koppla båda samtidigt, med separata scheman. Perfekt för att uppfylla egna krav på redundans.",
|
||||
"subscriptionNotice": "Kräver ett Google- eller Dropbox-konto. Uppladdningar sker direkt till din egen molnlagring: ingen data lagras hos tredje part utöver den tjänst du väljer."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Cloud backup storage targets.
|
||||
*
|
||||
* The extension syncs the same archive set to one or more providers. Each
|
||||
* provider owns its own three `extension_data` keys (connection, last sync,
|
||||
* schedule), so connecting Dropbox never touches the Google Drive records and
|
||||
* the two schedules run independently.
|
||||
*/
|
||||
export type CloudProviderId = 'google_drive' | 'dropbox'
|
||||
|
||||
/**
|
||||
* Connection stored per company + provider in extension_data (key
|
||||
* `google_drive_connection` / `dropbox_connection`). The refresh token is
|
||||
* AES-256-GCM encrypted (see lib/crypto.ts): never store it in plaintext.
|
||||
*/
|
||||
export interface CloudConnection {
|
||||
refresh_token_encrypted: string
|
||||
/** Account identifier shown in the UI: the account email on both providers. */
|
||||
account_email: string
|
||||
connected_at: string
|
||||
/**
|
||||
* Google Drive: ID of the top-level "gnubok" folder in the user's Drive.
|
||||
* Unused on Dropbox (app-folder scoped, so our root IS the app folder).
|
||||
*/
|
||||
root_folder_id: string | null
|
||||
/** Google Drive: ID of the per-company subfolder. Unused on Dropbox. */
|
||||
company_folder_id: string | null
|
||||
/**
|
||||
* Dropbox: app-folder-relative path of the company folder
|
||||
* (`/Testbolag AB (556000-0000)`). Unused on Google Drive.
|
||||
*/
|
||||
company_folder_path?: string | null
|
||||
/**
|
||||
* Connection health. `needs_reauth` means the provider rejected the refresh
|
||||
* token permanently (400 invalid_grant): the cron skips the connection
|
||||
* and the UI asks the user to reconnect. Absent/undefined means active
|
||||
* (records created before this field existed).
|
||||
*/
|
||||
status?: 'active' | 'needs_reauth'
|
||||
/** ISO timestamp of when the dead refresh token was detected. */
|
||||
needs_reauth_at?: string
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link CloudConnection}. Kept for existing call sites. */
|
||||
export type GoogleDriveConnection = CloudConnection
|
||||
|
||||
/**
|
||||
* State of one file in the company's backup folder: an `Arkiv <år>.zip`
|
||||
* per räkenskapsår, `Grunddata.zip`, and the folder LÄSMIG.txt. Files are
|
||||
* updated in place; `fingerprint` decides whether a sync re-uploads them.
|
||||
*/
|
||||
export interface CloudFileState {
|
||||
kind: 'period' | 'base' | 'readme'
|
||||
/** Set when kind = 'period'. */
|
||||
period_id?: string
|
||||
/**
|
||||
* Provider-native handle for the stored file: a Drive file id, or the
|
||||
* app-folder-relative path on Dropbox. Opaque to everything but the
|
||||
* provider that wrote it.
|
||||
*/
|
||||
file_id: string
|
||||
file_name: string
|
||||
size_bytes: number
|
||||
/** Change-detection key: the file re-uploads only when this differs. */
|
||||
fingerprint: string
|
||||
/**
|
||||
* SHA-256 of the uploaded bytes. The upload itself is verified against the
|
||||
* provider's own checksum (Drive md5Checksum, Dropbox content_hash); this
|
||||
* hash is recorded for evidentiary value (the user can prove the file in
|
||||
* their cloud storage is the one Accounted produced).
|
||||
*/
|
||||
sha256: string
|
||||
/** False when the file was built without document blobs (size fallback). */
|
||||
included_documents: boolean
|
||||
uploaded_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Last-sync snapshot stored under key `google_drive_last_sync` /
|
||||
* `dropbox_last_sync`.
|
||||
*
|
||||
* Current records carry `files` (per-fiscal-year layout). The flat
|
||||
* `file_id`/`file_name`/`file_size_bytes` fields are the legacy single-ZIP
|
||||
* layout, kept optional so old records still render.
|
||||
*/
|
||||
export interface CloudLastSync {
|
||||
at: string
|
||||
/**
|
||||
* Provider-native handle for the company backup folder: a Drive folder id,
|
||||
* or the app-folder-relative path on Dropbox.
|
||||
*/
|
||||
folder_id: string
|
||||
/**
|
||||
* Link a human can open to reach the backup folder. Written since the
|
||||
* Dropbox target landed; absent on older Drive records, which the UI
|
||||
* reconstructs from `folder_id`.
|
||||
*/
|
||||
web_view_link?: string
|
||||
files?: CloudFileState[]
|
||||
total_size_bytes?: number
|
||||
// Legacy single-file layout fields.
|
||||
file_id?: string
|
||||
file_name?: string
|
||||
file_size_bytes?: number
|
||||
included_documents?: boolean
|
||||
sha256?: string
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link CloudLastSync}. Kept for existing call sites. */
|
||||
export type GoogleDriveLastSync = CloudLastSync
|
||||
|
||||
/**
|
||||
* Schedule stored under key `google_drive_schedule` / `dropbox_schedule`.
|
||||
* Each provider carries its own schedule: a company can back up to Drive
|
||||
* nightly and to Dropbox weekly, or leave one of them off entirely. Runs once
|
||||
* per day at the configured hour via a cron route
|
||||
* (`app/api/extensions/cloud-backup/auto-sync/cron`).
|
||||
*/
|
||||
export interface CloudSchedule {
|
||||
enabled: boolean
|
||||
/**
|
||||
* 0-23, UTC hour when the daily auto-sync should run. Legacy field: kept
|
||||
* for records written before hour_local existed, and mirrored on writes so
|
||||
* old readers keep an approximate value.
|
||||
*/
|
||||
hour_utc: number
|
||||
/**
|
||||
* 0-23, Europe/Stockholm wall-clock hour. Preferred over hour_utc: it stays
|
||||
* put across DST transitions. Absent on records from before this field.
|
||||
*/
|
||||
hour_local?: number
|
||||
/** ISO timestamp of the last auto-sync attempt (success or failure). */
|
||||
last_auto_sync_at: string | null
|
||||
/** Outcome of the last auto-sync attempt. */
|
||||
last_auto_sync_status: 'success' | 'error' | null
|
||||
/** Short error message if the last auto-sync failed. */
|
||||
last_auto_sync_error: string | null
|
||||
/**
|
||||
* Number of auto-sync attempts in a row that failed. Reset to 0 on
|
||||
* success; drives the failure-alert email threshold.
|
||||
*/
|
||||
consecutive_failures?: number
|
||||
/** ISO timestamp of the last failure-alert email (throttle anchor). */
|
||||
last_alert_at?: string | null
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link CloudSchedule}. Kept for existing call sites. */
|
||||
export type GoogleDriveSchedule = CloudSchedule
|
||||
|
||||
/** Per-provider status block returned to the UI. */
|
||||
export interface CloudProviderStatus {
|
||||
provider: CloudProviderId
|
||||
/**
|
||||
* False when the deployment has no OAuth credentials for this provider.
|
||||
* The UI renders the row disabled rather than letting the user start a
|
||||
* flow that can only fail.
|
||||
*/
|
||||
configured: boolean
|
||||
connected: boolean
|
||||
/** True when the stored refresh token is dead and the user must reconnect. */
|
||||
needs_reauth: boolean
|
||||
account_email: string | null
|
||||
connected_at: string | null
|
||||
last_sync: CloudLastSync | null
|
||||
schedule: CloudSchedule | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Status returned to the UI. Mirrors the storage shapes above in a
|
||||
* shape safe to expose to the client (no encrypted token).
|
||||
*
|
||||
* The top-level fields describe Google Drive and predate multi-provider
|
||||
* support. They are kept so already-deployed clients (and the dashboard
|
||||
* health banner) keep working; new code reads `providers`.
|
||||
*/
|
||||
export interface CloudBackupStatus {
|
||||
providers: CloudProviderStatus[]
|
||||
connected: boolean
|
||||
needs_reauth: boolean
|
||||
account_email: string | null
|
||||
connected_at: string | null
|
||||
last_sync: CloudLastSync | null
|
||||
schedule: CloudSchedule | null
|
||||
}
|
||||
Reference in New Issue
Block a user