@preventive/triage 1.0.0-alpha.26 → 1.0.0-alpha.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/client/linked-findings.js +1 -1
  3. package/common/bundle-metadata.js +12 -10
  4. package/common/code-language.js +17 -2
  5. package/common/default-scan-models.ts +3 -3
  6. package/common/finding-id.js +1 -1
  7. package/common/managed/report-content.ts +1 -1
  8. package/common/managed/report-filter.ts +1 -1
  9. package/out/client-managed-import.js +24 -24
  10. package/out/client-managed.js +93 -68
  11. package/out/graph.js +11 -11
  12. package/out/index.html +1 -1
  13. package/out/prism.js +2 -2
  14. package/out/stasis.svg +0 -25
  15. package/out/terminal.js +163 -163
  16. package/out/view.css +1 -1
  17. package/out/view.js +223 -190
  18. package/package.json +29 -29
  19. package/server-common/storage-crypto.ts +182 -0
  20. package/server-common/storage-log.ts +5 -1
  21. package/server-common/vercel-blob.ts +6 -3
  22. package/server-e2e/static.ts +3 -4
  23. package/server-managed/avatar-store.ts +1 -40
  24. package/server-managed/blob-store.ts +3 -52
  25. package/server-managed/bundle-advisories.ts +53 -0
  26. package/server-managed/bundle-advisory-inventory.ts +75 -0
  27. package/server-managed/bundle-build-leases.ts +41 -0
  28. package/server-managed/bundle-build-worker.js +44 -0
  29. package/server-managed/bundle-build.ts +141 -0
  30. package/server-managed/bundle-cache.ts +22 -41
  31. package/server-managed/bundle-store.ts +3 -7
  32. package/server-managed/bundle-summary-cache.ts +27 -9
  33. package/server-managed/bundle.ts +66 -1
  34. package/server-managed/cache-storage.ts +4 -25
  35. package/server-managed/cli.js +10 -2
  36. package/server-managed/config.ts +12 -1
  37. package/server-managed/content-access.ts +1 -1
  38. package/server-managed/db-methods.ts +163 -40
  39. package/server-managed/db-neon.ts +124 -30
  40. package/server-managed/db-schema.ts +2 -0
  41. package/server-managed/db.ts +11 -1
  42. package/server-managed/github-app.ts +10 -15
  43. package/server-managed/github-errors.ts +21 -0
  44. package/server-managed/github-issues.ts +1 -1
  45. package/server-managed/github-metadata.ts +34 -1
  46. package/server-managed/github-pulls.ts +142 -30
  47. package/server-managed/http.ts +278 -167
  48. package/server-managed/index.ts +26 -9
  49. package/server-managed/management-catalog.ts +45 -0
  50. package/server-managed/object-storage-disk.ts +144 -0
  51. package/server-managed/object-storage-vercel.ts +60 -0
  52. package/server-managed/object-storage.ts +71 -0
  53. package/server-managed/public-workspace.ts +20 -14
  54. package/server-managed/report-migration.ts +1 -1
  55. package/server-managed/report-sources.ts +14 -4
  56. package/server-managed/repository-browser.ts +8 -1
  57. package/server-managed/repository-discovery.ts +1 -1
  58. package/server-managed/revisions.ts +35 -0
  59. package/server-managed/solidity-entry-points.ts +69 -0
  60. package/server-managed/sql-postgres.ts +1 -0
  61. package/server-managed/sql.ts +14 -8
  62. package/server-managed/storage-command.ts +16 -0
  63. package/server-managed/storage-db.ts +175 -0
  64. package/server-managed/storage-encryption.ts +211 -0
  65. package/server-managed/storage-maintenance.ts +197 -0
  66. package/server-managed/storage-payload.ts +72 -0
  67. package/server-managed/storage-stores.ts +81 -0
  68. package/server-managed/storage.ts +48 -24
  69. package/server-managed/team-feed.ts +50 -5
  70. package/server-managed/team-reports.ts +85 -22
  71. package/server-managed/uploads.ts +2 -2
  72. package/server-managed/workspace-shares.ts +15 -3
  73. package/report/index.js +0 -260
  74. package/report/src/finding-id.js +0 -80
  75. package/report/src/finding.js +0 -314
  76. package/report/src/labels.js +0 -35
  77. package/report/src/md-structure.js +0 -471
  78. package/report/src/md-text.js +0 -167
  79. package/report/src/meta.js +0 -76
  80. package/report/src/parse-codex.js +0 -149
  81. package/report/src/parse-deepsec.js +0 -199
  82. package/report/src/parse-deepview-fields.js +0 -375
  83. package/report/src/parse-deepview-md.js +0 -186
  84. package/report/src/parse-md-id.js +0 -137
  85. package/report/src/parse-md.js +0 -323
  86. package/report/src/parse-piolium-id.js +0 -79
  87. package/report/src/parse-piolium-rows.js +0 -126
  88. package/report/src/parse-piolium-tokens.js +0 -185
  89. package/report/src/parse-piolium.js +0 -399
  90. package/report/src/security.js +0 -63
  91. package/report/src/severity.js +0 -18
  92. package/report/src/utf8.js +0 -21
  93. package/report/src/write-md-finding.js +0 -273
  94. package/report/src/write-md.js +0 -291
  95. package/server-managed/blob-vercel.ts +0 -127
  96. /package/{LICENSE → LICENSE-MIT} +0 -0
@@ -0,0 +1,69 @@
1
+ import { normalizeTeamPath } from './repo-path.ts'
2
+
3
+ const MAX_SUGGESTIONS = 100
4
+ const EXCLUDED_DIRECTORIES = new Set(['test', 'tests', 'script', 'scripts', 'mock', 'mocks', 'node_modules', 'vendor', 'out', 'artifacts', 'cache', 'build', 'dist', 'broadcast'])
5
+
6
+ function sourcePath(value: unknown): value is string {
7
+ if (typeof value !== 'string' || !value.endsWith('.sol') || /\.(?:t|s|test|spec)\.sol$/iu.test(value)) return false
8
+ const normalized = normalizeTeamPath(value)
9
+ const directories = value.split('/').slice(0, -1).map(part => part.toLowerCase())
10
+ const sourceRoot = directories.findIndex(part => part === 'src' || part === 'contracts')
11
+ return normalized.ok && normalized.path === value && !directories.some((part, index) =>
12
+ EXCLUDED_DIRECTORIES.has(part) || (part === 'lib' && (sourceRoot < 0 || index < sourceRoot)))
13
+ }
14
+
15
+ type ListingEntry = { name?: unknown; path?: unknown; type?: unknown; sha?: unknown; submodule_git_url?: unknown }
16
+
17
+ // Maintain the alphabetically first 100 unique candidates even when GitHub's
18
+ // input is unordered. Return whether a unique candidate exceeds the capacity.
19
+ export function addSoliditySuggestion(paths: string[], path: string): boolean {
20
+ let start = 0
21
+ let end = paths.length
22
+ while (start < end) {
23
+ const middle = Math.floor((start + end) / 2)
24
+ if (paths[middle]! < path) start = middle + 1
25
+ else end = middle
26
+ }
27
+ if (paths[start] === path) return false
28
+ const full = paths.length === MAX_SUGGESTIONS
29
+ if (start < MAX_SUGGESTIONS) {
30
+ // Evict before inserting, so retained candidates never exceed the cap.
31
+ if (full) paths.pop()
32
+ paths.splice(start, 0, path)
33
+ }
34
+ return full
35
+ }
36
+
37
+ // Suggestions from filenames, not deployability or import analysis. Read at
38
+ // most two source trees, using SHAs from the authorized pinned directory.
39
+ export async function readSolidityEntryPoints(directory: string, listing: unknown[], read: (suffix: string) => Promise<unknown>) {
40
+ const prefix = directory ? directory + '/' : ''
41
+ const entries = listing.filter((entry): entry is ListingEntry => !!entry && typeof entry === 'object').filter(entry =>
42
+ typeof entry.name === 'string' && !entry.name.includes('/') && entry.path === prefix + entry.name && !entry.submodule_git_url)
43
+ const hasFramework = entries.some(entry => entry.type === 'file' && typeof entry.name === 'string'
44
+ && (entry.name === 'foundry.toml' || /^hardhat\.config\.(?:[cm]?js|ts)$/u.test(entry.name)))
45
+ const roots = entries.filter(entry => entry.type === 'dir' && (entry.name === 'contracts' || (hasFramework && entry.name === 'src'))
46
+ && typeof entry.sha === 'string' && /^[a-f\d]{40}$/iu.test(entry.sha)).slice(0, 2)
47
+ const paths: string[] = []
48
+ let limited = false
49
+ for (const entry of entries) {
50
+ if (entry.type === 'file' && sourcePath(entry.path) && addSoliditySuggestion(paths, entry.path)) limited = true
51
+ }
52
+ for (const root of roots) {
53
+ if (!sourcePath(`${root.path}/Contract.sol`)) continue
54
+ try {
55
+ const data = await read(`/git/trees/${root.sha}?recursive=1`) as { tree?: unknown; truncated?: unknown }
56
+ if (!Array.isArray(data?.tree)) continue
57
+ limited ||= data.truncated === true
58
+ for (const entry of data.tree) {
59
+ if (entry?.type !== 'blob' || !['100644', '100755'].includes(entry.mode) || typeof entry.path !== 'string') continue
60
+ const path = `${root.path}/${entry.path}`
61
+ if (sourcePath(path) && addSoliditySuggestion(paths, path)) limited = true
62
+ }
63
+ } catch {
64
+ // Optional suggestions must not block browsing. The request handler
65
+ // rechecks GitHub access and local path grants after all reads.
66
+ }
67
+ }
68
+ return { paths, limited }
69
+ }
@@ -4,6 +4,7 @@ export function postgresSql(source: string): { sql: string; names: string[] } {
4
4
  const names: string[] = []
5
5
  let position = 0
6
6
  let sql = source.replaceAll('json_each(:contexts)', 'jsonb_array_elements(:contexts::jsonb)')
7
+ .replaceAll("CAST(unixepoch('subsec') * 1000 AS INTEGER)", 'CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)')
7
8
  .replaceAll(/json_extract\((\w+\.value), '\$\.(\w+)'\)/gu, "($1->>'$2')")
8
9
  .replaceAll('json_each(?)', 'jsonb_array_elements_text(?::jsonb)')
9
10
  .replaceAll('INSERT OR IGNORE INTO', 'INSERT INTO')
@@ -1,14 +1,9 @@
1
1
  // Each public store operation owns a transaction. SQLite serializes access to
2
- // its single connection across awaits; Neon binds one connection per operation.
2
+ // its single connection across awaits; Neon can reuse a request-owned connection.
3
3
  import type { DatabaseSync, SQLInputValue } from 'node:sqlite'
4
4
  import type { ManagedDb } from './db-methods.ts'
5
5
 
6
6
  type MaybePromise<T> = T | Promise<T>
7
- // A failed COMMIT acknowledgement (or connection close after COMMIT) does not
8
- // establish rollback. Callers must retain primary bytes until reconciled.
9
- export class ManagedCommitError extends Error {
10
- constructor(cause: unknown) { super('Managed commit outcome is uncertain', { cause }) }
11
- }
12
7
  export interface ManagedSql {
13
8
  prepare(sql: string): {
14
9
  get(...params: unknown[]): MaybePromise<unknown>
@@ -18,14 +13,25 @@ export interface ManagedSql {
18
13
  close(): MaybePromise<void>
19
14
  }
20
15
  export interface ManagedSqlDriver extends ManagedSql {
21
- scope<T>(write: boolean, work: () => Promise<T>): Promise<T>
16
+ scope<T>(write: boolean, work: () => Promise<T>, options?: { lock?: boolean; statement?: boolean }): Promise<T>
22
17
  }
23
18
 
19
+ // These operations execute exactly one SQL statement. Postgres already gives
20
+ // that statement an atomic snapshot; an explicit BEGIN/COMMIT adds only trips.
21
+ // Lease writes coordinate through their conditional UPSERT/UPDATE alone.
22
+ const SINGLE_STATEMENTS = new Set(['getReport', 'getBundle', 'getStorageRow', 'getStorageEncryption',
23
+ 'listReports', 'listBundles', 'listReadableBundleIds', 'listAllRepos', 'listSelectedRepos', 'listRepoScopesForUser', 'listTriage',
24
+ 'getFeedState', 'getWorkspaceShareFeedState', 'claimMaintenanceLease', 'finishMaintenanceLease', 'cacheRepoDefaultBranch', 'releaseBundleBuildLease'])
25
+
24
26
  export function scopeManagedMethods(methods: ManagedDb, driver: ManagedSqlDriver): ManagedDb {
25
27
  const entries = Object.entries(methods).map(([name, method]) => {
26
28
  if (name === 'close') return [name, async () => { await driver.close() }]
27
29
  const write = !/^(?:get|list|userCanRead|reportPermissionsFor)/u.test(name)
28
- return [name, (...args: unknown[]) => driver.scope(write, () => method(...args))]
30
+ return [name, (...args: unknown[]) => driver.scope(write, () => method(...args), {
31
+ // Presence writes only one user's timestamp; they need no application
32
+ // writer lock. Keep the session/user read and timestamp in one transaction.
33
+ lock: write && name !== 'sessionWithUser', statement: SINGLE_STATEMENTS.has(name),
34
+ })]
29
35
  })
30
36
  return Object.fromEntries(entries) as ManagedDb
31
37
  }
@@ -0,0 +1,16 @@
1
+ import { loadManagedConfig } from './config.ts'
2
+ import { openManagedStorageDb } from './storage.ts'
3
+
4
+ // Require the deployment mode: DB_PATH belongs to e2e in combined deployments.
5
+ // Read the database requirement without opening bytes or enabling encryption.
6
+ export async function storageCommand(mode: string | undefined): Promise<void> {
7
+ if (mode !== 'managed' && mode !== 'managed-e2e' && mode !== 'e2e-managed') throw new Error('Storage status requires a deployment mode: --storage-encryption-status managed|managed-e2e|e2e-managed')
8
+ const db = await openManagedStorageDb(loadManagedConfig({ combined: mode !== 'managed' }))
9
+ try {
10
+ const status = await db.getStorageEncryption()
11
+ console.log(JSON.stringify(status ? {
12
+ encryption: 'chacha20-poly1305', complete: status.complete === 1, cleanupComplete: status.cleanupComplete === 1,
13
+ migrated: status.migrated, cursor: status.cursor,
14
+ } : { encryption: 'disabled' }))
15
+ } finally { await db.close() }
16
+ }
@@ -0,0 +1,175 @@
1
+ // Keys belong to the existing upload rows. Only installation state and bounded
2
+ // migration progress need a separate table; payload paths never move.
3
+ import { Buffer } from 'node:buffer'
4
+ import { randomBytes } from 'node:crypto'
5
+ import { type StorageKey, unwrapStorageValue, wrapStorageValue } from '../server-common/storage-crypto.ts'
6
+ import type { ManagedSql } from './sql.ts'
7
+
8
+ export const STORAGE_SCHEMA = `
9
+ CREATE TABLE IF NOT EXISTS managed_storage_encryption (
10
+ id INTEGER PRIMARY KEY CHECK (id = 1), test_value TEXT NOT NULL,
11
+ enabled_at INTEGER NOT NULL, cursor TEXT, complete INTEGER NOT NULL DEFAULT 0,
12
+ migrated INTEGER NOT NULL DEFAULT 0, cleanup_cursor TEXT,
13
+ cleanup_found INTEGER NOT NULL DEFAULT 0, cleanup_complete INTEGER NOT NULL DEFAULT 0
14
+ ) STRICT;
15
+ `
16
+ const SENTINEL = Buffer.from('deepview.storage.required.v1')
17
+ export type StorageRowKind = 'report' | 'bundle'
18
+ export interface StorageEncryptionState {
19
+ enabledAt: number; cursor: string | null; complete: number; migrated: number
20
+ cleanupCursor: string | null; cleanupFound: number; cleanupComplete: number
21
+ }
22
+ export interface StorageRow {
23
+ id: string; dataKey: string | null; encrypted: number; hash: string; kind: string | null
24
+ }
25
+ export interface StorageMigrationRow { position: string; id: string; type: StorageRowKind | 'user' }
26
+ export interface StorageDb {
27
+ enableStorageEncryption(): Promise<StorageEncryptionState>
28
+ getStorageEncryption(): Promise<StorageEncryptionState | null>
29
+ getStorageRow(type: StorageRowKind, id: string): Promise<StorageRow | null>
30
+ ensureStorageDataKey(type: StorageRowKind, id: string): Promise<StorageRow | null>
31
+ markStorageEncrypted(type: StorageRowKind, id: string, dataKey: string): Promise<void>
32
+ listStorageMigrationRows(after: string | null, limit: number): Promise<StorageMigrationRow[]>
33
+ advanceStorageMigration(expected: string | null, next: string | null): Promise<void>
34
+ advanceStorageCleanup(expected: string | null, next: string | null, removed: number): Promise<void>
35
+ migrateStorageUserTokens(id: string): Promise<void>
36
+ }
37
+
38
+ function table(type: StorageRowKind): string {
39
+ if (type !== 'report' && type !== 'bundle') throw new Error('Invalid storage row type')
40
+ return `managed_${type}`
41
+ }
42
+ export const dataKeyIdentity = (type: StorageRowKind, id: string): string => `${table(type)}:${id}`
43
+ export function unwrapDataKey(key: StorageKey, type: StorageRowKind, row: Pick<StorageRow, 'id' | 'dataKey'>): Buffer {
44
+ if (!row.dataKey) throw new Error('Missing storage data key')
45
+ const value = unwrapStorageValue(key, dataKeyIdentity(type, row.id), row.dataKey)
46
+ if (value.length !== 32) { value.fill(0); throw new Error('Invalid storage data key') }
47
+ return value
48
+ }
49
+
50
+ export async function storageState(db: ManagedSql, key: StorageKey | null): Promise<StorageEncryptionState | null> {
51
+ const row = await db.prepare(`SELECT test_value AS testValue, enabled_at AS enabledAt, cursor, complete, migrated,
52
+ cleanup_cursor AS cleanupCursor, cleanup_found AS cleanupFound, cleanup_complete AS cleanupComplete
53
+ FROM managed_storage_encryption WHERE id = 1`).get() as (StorageEncryptionState & { testValue: string }) | undefined
54
+ if (!row) return null
55
+ if (!key) throw new Error('Managed storage requires its configured encryption key')
56
+ const plain = unwrapStorageValue(key, 'managed_storage_encryption:1', row.testValue)
57
+ try { if (!plain.equals(SENTINEL)) throw new Error('Invalid storage encryption test value') }
58
+ finally { plain.fill(0) }
59
+ const { testValue: _testValue, ...state } = row
60
+ return state
61
+ }
62
+
63
+ // Called inside the insert transaction, fencing an old/plain upload that raced
64
+ // activation. The wrapped key never enters public report/bundle DTOs.
65
+ export async function validateStorageUpload(db: ManagedSql, key: StorageKey | null, type: StorageRowKind,
66
+ id: string, dataKey: string | null | undefined): Promise<void> {
67
+ const state = await storageState(db, key)
68
+ if (state) unwrapDataKey(key!, type, { id, dataKey: dataKey ?? null }).fill(0)
69
+ else if (dataKey) throw new Error('Storage encryption is not enabled')
70
+ }
71
+
72
+ export interface StoredTokens { access: string | null; refresh: string | null; exp: number | null; encrypted: number }
73
+ const tokenIdentity = (id: string, field: string) => `managed_user.gh_${field}_token:${id}`
74
+ export function encodeStorageTokens(key: StorageKey, id: string, access: string | null, refresh: string | null) {
75
+ const encode = (field: string, value: string | null) => value === null ? null : wrapStorageValue(key, tokenIdentity(id, field), Buffer.from(value))
76
+ return { access: encode('access', access), refresh: encode('refresh', refresh) }
77
+ }
78
+ export function decodeStorageTokens(key: StorageKey, id: string, row: StoredTokens) {
79
+ const decode = (field: string, value: string | null) => {
80
+ if (value === null) return null
81
+ const plain = unwrapStorageValue(key, tokenIdentity(id, field), value)
82
+ try { return plain.toString('utf8') } finally { plain.fill(0) }
83
+ }
84
+ return { access: decode('access', row.access), refresh: decode('refresh', row.refresh) }
85
+ }
86
+
87
+ // Fixed-width sizes make the saved position sort by type, then numeric byte
88
+ // size, then ID in both SQLite and Postgres. Sixteen digits cover JS safe sizes.
89
+ const PADDED_SIZE = "substr('0000000000000000', 1, 16 - length(CAST(byte_size AS TEXT))) || CAST(byte_size AS TEXT)"
90
+ const PENDING = `SELECT '0:' || ${PADDED_SIZE} || ':' || id AS position, id, 'report' AS type FROM managed_report WHERE storage_encrypted = 0
91
+ UNION ALL SELECT '1:' || ${PADDED_SIZE} || ':' || id AS position, id, 'bundle' AS type FROM managed_bundle WHERE storage_encrypted = 0
92
+ UNION ALL SELECT '2:0000000000000000:' || id AS position, id, 'user' AS type FROM managed_user
93
+ WHERE gh_tokens_encrypted = 0 AND (gh_access_token IS NOT NULL OR gh_refresh_token IS NOT NULL)`
94
+
95
+ // Restart the pending pass for a cursor saved under the previous ID ordering.
96
+ // Completed rows are excluded by PENDING; the original cursor still fences CAS.
97
+ const orderedCursor = (cursor: string | null): string => cursor && /^[012]:[0-9]{16}:/u.test(cursor) ? cursor : ''
98
+
99
+ export function storageMethods(db: ManagedSql, key: StorageKey | null): StorageDb {
100
+ async function requireEnabled() {
101
+ const state = await storageState(db, key)
102
+ if (!state) throw new Error('Storage encryption is not enabled; configure MANAGED_STORAGE_ENCRYPTION_KEY')
103
+ return state
104
+ }
105
+ async function getRow(type: StorageRowKind, id: string): Promise<StorageRow | null> {
106
+ const row = await db.prepare(`SELECT id, data_key AS dataKey, storage_encrypted AS encrypted,
107
+ ${type === 'report' ? 'sha256 AS hash, NULL AS kind' : 'integrity AS hash, kind'} FROM ${table(type)} WHERE id = ?`).get(id) as StorageRow | undefined ?? null
108
+ if (row && row.encrypted !== 0 && row.encrypted !== 1) throw new Error('Invalid storage encryption state')
109
+ if (row?.encrypted && !row.dataKey) throw new Error('Encrypted storage row is missing its data key')
110
+ return row
111
+ }
112
+ return {
113
+ async enableStorageEncryption() {
114
+ if (!key) throw new Error('Set MANAGED_STORAGE_ENCRYPTION_KEY before enabling storage encryption')
115
+ // Called during startup in a writer transaction. Concurrent instances
116
+ // must reuse the marker and validate its key before serving requests.
117
+ const existing = await storageState(db, key)
118
+ if (existing) return existing
119
+ await db.prepare('INSERT INTO managed_storage_encryption (id, test_value, enabled_at) VALUES (1, ?, ?)')
120
+ .run(wrapStorageValue(key, 'managed_storage_encryption:1', SENTINEL), Date.now())
121
+ return (await storageState(db, key))!
122
+ },
123
+ getStorageEncryption: () => storageState(db, key),
124
+ getStorageRow: getRow,
125
+ async ensureStorageDataKey(type, id) {
126
+ await requireEnabled()
127
+ const current = await getRow(type, id)
128
+ if (!current || current.dataKey) return current
129
+ const bytes = randomBytes(32)
130
+ let wrapped: string
131
+ try { wrapped = wrapStorageValue(key!, dataKeyIdentity(type, id), bytes) } finally { bytes.fill(0) }
132
+ await db.prepare(`UPDATE ${table(type)} SET data_key = ? WHERE id = ? AND data_key IS NULL`).run(wrapped, id)
133
+ // Return the persisted winner, never a worker's uncommitted candidate.
134
+ return getRow(type, id)
135
+ },
136
+ async markStorageEncrypted(type, id, wrapped) {
137
+ await requireEnabled()
138
+ const result = await db.prepare(`UPDATE ${table(type)} SET storage_encrypted = 1
139
+ WHERE id = ? AND data_key = ? AND storage_encrypted = 0`).run(id, wrapped)
140
+ if (Number(result.changes)) await db.prepare('UPDATE managed_storage_encryption SET migrated = migrated + 1 WHERE id = 1').run()
141
+ },
142
+ async listStorageMigrationRows(after, limit) {
143
+ await requireEnabled()
144
+ return await db.prepare(`SELECT position, id, type FROM (${PENDING}) AS pending
145
+ WHERE position > ? ORDER BY position LIMIT ?`).all(orderedCursor(after), limit) as StorageMigrationRow[]
146
+ },
147
+ async advanceStorageMigration(expected, next) {
148
+ await requireEnabled()
149
+ if (next !== null && next <= orderedCursor(expected)) return
150
+ // End-of-pass completion checks every pending row, including failed rows
151
+ // before the cursor. A failure cannot be mistaken for a finished pass.
152
+ await db.prepare(`UPDATE managed_storage_encryption SET cursor = ?, complete =
153
+ CASE WHEN ? IS NULL AND NOT EXISTS (SELECT 1 FROM (${PENDING}) AS pending) THEN 1 ELSE 0 END
154
+ WHERE id = 1 AND (cursor = ? OR (cursor IS NULL AND ? IS NULL))`).run(next, next, expected, expected)
155
+ },
156
+ async advanceStorageCleanup(expected, next, removed) {
157
+ const state = await requireEnabled()
158
+ const found = state.cleanupFound + removed
159
+ await db.prepare(`UPDATE managed_storage_encryption SET cleanup_cursor = ?, cleanup_found = ?, cleanup_complete = ?
160
+ WHERE id = 1 AND (cleanup_cursor = ? OR (cleanup_cursor IS NULL AND ? IS NULL))`).run(next, next === null ? 0 : found, next === null && found === 0 ? 1 : 0, expected, expected)
161
+ },
162
+ async migrateStorageUserTokens(id) {
163
+ await requireEnabled()
164
+ const row = await db.prepare(`SELECT gh_access_token AS access, gh_refresh_token AS refresh, gh_token_expires_at AS exp,
165
+ gh_tokens_encrypted AS encrypted FROM managed_user WHERE id = ?`).get(id) as StoredTokens | undefined
166
+ if (!row || row.encrypted || (row.access === null && row.refresh === null)) return
167
+ const value = encodeStorageTokens(key!, id, row.access, row.refresh)
168
+ // This operation holds the writer transaction; token refresh cannot be
169
+ // overwritten by a migration that read an earlier token value.
170
+ await db.prepare('UPDATE managed_user SET gh_access_token = ?, gh_refresh_token = ?, gh_tokens_encrypted = 1 WHERE id = ?')
171
+ .run(value.access, value.refresh, id)
172
+ await db.prepare('UPDATE managed_storage_encryption SET migrated = migrated + 1 WHERE id = 1').run()
173
+ },
174
+ }
175
+ }
@@ -0,0 +1,211 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { Readable } from 'node:stream'
4
+ import { type StorageKey, decryptStorageStream, encryptStorageStream, wrapStorageValue } from '../server-common/storage-crypto.ts'
5
+ import { ENCRYPTED_CACHE_PREFIX, type ObjectStorage, type RawObject, type RawObjectStorage, deleteObjects, objectPath, openObjectVersion } from './object-storage.ts'
6
+ import { type StorageDb, type StorageEncryptionState, type StorageRow, type StorageRowKind, dataKeyIdentity, unwrapDataKey } from './storage-db.ts'
7
+ import { inspectStorageObject, storageOwner, storageRowPath, verifyStoragePayload } from './storage-payload.ts'
8
+
9
+ const STORAGE_WRITE_MS = 180_000
10
+ export const STORAGE_UPLOAD_TTL_MS = 86_400_000
11
+ export const STORAGE_DISABLED_TTL_MS = 5_000
12
+
13
+ async function readBytes(stored: Awaited<ReturnType<ObjectStorage['open']>>): Promise<Buffer | null> {
14
+ if (!stored) return null
15
+ const parts: Buffer[] = []
16
+ try { for await (const part of stored.stream) parts.push(Buffer.from(part)); return Buffer.concat(parts) }
17
+ finally { stored.stream.destroy() }
18
+ }
19
+ function logicalKey(identity: string) {
20
+ objectPath(identity)
21
+ if (identity.startsWith(ENCRYPTED_CACHE_PREFIX)) throw new Error('Encrypted cache paths are internal')
22
+ }
23
+ const encryptedCachePath = (identity: string) => `${ENCRYPTED_CACHE_PREFIX}${identity.slice('cache/'.length)}`
24
+ const deletionPaths = (identity: string) => identity.startsWith('cache/') ? [identity, encryptedCachePath(identity)] : [identity]
25
+
26
+ // A PUT can commit and still throw. Remove only this attempted plaintext,
27
+ // comparing bytes rather than magic: arbitrary uploads can share the header.
28
+ // A concurrent migration's ciphertext must survive this reconciliation.
29
+ async function discardPlaintextWrite(raw: RawObjectStorage, identity: string, bytes: Buffer): Promise<void> {
30
+ // Leave time to report the original failure inside a serverless invocation.
31
+ const signal = AbortSignal.timeout(30_000)
32
+ const current = await raw.open(identity, signal)
33
+ if (!current) return
34
+ try {
35
+ let offset = 0
36
+ for await (const part of current.stream) {
37
+ const chunk = Buffer.from(part)
38
+ if (!chunk.equals(bytes.subarray(offset, offset + chunk.length))) return
39
+ offset += chunk.length
40
+ }
41
+ if (offset === bytes.length) await raw.delete(identity, current.version, signal)
42
+ } finally { current.stream.destroy() }
43
+ }
44
+
45
+ async function putPlaintext(raw: RawObjectStorage, identity: string, bytes: Buffer, mode: () => Promise<StorageEncryptionState | null>): Promise<null> {
46
+ try {
47
+ await raw.put(identity, bytes, AbortSignal.timeout(STORAGE_WRITE_MS))
48
+ if (!await mode()) return null
49
+ throw new Error('Storage encryption was enabled during upload; retry the upload')
50
+ } catch (err) {
51
+ try { await discardPlaintextWrite(raw, identity, bytes) }
52
+ catch (cleanup) { throw new AggregateError([err, cleanup], 'Storage write and plaintext cleanup failed', { cause: cleanup }) }
53
+ throw err
54
+ }
55
+ }
56
+
57
+ async function decryptOwned(stored: RawObject, key: StorageKey, type: StorageRowKind, row: StorageRow, identity: string) {
58
+ let dataKey: Buffer | undefined
59
+ try {
60
+ dataKey = unwrapDataKey(key, type, row)
61
+ return await decryptStorageStream(stored.stream, dataKey, identity)
62
+ } catch (err) { stored.stream.destroy(); throw err }
63
+ finally { dataKey?.fill(0) }
64
+ }
65
+
66
+ async function openEncrypted(raw: RawObjectStorage, db: StorageDb, key: StorageKey, identity: string, state: StorageEncryptionState): ReturnType<ObjectStorage['open']> {
67
+ const owner = storageOwner(identity)
68
+ if (!owner) {
69
+ if (!identity.startsWith('uploads/')) throw new Error('Unknown managed storage owner')
70
+ const stored = await raw.open(identity)
71
+ if (!stored) return null
72
+ const inspected = await inspectStorageObject(stored)
73
+ if (inspected.encrypted) return decryptStorageStream(inspected.stream, key.bytes, identity)
74
+ if (stored.modifiedAt <= state.enabledAt && Date.now() < state.enabledAt + STORAGE_UPLOAD_TTL_MS) return inspected
75
+ inspected.stream.destroy()
76
+ throw new Error('Unexpected plaintext upload part')
77
+ }
78
+ for (let attempt = 0; attempt < 3; attempt++) {
79
+ const row = await db.getStorageRow(owner.type, owner.id)
80
+ if (!row) return null
81
+ if (!owner.cache && storageRowPath(owner.type, row) !== identity) return null
82
+ if (owner.cache && !row.dataKey) return null
83
+ if (!owner.cache && !row.encrypted) state = (await db.getStorageEncryption())!
84
+ const stored = await raw.open(owner.cache ? encryptedCachePath(identity) : identity)
85
+ if (!stored) return null
86
+ // Completed uploads and all new caches are always encrypted. Only legacy
87
+ // pending rows need header inspection and hash-verified plaintext fallback.
88
+ if (row.encrypted || owner.cache || state.complete) {
89
+ return decryptOwned(stored, key, owner.type, row, identity)
90
+ }
91
+ let inspected = await inspectStorageObject(stored)
92
+ if (inspected.encrypted && !row.dataKey && (await db.getStorageRow(owner.type, owner.id))?.dataKey) {
93
+ inspected.stream.destroy(); continue
94
+ }
95
+ if (inspected.encrypted && row.dataKey) {
96
+ try { return await decryptOwned(inspected, key, owner.type, row, identity) }
97
+ catch {
98
+ // An arbitrary legacy upload can begin with our magic bytes. Only
99
+ // its original SQL hash can authorize that plaintext interpretation.
100
+ const legacy = await openObjectVersion(raw, identity, stored.version)
101
+ if (!legacy) continue
102
+ inspected = { ...legacy, encrypted: false }
103
+ }
104
+ }
105
+ // Only a pending row may read plaintext, and only the original upload.
106
+ // Verify first, then reopen that exact version before exposing bytes.
107
+ await verifyStoragePayload(owner.type, row, inspected.stream)
108
+ const current = await openObjectVersion(raw, identity, stored.version)
109
+ if (current) return current
110
+ }
111
+ throw new Error('Storage changed repeatedly during read')
112
+ }
113
+
114
+ // Startup enables encryption before constructing stores; validate the persisted
115
+ // requirement even when this adapter is opened without a key.
116
+ async function storagePolicy(db: StorageDb, key: StorageKey | null) {
117
+ let enabled = await db.getStorageEncryption()
118
+ let checkedAt = Date.now()
119
+ return async (fresh = false) => {
120
+ // Enabled is irreversible. Keyless instances cache "off" briefly, while
121
+ // writes and detected ciphertext always recheck the activation fence.
122
+ if (!enabled && (fresh || key || Date.now() - checkedAt >= STORAGE_DISABLED_TTL_MS)) {
123
+ const state = await db.getStorageEncryption()
124
+ if (state) enabled = state // A delayed disabled read cannot undo "on".
125
+ checkedAt = Date.now()
126
+ }
127
+ if (enabled && !key) throw new Error('Managed storage requires its configured encryption key')
128
+ return enabled
129
+ }
130
+ }
131
+
132
+ export async function createEncryptedObjectStorage(raw: RawObjectStorage, db: StorageDb, key: StorageKey | null): Promise<ObjectStorage> {
133
+ const mode = await storagePolicy(db, key)
134
+ async function open(identity: string): ReturnType<ObjectStorage['open']> {
135
+ logicalKey(identity)
136
+ const state = await mode()
137
+ if (identity.startsWith('avatars/')) return raw.open(identity)
138
+ if (state) return openEncrypted(raw, db, key!, identity, state)
139
+ const stored = await raw.open(identity)
140
+ if (!stored) return null
141
+ const inspected = await inspectStorageObject(stored)
142
+ // Activation/migration can win after the disabled-state read. Never send
143
+ // that ciphertext to a caller expecting the original plaintext bytes.
144
+ if (inspected.encrypted) {
145
+ let current: StorageEncryptionState | null
146
+ try { current = await mode(true) } catch (err) { inspected.stream.destroy(); throw err }
147
+ if (current) { inspected.stream.destroy(); return openEncrypted(raw, db, key!, identity, current) }
148
+ }
149
+ return inspected
150
+ }
151
+ return {
152
+ open,
153
+ get: async identity => readBytes(await open(identity)),
154
+ async exists(identity) {
155
+ logicalKey(identity)
156
+ const owner = storageOwner(identity), state = await mode()
157
+ if (state && owner) {
158
+ const row = await db.getStorageRow(owner.type, owner.id)
159
+ if (!row || (owner.cache ? !row.dataKey : storageRowPath(owner.type, row) !== identity)) return false
160
+ }
161
+ // Existence is metadata only; open() authenticates the actual bytes.
162
+ return await raw.head(state && owner?.cache ? encryptedCachePath(identity) : identity) !== null
163
+ },
164
+ async put(identity, bytes) {
165
+ logicalKey(identity)
166
+ const state = await mode()
167
+ if (identity.startsWith('avatars/')) { await raw.put(identity, bytes); return null }
168
+ if (!state) return putPlaintext(raw, identity, bytes, () => mode(true))
169
+ const owner = storageOwner(identity)
170
+ let dataKey: Buffer, wrapped: string | null = null
171
+ if (owner?.cache) {
172
+ const row = await db.ensureStorageDataKey(owner.type, owner.id)
173
+ if (!row) throw new Error('Cache owner unavailable')
174
+ dataKey = unwrapDataKey(key!, owner.type, row)
175
+ } else if (owner) {
176
+ if (await db.getStorageRow(owner.type, owner.id)) throw new Error('Stored payloads are immutable')
177
+ dataKey = randomBytes(32)
178
+ wrapped = wrapStorageValue(key!, dataKeyIdentity(owner.type, owner.id), dataKey)
179
+ } else {
180
+ if (!identity.startsWith('uploads/')) throw new Error('Unknown managed storage owner')
181
+ dataKey = Buffer.from(key!.bytes)
182
+ }
183
+ const target = owner?.cache ? encryptedCachePath(identity) : identity
184
+ const encrypted = encryptStorageStream(Readable.from([bytes]), dataKey, identity, bytes.length)
185
+ try {
186
+ await raw.put(target, encrypted, AbortSignal.timeout(STORAGE_WRITE_MS), undefined, bytes.length)
187
+ // A late cache builder must not leave a readable cache for a deleted
188
+ // bundle. The missing SQL key also makes failed cleanup unreadable.
189
+ if (owner?.cache && !await db.getStorageRow(owner.type, owner.id)) await raw.delete(target)
190
+ return wrapped
191
+ } finally { encrypted.destroy(); dataKey.fill(0) }
192
+ },
193
+ async delete(identity) {
194
+ logicalKey(identity)
195
+ await mode()
196
+ // Always remove both generations, including caches predating activation
197
+ // when migration is disabled or another instance has just enabled it.
198
+ for (const target of deletionPaths(identity)) await raw.delete(target)
199
+ },
200
+ async deletePrefix(prefix) {
201
+ logicalKey(`${prefix}validate`)
202
+ if (!prefix.endsWith('/')) throw new Error('Invalid storage prefix')
203
+ await mode()
204
+ const signal = AbortSignal.timeout(STORAGE_WRITE_MS)
205
+ for (const target of deletionPaths(prefix)) {
206
+ await deleteObjects(raw, target, signal)
207
+ await raw.prune?.(target, signal)
208
+ }
209
+ },
210
+ }
211
+ }