@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
package/README.md CHANGED
@@ -40,7 +40,7 @@ All-in-one workspace for AI coding agents — Claude Code, OpenCode, Codex, Copi
40
40
 
41
41
  ![Browser preview panel](https://clopen.myrialabs.dev/images/preview-panel.webp)
42
42
 
43
- ![Connectors settings](https://clopen.myrialabs.dev/images/connectors-setting.webp)
43
+ ![Integrations settings](https://clopen.myrialabs.dev/images/connectors-setting.webp)
44
44
 
45
45
  ![Public tunnel](https://clopen.myrialabs.dev/images/public-tunnel.webp)
46
46
 
@@ -67,7 +67,7 @@ A complete development environment designed around AI-assisted workflows, built
67
67
  - **Real-Time Collaboration** — See who's working on which project, and collaborate live in the same codebase
68
68
  - **Monaco File Editor** — VS Code's editor right in the browser. Full syntax highlighting, autocomplete, and live file watching, beside your AI chat
69
69
  - **Cloudflare Tunnel** — One-click public HTTPS URL for your local dev server. Built-in QR code for instant mobile access. Share your work without deploying
70
- - **Connectors (MCP)** — Browse a searchable catalog of Model Context Protocol servers, connect with OAuth or custom env/headers, and sync every connector across all your AI engines
70
+ - **Integrations** — Connect a third-party account once and every engine and project can use it. Credentials are sealed at rest with AES-256-GCM. Includes the full MCP surface: browse the official Model Context Protocol registry, connect with OAuth or custom env/headers, control tool exposure per engine, and sync every connector across all your AI engines
71
71
  - **Skills, Commands & Subagents** — Build reusable Skills, slash Commands, delegated Subagents, shared Instructions, and tool Permissions or Profiles once, synced automatically across every engine
72
72
  - **Flexible Authentication** — No Login or With Login mode with admin/member roles, invite links, rate-limited login, and CLI token recovery
73
73
  - **Stack** — Install AI engines, Git, Chrome, and Cloudflared (for Public Tunnel) from a one-click admin panel. Engines install on demand into a clopen-managed directory (`~/.clopen/stack/engines`) — isolated from your global setup, no PATH pollution
@@ -143,6 +143,20 @@ export const ADMIN_ONLY_ROUTES = new Set([
143
143
  'mcp:tools',
144
144
  'mcp:set-tool-overrides',
145
145
  'mcp:call-tool',
146
+ 'mcp:engine-config',
147
+ // Third-party integrations. A connected account holds a credential and
148
+ // projects rows onto surfaces every engine and every project can reach, so
149
+ // the whole surface is admin-only for the same reason MCP is. The read
150
+ // events are gated too: `integrations:list` names which services this
151
+ // install is connected to, and `integrations:secrets-health` describes the
152
+ // state of the key that protects them.
153
+ 'integrations:providers',
154
+ 'integrations:list',
155
+ 'integrations:connect',
156
+ 'integrations:update',
157
+ 'integrations:disconnect',
158
+ 'integrations:health',
159
+ 'integrations:secrets-health',
146
160
  // Memory Graph — the graph is instance-global and is injected into every
147
161
  // future turn on every engine, so editing it changes what every agent is told.
148
162
  // Mutations only: the read surface (memory:graph / :node / :search / :stats /
@@ -15,6 +15,9 @@
15
15
  */
16
16
 
17
17
  import { syncInternalServers } from './mcp';
18
+ import { getDatabase } from './database';
19
+ import { logSecretColumnAudit } from './database/crypto';
20
+ import { SERVER_ENV } from './utils/env';
18
21
  import { ensureDefaultEngineInstalled } from './engine/bootstrap-default-engine';
19
22
  import { bootstrapMemoryGraph } from './memory/bootstrap';
20
23
  import { ensureMemoryModel } from './memory/model';
@@ -47,6 +50,19 @@ export function bootstrapAfterDbInit(): void {
47
50
  .then(() => ensureMemoryModel())
48
51
  .catch(error => debug.warn('server', 'Default engine / memory model bootstrap failed', error));
49
52
 
53
+ // Outside production, report any declared secret column still holding
54
+ // plaintext. This is the safety net for sealing in the query modules rather
55
+ // than in a wrapper: a new write path that forgets `sealFor()` shows up here
56
+ // instead of leaking quietly. Left off in production — it reads every secret
57
+ // column on every start, and there it is a cost without a reader.
58
+ if (SERVER_ENV.isDevelopment) {
59
+ try {
60
+ logSecretColumnAudit(getDatabase());
61
+ } catch (error) {
62
+ debug.warn('server', 'Secret-column audit failed', error);
63
+ }
64
+ }
65
+
50
66
  // Fetch the embedding artifact and backfill memory vectors in the background.
51
67
  // Recall is gated on the artifact, but recording is not, so nothing here
52
68
  // blocks startup.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Tests for the secrets-at-rest envelope.
3
+ *
4
+ * The cases that matter are the ones the rollout depends on rather than the
5
+ * happy path: plaintext must survive a read untouched (a half-migrated table),
6
+ * sealing twice must not double-encrypt (a re-run migration, or a
7
+ * read-modify-write that hands a sealed value straight back), and a value the
8
+ * active key cannot open must degrade to null instead of throwing — because a
9
+ * throw here would take down every read path that touches a stored credential.
10
+ */
11
+
12
+ import { describe, it, expect, afterEach } from 'bun:test';
13
+
14
+ import { isSealed, open, seal, getDecryptFailures, resetDecryptFailures } from './envelope';
15
+ import { getMasterKey, resetMasterKeyCache } from './master-key';
16
+
17
+ afterEach(() => {
18
+ resetDecryptFailures();
19
+ delete process.env.CLOPEN_MASTER_KEY;
20
+ resetMasterKeyCache();
21
+ });
22
+
23
+ describe('envelope', () => {
24
+ it('round-trips a value', () => {
25
+ const sealed = seal('ghp_super_secret');
26
+ expect(sealed).not.toBe('ghp_super_secret');
27
+ expect(isSealed(sealed!)).toBe(true);
28
+ expect(open(sealed)).toBe('ghp_super_secret');
29
+ });
30
+
31
+ it('produces a different ciphertext each time (random IV)', () => {
32
+ expect(seal('same')).not.toBe(seal('same'));
33
+ });
34
+
35
+ it('returns unsealed input untouched — pre-migration plaintext still reads', () => {
36
+ expect(open('plain-token')).toBe('plain-token');
37
+ expect(open('{"API_KEY":"abc"}')).toBe('{"API_KEY":"abc"}');
38
+ });
39
+
40
+ it('is a no-op when sealing an already-sealed value', () => {
41
+ const once = seal('token');
42
+ expect(seal(once)).toBe(once);
43
+ expect(open(seal(seal(once)))).toBe('token');
44
+ });
45
+
46
+ it('passes null and empty string through — an empty secret stays falsy', () => {
47
+ expect(seal(null)).toBe(null);
48
+ expect(seal('')).toBe('');
49
+ expect(open(null)).toBe(null);
50
+ expect(open('')).toBe('');
51
+ });
52
+
53
+ it('stamps the active key fingerprint into the envelope', () => {
54
+ const { fingerprint } = getMasterKey();
55
+ expect(seal('x')!.startsWith(`clpsec:v1:${fingerprint}:`)).toBe(true);
56
+ });
57
+
58
+ it('returns null and counts a failure when the key cannot open the value', () => {
59
+ const sealed = seal('token')!;
60
+
61
+ // Swap in a different key without restarting — the same situation as a
62
+ // restored backup landing next to the wrong secret.key.
63
+ process.env.CLOPEN_MASTER_KEY = Buffer.alloc(32, 7).toString('base64');
64
+ resetMasterKeyCache();
65
+
66
+ expect(open(sealed)).toBe(null);
67
+
68
+ const failures = getDecryptFailures();
69
+ expect(failures.count).toBe(1);
70
+ expect(failures.lastAt).not.toBe(null);
71
+ expect(failures.fingerprints.length).toBe(1);
72
+ });
73
+
74
+ it('returns null rather than throwing on a tampered payload', () => {
75
+ const sealed = seal('token')!;
76
+ const tampered = `${sealed.slice(0, -4)}AAAA`;
77
+ expect(open(tampered)).toBe(null);
78
+ expect(getDecryptFailures().count).toBe(1);
79
+ });
80
+
81
+ it('rejects an override that is not 32 bytes instead of falling back', () => {
82
+ process.env.CLOPEN_MASTER_KEY = 'too-short';
83
+ resetMasterKeyCache();
84
+ expect(() => getMasterKey()).toThrow();
85
+ });
86
+
87
+ it('accepts a hex override as well as base64', () => {
88
+ process.env.CLOPEN_MASTER_KEY = Buffer.alloc(32, 3).toString('hex');
89
+ resetMasterKeyCache();
90
+ expect(getMasterKey().key.length).toBe(32);
91
+ expect(getMasterKey().source).toBe('env');
92
+ });
93
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * AES-256-GCM envelope for secrets at rest.
3
+ *
4
+ * Format: `clpsec:v1:<fingerprint>:<base64(iv ‖ tag ‖ ciphertext)>`
5
+ *
6
+ * The PREFIX is what makes the rollout safe, and it carries three properties
7
+ * the migration and every query module depend on:
8
+ *
9
+ * 1. A value WITHOUT the prefix is pre-migration plaintext and is returned
10
+ * untouched. A half-migrated table therefore reads correctly.
11
+ * 2. Sealing a value that already carries the prefix is a NO-OP, so a re-run
12
+ * migration cannot double-encrypt, and a read-modify-write path that hands
13
+ * a still-sealed value back to `seal()` stays correct.
14
+ * 3. The fingerprint identifies WHICH key sealed the value, so a value the
15
+ * active key cannot open is recognisable as a key mismatch rather than
16
+ * corruption.
17
+ *
18
+ * `open()` NEVER throws. Throwing here would take down every read path that
19
+ * touches a stored connection the moment a key went missing — the Settings
20
+ * page, the MCP config builder, the db-client list. An unopenable value returns
21
+ * null and increments a counter the Integrations hub surfaces as a banner.
22
+ */
23
+
24
+ import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
25
+ import { getMasterKey } from './master-key';
26
+ import { debug } from '$shared/utils/logger';
27
+
28
+ const PREFIX = 'clpsec';
29
+ const VERSION = 'v1';
30
+ const IV_BYTES = 12;
31
+ const TAG_BYTES = 16;
32
+
33
+ /** `clpsec:v1:<8 hex>:<base64>` */
34
+ const SEALED_PATTERN = /^clpsec:v1:[0-9a-f]{8}:[A-Za-z0-9+/=]+$/;
35
+
36
+ export interface DecryptFailureState {
37
+ /** Number of values the active key could not open since process start. */
38
+ count: number;
39
+ /** ISO timestamp of the most recent failure, or null. */
40
+ lastAt: string | null;
41
+ /** Key fingerprints seen on values we could not open — helps identify the missing key. */
42
+ fingerprints: string[];
43
+ }
44
+
45
+ const failures = {
46
+ count: 0,
47
+ lastAt: null as string | null,
48
+ fingerprints: new Set<string>()
49
+ };
50
+
51
+ /** True when the value already carries a sealed envelope. */
52
+ export function isSealed(value: string): boolean {
53
+ return SEALED_PATTERN.test(value);
54
+ }
55
+
56
+ /**
57
+ * Seal a value. `null`, `undefined` and the empty string pass through unchanged
58
+ * — an empty secret is "not set", and sealing it would turn a falsy check into
59
+ * a truthy one everywhere downstream.
60
+ */
61
+ export function seal(value: string | null | undefined): string | null {
62
+ if (value === null || value === undefined || value === '') {
63
+ return value === undefined ? null : value;
64
+ }
65
+ if (isSealed(value)) return value;
66
+
67
+ const { key, fingerprint } = getMasterKey();
68
+ const iv = randomBytes(IV_BYTES);
69
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
70
+ const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
71
+ const payload = Buffer.concat([iv, cipher.getAuthTag(), ciphertext]);
72
+
73
+ return `${PREFIX}:${VERSION}:${fingerprint}:${payload.toString('base64')}`;
74
+ }
75
+
76
+ /**
77
+ * Open a sealed value.
78
+ *
79
+ * Returns the input unchanged when it is not sealed (pre-migration plaintext),
80
+ * and `null` when it is sealed but cannot be opened. Never throws.
81
+ */
82
+ export function open(value: string | null | undefined): string | null {
83
+ if (value === null || value === undefined || value === '') {
84
+ return value === undefined ? null : value;
85
+ }
86
+ if (!isSealed(value)) return value;
87
+
88
+ const [, , fingerprint, encoded] = value.split(':');
89
+
90
+ try {
91
+ const { key, fingerprint: activeFingerprint } = getMasterKey();
92
+ if (fingerprint !== activeFingerprint) {
93
+ throw new Error(`sealed with key ${fingerprint}, active key is ${activeFingerprint}`);
94
+ }
95
+
96
+ const payload = Buffer.from(encoded!, 'base64');
97
+ const iv = payload.subarray(0, IV_BYTES);
98
+ const tag = payload.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
99
+ const ciphertext = payload.subarray(IV_BYTES + TAG_BYTES);
100
+
101
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
102
+ decipher.setAuthTag(tag);
103
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
104
+ } catch (error) {
105
+ failures.count += 1;
106
+ failures.lastAt = new Date().toISOString();
107
+ if (fingerprint) failures.fingerprints.add(fingerprint);
108
+ debug.error('database', '🔒 Could not open a sealed value:', error);
109
+ return null;
110
+ }
111
+ }
112
+
113
+ /** Snapshot of decryption failures — the hub renders this as a banner. */
114
+ export function getDecryptFailures(): DecryptFailureState {
115
+ return {
116
+ count: failures.count,
117
+ lastAt: failures.lastAt,
118
+ fingerprints: [...failures.fingerprints]
119
+ };
120
+ }
121
+
122
+ /** Clear the failure counter. Tests, and the hub's "dismiss" action. */
123
+ export function resetDecryptFailures(): void {
124
+ failures.count = 0;
125
+ failures.lastAt = null;
126
+ failures.fingerprints.clear();
127
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Secrets at rest.
3
+ *
4
+ * `envelope.ts` — AES-256-GCM seal/open, prefixed and fingerprinted.
5
+ * `master-key.ts` — where the key comes from, and the threat model.
6
+ * `secret-columns.ts` — which columns are secret, plus the plaintext audit.
7
+ */
8
+
9
+ export { isSealed, seal, open, getDecryptFailures, resetDecryptFailures } from './envelope';
10
+ export type { DecryptFailureState } from './envelope';
11
+ export { getMasterKey, resetMasterKeyCache } from './master-key';
12
+ export type { MasterKey } from './master-key';
13
+ export {
14
+ SECRET_COLUMNS,
15
+ secretColumnsOf,
16
+ openRow,
17
+ openRows,
18
+ sealFor,
19
+ auditSecretColumns,
20
+ logSecretColumnAudit
21
+ } from './secret-columns';
22
+ export type { SecretColumnAudit } from './secret-columns';
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Master key resolution for secrets at rest.
3
+ *
4
+ * THREAT MODEL — read this before changing anything here.
5
+ *
6
+ * This protects a DATABASE FILE THAT LEAVES THE MACHINE: a backup, an rsync, a
7
+ * volume snapshot, a stolen `app.db`. It does NOT protect against an attacker
8
+ * who already has read access to the data directory, because the default key
9
+ * lives inside that same directory. A self-hoster who wants protection beyond
10
+ * "the db file leaked" must set `CLOPEN_MASTER_KEY` and keep it out of the data
11
+ * directory. Say this plainly wherever it surfaces in the UI — claiming more
12
+ * than this is worse than claiming nothing.
13
+ *
14
+ * The key is deliberately NOT derived from a machine id. Binding it to hardware
15
+ * would make a restored backup undecryptable on a new host, and self-hosters
16
+ * migrate hosts. A key that cannot survive a restore is a key that eats data.
17
+ */
18
+
19
+ import { createHash, randomBytes } from 'crypto';
20
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
21
+ import { dirname, join } from 'path';
22
+ import { getClopenDir } from '$backend/utils/paths';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ /** File name of the generated key inside the data directory. */
26
+ const KEY_FILE_NAME = 'secret.key';
27
+
28
+ /** Raw key length for AES-256. */
29
+ const KEY_BYTES = 32;
30
+
31
+ export interface MasterKey {
32
+ /** The 32-byte key material. */
33
+ key: Buffer;
34
+ /** Short, non-secret identifier stamped into every envelope. */
35
+ fingerprint: string;
36
+ /** Where the key came from — surfaced in the hub so the source is never a mystery. */
37
+ source: 'env' | 'file';
38
+ }
39
+
40
+ let cached: MasterKey | null = null;
41
+
42
+ /**
43
+ * A fingerprint is a truncated hash of the key, never the key itself. It exists
44
+ * so a value sealed with a key we no longer hold can be RECOGNISED as such
45
+ * rather than being mistaken for corruption.
46
+ */
47
+ function fingerprintOf(key: Buffer): string {
48
+ return createHash('sha256').update(key).digest('hex').slice(0, 8);
49
+ }
50
+
51
+ /**
52
+ * Accept the env override in base64 or hex, whichever the operator pasted.
53
+ * Anything that does not decode to exactly 32 bytes is rejected loudly at
54
+ * startup rather than silently falling back to the file — a typo in the
55
+ * override must not quietly change which key seals new rows.
56
+ */
57
+ function parseEnvKey(raw: string): Buffer {
58
+ const trimmed = raw.trim();
59
+
60
+ if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
61
+ return Buffer.from(trimmed, 'hex');
62
+ }
63
+
64
+ const decoded = Buffer.from(trimmed, 'base64');
65
+ if (decoded.length === KEY_BYTES) return decoded;
66
+
67
+ throw new Error(
68
+ `CLOPEN_MASTER_KEY must be ${KEY_BYTES} bytes encoded as base64 or hex ` +
69
+ `(got ${decoded.length} bytes after decoding)`
70
+ );
71
+ }
72
+
73
+ function keyFilePath(): string {
74
+ return join(getClopenDir(), KEY_FILE_NAME);
75
+ }
76
+
77
+ /**
78
+ * Read the generated key file, creating it on first run.
79
+ *
80
+ * The write is 0600 where the platform honours it. Windows ignores the mode,
81
+ * which is one more reason the module never claims to defend against a local
82
+ * attacker.
83
+ */
84
+ function loadOrCreateKeyFile(): Buffer {
85
+ const path = keyFilePath();
86
+
87
+ try {
88
+ const contents = readFileSync(path, 'utf8').trim();
89
+ const key = Buffer.from(contents, 'base64');
90
+ if (key.length === KEY_BYTES) return key;
91
+ // A key file of the wrong length is corrupt, not empty. Refuse rather
92
+ // than regenerate: regenerating would strand every sealed row.
93
+ throw new Error(`key file at ${path} is ${key.length} bytes, expected ${KEY_BYTES}`);
94
+ } catch (error) {
95
+ const code = (error as NodeJS.ErrnoException)?.code;
96
+ if (code !== 'ENOENT') throw error;
97
+ }
98
+
99
+ const key = randomBytes(KEY_BYTES);
100
+ mkdirSync(dirname(path), { recursive: true });
101
+ writeFileSync(path, key.toString('base64'), { encoding: 'utf8', mode: 0o600 });
102
+ try {
103
+ chmodSync(path, 0o600);
104
+ } catch {
105
+ // Best effort — Windows has no equivalent and failing here would block startup.
106
+ }
107
+ debug.log('database', `🔑 Generated secrets master key at ${path}`);
108
+ return key;
109
+ }
110
+
111
+ /** Resolve the active master key, generating one on first run. Cached per process. */
112
+ export function getMasterKey(): MasterKey {
113
+ if (cached) return cached;
114
+
115
+ const override = process.env.CLOPEN_MASTER_KEY;
116
+ const key = override ? parseEnvKey(override) : loadOrCreateKeyFile();
117
+
118
+ cached = {
119
+ key,
120
+ fingerprint: fingerprintOf(key),
121
+ source: override ? 'env' : 'file'
122
+ };
123
+ return cached;
124
+ }
125
+
126
+ /** Drop the cached key. Tests only — a running server must not swap keys mid-flight. */
127
+ export function resetMasterKeyCache(): void {
128
+ cached = null;
129
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The single declaration of which columns hold secrets.
3
+ *
4
+ * Sealing happens in the QUERY MODULES (`backend/database/queries/`) rather than
5
+ * inside a wrapper around the connection. That choice is deliberate: an
6
+ * automatic wrapper would have to parse SQL to map `?` placeholders onto
7
+ * columns, and a mis-parse fails silently in the worst possible direction —
8
+ * storing plaintext while reporting success. Every statement touching these
9
+ * columns already lives in a query module, so there is nothing for the parse to
10
+ * buy.
11
+ *
12
+ * What the wrapper WOULD have given us for free is a safety net, so this module
13
+ * provides it explicitly: `auditSecretColumns()` reads every declared column and
14
+ * reports any value sitting there unsealed. It runs at startup outside
15
+ * production and is what catches a future query module that forgets to seal.
16
+ */
17
+
18
+ import type { DatabaseConnection } from '$shared/types/database/connection';
19
+ import { isSealed, open, seal } from './envelope';
20
+ import { debug } from '$shared/utils/logger';
21
+
22
+ /** Every table that stores a secret, and which of its columns do. */
23
+ export const SECRET_COLUMNS: Record<string, readonly string[]> = {
24
+ // JSON blobs: the whole column is sealed, not individual keys inside it.
25
+ // Engines read these through `resolveServerRow()`, which is unchanged.
26
+ mcp_servers: ['env', 'headers', 'oauth'],
27
+ db_client_connections: ['password', 'ssh_password', 'ssh_private_key', 'ssh_passphrase'],
28
+ ssh_connections: ['password', 'private_key', 'passphrase'],
29
+ engine_accounts: ['credential'],
30
+ integration_accounts: ['credentials']
31
+ } as const;
32
+
33
+ /** Column names of one table, or an empty list when the table holds no secrets. */
34
+ export function secretColumnsOf(table: string): readonly string[] {
35
+ return SECRET_COLUMNS[table] ?? [];
36
+ }
37
+
38
+ /**
39
+ * Open every declared secret column on a row read straight out of SQLite.
40
+ *
41
+ * Mutates a shallow copy, so the caller's row object is untouched. A column the
42
+ * active key cannot open becomes `null` — the caller then behaves exactly as it
43
+ * would for a credential that was never set, which is the only safe degradation.
44
+ */
45
+ export function openRow<T extends object>(table: string, row: T): T {
46
+ const columns = secretColumnsOf(table);
47
+ if (columns.length === 0) return row;
48
+
49
+ // Rows are declared as interfaces without an index signature, so the write
50
+ // goes through a widened alias rather than `keyof T` — the column names come
51
+ // from the registry, not from the type.
52
+ const out = { ...row } as Record<string, unknown>;
53
+ for (const column of columns) {
54
+ const value = out[column];
55
+ if (typeof value === 'string') {
56
+ out[column] = open(value);
57
+ }
58
+ }
59
+ return out as T;
60
+ }
61
+
62
+ /** `openRow` over a result set. */
63
+ export function openRows<T extends object>(table: string, rows: T[]): T[] {
64
+ const columns = secretColumnsOf(table);
65
+ if (columns.length === 0) return rows;
66
+ return rows.map((row) => openRow(table, row));
67
+ }
68
+
69
+ /**
70
+ * Seal one value for a declared column.
71
+ *
72
+ * Named rather than positional because the write paths in the query modules
73
+ * build their parameter lists by hand — `sealFor('ssh_connections', 'password',
74
+ * value)` at the call site reads as what it is, and a column that is not
75
+ * declared secret throws instead of silently passing plaintext through.
76
+ */
77
+ export function sealFor(table: string, column: string, value: string | null | undefined): string | null {
78
+ if (!secretColumnsOf(table).includes(column)) {
79
+ throw new Error(`${table}.${column} is not declared in SECRET_COLUMNS`);
80
+ }
81
+ return seal(value);
82
+ }
83
+
84
+ export interface SecretColumnAudit {
85
+ table: string;
86
+ column: string;
87
+ /** Rows holding a non-empty value that is NOT sealed. */
88
+ unsealed: number;
89
+ /** Rows holding a sealed value. */
90
+ sealed: number;
91
+ }
92
+
93
+ /**
94
+ * Report any declared secret column still holding plaintext.
95
+ *
96
+ * A non-zero `unsealed` count after migration 072 means one of two things: a
97
+ * write path that skips `sealFor`, or a table written before the migration ran.
98
+ * Both are worth knowing about, and neither is visible any other way.
99
+ */
100
+ export function auditSecretColumns(db: DatabaseConnection): SecretColumnAudit[] {
101
+ const existing = new Set(
102
+ (db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`).all() as { name: string }[])
103
+ .map((r) => r.name)
104
+ );
105
+
106
+ const results: SecretColumnAudit[] = [];
107
+
108
+ for (const [table, columns] of Object.entries(SECRET_COLUMNS)) {
109
+ if (!existing.has(table)) continue;
110
+
111
+ for (const column of columns) {
112
+ try {
113
+ const rows = db.prepare(
114
+ `SELECT ${column} AS value FROM ${table} WHERE ${column} IS NOT NULL AND ${column} != ''`
115
+ ).all() as { value: unknown }[];
116
+
117
+ let unsealed = 0;
118
+ let sealed = 0;
119
+ for (const { value } of rows) {
120
+ if (typeof value !== 'string') continue;
121
+ if (isSealed(value)) sealed += 1;
122
+ else unsealed += 1;
123
+ }
124
+ results.push({ table, column, unsealed, sealed });
125
+ } catch (error) {
126
+ // A declared column the schema does not have yet (a migration is
127
+ // mid-flight, or the declaration ran ahead of the table). Not fatal.
128
+ debug.warn('database', `Secret-column audit skipped ${table}.${column}:`, error);
129
+ }
130
+ }
131
+ }
132
+
133
+ return results;
134
+ }
135
+
136
+ /** Log the audit when anything is still plaintext. Called at startup outside production. */
137
+ export function logSecretColumnAudit(db: DatabaseConnection): void {
138
+ const leaks = auditSecretColumns(db).filter((entry) => entry.unsealed > 0);
139
+ if (leaks.length === 0) return;
140
+
141
+ for (const leak of leaks) {
142
+ debug.warn(
143
+ 'database',
144
+ `🔓 ${leak.table}.${leak.column} holds ${leak.unsealed} unsealed value(s) — a write path is missing sealFor()`
145
+ );
146
+ }
147
+ }
@@ -0,0 +1,90 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create note collections, notes and note images';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating notes tables...');
8
+
9
+ // Scope lives here and only here. A note inherits who may read it from its
10
+ // collection, so there is no second copy of the scope that could disagree
11
+ // with this one — and no note that is reachable through two different
12
+ // permission rules.
13
+ db.exec(`
14
+ CREATE TABLE IF NOT EXISTS note_collections (
15
+ id TEXT PRIMARY KEY,
16
+ name TEXT NOT NULL,
17
+ scope TEXT NOT NULL CHECK (scope IN ('project', 'global')),
18
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
19
+ created_by TEXT,
20
+ created_at TEXT NOT NULL,
21
+ updated_at TEXT NOT NULL,
22
+ CHECK (
23
+ (scope = 'project' AND project_id IS NOT NULL) OR
24
+ (scope = 'global' AND project_id IS NULL)
25
+ )
26
+ )
27
+ `);
28
+
29
+ db.exec(`
30
+ CREATE INDEX IF NOT EXISTS idx_note_collections_project ON note_collections(project_id)
31
+ `);
32
+
33
+ db.exec(`
34
+ CREATE INDEX IF NOT EXISTS idx_note_collections_scope ON note_collections(scope)
35
+ `);
36
+
37
+ db.exec(`
38
+ CREATE TABLE IF NOT EXISTS notes (
39
+ id TEXT PRIMARY KEY,
40
+ collection_id TEXT NOT NULL REFERENCES note_collections(id) ON DELETE CASCADE,
41
+ title TEXT,
42
+ content TEXT NOT NULL DEFAULT '',
43
+ created_by TEXT,
44
+ created_at TEXT NOT NULL,
45
+ updated_at TEXT NOT NULL
46
+ )
47
+ `);
48
+
49
+ db.exec(`
50
+ CREATE INDEX IF NOT EXISTS idx_notes_collection ON notes(collection_id)
51
+ `);
52
+
53
+ db.exec(`
54
+ CREATE INDEX IF NOT EXISTS idx_notes_updated ON notes(updated_at DESC)
55
+ `);
56
+
57
+ // `storage_path` is relative to the data dir with forward slashes
58
+ // (`notes/<collectionId>/<noteId>/<uuid>-<name>`), never absolute — see
59
+ // `backend/notes/storage.ts` for why.
60
+ db.exec(`
61
+ CREATE TABLE IF NOT EXISTS note_images (
62
+ id TEXT PRIMARY KEY,
63
+ note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
64
+ file_name TEXT NOT NULL,
65
+ mime_type TEXT NOT NULL,
66
+ size INTEGER NOT NULL,
67
+ storage_path TEXT NOT NULL,
68
+ created_at TEXT NOT NULL
69
+ )
70
+ `);
71
+
72
+ db.exec(`
73
+ CREATE INDEX IF NOT EXISTS idx_note_images_note ON note_images(note_id)
74
+ `);
75
+
76
+ debug.log('migration', 'Notes tables created');
77
+ };
78
+
79
+ export const down = (db: DatabaseConnection): void => {
80
+ debug.log('migration', 'Dropping notes tables...');
81
+ db.exec('DROP INDEX IF EXISTS idx_note_images_note');
82
+ db.exec('DROP TABLE IF EXISTS note_images');
83
+ db.exec('DROP INDEX IF EXISTS idx_notes_updated');
84
+ db.exec('DROP INDEX IF EXISTS idx_notes_collection');
85
+ db.exec('DROP TABLE IF EXISTS notes');
86
+ db.exec('DROP INDEX IF EXISTS idx_note_collections_scope');
87
+ db.exec('DROP INDEX IF EXISTS idx_note_collections_project');
88
+ db.exec('DROP TABLE IF EXISTS note_collections');
89
+ debug.log('migration', 'Notes tables dropped');
90
+ };