Files
accounted/extensions/general/cloud-backup/lib/google-drive.ts
T
Mattsson d708a85d4c Feat/cloud backup (#277)
* feat: cloud backup to Google Drive + full-archive all-scope

Adds a cloud-backup extension that uploads a full-company backup ZIP to
the user's own Google Drive via OAuth (drive.file scope only). Refresh
tokens are AES-256-GCM encrypted before being stored in extension_data.

The full-archive export gains a scope=all mode for whole-company
backups (per-period SIE under sie/, per-period rapporter/ subfolders,
flat dokument/ manifest tagged with fiscal_period_id). An 80 MB size
guard short-circuits generation before the platform response limit.

Also fixes a latent bug in lib/core/audit/audit-service.ts where the
parameter was named userId while the query filtered by company_id; the
audit-trail API route was passing user.id so audit queries returned
empty unless user and company shared a UUID.

Drive-by: scope the dashboard "fresh start" localStorage key per
companyId so dismissing the setup checklist in one company no longer
carries over to others.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: address review comments on cloud backup + archive export

- Extend audit trail to_date to end-of-day so last-day entries aren't
  silently excluded from period-scoped archives.
- Apply 413 size-limit guard regardless of include_documents, using the
  overhead-only figure when documents are excluded.
- Use crypto.randomUUID() for Drive multipart boundary to eliminate any
  collision risk with ZIP payload bytes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: migrate legacy setup-gate localStorage keys on dashboard

Users who previously dismissed the setup checklist via the old global
erp_setup_fresh_start or erp_checklist_dismissed keys were re-gated after
the switch to a company-scoped key. Fall back to the legacy keys on read
and migrate them to the scoped key on first hit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: update customer email handling and anonymization rules in supportmail-to-ticket skill

* test: update audit trail to_date expectation for end-of-day timestamp

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 10:49:59 +02:00

163 lines
4.2 KiB
TypeScript

/**
* Minimal Google Drive v3 client — just enough to:
* - find or create a named folder,
* - upload a file via multipart.
*
* 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.
*/
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'
interface DriveFile {
id: string
name: string
}
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 UploadResult {
id: string
name: string
size_bytes: number
web_view_link: string
}
/**
* Multipart upload: metadata + bytes in one request. Suitable for files
* up to ~100 MB; beyond that Drive recommends resumable uploads.
*/
export async function uploadFile(
accessToken: string,
folderId: string,
fileName: string,
data: ArrayBuffer,
contentType = 'application/zip'
): Promise<UploadResult> {
const boundary = `gnubok-${crypto.randomUUID().replace(/-/g, '')}`
const metadata = JSON.stringify({
name: fileName,
parents: [folderId],
})
const head =
`--${boundary}\r\n` +
`Content-Type: application/json; charset=UTF-8\r\n\r\n` +
`${metadata}\r\n` +
`--${boundary}\r\n` +
`Content-Type: ${contentType}\r\n\r\n`
const tail = `\r\n--${boundary}--`
const body = Buffer.concat([
Buffer.from(head, 'utf8'),
Buffer.from(data),
Buffer.from(tail, 'utf8'),
])
const res = await fetch(
`${DRIVE_UPLOAD_API}?uploadType=multipart&fields=id,name,size,webViewLink`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': `multipart/related; boundary=${boundary}`,
'Content-Length': String(body.length),
},
body,
}
)
if (!res.ok) {
const errText = await res.text()
throw new Error(`Drive upload failed: ${res.status} ${errText.slice(0, 200)}`)
}
const json = (await res.json()) as {
id: string
name: string
size?: string
webViewLink?: string
}
return {
id: json.id,
name: json.name,
size_bytes: json.size ? Number(json.size) : data.byteLength,
web_view_link: json.webViewLink || `https://drive.google.com/file/d/${json.id}/view`,
}
}
function escapeName(name: string): string {
// Drive query string: escape single quotes and backslashes.
return name.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
}