repoburg 1.3.311 → 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.
Files changed (30) hide show
  1. package/agent-pane/frontend/dist/assets/{TerminalView-CdL80e84.js → TerminalView-Xaq6tVfx.js} +1 -1
  2. package/agent-pane/frontend/dist/assets/index-B8vQbeJk.js +841 -0
  3. package/agent-pane/frontend/dist/index.html +1 -1
  4. package/daemon/dist/api/auth.js +27 -63
  5. package/daemon/dist/auth/accountServer.js +11 -0
  6. package/daemon/dist/auth/authManager.js +27 -30
  7. package/daemon/dist/auth/deviceLogin.js +122 -0
  8. package/daemon/dist/auth/deviceLogin.spec.js +74 -0
  9. package/daemon/dist/index.js +0 -3
  10. package/daemon/dist/middleware/checkRemoteAuth.js +10 -25
  11. package/daemon/dist/middleware/checkRemoteAuth.spec.js +5 -21
  12. package/daemon/dist/remote/orchestrator.js +29 -2
  13. package/daemon/dist/remote/orchestrator.spec.js +49 -2
  14. package/daemon/dist/remote/provisioner.js +9 -38
  15. package/daemon/dist/remote/provisioner.spec.js +5 -86
  16. package/daemon/dist/remote/routes.js +2 -5
  17. package/daemon/dist/remote/routes.spec.js +1 -8
  18. package/daemon/dist/remote/tunnel-state.spec.js +0 -2
  19. package/package.json +1 -1
  20. package/platform-cli.js +4 -2
  21. package/tabtape/extension/dist/build-info.json +3 -3
  22. package/tabtape/extension/dist/manifest.json +1 -1
  23. package/tabtape/ui/dist/build-info.json +3 -3
  24. package/agent-pane/frontend/dist/assets/index-NpywVkQl.js +0 -841
  25. package/daemon/dist/middleware/corsOrigin.js +0 -53
  26. package/daemon/dist/middleware/corsOrigin.spec.js +0 -46
  27. package/daemon/dist/remote/access-jwt.js +0 -67
  28. package/daemon/dist/remote/access-jwt.spec.js +0 -94
  29. package/daemon/dist/remote/edge-gate-move.js +0 -40
  30. package/daemon/dist/remote/edge-gate-move.spec.js +0 -44
@@ -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-NpywVkQl.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
+ });
@@ -18,7 +18,6 @@ const mcp_gateway_1 = require("./mcp-gateway");
18
18
  const agentPane_1 = require("./agentPane");
19
19
  const routes_1 = require("./remote/routes");
20
20
  const checkRemoteAuth_1 = require("./middleware/checkRemoteAuth");
21
- const edge_gate_move_1 = require("./remote/edge-gate-move");
22
21
  const staticServing_1 = require("./staticServing");
23
22
  const router_1 = require("./recorder/router");
24
23
  const tabtape_1 = require("./tabtape");
@@ -168,8 +167,6 @@ async function main() {
168
167
  console.log(`Repoburg Platform Daemon listening on http://127.0.0.1:${PORT}`);
169
168
  console.log(`MCP Gateway available at http://localhost:${PORT}/mcp`);
170
169
  tabtape = loadTabtape();
171
- // A tunnel still behind Cloudflare Access moves to the edge gate.
172
- (0, edge_gate_move_1.scheduleEdgeGateMove)();
173
170
  // Adopt the agents the previous daemon left running in session hosts and
174
171
  // resume the turns it left interrupted (restart, crash, power loss) —
175
172
  // only now that the port is ours.
@@ -4,7 +4,6 @@ exports.remoteAuthFailure = remoteAuthFailure;
4
4
  exports.checkRemoteAuth = checkRemoteAuth;
5
5
  exports.checkRemoteWsAuth = checkRemoteWsAuth;
6
6
  const tunnel_state_1 = require("../remote/tunnel-state");
7
- const access_jwt_1 = require("../remote/access-jwt");
8
7
  const edge_jwt_1 = require("../remote/edge-jwt");
9
8
  const originGuard_1 = require("./originGuard");
10
9
  /**
@@ -20,12 +19,9 @@ const originGuard_1 = require("./originGuard");
20
19
  * - a host of REPOBURG_ALLOWED_ORIGINS (the owner's own proxy): no;
21
20
  * - anything else: yes (it cannot be this machine's tunnel, so it fails).
22
21
  *
23
- * Accepted credentials, either one (fail closed: without one, 401):
24
- * - an edge token (X-Repoburg-Edge-Auth) from the account server's edge
25
- * gate, for this hostname and the pinned owner email (MUH-108);
26
- * - a Cloudflare Access JWT (Cf-Access-Jwt-Assertion), while this tunnel
27
- * still has its Access app (remote.json has accessTeamDomain + accessAud),
28
- * also pinned to the owner email.
22
+ * The credential (fail closed: without it, 401) is an edge token
23
+ * (X-Repoburg-Edge-Auth) from the account server's edge gate, for this
24
+ * hostname and the pinned owner email (MUH-108).
29
25
  */
30
26
  function needsCredential(host) {
31
27
  if (!host)
@@ -51,26 +47,15 @@ async function remoteAuthFailure(headers, state = (0, tunnel_state_1.loadTunnelS
51
47
  if (!state.ownerEmail)
52
48
  return 'Tunnel owner email is missing — re-provision this machine.';
53
49
  const edgeToken = header(headers, edge_jwt_1.EDGE_AUTH_HEADER);
54
- if (edgeToken) {
55
- try {
56
- await (0, edge_jwt_1.verifyEdgeJwt)(edgeToken, { hostname: state.hostname, ownerEmail: state.ownerEmail });
57
- return null;
58
- }
59
- catch {
60
- return 'Invalid or expired sign-in token.';
61
- }
50
+ if (!edgeToken)
51
+ return 'Sign in to this machine first.';
52
+ try {
53
+ await (0, edge_jwt_1.verifyEdgeJwt)(edgeToken, { hostname: state.hostname, ownerEmail: state.ownerEmail });
54
+ return null;
62
55
  }
63
- const assertion = header(headers, 'cf-access-jwt-assertion');
64
- if (assertion && state.accessTeamDomain && state.accessAud) {
65
- try {
66
- await (0, access_jwt_1.verifyAccessJwt)(assertion, { teamDomain: state.accessTeamDomain, aud: state.accessAud }, { ownerEmail: state.ownerEmail });
67
- return null;
68
- }
69
- catch {
70
- return 'Invalid or expired Cloudflare Access token.';
71
- }
56
+ catch {
57
+ return 'Invalid or expired sign-in token.';
72
58
  }
73
- return 'Sign in to this machine first.';
74
59
  }
75
60
  /** Express middleware for every route. */
76
61
  async function checkRemoteAuth(req, res, next) {
@@ -37,16 +37,13 @@ const jose = __importStar(require("jose"));
37
37
  const checkRemoteAuth_1 = require("./checkRemoteAuth");
38
38
  const originGuard_1 = require("./originGuard");
39
39
  const tunnel_state_1 = require("../remote/tunnel-state");
40
- const access_jwt_1 = require("../remote/access-jwt");
41
40
  jest.mock('../remote/tunnel-state');
42
- jest.mock('../remote/access-jwt');
43
41
  const mockedLoad = tunnel_state_1.loadTunnelState;
44
- const mockedVerifyAccess = access_jwt_1.verifyAccessJwt;
45
42
  /** Requests THROUGH THE TUNNEL carry the machine hostname as Host. */
46
43
  const HOSTNAME = 'zztest.repoburg.com';
47
44
  const TUNNEL_HOST = `${HOSTNAME}:443`;
48
45
  const OWNER = 'owner@repoburg.com';
49
- /** A tunnel behind the edge gate (provisioned with edgeAuth, or moved). */
46
+ /** A tunnel behind the edge gate. */
50
47
  const GATE_STATE = {
51
48
  mahlas: 'zztest',
52
49
  hostname: HOSTNAME,
@@ -54,7 +51,7 @@ const GATE_STATE = {
54
51
  tunnelToken: 'connector',
55
52
  ownerEmail: OWNER,
56
53
  };
57
- /** A tunnel still behind Cloudflare Access. */
54
+ /** remote.json of a tunnel from before the gate: its Access fields mean nothing now. */
58
55
  const ACCESS_STATE = {
59
56
  ...GATE_STATE,
60
57
  accessTeamDomain: 'team.cloudflareaccess.com',
@@ -83,7 +80,6 @@ afterAll(() => {
83
80
  });
84
81
  beforeEach(() => {
85
82
  mockedLoad.mockReset().mockReturnValue(null);
86
- mockedVerifyAccess.mockReset().mockResolvedValue(undefined);
87
83
  (0, originGuard_1.setExtraOriginsForTest)([]);
88
84
  });
89
85
  describe('remoteAuthFailure: who needs a credential', () => {
@@ -93,7 +89,6 @@ describe('remoteAuthFailure: who needs a credential', () => {
93
89
  expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host }, state)).toBeNull();
94
90
  }
95
91
  }
96
- expect(mockedVerifyAccess).not.toHaveBeenCalled();
97
92
  });
98
93
  it('does not take a lookalike Host for a local one', async () => {
99
94
  for (const host of ['localhost.evil.com', '127.0.0.1.evil.com:9998', '0.0.0.0.evil.com']) {
@@ -122,7 +117,7 @@ describe('remoteAuthFailure: edge tokens', () => {
122
117
  expect(await withToken(await edgeToken())).toBeNull();
123
118
  expect(await withToken(await edgeToken({ email: 'Owner@Repoburg.com' }))).toBeNull();
124
119
  });
125
- it('accepts it on a tunnel still behind Access too (the move is under way)', async () => {
120
+ it('accepts it with a remote.json from before the gate too', async () => {
126
121
  expect(await withToken(await edgeToken(), ACCESS_STATE)).toBeNull();
127
122
  });
128
123
  it('refuses a token without credentials, of another machine, owner, issuer or key, or expired', async () => {
@@ -148,21 +143,10 @@ describe('remoteAuthFailure: edge tokens', () => {
148
143
  it('asks to sign in when there is no credential at all', async () => {
149
144
  expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host: TUNNEL_HOST }, GATE_STATE)).toBe('Sign in to this machine first.');
150
145
  });
151
- it('does not take an Access JWT on a tunnel that moved to the gate', async () => {
146
+ it('takes no Cloudflare Access JWT, whatever remote.json says', async () => {
152
147
  const headers = { host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' };
153
148
  expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, GATE_STATE)).toBe('Sign in to this machine first.');
154
- expect(mockedVerifyAccess).not.toHaveBeenCalled();
155
- });
156
- });
157
- describe('remoteAuthFailure: Cloudflare Access (tunnels from before the gate)', () => {
158
- const headers = { host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' };
159
- it('accepts a valid Access JWT and pins the owner email', async () => {
160
- expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, ACCESS_STATE)).toBeNull();
161
- expect(mockedVerifyAccess).toHaveBeenCalledWith('jwt', { teamDomain: 'team.cloudflareaccess.com', aud: 'aud-tag' }, { ownerEmail: OWNER });
162
- });
163
- it('rejects an invalid one, or one for the wrong email (email pinning)', async () => {
164
- mockedVerifyAccess.mockRejectedValue(new Error('Access token email does not match the machine owner'));
165
- expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, ACCESS_STATE)).toBe('Invalid or expired Cloudflare Access token.');
149
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, ACCESS_STATE)).toBe('Sign in to this machine first.');
166
150
  });
167
151
  });
168
152
  describe('checkRemoteAuth (HTTP, every route)', () => {
@@ -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 {