@myrialabs/clopen 0.4.27 → 0.4.29
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.
- package/backend/auth/auth-service.ts +45 -25
- package/backend/auth/onboarding.test.ts +106 -0
- package/backend/auth/permissions.ts +1 -1
- package/backend/database/utils/connection.ts +7 -31
- package/backend/engine/README.md +8 -3
- package/backend/engine/adapters/claude/message-converter.ts +55 -23
- package/backend/engine/adapters/codex/message-converter.ts +8 -2
- package/backend/engine/adapters/codex/models.ts +85 -98
- package/backend/engine/adapters/codex/stream.ts +5 -7
- package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
- package/backend/engine/adapters/copilot/stream.ts +24 -0
- package/backend/engine/docs/lessons-learned.md +78 -1
- package/backend/engine/docs/stack.md +8 -0
- package/backend/engine/install-recipes.ts +19 -2
- package/backend/files/file-size-limit.ts +5 -14
- package/backend/files/file-watcher.test.ts +160 -0
- package/backend/files/file-watcher.ts +276 -58
- package/backend/git/git-executor.ts +8 -0
- package/backend/git/git-service.test.ts +136 -0
- package/backend/git/git-service.ts +113 -17
- package/backend/index.ts +11 -4
- package/backend/mcp/internal/remote-server.test.ts +8 -3
- package/backend/mcp/internal/remote-server.ts +1 -1
- package/backend/settings/system-settings.ts +97 -0
- package/backend/tunnel/public-origin.ts +5 -13
- package/backend/utils/env.ts +29 -0
- package/backend/utils/paths.ts +9 -3
- package/backend/ws/auth/login.test.ts +8 -1
- package/backend/ws/auth/login.ts +22 -15
- package/backend/ws/auth/status.ts +24 -1
- package/backend/ws/chat/stream.ts +1 -0
- package/backend/ws/engine/claude/accounts.ts +4 -12
- package/backend/ws/engine/codex/accounts.ts +4 -13
- package/backend/ws/engine/pty-output.test.ts +37 -0
- package/backend/ws/engine/pty-output.ts +43 -0
- package/backend/ws/files/watch.ts +9 -0
- package/backend/ws/settings/crud.ts +14 -22
- package/dist/assets/{index-BTGcf_Vy.js → index-C7e5TWG3.js} +1 -1
- package/dist/assets/{index-BCv5HlPk.js → index-Derlqeyy.js} +1 -1
- package/dist/assets/{main-BrqMMMRX.css → main-CqzaPnux.css} +1 -1
- package/dist/assets/main-OGhsRKU1.js +1037 -0
- package/dist/index.html +2 -2
- package/package.json +14 -14
- package/shared/constants/engines.ts +1 -0
- package/shared/types/stores/settings.ts +11 -1
- package/shared/types/unified/stream.ts +10 -4
- package/dist/assets/main-CgmAFpU3.js +0 -1036
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* High-level git operations built on top of executor and parser
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { execGit, isGitRepo, getGitRoot } from './git-executor';
|
|
6
|
+
import { execGit, isGitRepo, getGitRoot, type GitExecResult } from './git-executor';
|
|
7
7
|
import { resolveBinary } from '../utils/cli';
|
|
8
8
|
import { getCleanSpawnEnv } from '../utils/env';
|
|
9
9
|
import {
|
|
@@ -69,6 +69,32 @@ export class GitService {
|
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
// ============================================
|
|
73
|
+
// Revision probes
|
|
74
|
+
// ============================================
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* True when the repo has at least one commit.
|
|
78
|
+
*
|
|
79
|
+
* A freshly `git init`ed repo has an unborn HEAD: every HEAD-relative revision
|
|
80
|
+
* (`HEAD`, `HEAD~1`, `HEAD^`) fails to resolve, and git reports it as a raw
|
|
81
|
+
* `fatal: ambiguous argument` / `bad revision`. Callers probe this so they can
|
|
82
|
+
* answer with an actionable message — or skip the operation entirely — instead
|
|
83
|
+
* of leaking that fatal into a toast.
|
|
84
|
+
*/
|
|
85
|
+
private async hasCommits(cwd: string): Promise<boolean> {
|
|
86
|
+
return (await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], cwd)).exitCode === 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* True when `ref` has a parent commit — false for a root (parentless) commit,
|
|
91
|
+
* where `<ref>^` / `<ref>~1` cannot resolve even though `<ref>` itself does.
|
|
92
|
+
*/
|
|
93
|
+
private async hasParent(cwd: string, ref = 'HEAD'): Promise<boolean> {
|
|
94
|
+
assertSafeGitRevish(ref, 'parent probe ref');
|
|
95
|
+
return (await execGit(['rev-parse', '--verify', '--quiet', `${ref}^`], cwd)).exitCode === 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
72
98
|
// ============================================
|
|
73
99
|
// Status
|
|
74
100
|
// ============================================
|
|
@@ -175,6 +201,11 @@ export class GitService {
|
|
|
175
201
|
}
|
|
176
202
|
const result = await execGit(args, cwd);
|
|
177
203
|
if (result.exitCode !== 0) {
|
|
204
|
+
// Unborn HEAD — git says "You have nothing to amend", which reads like a
|
|
205
|
+
// failure rather than "commit normally instead".
|
|
206
|
+
if (!(await this.hasCommits(cwd))) {
|
|
207
|
+
throw new Error('There is no commit to amend yet — create the first commit instead.');
|
|
208
|
+
}
|
|
178
209
|
throw new Error(`git commit --amend failed: ${result.stderr}`);
|
|
179
210
|
}
|
|
180
211
|
const hashResult = await execGit(['rev-parse', 'HEAD'], cwd);
|
|
@@ -212,8 +243,7 @@ export class GitService {
|
|
|
212
243
|
// changed". Detect the parentless case and diff against the empty tree via
|
|
213
244
|
// `diff-tree --root` so the initial commit's files show up as additions.
|
|
214
245
|
// Commits with a parent (including merges) keep the original behaviour.
|
|
215
|
-
const hasParent =
|
|
216
|
-
(await execGit(['rev-parse', '--verify', '--quiet', `${commitHash}^`], cwd)).exitCode === 0;
|
|
246
|
+
const hasParent = await this.hasParent(cwd, commitHash);
|
|
217
247
|
// Fetch the full commit message alongside the diff so the detail view can
|
|
218
248
|
// render the body. `%s\0%b` splits cleanly on NUL since a subject never
|
|
219
249
|
// contains one; the body is kept verbatim (it may span many lines).
|
|
@@ -460,6 +490,11 @@ export class GitService {
|
|
|
460
490
|
|
|
461
491
|
const result = await execGit(args, cwd);
|
|
462
492
|
if (result.exitCode !== 0) {
|
|
493
|
+
// A repo with no commits yet isn't an error — `git log` just has nothing
|
|
494
|
+
// to walk. Report it as an empty history so the UI shows its empty state.
|
|
495
|
+
if (!(await this.hasCommits(cwd))) {
|
|
496
|
+
return { commits: [], total: 0, hasMore: false };
|
|
497
|
+
}
|
|
463
498
|
throw new Error(`git log failed: ${result.stderr}`);
|
|
464
499
|
}
|
|
465
500
|
|
|
@@ -510,6 +545,24 @@ export class GitService {
|
|
|
510
545
|
};
|
|
511
546
|
}
|
|
512
547
|
|
|
548
|
+
/**
|
|
549
|
+
* Shape a `git push` outcome. On an unborn HEAD git only reports
|
|
550
|
+
* `src refspec <branch> does not match any`, which reads like a broken remote
|
|
551
|
+
* rather than "there is nothing here to push yet".
|
|
552
|
+
*/
|
|
553
|
+
private async describePushResult(
|
|
554
|
+
cwd: string,
|
|
555
|
+
result: GitExecResult
|
|
556
|
+
): Promise<{ success: boolean; message: string }> {
|
|
557
|
+
if (result.exitCode === 0) {
|
|
558
|
+
return { success: true, message: result.stderr || result.stdout };
|
|
559
|
+
}
|
|
560
|
+
if (!(await this.hasCommits(cwd))) {
|
|
561
|
+
return { success: false, message: 'This branch has no commits yet, so there is nothing to push.' };
|
|
562
|
+
}
|
|
563
|
+
return { success: false, message: result.stderr };
|
|
564
|
+
}
|
|
565
|
+
|
|
513
566
|
async push(cwd: string, remote = 'origin', branch?: string, force = false): Promise<{ success: boolean; message: string }> {
|
|
514
567
|
assertSafeGitRemoteName(remote);
|
|
515
568
|
const args = ['push', remote];
|
|
@@ -520,11 +573,7 @@ export class GitService {
|
|
|
520
573
|
if (force) args.push('--force-with-lease');
|
|
521
574
|
// Set upstream if needed
|
|
522
575
|
args.push('-u');
|
|
523
|
-
|
|
524
|
-
return {
|
|
525
|
-
success: result.exitCode === 0,
|
|
526
|
-
message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
|
|
527
|
-
};
|
|
576
|
+
return this.describePushResult(cwd, await execGit(args, cwd, 60000));
|
|
528
577
|
}
|
|
529
578
|
|
|
530
579
|
/**
|
|
@@ -554,11 +603,7 @@ export class GitService {
|
|
|
554
603
|
else if (mode === 'force') args.push('--force');
|
|
555
604
|
args.push('-u');
|
|
556
605
|
}
|
|
557
|
-
|
|
558
|
-
return {
|
|
559
|
-
success: result.exitCode === 0,
|
|
560
|
-
message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
|
|
561
|
-
};
|
|
606
|
+
return this.describePushResult(cwd, await execGit(args, cwd, 60000));
|
|
562
607
|
}
|
|
563
608
|
|
|
564
609
|
/** Fetch every configured remote and prune deleted remote-tracking refs. */
|
|
@@ -637,6 +682,10 @@ export class GitService {
|
|
|
637
682
|
'Stashing staged changes only requires Git 2.35 or newer. Please update Git to use this option.'
|
|
638
683
|
);
|
|
639
684
|
}
|
|
685
|
+
// Stashing needs a commit to record the base state against.
|
|
686
|
+
if (!(await this.hasCommits(cwd))) {
|
|
687
|
+
throw new Error('Stashing requires at least one commit — create the first commit first.');
|
|
688
|
+
}
|
|
640
689
|
throw new Error(`git stash failed: ${result.stderr}`);
|
|
641
690
|
}
|
|
642
691
|
}
|
|
@@ -868,12 +917,55 @@ export class GitService {
|
|
|
868
917
|
* - `soft` keeps the changes staged
|
|
869
918
|
* - `mixed` keeps the changes in the working tree (unstaged)
|
|
870
919
|
* - `hard` discards the changes entirely (destructive)
|
|
920
|
+
*
|
|
921
|
+
* The root commit has no `HEAD~1` to reset onto, so undoing it means deleting
|
|
922
|
+
* the branch ref itself: `update-ref -d HEAD` returns the repo to the unborn
|
|
923
|
+
* state while leaving the index intact — which is exactly `--soft`. `--mixed`
|
|
924
|
+
* and `--hard` then unwind the index (and working tree) from there.
|
|
871
925
|
*/
|
|
872
926
|
async undoLastCommit(cwd: string, mode: 'soft' | 'mixed' | 'hard'): Promise<void> {
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
927
|
+
if (!(await this.hasCommits(cwd))) {
|
|
928
|
+
throw new Error('This repository has no commits yet, so there is nothing to undo.');
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
if (await this.hasParent(cwd)) {
|
|
932
|
+
const flag = mode === 'soft' ? '--soft' : mode === 'hard' ? '--hard' : '--mixed';
|
|
933
|
+
const result = await execGit(['reset', flag, 'HEAD~1'], cwd);
|
|
934
|
+
if (result.exitCode !== 0) {
|
|
935
|
+
throw new Error(`git reset ${flag} failed: ${result.stderr}`);
|
|
936
|
+
}
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// Root commit. `--hard` must discard the working tree while HEAD still
|
|
941
|
+
// resolves — once the ref is gone there is no commit left to reset onto.
|
|
942
|
+
if (mode === 'hard') {
|
|
943
|
+
const discard = await execGit(['reset', '--hard', 'HEAD'], cwd);
|
|
944
|
+
if (discard.exitCode !== 0) {
|
|
945
|
+
throw new Error(`git reset --hard failed: ${discard.stderr}`);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const removeRef = await execGit(['update-ref', '-d', 'HEAD'], cwd);
|
|
950
|
+
if (removeRef.exitCode !== 0) {
|
|
951
|
+
throw new Error(`git update-ref -d HEAD failed: ${removeRef.stderr}`);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
if (mode === 'mixed') {
|
|
955
|
+
// Drop the index so the commit's files come back as untracked changes.
|
|
956
|
+
const unstage = await execGit(['reset'], cwd);
|
|
957
|
+
if (unstage.exitCode !== 0) {
|
|
958
|
+
throw new Error(`git reset failed: ${unstage.stderr}`);
|
|
959
|
+
}
|
|
960
|
+
} else if (mode === 'hard') {
|
|
961
|
+
// Delete exactly what the commit tracked — unrelated untracked files
|
|
962
|
+
// survive, matching `reset --hard HEAD~1` on a non-root commit. The
|
|
963
|
+
// `:/` pathspec covers the whole work tree even when cwd is a subdir,
|
|
964
|
+
// and `--ignore-unmatch` keeps an empty root commit from erroring.
|
|
965
|
+
const clearIndex = await execGit(['rm', '-rf', '--quiet', '--ignore-unmatch', '--', ':/'], cwd);
|
|
966
|
+
if (clearIndex.exitCode !== 0) {
|
|
967
|
+
throw new Error(`git rm failed: ${clearIndex.stderr}`);
|
|
968
|
+
}
|
|
877
969
|
}
|
|
878
970
|
}
|
|
879
971
|
|
|
@@ -881,6 +973,10 @@ export class GitService {
|
|
|
881
973
|
async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
|
|
882
974
|
assertSafeGitRevish(ref, 'revert ref');
|
|
883
975
|
const result = await execGit(['revert', '--no-edit', ref], cwd);
|
|
976
|
+
if (result.exitCode !== 0 && !(await this.hasCommits(cwd))) {
|
|
977
|
+
// Unborn HEAD — git only reports `bad revision 'HEAD'`.
|
|
978
|
+
return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
|
|
979
|
+
}
|
|
884
980
|
return {
|
|
885
981
|
success: result.exitCode === 0,
|
|
886
982
|
message: result.exitCode === 0 ? (result.stdout || result.stderr) : result.stderr
|
package/backend/index.ts
CHANGED
|
@@ -50,7 +50,7 @@ import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAut
|
|
|
50
50
|
|
|
51
51
|
// Auth middleware
|
|
52
52
|
import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
|
|
53
|
-
import { getAuthMode } from './
|
|
53
|
+
import { getAuthMode } from './settings/system-settings';
|
|
54
54
|
import { authQueries } from './database/queries';
|
|
55
55
|
import { authRateLimiter } from './auth';
|
|
56
56
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
@@ -232,10 +232,15 @@ async function startServer() {
|
|
|
232
232
|
debug.warn('path', '⚠️ Initial PATH enrichment failed:', error);
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
-
// Initialize database first before accepting connections
|
|
235
|
+
// Initialize database first before accepting connections.
|
|
236
|
+
//
|
|
237
|
+
// A failure here is fatal on purpose. Serving requests without a database
|
|
238
|
+
// means every settings read fails, and callers that fall back to defaults
|
|
239
|
+
// report a configured instance as unconfigured — an empty project list, an
|
|
240
|
+
// unfinished setup wizard. Refusing to start is both louder and safer.
|
|
236
241
|
try {
|
|
237
242
|
await initializeDatabase();
|
|
238
|
-
debug.log('database',
|
|
243
|
+
debug.log('database', `✅ Database initialized successfully (data dir: ${SERVER_ENV.DATA_DIR})`);
|
|
239
244
|
// Re-establish code-defined built-ins that live outside migrations/seeders
|
|
240
245
|
// (internal MCP servers like Browser Automation + the default engine).
|
|
241
246
|
// Shared with the clear-data handler so a DB wipe on the live process
|
|
@@ -245,7 +250,9 @@ async function startServer() {
|
|
|
245
250
|
sessionCleanupScheduler.start();
|
|
246
251
|
uploadTempCleanup.start();
|
|
247
252
|
} catch (error) {
|
|
248
|
-
|
|
253
|
+
console.error('❌ Database initialization failed — refusing to start:', error);
|
|
254
|
+
console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
|
|
255
|
+
process.exit(1);
|
|
249
256
|
}
|
|
250
257
|
|
|
251
258
|
// Start listening after database is ready
|
|
@@ -13,7 +13,8 @@ import { randomUUID } from 'node:crypto';
|
|
|
13
13
|
|
|
14
14
|
import { handleMcpRequest } from './remote-server';
|
|
15
15
|
import { getMcpServiceToken } from './service-token';
|
|
16
|
-
import { authQueries
|
|
16
|
+
import { authQueries } from '../../database/queries';
|
|
17
|
+
import { writeSystemSettings } from '../../settings/system-settings';
|
|
17
18
|
import { generatePAT, generateSessionToken, hashToken } from '../../auth/tokens';
|
|
18
19
|
import { initializeDatabase, closeDatabase, getDatabase } from '../../database';
|
|
19
20
|
|
|
@@ -22,7 +23,11 @@ let sessionToken: string;
|
|
|
22
23
|
let patToken: string;
|
|
23
24
|
|
|
24
25
|
function setAuthMode(mode: 'none' | 'required'): void {
|
|
25
|
-
|
|
26
|
+
// Merge rather than replace: the system settings blob holds unrelated state
|
|
27
|
+
// (the onboarding marker, admin limits) and a test must never be able to drop
|
|
28
|
+
// it — the data directory is isolated under NODE_ENV=test, but the habit is
|
|
29
|
+
// what keeps it isolated if that ever changes.
|
|
30
|
+
writeSystemSettings({ authMode: mode });
|
|
26
31
|
}
|
|
27
32
|
|
|
28
33
|
function sessionCount(userId: string): number {
|
|
@@ -80,7 +85,7 @@ beforeAll(async () => {
|
|
|
80
85
|
afterAll(() => {
|
|
81
86
|
authQueries.deleteSessionsByUserId(testUserId);
|
|
82
87
|
authQueries.deleteUser(testUserId);
|
|
83
|
-
|
|
88
|
+
setAuthMode('required');
|
|
84
89
|
closeDatabase();
|
|
85
90
|
});
|
|
86
91
|
|
|
@@ -23,7 +23,7 @@ import { createExternalProxyServer } from '../external/proxy';
|
|
|
23
23
|
import { debug } from '$shared/utils/logger';
|
|
24
24
|
import { authQueries } from '$backend/database/queries';
|
|
25
25
|
import { hashToken } from '$backend/auth/tokens';
|
|
26
|
-
import { getAuthMode } from '$backend/
|
|
26
|
+
import { getAuthMode } from '$backend/settings/system-settings';
|
|
27
27
|
import { isMcpServiceToken } from './service-token';
|
|
28
28
|
import type { EngineType } from '$shared/types/unified';
|
|
29
29
|
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Settings — single source of truth for the `system:settings` row.
|
|
3
|
+
*
|
|
4
|
+
* Every reader and writer of that blob goes through here. Two rules keep the
|
|
5
|
+
* "wizard came back / settings reset themselves" class of bug from returning:
|
|
6
|
+
*
|
|
7
|
+
* 1. A failed read is never flattened into "the setting is unset".
|
|
8
|
+
* `readSystemSettings()` throws when the database is unavailable or the blob
|
|
9
|
+
* is unparseable, so each caller has to pick its fallback deliberately. The
|
|
10
|
+
* old copy-pasted readers swallowed every error and returned `{}`, which told
|
|
11
|
+
* a perfectly healthy install that it had never been onboarded.
|
|
12
|
+
* 2. Writes always merge into the stored blob, never replace it, so a caller
|
|
13
|
+
* holding a stale copy of the settings cannot drop sibling fields.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { settingsQueries } from '$backend/database/queries';
|
|
17
|
+
import type { AuthMode, SystemSettings } from '$shared/types/stores/settings';
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
|
|
20
|
+
/** The settings-table key the whole system-settings blob lives under. */
|
|
21
|
+
export const SYSTEM_SETTINGS_KEY = 'system:settings';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Stored shape: the typed fields, plus anything a newer or older build wrote.
|
|
25
|
+
* Unknown keys are preserved by every write so a downgrade never loses data.
|
|
26
|
+
*/
|
|
27
|
+
export type StoredSystemSettings = Partial<SystemSettings> & Record<string, unknown>;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read and parse the system settings blob.
|
|
31
|
+
*
|
|
32
|
+
* Returns `{}` only when the row genuinely does not exist yet (fresh install).
|
|
33
|
+
* THROWS when the database is unreachable or the stored value is not valid
|
|
34
|
+
* JSON — those are failures, not "no settings", and callers must not treat them
|
|
35
|
+
* the same way.
|
|
36
|
+
*/
|
|
37
|
+
export function readSystemSettings(): StoredSystemSettings {
|
|
38
|
+
const row = settingsQueries.get(SYSTEM_SETTINGS_KEY);
|
|
39
|
+
if (!row?.value) return {};
|
|
40
|
+
|
|
41
|
+
const parsed = typeof row.value === 'string' ? JSON.parse(row.value) : row.value;
|
|
42
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
43
|
+
throw new Error(`${SYSTEM_SETTINGS_KEY} holds a non-object value`);
|
|
44
|
+
}
|
|
45
|
+
return parsed as StoredSystemSettings;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Read a single field with an explicit fallback, tolerating an unreadable blob.
|
|
50
|
+
*
|
|
51
|
+
* Use this for settings where continuing with the default is genuinely correct
|
|
52
|
+
* (a size limit, a public URL). Do NOT use it for state that decides whether the
|
|
53
|
+
* user has already completed something — see `auth-service`'s onboarding state.
|
|
54
|
+
*/
|
|
55
|
+
export function readSystemSetting<T>(pick: (settings: StoredSystemSettings) => T | undefined, fallback: T): T {
|
|
56
|
+
try {
|
|
57
|
+
const value = pick(readSystemSettings());
|
|
58
|
+
return value === undefined ? fallback : value;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
debug.warn('settings', 'System settings unreadable, using default for one field:', error);
|
|
61
|
+
return fallback;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Merge a patch into the stored blob — the only writer of this row.
|
|
67
|
+
*
|
|
68
|
+
* Returns the merged result so callers can confirm what was persisted.
|
|
69
|
+
*/
|
|
70
|
+
export function writeSystemSettings(patch: StoredSystemSettings): StoredSystemSettings {
|
|
71
|
+
let current: StoredSystemSettings = {};
|
|
72
|
+
try {
|
|
73
|
+
current = readSystemSettings();
|
|
74
|
+
} catch (error) {
|
|
75
|
+
// The blob is unreadable, so rebuilding from the patch is the only way
|
|
76
|
+
// forward — but it is also the moment sibling settings are lost, so it is
|
|
77
|
+
// logged as an error rather than quietly absorbed.
|
|
78
|
+
debug.error('settings', 'System settings unreadable, rebuilding from patch:', error);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const merged = { ...current, ...patch };
|
|
82
|
+
settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify(merged));
|
|
83
|
+
return merged;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Current auth mode.
|
|
88
|
+
*
|
|
89
|
+
* Fail-secure: an unreadable blob resolves to 'required' (login enforced), and
|
|
90
|
+
* this runs inside the WebSocket auth gate, so it must never throw.
|
|
91
|
+
*/
|
|
92
|
+
export function getAuthMode(): AuthMode {
|
|
93
|
+
return readSystemSetting(
|
|
94
|
+
(s) => (s.authMode === 'none' || s.authMode === 'required' ? s.authMode : undefined),
|
|
95
|
+
'required'
|
|
96
|
+
);
|
|
97
|
+
}
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { tunnelKit, portFromService } from './tunnel-config';
|
|
18
18
|
import { SERVER_ENV } from '../utils/env';
|
|
19
|
-
import {
|
|
19
|
+
import { readSystemSetting } from '$backend/settings/system-settings';
|
|
20
20
|
import { debug } from '$shared/utils/logger';
|
|
21
21
|
|
|
22
22
|
export type PublicOriginSource = 'configured' | 'domain' | 'tunnel';
|
|
@@ -50,18 +50,10 @@ function normalizeOrigin(url: string): string {
|
|
|
50
50
|
|
|
51
51
|
/** Read the admin-configured public base URL from system settings, if any. */
|
|
52
52
|
function getConfiguredPublicBaseUrl(): string | null {
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const url = parsed?.publicBaseUrl;
|
|
58
|
-
if (typeof url === 'string' && url.trim()) {
|
|
59
|
-
return normalizeOrigin(url.trim());
|
|
60
|
-
}
|
|
61
|
-
} catch {
|
|
62
|
-
// Settings may not exist yet.
|
|
63
|
-
}
|
|
64
|
-
return null;
|
|
53
|
+
return readSystemSetting((settings) => {
|
|
54
|
+
const url = settings.publicBaseUrl;
|
|
55
|
+
return typeof url === 'string' && url.trim() ? normalizeOrigin(url.trim()) : undefined;
|
|
56
|
+
}, null);
|
|
65
57
|
}
|
|
66
58
|
|
|
67
59
|
/** Find an already-running quick tunnel pointing at the given local port. */
|
package/backend/utils/env.ts
CHANGED
|
@@ -16,12 +16,41 @@
|
|
|
16
16
|
|
|
17
17
|
import { readFileSync } from 'fs';
|
|
18
18
|
import { join } from 'path';
|
|
19
|
+
import { homedir } from 'os';
|
|
19
20
|
|
|
20
21
|
// ── Server configuration (read once at import time) ─────────────────
|
|
21
22
|
const isDev = process.env.NODE_ENV !== 'production';
|
|
22
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Resolve the Clopen data directory — the single decision point for where ALL
|
|
26
|
+
* persisted state lives (app.db, engine homes, stack, snapshots, tunnel…).
|
|
27
|
+
*
|
|
28
|
+
* Resolved once, at import time, for two reasons:
|
|
29
|
+
*
|
|
30
|
+
* 1. `NODE_ENV` is not stable at runtime. Any dependency that assigns to
|
|
31
|
+
* `process.env.NODE_ENV` mid-process would otherwise silently move the data
|
|
32
|
+
* directory out from under a running server.
|
|
33
|
+
* 2. The test runner sets `NODE_ENV=test`, which used to fall through to the
|
|
34
|
+
* production directory — so `bun test` opened the developer's real
|
|
35
|
+
* `~/.clopen/app.db` and rewrote live rows (that is what kept resetting the
|
|
36
|
+
* onboarding flag and system settings). Tests get their own directory here,
|
|
37
|
+
* once, so no individual test has to remember to isolate itself.
|
|
38
|
+
*
|
|
39
|
+
* `CLOPEN_DATA_DIR` overrides everything, for deployments that keep state
|
|
40
|
+
* outside the home directory.
|
|
41
|
+
*/
|
|
42
|
+
function resolveDataDir(): string {
|
|
43
|
+
const override = process.env.CLOPEN_DATA_DIR?.trim();
|
|
44
|
+
if (override) return override;
|
|
45
|
+
if (process.env.NODE_ENV === 'test') return join(homedir(), '.clopen-test');
|
|
46
|
+
if (process.env.NODE_ENV === 'development') return join(homedir(), '.clopen-dev');
|
|
47
|
+
return join(homedir(), '.clopen');
|
|
48
|
+
}
|
|
49
|
+
|
|
23
50
|
export const SERVER_ENV = {
|
|
24
51
|
NODE_ENV: (process.env.NODE_ENV || 'development') as string,
|
|
52
|
+
/** Absolute path to the Clopen data directory — see `resolveDataDir()`. */
|
|
53
|
+
DATA_DIR: resolveDataDir(),
|
|
25
54
|
/** Backend port — dev: CLOPEN_PORT_BACKEND (default 9161), prod: CLOPEN_PORT (default 9141) */
|
|
26
55
|
PORT: isDev
|
|
27
56
|
? (process.env.CLOPEN_PORT_BACKEND ? parseInt(process.env.CLOPEN_PORT_BACKEND) : 9161)
|
package/backend/utils/paths.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { join, resolve } from 'path';
|
|
2
|
-
import {
|
|
2
|
+
import { SERVER_ENV } from './env';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Returns the Clopen data directory.
|
|
6
6
|
* - development: ~/.clopen-dev
|
|
7
|
-
* -
|
|
7
|
+
* - test: ~/.clopen-test (never the real one — see resolveDataDir)
|
|
8
|
+
* - production: ~/.clopen
|
|
9
|
+
* - `CLOPEN_DATA_DIR` overrides all of the above.
|
|
10
|
+
*
|
|
11
|
+
* The value is resolved once at import time in `SERVER_ENV.DATA_DIR`; this is
|
|
12
|
+
* only a named accessor for it, so every caller sees the same directory for the
|
|
13
|
+
* lifetime of the process.
|
|
8
14
|
*/
|
|
9
15
|
export function getClopenDir(): string {
|
|
10
|
-
return
|
|
16
|
+
return SERVER_ENV.DATA_DIR;
|
|
11
17
|
}
|
|
12
18
|
|
|
13
19
|
/**
|
|
@@ -53,6 +53,8 @@ const mockCreateUserFromInvite = mock((inviteToken: string, name: string) => ({
|
|
|
53
53
|
|
|
54
54
|
const mockNeedsSetup = mock(() => true);
|
|
55
55
|
const mockGetAuthMode = mock(() => 'none');
|
|
56
|
+
const mockMarkOnboardingPending = mock(() => {});
|
|
57
|
+
const mockWriteSystemSettings = mock((patch: Record<string, unknown>) => patch);
|
|
56
58
|
|
|
57
59
|
// Mock settings
|
|
58
60
|
let mockSettings: any = { value: JSON.stringify({ authMode: 'required' }) };
|
|
@@ -83,12 +85,17 @@ mock.module('$backend/database/queries', () => ({
|
|
|
83
85
|
}
|
|
84
86
|
}));
|
|
85
87
|
|
|
88
|
+
mock.module('$backend/settings/system-settings', () => ({
|
|
89
|
+
getAuthMode: mockGetAuthMode,
|
|
90
|
+
writeSystemSettings: mockWriteSystemSettings
|
|
91
|
+
}));
|
|
92
|
+
|
|
86
93
|
mock.module('$backend/auth/auth-service', () => ({
|
|
87
94
|
createAdmin: mockCreateAdmin,
|
|
88
95
|
createOrGetNoAuthAdmin: mockCreateOrGetNoAuthAdmin,
|
|
89
96
|
createUserFromInvite: mockCreateUserFromInvite,
|
|
90
97
|
needsSetup: mockNeedsSetup,
|
|
91
|
-
|
|
98
|
+
markOnboardingPending: mockMarkOnboardingPending,
|
|
92
99
|
loginWithToken: mock(() => ({})),
|
|
93
100
|
logout: mock(() => {}),
|
|
94
101
|
logoutAllSessions: mock(() => 0),
|
package/backend/ws/auth/login.ts
CHANGED
|
@@ -2,7 +2,6 @@ import { t } from 'elysia';
|
|
|
2
2
|
import { createRouter } from '$shared/utils/ws-server';
|
|
3
3
|
import {
|
|
4
4
|
createAdmin,
|
|
5
|
-
getAuthMode,
|
|
6
5
|
loginWithToken,
|
|
7
6
|
createUserFromInvite,
|
|
8
7
|
logout,
|
|
@@ -11,9 +10,11 @@ import {
|
|
|
11
10
|
regeneratePAT,
|
|
12
11
|
updateUserName,
|
|
13
12
|
createOrGetNoAuthAdmin,
|
|
14
|
-
needsSetup
|
|
13
|
+
needsSetup,
|
|
14
|
+
markOnboardingPending
|
|
15
15
|
} from '$backend/auth/auth-service';
|
|
16
|
-
import {
|
|
16
|
+
import { getAuthMode, writeSystemSettings } from '$backend/settings/system-settings';
|
|
17
|
+
import { auditLogQueries } from '$backend/database/queries';
|
|
17
18
|
import { getTokenType } from '$backend/auth/tokens';
|
|
18
19
|
import { authRateLimiter } from '$backend/auth/rate-limiter';
|
|
19
20
|
import { ws } from '$backend/utils/ws';
|
|
@@ -42,15 +43,22 @@ export const loginHandler = createRouter()
|
|
|
42
43
|
expiresAt: t.String()
|
|
43
44
|
})
|
|
44
45
|
}, async ({ data, conn }) => {
|
|
46
|
+
// Refuse before touching any state. This route is public, so without the
|
|
47
|
+
// guard a stray call against a live instance would flip the onboarding
|
|
48
|
+
// marker below and send every user back through the wizard.
|
|
49
|
+
if (!needsSetup()) {
|
|
50
|
+
throw new Error('Setup already completed. Admin account exists.');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Mark the wizard as in-progress BEFORE the first user exists, so a refresh
|
|
54
|
+
// between here and "Finish" resumes setup instead of looking like a
|
|
55
|
+
// completed install (which is how onboarding state is inferred).
|
|
56
|
+
markOnboardingPending();
|
|
57
|
+
|
|
45
58
|
const result = createAdmin(data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
|
|
46
59
|
|
|
47
60
|
// Save authMode to system settings
|
|
48
|
-
|
|
49
|
-
const parsed = currentSettings?.value
|
|
50
|
-
? (typeof currentSettings.value === 'string' ? JSON.parse(currentSettings.value) : currentSettings.value)
|
|
51
|
-
: {};
|
|
52
|
-
parsed.authMode = 'required';
|
|
53
|
-
settingsQueries.set('system:settings', JSON.stringify(parsed));
|
|
61
|
+
writeSystemSettings({ authMode: 'required' });
|
|
54
62
|
|
|
55
63
|
auditLogQueries.logEvent({
|
|
56
64
|
userId: result.user.id,
|
|
@@ -80,13 +88,12 @@ export const loginHandler = createRouter()
|
|
|
80
88
|
throw new Error('Setup already completed.');
|
|
81
89
|
}
|
|
82
90
|
|
|
91
|
+
// Same ordering as auth:setup — record the in-progress wizard before the
|
|
92
|
+
// first user exists.
|
|
93
|
+
markOnboardingPending();
|
|
94
|
+
|
|
83
95
|
// Save authMode to system settings
|
|
84
|
-
|
|
85
|
-
const parsed = currentSettings?.value
|
|
86
|
-
? (typeof currentSettings.value === 'string' ? JSON.parse(currentSettings.value) : currentSettings.value)
|
|
87
|
-
: {};
|
|
88
|
-
parsed.authMode = 'none';
|
|
89
|
-
settingsQueries.set('system:settings', JSON.stringify(parsed));
|
|
96
|
+
writeSystemSettings({ authMode: 'none' });
|
|
90
97
|
|
|
91
98
|
// Create or get default admin
|
|
92
99
|
const result = createOrGetNoAuthAdmin();
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { t } from 'elysia';
|
|
2
2
|
import { createRouter } from '$shared/utils/ws-server';
|
|
3
|
-
import { needsSetup, getUserById,
|
|
3
|
+
import { needsSetup, getUserById, isOnboardingComplete, markOnboardingComplete } from '$backend/auth/auth-service';
|
|
4
|
+
import { getAuthMode } from '$backend/settings/system-settings';
|
|
4
5
|
import { ws } from '$backend/utils/ws';
|
|
5
6
|
|
|
6
7
|
export const statusHandler = createRouter()
|
|
@@ -22,6 +23,10 @@ export const statusHandler = createRouter()
|
|
|
22
23
|
})
|
|
23
24
|
}, async ({ conn }) => {
|
|
24
25
|
const setup = needsSetup();
|
|
26
|
+
// Deliberately NOT wrapped in a try/catch: if onboarding state cannot be
|
|
27
|
+
// read, this request must fail so the client keeps its current screen.
|
|
28
|
+
// Reporting "not onboarded" on a read error is what used to drop working
|
|
29
|
+
// installs into the setup wizard.
|
|
25
30
|
const onboardingDone = isOnboardingComplete();
|
|
26
31
|
const authMode = getAuthMode();
|
|
27
32
|
const authenticated = ws.isAuthenticated(conn);
|
|
@@ -38,4 +43,22 @@ export const statusHandler = createRouter()
|
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
return { needsSetup: setup, onboardingComplete: onboardingDone, authenticated, authMode, user };
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
// Mark the setup wizard as finished.
|
|
49
|
+
//
|
|
50
|
+
// The server owns this marker rather than letting the client write the raw
|
|
51
|
+
// settings key: the wizard may only be dismissed once persistence is
|
|
52
|
+
// confirmed, otherwise a failed write drops the user straight back into it on
|
|
53
|
+
// the next refresh — silently, because the old client-side write was
|
|
54
|
+
// fire-and-forget. The response echoes the stored state so the client can
|
|
55
|
+
// verify instead of assume.
|
|
56
|
+
.http('auth:complete-onboarding', {
|
|
57
|
+
data: t.Object({}),
|
|
58
|
+
response: t.Object({
|
|
59
|
+
onboardingComplete: t.Boolean()
|
|
60
|
+
})
|
|
61
|
+
}, async () => {
|
|
62
|
+
markOnboardingComplete();
|
|
63
|
+
return { onboardingComplete: isOnboardingComplete() };
|
|
41
64
|
});
|
|
@@ -23,25 +23,17 @@ import { resolveBinaryWithRefresh } from '../../../utils/cli';
|
|
|
23
23
|
import { debug } from '$shared/utils/logger';
|
|
24
24
|
import { getCleanSpawnEnv } from '../../../utils/env';
|
|
25
25
|
import { requireSetupSessionAccess } from '../access';
|
|
26
|
+
import { stripAnsi, extractHttpsUrl } from '../pty-output';
|
|
26
27
|
|
|
27
28
|
// ── Helpers ──
|
|
28
29
|
|
|
29
|
-
function stripAnsi(str: string): string {
|
|
30
|
-
// Replace cursor positioning sequences (CSI row;colH/f) with newline
|
|
31
|
-
// so line structure is preserved after stripping
|
|
32
|
-
return str
|
|
33
|
-
.replace(/\x1B\[\d+;\d+[Hf]/g, '\n')
|
|
34
|
-
.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
30
|
// Extracts the first https:// URL from PTY output.
|
|
38
31
|
// Known formats (may change across Claude Code versions):
|
|
39
32
|
// - https://claude.ai/oauth/authorize?...
|
|
40
33
|
// - https://claude.com/cai/oauth/authorize?...
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
34
|
+
// The CLI prints it as an OSC 8 hyperlink, so stripAnsi must drop the escape
|
|
35
|
+
// payload or the URL arrives duplicated.
|
|
36
|
+
const extractAuthUrl = extractHttpsUrl;
|
|
45
37
|
|
|
46
38
|
function extractOAuthToken(clean: string): string | null {
|
|
47
39
|
const tokenPrefix = 'sk-ant-oat01-';
|