repoburg 1.3.312 → 1.3.313

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.
@@ -10,7 +10,7 @@
10
10
  href="https://fonts.googleapis.com/css2?family=Inter:wght@400;450;510;590;600&family=JetBrains+Mono:wght@400;500&display=swap"
11
11
  rel="stylesheet"
12
12
  />
13
- <script type="module" crossorigin src="/assets/index-7ikRAI4J.js"></script>
13
+ <script type="module" crossorigin src="/assets/index-B8vQbeJk.js"></script>
14
14
  <link rel="stylesheet" crossorigin href="/assets/index-wFHgyM6i.css">
15
15
  </head>
16
16
  <body>
@@ -3,35 +3,43 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = createAuthRouter;
4
4
  const express_1 = require("express");
5
5
  const authManager_1 = require("../auth/authManager");
6
- const isDevelopment = process.env.NODE_ENV === 'development';
7
- const ACCOUNT_SERVER_URL = isDevelopment ? 'http://localhost:2999' : 'https://repoburg.com/api/account';
8
- console.log(`Running in ${isDevelopment ? 'development' : 'production'} mode`);
9
- console.log(`Using ACCOUNT_SERVER_URL: ${ACCOUNT_SERVER_URL}`);
6
+ const deviceLogin_1 = require("../auth/deviceLogin");
7
+ /**
8
+ * This machine's Repoburg account: the device token in ~/.repoburg/token.jwt.
9
+ * The account is needed for Remote Access (tunnels); the Remote Access dialog
10
+ * and `repoburg login` sign in through POST /auth/initiate.
11
+ */
10
12
  function createAuthRouter(wss) {
11
13
  const router = (0, express_1.Router)();
12
- router.get('/status', async (req, res) => {
13
- const status = await authManager_1.authManager.getAuthStatus();
14
- res.json({ status });
14
+ router.get('/status', async (_req, res) => {
15
+ const { status, email } = await authManager_1.authManager.getAccount();
16
+ res.json({ status, email, login: (0, deviceLogin_1.getDeviceLogin)() });
15
17
  });
16
- router.post('/initiate', async (req, res) => {
18
+ // Starts the device login (or returns the pending one). The user approves
19
+ // the code at loginUrl; the daemon polls and saves the token.
20
+ router.post('/initiate', async (_req, res) => {
17
21
  try {
18
- const response = await fetch(`${ACCOUNT_SERVER_URL}/device/initiate`, {
19
- method: 'POST',
20
- headers: { 'Content-Type': 'application/json' }
22
+ const login = await (0, deviceLogin_1.startDeviceLogin)({
23
+ onAuthorized: () => {
24
+ // Notify connected clients (e.g., the old frontend's AuthGate).
25
+ wss.clients.forEach((client) => {
26
+ if (client.readyState === client.OPEN) {
27
+ client.send(JSON.stringify({ event: 'auth_success' }));
28
+ }
29
+ });
30
+ },
21
31
  });
22
- if (!response.ok) {
23
- throw new Error(`Failed to initiate device auth: ${response.statusText}`);
24
- }
25
- const { device_code, loginUrl } = await response.json();
26
- // Start polling in the background
27
- pollForToken(device_code, wss);
28
- res.json({ loginUrl });
32
+ res.json(login);
29
33
  }
30
34
  catch (error) {
31
35
  console.error('Error initiating device auth flow:', error);
32
- res.status(500).json({ error: 'Could not start authentication flow.' });
36
+ res.status(502).json({ error: error?.message ?? 'Could not start authentication flow.' });
33
37
  }
34
38
  });
39
+ router.post('/cancel', (_req, res) => {
40
+ (0, deviceLogin_1.cancelDeviceLogin)();
41
+ res.json({ login: (0, deviceLogin_1.getDeviceLogin)() });
42
+ });
35
43
  router.post('/logout', async (req, res) => {
36
44
  try {
37
45
  await authManager_1.authManager.logout();
@@ -44,47 +52,3 @@ function createAuthRouter(wss) {
44
52
  });
45
53
  return router;
46
54
  }
47
- async function pollForToken(deviceCode, wss) {
48
- const pollInterval = 5000; // 5 seconds
49
- const maxAttempts = 120; // 10 minutes
50
- let attempts = 0;
51
- console.log(`Polling for token with device code: ${deviceCode}`);
52
- const intervalId = setInterval(async () => {
53
- if (attempts >= maxAttempts) {
54
- clearInterval(intervalId);
55
- console.log(`Polling stopped for ${deviceCode} after reaching max attempts.`);
56
- return;
57
- }
58
- attempts++;
59
- try {
60
- // account-server expects 'code' query param, not 'device_code'
61
- const response = await fetch(`${ACCOUNT_SERVER_URL}/device/poll?code=${deviceCode}`);
62
- if (response.status === 410) { // Gone (expired)
63
- console.log(`Device code ${deviceCode} has expired.`);
64
- clearInterval(intervalId);
65
- return;
66
- }
67
- if (!response.ok) {
68
- // Continue polling on other errors
69
- console.warn(`Polling failed with status: ${response.status}`);
70
- return;
71
- }
72
- const data = await response.json();
73
- // account-server returns { status: 'authorized', access_token: '...' }
74
- if (data.status === 'authorized' && data.access_token) {
75
- console.log(`Successfully retrieved access token for ${deviceCode}.`);
76
- await authManager_1.authManager.saveToken(data.access_token);
77
- // Notify connected clients (e.g., frontend app)
78
- wss.clients.forEach(client => {
79
- if (client.readyState === client.OPEN) {
80
- client.send(JSON.stringify({ event: 'auth_success' }));
81
- }
82
- });
83
- clearInterval(intervalId);
84
- }
85
- }
86
- catch (error) {
87
- console.error(`Error during polling for ${deviceCode}:`, error);
88
- }
89
- }, pollInterval);
90
- }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.accountServerUrl = accountServerUrl;
4
+ /** Where the daemon reaches the account server (device login, tunnels). */
5
+ const isDevelopment = process.env.NODE_ENV === 'development';
6
+ const DEFAULT_ACCOUNT_SERVER_URL = isDevelopment
7
+ ? 'http://localhost:2999'
8
+ : 'https://repoburg.com/api/account';
9
+ function accountServerUrl() {
10
+ return process.env.ACCOUNT_SERVER_URL ?? DEFAULT_ACCOUNT_SERVER_URL;
11
+ }
@@ -52,11 +52,13 @@ class AuthManager {
52
52
  this.publicKey = null;
53
53
  this.loadPublicKey();
54
54
  }
55
+ /** The built-in key, or REPOBURG_DEVICE_PUBLIC_KEY (a dev account server's, as REPOBURG_EDGE_PUBLIC_KEY for edge tokens). */
55
56
  async loadPublicKey() {
56
57
  try {
57
- const keyData = exports.PUBLIC_KEY;
58
- console.log(`[AuthManager] Loading hardcoded public key: ${keyData.substring(0, 50)}...`);
59
- this.publicKey = await jose.importSPKI(keyData, 'EdDSA');
58
+ const override = process.env.REPOBURG_DEVICE_PUBLIC_KEY;
59
+ if (override)
60
+ console.warn('[AuthManager] Verifying device tokens with REPOBURG_DEVICE_PUBLIC_KEY, not the built-in key.');
61
+ this.publicKey = await jose.importSPKI(override ? override.replace(/\\n/g, '\n') : exports.PUBLIC_KEY, 'EdDSA');
60
62
  }
61
63
  catch (error) {
62
64
  console.error('FATAL: Could not load JWT public key.', error);
@@ -64,43 +66,38 @@ class AuthManager {
64
66
  }
65
67
  }
66
68
  async getAuthStatus() {
69
+ return (await this.getAccount()).status;
70
+ }
71
+ /**
72
+ * The saved device token's state and, for tokens that carry it, the account
73
+ * email. Quiet on purpose: the Remote Access dialog polls it while the user
74
+ * signs in.
75
+ */
76
+ async getAccount() {
67
77
  if (!this.publicKey) {
68
78
  console.error('[AuthManager] Public key not loaded, cannot verify auth status.');
69
- return 'invalid';
79
+ return { status: 'invalid', email: null };
70
80
  }
81
+ let token;
71
82
  try {
72
- const token = await fs_extra_1.default.readFile(TOKEN_PATH, 'utf-8');
73
- console.log(`[AuthManager] Verifying token from ${TOKEN_PATH}. Token starts with: ${token.substring(0, 20)}...`);
74
- try {
75
- const decoded = jose.decodeJwt(token);
76
- console.log('[AuthManager] Decoded JWT payload for debugging:', decoded);
77
- }
78
- catch (decodeError) {
79
- console.warn('[AuthManager] Could not decode JWT, it might be malformed.', decodeError);
80
- }
81
- await jose.jwtVerify(token, this.publicKey, {
83
+ token = await fs_extra_1.default.readFile(TOKEN_PATH, 'utf-8');
84
+ }
85
+ catch {
86
+ return { status: 'unauthorized', email: null }; // No token file
87
+ }
88
+ try {
89
+ const { payload } = await jose.jwtVerify(token, this.publicKey, {
82
90
  issuer: 'repoburg.com',
83
91
  audience: 'repoburg-daemon',
84
92
  });
85
- console.log('[AuthManager] JWT verification successful.');
86
- return 'authorized';
93
+ return { status: 'authorized', email: typeof payload.email === 'string' ? payload.email : null };
87
94
  }
88
95
  catch (error) {
89
- if (error instanceof Error) {
90
- if ('code' in error && error.code === 'ENOENT') {
91
- console.log(`[AuthManager] No token file found at ${TOKEN_PATH}.`);
92
- return 'unauthorized'; // No token file
93
- }
94
- if ('code' in error && error.code === 'ERR_JWT_EXPIRED') {
95
- console.warn('[AuthManager] JWT has expired.');
96
- return 'expired';
97
- }
98
- console.warn('[AuthManager] JWT verification failed:', error.message, error);
99
- }
100
- else {
101
- console.warn('[AuthManager] An unknown error occurred during JWT verification:', error);
96
+ if (error?.code === 'ERR_JWT_EXPIRED') {
97
+ return { status: 'expired', email: null };
102
98
  }
103
- return 'invalid';
99
+ console.warn('[AuthManager] JWT verification failed:', error?.message);
100
+ return { status: 'invalid', email: null };
104
101
  }
105
102
  }
106
103
  async verifyToken(token) {
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getDeviceLogin = getDeviceLogin;
7
+ exports.cancelDeviceLogin = cancelDeviceLogin;
8
+ exports.startDeviceLogin = startDeviceLogin;
9
+ exports.resetDeviceLoginForTests = resetDeviceLoginForTests;
10
+ /**
11
+ * Device login against the account server, shared by the Remote Access
12
+ * dialog ("Continue with Google") and `repoburg login`.
13
+ *
14
+ * The daemon asks for a short user code and binds it to a secret verifier
15
+ * that never leaves this process (the account server keeps only its SHA-256).
16
+ * The user approves the code on repoburg.com/device-login; the daemon polls
17
+ * with the verifier and saves the token. Knowing the code (it is in the login
18
+ * link) is not enough to collect the token.
19
+ *
20
+ * One login at a time: starting again while one is pending returns the same
21
+ * code, so a second click or a second tab does not start a second poller.
22
+ */
23
+ const crypto_1 = __importDefault(require("crypto"));
24
+ const accountServer_1 = require("./accountServer");
25
+ const authManager_1 = require("./authManager");
26
+ const DEFAULT_POLL_INTERVAL_MS = 3000;
27
+ let current = null;
28
+ function getDeviceLogin() {
29
+ return current?.login ?? null;
30
+ }
31
+ /** Stops polling; the code expires on the account server by itself. */
32
+ function cancelDeviceLogin() {
33
+ if (current?.login.state === 'pending') {
34
+ current.stop();
35
+ current.login.state = 'failed';
36
+ current.login.error = 'Sign-in cancelled.';
37
+ }
38
+ }
39
+ function isLive(login) {
40
+ return login.state === 'pending' && Date.now() < new Date(login.expiresAt).getTime();
41
+ }
42
+ async function startDeviceLogin(deps = {}) {
43
+ if (current && isLive(current.login))
44
+ return current.login;
45
+ current?.stop();
46
+ const http = deps.fetchImpl ?? fetch;
47
+ const saveToken = deps.saveToken ?? ((token) => authManager_1.authManager.saveToken(token));
48
+ const interval = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
49
+ const verifier = crypto_1.default.randomBytes(32).toString('base64url');
50
+ const challenge = crypto_1.default.createHash('sha256').update(verifier).digest('hex');
51
+ const response = await http(`${(0, accountServer_1.accountServerUrl)()}/device/initiate`, {
52
+ method: 'POST',
53
+ headers: { 'Content-Type': 'application/json' },
54
+ body: JSON.stringify({ code_challenge: challenge }),
55
+ });
56
+ if (!response.ok) {
57
+ throw new Error(`Could not start the sign-in (account server answered ${response.status}).`);
58
+ }
59
+ const data = (await response.json());
60
+ const login = {
61
+ state: 'pending',
62
+ userCode: data.device_code,
63
+ loginUrl: data.loginUrl,
64
+ expiresAt: new Date(Date.now() + data.expires_in * 1000).toISOString(),
65
+ error: null,
66
+ };
67
+ let timer = null;
68
+ let stopped = false;
69
+ const stop = () => {
70
+ stopped = true;
71
+ if (timer)
72
+ clearTimeout(timer);
73
+ };
74
+ current = { login, stop };
75
+ const finish = (state, error) => {
76
+ login.state = state;
77
+ login.error = error;
78
+ stop();
79
+ };
80
+ const poll = async () => {
81
+ if (stopped)
82
+ return;
83
+ if (!isLive(login))
84
+ return finish('expired', 'The sign-in code expired. Start again.');
85
+ try {
86
+ const res = await http(`${(0, accountServer_1.accountServerUrl)()}/device/poll`, {
87
+ method: 'POST',
88
+ headers: { 'Content-Type': 'application/json' },
89
+ body: JSON.stringify({ code: login.userCode, code_verifier: verifier }),
90
+ });
91
+ if (stopped)
92
+ return;
93
+ if (res.status === 410)
94
+ return finish('expired', 'The sign-in code expired. Start again.');
95
+ if (res.status === 403 || res.status === 404) {
96
+ return finish('failed', `The account server refused the sign-in (${res.status}).`);
97
+ }
98
+ if (res.ok) {
99
+ const body = (await res.json());
100
+ if (body.status === 'authorized' && body.access_token) {
101
+ await saveToken(body.access_token);
102
+ finish('authorized', null);
103
+ deps.onAuthorized?.();
104
+ return;
105
+ }
106
+ }
107
+ }
108
+ catch (error) {
109
+ // Network hiccup: keep polling until the code expires.
110
+ console.warn('[deviceLogin] poll failed:', error?.message);
111
+ }
112
+ if (!stopped)
113
+ timer = setTimeout(() => void poll(), interval);
114
+ };
115
+ timer = setTimeout(() => void poll(), interval);
116
+ return login;
117
+ }
118
+ /** Test hook: forget the current login. */
119
+ function resetDeviceLoginForTests() {
120
+ current?.stop();
121
+ current = null;
122
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const crypto_1 = __importDefault(require("crypto"));
7
+ process.env.ACCOUNT_SERVER_URL = 'http://account-server.test';
8
+ jest.mock('./authManager', () => ({ authManager: { saveToken: jest.fn() } }));
9
+ const deviceLogin_1 = require("./deviceLogin");
10
+ /** Account server double: pending `pendingPolls` times, then the token. */
11
+ function accountServer(opts = {}) {
12
+ const calls = [];
13
+ let polls = 0;
14
+ const fetchImpl = jest.fn(async (url, init) => {
15
+ const body = init?.body ? JSON.parse(String(init.body)) : {};
16
+ calls.push({ url: String(url), body });
17
+ if (String(url).endsWith('/device/initiate')) {
18
+ return new Response(JSON.stringify({ device_code: 'AbCd1234', loginUrl: 'https://repoburg.test/device-login?code=AbCd1234', expires_in: 600 }), { status: 201 });
19
+ }
20
+ polls += 1;
21
+ if (opts.pollStatus)
22
+ return new Response('{}', { status: opts.pollStatus });
23
+ if (polls <= (opts.pendingPolls ?? 1))
24
+ return new Response(JSON.stringify({ status: 'pending' }));
25
+ return new Response(JSON.stringify({ status: 'authorized', access_token: 'eyTOKEN' }));
26
+ });
27
+ return { fetchImpl, calls };
28
+ }
29
+ const waitFor = async (check) => {
30
+ for (let i = 0; i < 200 && !check(); i++)
31
+ await new Promise((r) => setTimeout(r, 2));
32
+ expect(check()).toBe(true);
33
+ };
34
+ describe('device login', () => {
35
+ afterEach(() => (0, deviceLogin_1.resetDeviceLoginForTests)());
36
+ it('binds the code to a verifier and saves the token once approved', async () => {
37
+ const { fetchImpl, calls } = accountServer();
38
+ const saveToken = jest.fn().mockResolvedValue(undefined);
39
+ const onAuthorized = jest.fn();
40
+ const login = await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl, saveToken, onAuthorized, pollIntervalMs: 1 });
41
+ expect(login).toMatchObject({ state: 'pending', userCode: 'AbCd1234' });
42
+ await waitFor(() => (0, deviceLogin_1.getDeviceLogin)()?.state === 'authorized');
43
+ expect(saveToken).toHaveBeenCalledWith('eyTOKEN');
44
+ expect(onAuthorized).toHaveBeenCalledTimes(1);
45
+ const challenge = calls[0].body.code_challenge;
46
+ const verifier = calls[1].body.code_verifier;
47
+ expect(calls[1].url).toBe('http://account-server.test/device/poll');
48
+ expect(calls[1].body.code).toBe('AbCd1234');
49
+ expect(crypto_1.default.createHash('sha256').update(verifier).digest('hex')).toBe(challenge);
50
+ // The verifier never goes to the account server before the poll.
51
+ expect(JSON.stringify(calls[0].body)).not.toContain(verifier);
52
+ });
53
+ it('returns the pending login instead of starting a second one', async () => {
54
+ const { fetchImpl } = accountServer({ pendingPolls: 1000 });
55
+ const first = await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl, pollIntervalMs: 1000 });
56
+ const second = await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl, pollIntervalMs: 1000 });
57
+ expect(second).toBe(first);
58
+ expect(fetchImpl.mock.calls).toHaveLength(1);
59
+ });
60
+ it('stops on cancel and on an expired code', async () => {
61
+ const pending = accountServer({ pendingPolls: 1000 });
62
+ await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl: pending.fetchImpl, pollIntervalMs: 1000 });
63
+ (0, deviceLogin_1.cancelDeviceLogin)();
64
+ expect((0, deviceLogin_1.getDeviceLogin)()?.state).toBe('failed');
65
+ const gone = accountServer({ pollStatus: 410 });
66
+ await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl: gone.fetchImpl, pollIntervalMs: 1 });
67
+ await waitFor(() => (0, deviceLogin_1.getDeviceLogin)()?.state === 'expired');
68
+ });
69
+ it('fails when the account server refuses the verifier', async () => {
70
+ const { fetchImpl } = accountServer({ pollStatus: 403 });
71
+ await (0, deviceLogin_1.startDeviceLogin)({ fetchImpl, pollIntervalMs: 1 });
72
+ await waitFor(() => (0, deviceLogin_1.getDeviceLogin)()?.state === 'failed');
73
+ });
74
+ });
File without changes
@@ -17,6 +17,11 @@ exports.runEnable = runEnable;
17
17
  * - service already running with live edge connections → everything is
18
18
  * skipped (the job goes straight to ready).
19
19
  *
20
+ * Provisioning needs this machine's Repoburg account (the device token).
21
+ * Without one — or when the account server answers 401 — the job stops in
22
+ * `needs_login`: the dialog signs the user in and starts the job again. No
23
+ * troubleshooting session for that; an agent cannot sign in for the user.
24
+ *
20
25
  * When a deterministic step fails, the orchestrator opens a troubleshooting
21
26
  * SESSION on the embedded pane (last used provider/model/cwd combo) with the
22
27
  * diagnostics inlined — the agent then works the problem in the background
@@ -26,9 +31,12 @@ exports.runEnable = runEnable;
26
31
  const os_1 = __importDefault(require("os"));
27
32
  const tunnel_state_1 = require("./tunnel-state");
28
33
  const provisioner_1 = require("./provisioner");
34
+ const authManager_1 = require("../auth/authManager");
29
35
  const cloudflared_1 = require("./cloudflared");
30
36
  const probes_1 = require("./probes");
31
- const DEFAULT_PANE_BASE_URL = 'http://127.0.0.1:9998';
37
+ // This daemon's own pane: a second daemon (REPOBURG_DAEMON_PORT, see index.ts)
38
+ // must not open its troubleshooting session in the one on :9998.
39
+ const DEFAULT_PANE_BASE_URL = `http://127.0.0.1:${Number(process.env.REPOBURG_DAEMON_PORT) || 9998}`;
32
40
  const DEFAULT_VERIFY_TIMEOUT_MS = 90000;
33
41
  const DEFAULT_VERIFY_INTERVAL_MS = 5000;
34
42
  /** The single active (or last finished) job — one enable at a time. */
@@ -68,6 +76,11 @@ function startEnableJob(mahlas, deps = {}) {
68
76
  });
69
77
  return job;
70
78
  }
79
+ function finishNeedsLogin(job) {
80
+ log(job, 'provision', 'This machine is not signed in to a Repoburg account.');
81
+ job.state = 'needs_login';
82
+ job.finishedAt = new Date().toISOString();
83
+ }
71
84
  function finishFailed(job, error) {
72
85
  job.state = 'failed';
73
86
  job.step = 'failed';
@@ -79,6 +92,7 @@ async function runEnable(job, depOverrides = {}) {
79
92
  const d = {
80
93
  loadTunnelState: tunnel_state_1.loadTunnelState,
81
94
  provisionTunnel: provisioner_1.provisionTunnel,
95
+ isSignedIn: async () => (await authManager_1.authManager.getAuthStatus()) === 'authorized',
82
96
  isInstalled: cloudflared_1.isInstalled,
83
97
  downloadCloudflared: cloudflared_1.downloadCloudflared,
84
98
  installService: cloudflared_1.installService,
@@ -107,8 +121,21 @@ async function runEnable(job, depOverrides = {}) {
107
121
  // ---- provision (only when no local state exists) ----
108
122
  let state = existing;
109
123
  if (!state) {
124
+ if (!(await d.isSignedIn())) {
125
+ finishNeedsLogin(job);
126
+ return;
127
+ }
110
128
  log(job, 'provision', `Provisioning the tunnel as "${job.mahlas ?? ''}".`);
111
- state = await d.provisionTunnel(job.mahlas ?? '');
129
+ try {
130
+ state = await d.provisionTunnel(job.mahlas ?? '');
131
+ }
132
+ catch (error) {
133
+ if (error?.statusCode === 401) {
134
+ finishNeedsLogin(job);
135
+ return;
136
+ }
137
+ throw error;
138
+ }
112
139
  job.hostname = state.hostname;
113
140
  }
114
141
  else {
@@ -43,6 +43,7 @@ function makeDeps(overrides = {}) {
43
43
  return {
44
44
  loadTunnelState: mockedLoad,
45
45
  provisionTunnel: jest.fn().mockResolvedValue(STATE),
46
+ isSignedIn: jest.fn().mockResolvedValue(true),
46
47
  isInstalled: mockedIsInstalled,
47
48
  downloadCloudflared: jest.fn().mockResolvedValue('/bin/cloudflared'),
48
49
  installService: jest.fn().mockResolvedValue('/service'),
@@ -188,3 +189,51 @@ describe('orchestrator: troubleshooting fallback', () => {
188
189
  expect((0, orchestrator_1.getEnableJob)()).toBeNull();
189
190
  });
190
191
  });
192
+ describe('orchestrator: sign-in', () => {
193
+ beforeEach(() => {
194
+ jest.clearAllMocks();
195
+ });
196
+ it('stops in needs_login before provisioning when the machine has no account', async () => {
197
+ mockedLoad.mockReturnValue(null);
198
+ mockedConnected.mockResolvedValue(false);
199
+ const deps = makeDeps({
200
+ isSignedIn: jest.fn().mockResolvedValue(false),
201
+ isServiceRunning: jest.fn().mockResolvedValue(false),
202
+ });
203
+ const job = makeJob();
204
+ await (0, orchestrator_1.runEnable)(job, deps);
205
+ expect(job.state).toBe('needs_login');
206
+ expect(job.finishedAt).not.toBeNull();
207
+ expect(deps.provisionTunnel).not.toHaveBeenCalled();
208
+ expect(deps.fetchImpl).not.toHaveBeenCalled(); // no troubleshooting session
209
+ });
210
+ it('stops in needs_login when the account server answers 401', async () => {
211
+ mockedLoad.mockReturnValue(null);
212
+ mockedConnected.mockResolvedValue(false);
213
+ const deps = makeDeps({
214
+ provisionTunnel: jest
215
+ .fn()
216
+ .mockRejectedValue(Object.assign(new Error('Account server: expired'), { statusCode: 401 })),
217
+ isServiceRunning: jest.fn().mockResolvedValue(false),
218
+ });
219
+ const job = makeJob();
220
+ await (0, orchestrator_1.runEnable)(job, deps);
221
+ expect(job.state).toBe('needs_login');
222
+ expect(deps.installService).not.toHaveBeenCalled();
223
+ expect(deps.fetchImpl).not.toHaveBeenCalled();
224
+ });
225
+ it('needs no account to resume a provisioned tunnel', async () => {
226
+ mockedLoad.mockReturnValue(STATE);
227
+ mockedIsInstalled.mockReturnValue(true);
228
+ mockedConnected.mockResolvedValue(true);
229
+ const isSignedIn = jest.fn().mockResolvedValue(false);
230
+ const deps = makeDeps({
231
+ isSignedIn,
232
+ isServiceRunning: jest.fn().mockResolvedValueOnce(false).mockResolvedValue(true),
233
+ });
234
+ const job = makeJob('zz');
235
+ await (0, orchestrator_1.runEnable)(job, deps);
236
+ expect(job.state).toBe('ready');
237
+ expect(isSignedIn).not.toHaveBeenCalled();
238
+ });
239
+ });
@@ -1,23 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ProvisioningError = void 0;
4
- exports.accountServerUrl = accountServerUrl;
3
+ exports.ProvisioningError = exports.accountServerUrl = void 0;
5
4
  exports.provisionTunnel = provisionTunnel;
6
5
  exports.listTunnels = listTunnels;
7
6
  exports.uninstallTunnel = uninstallTunnel;
8
7
  /**
9
8
  * Account-server client for tunnel lifecycle. The daemon authenticates with
10
- * the device JWT from `repoburg login` (~/.repoburg/token.jwt).
9
+ * the device JWT from the device login (~/.repoburg/token.jwt): the Remote
10
+ * Access dialog's "Continue with Google" or `repoburg login`.
11
11
  */
12
12
  const authManager_1 = require("../auth/authManager");
13
+ const accountServer_1 = require("../auth/accountServer");
14
+ Object.defineProperty(exports, "accountServerUrl", { enumerable: true, get: function () { return accountServer_1.accountServerUrl; } });
13
15
  const tunnel_state_1 = require("./tunnel-state");
14
- const isDevelopment = process.env.NODE_ENV === 'development';
15
- const DEFAULT_ACCOUNT_SERVER_URL = isDevelopment
16
- ? 'http://localhost:2999'
17
- : 'https://repoburg.com/api/account';
18
- function accountServerUrl() {
19
- return process.env.ACCOUNT_SERVER_URL ?? DEFAULT_ACCOUNT_SERVER_URL;
20
- }
21
16
  class ProvisioningError extends Error {
22
17
  constructor(message, statusCode) {
23
18
  super(message);
@@ -26,7 +21,7 @@ class ProvisioningError extends Error {
26
21
  }
27
22
  exports.ProvisioningError = ProvisioningError;
28
23
  async function callAccountServer(method, path, token, body) {
29
- const response = await fetch(`${accountServerUrl()}${path}`, {
24
+ const response = await fetch(`${(0, accountServer_1.accountServerUrl)()}${path}`, {
30
25
  method,
31
26
  headers: {
32
27
  Authorization: `Bearer ${token}`,
@@ -48,7 +43,7 @@ async function callAccountServer(method, path, token, body) {
48
43
  async function provisionTunnel(mahlas) {
49
44
  const token = await authManager_1.authManager.readToken();
50
45
  if (!token) {
51
- throw new ProvisioningError('Not logged in. Run `repoburg login` first.', 401);
46
+ throw new ProvisioningError('Not signed in to a Repoburg account.', 401);
52
47
  }
53
48
  // `edgeAuth`: this daemon checks the edge gate's tokens (MUH-108). The
54
49
  // account server refuses daemons that do not say so (426).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repoburg",
3
- "version": "1.3.312",
3
+ "version": "1.3.313",
4
4
  "description": "A local AI-powered software developer assistant that runs on your own machine.",
5
5
  "author": "Celal Ertug",
6
6
  "license": "SEE LICENSE IN LICENSE",
package/platform-cli.js CHANGED
@@ -149,11 +149,12 @@ program
149
149
  // 2. Initiate login
150
150
  console.log(chalk.yellow('Opening your browser to log in...'));
151
151
  const initiateResponse = await axios.post(`${DAEMON_BASE_URL}/auth/initiate`);
152
- const { loginUrl } = initiateResponse.data;
152
+ const { loginUrl, userCode } = initiateResponse.data;
153
153
 
154
154
  if (loginUrl) {
155
155
  await open(loginUrl);
156
156
  console.log(chalk.green('✓ Please complete the authentication in your browser.'));
157
+ if (userCode) console.log(chalk.cyan(` Approve it only if the page shows the code ${userCode}.`));
157
158
  await pollForAuth();
158
159
  } else {
159
160
  console.error(chalk.red('Could not retrieve login URL from the daemon.'));
@@ -354,11 +355,12 @@ program
354
355
  try {
355
356
  console.log(chalk.yellow('Opening your browser to log in...'));
356
357
  const response = await axios.post(`${DAEMON_BASE_URL}/auth/initiate`);
357
- const { loginUrl } = response.data;
358
+ const { loginUrl, userCode } = response.data;
358
359
 
359
360
  if (loginUrl) {
360
361
  await open(loginUrl);
361
362
  console.log(chalk.green('✓ Please complete the authentication in your browser.'));
363
+ if (userCode) console.log(chalk.cyan(` Approve it only if the page shows the code ${userCode}.`));
362
364
  } else {
363
365
  console.error(chalk.red('Could not retrieve login URL from the daemon.'));
364
366
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "tree": "3f01773d2dfcfcfee7b73a8c7d7497c15ad692bc",
3
- "commit": "98373b2b5d9e1ece8cbc7ffe6a38862f0a9a1695",
3
+ "commit": "292e390c833ac3fa8dd39a54f55dd75c6dd77441",
4
4
  "dirty": false,
5
- "repoburgVersion": "1.3.312",
6
- "builtAt": "2026-11-09T03:36:41.034Z"
5
+ "repoburgVersion": "1.3.313",
6
+ "builtAt": "2026-11-09T06:44:47.614Z"
7
7
  }
@@ -58,5 +58,5 @@
58
58
  ]
59
59
  }
60
60
  ],
61
- "version_name": "0.6.0 (repoburg 1.3.312, 98373b2)"
61
+ "version_name": "0.6.0 (repoburg 1.3.313, 292e390)"
62
62
  }