repoburg 1.3.310 → 1.3.312

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.
@@ -1,156 +1,194 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ const jose = __importStar(require("jose"));
3
37
  const checkRemoteAuth_1 = require("./checkRemoteAuth");
38
+ const originGuard_1 = require("./originGuard");
4
39
  const tunnel_state_1 = require("../remote/tunnel-state");
5
- const access_jwt_1 = require("../remote/access-jwt");
6
40
  jest.mock('../remote/tunnel-state');
7
- jest.mock('../remote/access-jwt');
8
41
  const mockedLoad = tunnel_state_1.loadTunnelState;
9
- const mockedVerify = access_jwt_1.verifyAccessJwt;
10
42
  /** Requests THROUGH THE TUNNEL carry the machine hostname as Host. */
11
- const TUNNEL_HOST = 'zztest.repoburg.com:443';
12
- /** Fully provisioned state (Access + pinned owner email). */
13
- const PINNED_STATE = {
43
+ const HOSTNAME = 'zztest.repoburg.com';
44
+ const TUNNEL_HOST = `${HOSTNAME}:443`;
45
+ const OWNER = 'owner@repoburg.com';
46
+ /** A tunnel behind the edge gate. */
47
+ const GATE_STATE = {
48
+ mahlas: 'zztest',
49
+ hostname: HOSTNAME,
50
+ accountTunnelId: 'tunnel-id',
51
+ tunnelToken: 'connector',
52
+ ownerEmail: OWNER,
53
+ };
54
+ /** remote.json of a tunnel from before the gate: its Access fields mean nothing now. */
55
+ const ACCESS_STATE = {
56
+ ...GATE_STATE,
14
57
  accessTeamDomain: 'team.cloudflareaccess.com',
15
58
  accessAud: 'aud-tag',
16
- ownerEmail: 'owner@repoburg.com',
17
- };
18
- const makeRes = () => {
19
- const res = { status: jest.fn(), json: jest.fn() };
20
- res.status.mockReturnValue(res);
21
- return res;
22
59
  };
23
- const makeReq = (headers) => ({ headers });
60
+ let signingKey;
61
+ /** An edge token as the account server's gate signs it. */
62
+ async function edgeToken(claims = {}, key = signingKey) {
63
+ const jwt = new jose.SignJWT({ email: claims.email ?? OWNER })
64
+ .setProtectedHeader({ alg: 'EdDSA' })
65
+ .setIssuedAt()
66
+ .setIssuer(claims.iss ?? 'repoburg.com')
67
+ .setAudience(claims.aud ?? `tunnel:${HOSTNAME}`)
68
+ .setExpirationTime(claims.exp ?? '5m');
69
+ if (claims.sub !== '')
70
+ jwt.setSubject(claims.sub ?? 'user-id');
71
+ return jwt.sign(key);
72
+ }
73
+ beforeAll(async () => {
74
+ const pair = await jose.generateKeyPair('EdDSA', { extractable: true });
75
+ signingKey = pair.privateKey;
76
+ process.env.REPOBURG_EDGE_PUBLIC_KEY = await jose.exportSPKI(pair.publicKey);
77
+ });
78
+ afterAll(() => {
79
+ delete process.env.REPOBURG_EDGE_PUBLIC_KEY;
80
+ });
24
81
  beforeEach(() => {
25
82
  mockedLoad.mockReset().mockReturnValue(null);
26
- mockedVerify.mockReset().mockResolvedValue(undefined);
83
+ (0, originGuard_1.setExtraOriginsForTest)([]);
27
84
  });
28
- describe('checkRemoteAuth (HTTP)', () => {
29
- it('passes through when no tunnel state exists (local usage)', async () => {
30
- const next = jest.fn();
31
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: 'localhost:9998' }), makeRes(), next);
32
- expect(next).toHaveBeenCalled();
33
- });
34
- it('passes through when Access is not configured yet', async () => {
35
- mockedLoad.mockReturnValue({ accessTeamDomain: undefined, accessAud: undefined });
36
- const next = jest.fn();
37
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST }), makeRes(), next);
38
- expect(next).toHaveBeenCalled();
39
- });
40
- it('passes local requests even when Access is configured (local pane + agent.repoburg.com FE)', async () => {
41
- mockedLoad.mockReturnValue(PINNED_STATE);
42
- for (const host of ['localhost:9998', '127.0.0.1:9998', '0.0.0.0:9998']) {
43
- const next = jest.fn();
44
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host }), makeRes(), next);
45
- expect(next).toHaveBeenCalledWith();
85
+ describe('remoteAuthFailure: who needs a credential', () => {
86
+ it('lets local requests through, whatever the tunnel state', async () => {
87
+ for (const state of [null, GATE_STATE, ACCESS_STATE]) {
88
+ for (const host of ['localhost:9998', '127.0.0.1:9998', '0.0.0.0:9998', undefined]) {
89
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host }, state)).toBeNull();
90
+ }
46
91
  }
47
- expect(mockedVerify).not.toHaveBeenCalled();
48
92
  });
49
93
  it('does not take a lookalike Host for a local one', async () => {
50
- mockedLoad.mockReturnValue(PINNED_STATE);
51
94
  for (const host of ['localhost.evil.com', '127.0.0.1.evil.com:9998', '0.0.0.0.evil.com']) {
52
- const res = makeRes();
53
- const next = jest.fn();
54
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host }), res, next);
55
- expect(res.status).toHaveBeenCalledWith(401);
56
- expect(next).not.toHaveBeenCalled();
95
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host }, GATE_STATE)).not.toBeNull();
57
96
  }
58
97
  });
59
- it('requires an Access assertion for tunnel-host requests when configured', async () => {
60
- mockedLoad.mockReturnValue(PINNED_STATE);
61
- const res = makeRes();
62
- const next = jest.fn();
63
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST }), res, next);
64
- expect(res.status).toHaveBeenCalledWith(401);
65
- expect(next).not.toHaveBeenCalled();
98
+ it('fails closed on tunnel traffic with no tunnel, or for another hostname', async () => {
99
+ const token = await edgeToken();
100
+ const headers = { host: TUNNEL_HOST, 'x-repoburg-edge-auth': token };
101
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, null)).toBe('This machine has no tunnel at this address.');
102
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ ...headers, host: 'other.repoburg.com' }, GATE_STATE)).toBe('This machine has no tunnel at this address.');
66
103
  });
67
- it('FAILS CLOSED when Access is configured but no owner email is pinned (pre-pinning state)', async () => {
68
- mockedLoad.mockReturnValue({ accessTeamDomain: 'team.cloudflareaccess.com', accessAud: 'aud-tag' });
69
- const res = makeRes();
70
- const next = jest.fn();
71
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' }), res, next);
72
- expect(res.status).toHaveBeenCalledWith(401);
73
- expect(mockedVerify).not.toHaveBeenCalled();
74
- expect(next).not.toHaveBeenCalled();
104
+ it('fails closed without a pinned owner email', async () => {
105
+ const headers = { host: TUNNEL_HOST, 'x-repoburg-edge-auth': await edgeToken() };
106
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, { ...GATE_STATE, ownerEmail: undefined })).toBe('Tunnel owner email is missing — re-provision this machine.');
75
107
  });
76
- it('accepts a valid Access JWT and pins the owner email', async () => {
77
- mockedLoad.mockReturnValue(PINNED_STATE);
78
- const next = jest.fn();
79
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' }), makeRes(), next);
80
- expect(mockedVerify).toHaveBeenCalledWith('jwt', { teamDomain: 'team.cloudflareaccess.com', aud: 'aud-tag' }, { ownerEmail: 'owner@repoburg.com' });
81
- expect(next).toHaveBeenCalled();
108
+ it('lets the owner’s own proxy host through (REPOBURG_ALLOWED_ORIGINS), but never a tunnel host', async () => {
109
+ (0, originGuard_1.setExtraOriginsForTest)(['https://pane.example.org', `https://${HOSTNAME}`]);
110
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host: 'pane.example.org' }, null)).toBeNull();
111
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host: TUNNEL_HOST }, GATE_STATE)).toBe('Sign in to this machine first.');
82
112
  });
83
- it('rejects a valid-signature JWT for the WRONG email with 401 (email pinning)', async () => {
84
- mockedLoad.mockReturnValue(PINNED_STATE);
85
- // Simulates a policy edited by a compromised account-server: CF signed
86
- // the token, but common_name is the attacker's email.
87
- mockedVerify.mockRejectedValue(new Error('Access token email does not match the machine owner'));
88
- const res = makeRes();
89
- const next = jest.fn();
90
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' }), res, next);
91
- expect(res.status).toHaveBeenCalledWith(401);
92
- expect(next).not.toHaveBeenCalled();
113
+ });
114
+ describe('remoteAuthFailure: edge tokens', () => {
115
+ const withToken = async (token, state = GATE_STATE) => (0, checkRemoteAuth_1.remoteAuthFailure)({ host: TUNNEL_HOST, 'x-repoburg-edge-auth': token }, state);
116
+ it('accepts the gate’s token for this hostname and the owner', async () => {
117
+ expect(await withToken(await edgeToken())).toBeNull();
118
+ expect(await withToken(await edgeToken({ email: 'Owner@Repoburg.com' }))).toBeNull();
119
+ });
120
+ it('accepts it with a remote.json from before the gate too', async () => {
121
+ expect(await withToken(await edgeToken(), ACCESS_STATE)).toBeNull();
122
+ });
123
+ it('refuses a token without credentials, of another machine, owner, issuer or key, or expired', async () => {
124
+ const other = await jose.generateKeyPair('EdDSA');
125
+ const bad = [
126
+ await edgeToken({ aud: 'tunnel:other.repoburg.com' }),
127
+ await edgeToken({ aud: 'repoburg-daemon' }), // a device token is no edge token
128
+ await edgeToken({ email: 'hacker@evil.com' }),
129
+ await edgeToken({ iss: 'evil.com' }),
130
+ await edgeToken({ exp: Math.floor(Date.now() / 1000) - 600 }),
131
+ await edgeToken({ sub: '' }),
132
+ await edgeToken({}, other.privateKey),
133
+ 'not-a-jwt',
134
+ ];
135
+ for (const token of bad) {
136
+ expect(await withToken(token)).toBe('Invalid or expired sign-in token.');
137
+ }
93
138
  });
94
- it('rejects an invalid Access JWT with 401', async () => {
95
- mockedLoad.mockReturnValue(PINNED_STATE);
96
- mockedVerify.mockRejectedValue(new Error('bad token'));
139
+ it('tolerates a machine clock a minute off', async () => {
140
+ const token = await edgeToken({ exp: Math.floor(Date.now() / 1000) - 60 });
141
+ expect(await withToken(token)).toBeNull();
142
+ });
143
+ it('asks to sign in when there is no credential at all', async () => {
144
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)({ host: TUNNEL_HOST }, GATE_STATE)).toBe('Sign in to this machine first.');
145
+ });
146
+ it('takes no Cloudflare Access JWT, whatever remote.json says', async () => {
147
+ const headers = { host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' };
148
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, GATE_STATE)).toBe('Sign in to this machine first.');
149
+ expect(await (0, checkRemoteAuth_1.remoteAuthFailure)(headers, ACCESS_STATE)).toBe('Sign in to this machine first.');
150
+ });
151
+ });
152
+ describe('checkRemoteAuth (HTTP, every route)', () => {
153
+ const makeRes = () => {
154
+ const res = { status: jest.fn(), json: jest.fn() };
155
+ res.status.mockReturnValue(res);
156
+ return res;
157
+ };
158
+ const makeReq = (headers) => ({ headers });
159
+ it('answers 401 with the reason and runs no route', async () => {
160
+ mockedLoad.mockReturnValue(GATE_STATE);
97
161
  const res = makeRes();
98
162
  const next = jest.fn();
99
- await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' }), res, next);
163
+ await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq({ host: TUNNEL_HOST }), res, next);
100
164
  expect(res.status).toHaveBeenCalledWith(401);
165
+ expect(res.json).toHaveBeenCalledWith({ error: 'Sign in to this machine first.' });
101
166
  expect(next).not.toHaveBeenCalled();
102
167
  });
103
- });
104
- describe('checkRemoteWsAuth (WebSocket upgrade)', () => {
105
- it('allows everything when Access is not configured', async () => {
106
- mockedLoad.mockReturnValue(null);
107
- await expect((0, checkRemoteAuth_1.checkRemoteWsAuth)(makeReq({ host: 'localhost:9998' }))).resolves.toBe(true);
108
- });
109
- it('allows local upgrades even when configured', async () => {
110
- mockedLoad.mockReturnValue(PINNED_STATE);
111
- await expect((0, checkRemoteAuth_1.checkRemoteWsAuth)(makeReq({ host: 'localhost:9998' }))).resolves.toBe(true);
112
- expect(mockedVerify).not.toHaveBeenCalled();
113
- });
114
- it('denies tunnel-host upgrades without an assertion when configured', async () => {
115
- mockedLoad.mockReturnValue(PINNED_STATE);
116
- await expect((0, checkRemoteAuth_1.checkRemoteWsAuth)(makeReq({ host: TUNNEL_HOST }))).resolves.toBe(false);
117
- });
118
- it('fails closed when configured without a pinned owner email', async () => {
119
- mockedLoad.mockReturnValue({ accessTeamDomain: 'team.cloudflareaccess.com', accessAud: 'aud' });
120
- await expect((0, checkRemoteAuth_1.checkRemoteWsAuth)(makeReq({ host: TUNNEL_HOST }))).resolves.toBe(false);
121
- });
122
- it('allows tunnel-host upgrades with a valid assertion and pins the owner email', async () => {
123
- mockedLoad.mockReturnValue(PINNED_STATE);
124
- await expect((0, checkRemoteAuth_1.checkRemoteWsAuth)(makeReq({ host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'jwt' }))).resolves.toBe(true);
125
- expect(mockedVerify).toHaveBeenCalledWith('jwt', { teamDomain: 'team.cloudflareaccess.com', aud: 'aud-tag' }, { ownerEmail: 'owner@repoburg.com' });
168
+ it('runs the route for the owner’s edge token and for local requests', async () => {
169
+ mockedLoad.mockReturnValue(GATE_STATE);
170
+ const requests = [
171
+ { host: TUNNEL_HOST, 'x-repoburg-edge-auth': await edgeToken() },
172
+ { host: 'localhost:9998' },
173
+ ];
174
+ for (const headers of requests) {
175
+ const next = jest.fn();
176
+ await (0, checkRemoteAuth_1.checkRemoteAuth)(makeReq(headers), makeRes(), next);
177
+ expect(next).toHaveBeenCalledWith();
178
+ }
126
179
  });
127
180
  });
128
- describe('checkTerminalWsAuth (a shell over WebSocket)', () => {
181
+ describe('checkRemoteWsAuth (every WebSocket upgrade, the shell included)', () => {
129
182
  const upgrade = (headers) => ({ headers });
130
- it('lets a request on this machine through, with or without Access', async () => {
131
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: 'localhost:9998' }))).toBe(true);
132
- mockedLoad.mockReturnValue(PINNED_STATE);
133
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: '127.0.0.1:9998' }))).toBe(true);
134
- expect(mockedVerify).not.toHaveBeenCalled();
135
- });
136
- it('never gives the tunnel a shell without Access, even when nothing is configured', async () => {
137
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
138
- mockedLoad.mockReturnValue({ accessTeamDomain: undefined, accessAud: undefined });
139
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
140
- mockedLoad.mockReturnValue({ accessTeamDomain: 'team.cloudflareaccess.com' });
141
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
142
- });
143
- it('refuses the tunnel without a valid Access token', async () => {
144
- mockedLoad.mockReturnValue(PINNED_STATE);
145
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
146
- mockedVerify.mockRejectedValue(new Error('bad signature'));
147
- const forged = { host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'forged' };
148
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade(forged))).toBe(false);
149
- });
150
- it('lets the owner through the tunnel with a valid Access token', async () => {
151
- mockedLoad.mockReturnValue(PINNED_STATE);
152
- mockedVerify.mockResolvedValue({ email: PINNED_STATE.ownerEmail });
153
- const headers = { host: TUNNEL_HOST, 'cf-access-jwt-assertion': 'valid' };
154
- expect(await (0, checkRemoteAuth_1.checkTerminalWsAuth)(upgrade(headers))).toBe(true);
183
+ it('never gives the tunnel a socket without a credential, even when nothing is configured', async () => {
184
+ expect(await (0, checkRemoteAuth_1.checkRemoteWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
185
+ mockedLoad.mockReturnValue(GATE_STATE);
186
+ expect(await (0, checkRemoteAuth_1.checkRemoteWsAuth)(upgrade({ host: TUNNEL_HOST }))).toBe(false);
187
+ expect(await (0, checkRemoteAuth_1.checkRemoteWsAuth)(upgrade({ host: TUNNEL_HOST, 'x-repoburg-edge-auth': 'forged' }))).toBe(false);
188
+ });
189
+ it('lets the owner through the tunnel, and local upgrades', async () => {
190
+ mockedLoad.mockReturnValue(GATE_STATE);
191
+ expect(await (0, checkRemoteAuth_1.checkRemoteWsAuth)(upgrade({ host: TUNNEL_HOST, 'x-repoburg-edge-auth': await edgeToken() }))).toBe(true);
192
+ expect(await (0, checkRemoteAuth_1.checkRemoteWsAuth)(upgrade({ host: 'localhost:9998' }))).toBe(true);
155
193
  });
156
194
  });
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.corsOrigin = corsOrigin;
4
+ exports.setExtraOriginsForTest = setExtraOriginsForTest;
5
+ /**
6
+ * CORS origin allowlist for the daemon.
7
+ *
8
+ * Spec: the daemon serves the embedded agent-pane to local tooling
9
+ * (vite dev servers, daemon-desktop) and, once a tunnel is provisioned, to
10
+ * `*.repoburg.com` machine hostnames. Everything else is rejected — the
11
+ * previous `origin: '*'` with `credentials: true` is an open API surface.
12
+ *
13
+ * Allowed:
14
+ * - no Origin header (same-origin / non-browser clients such as curl)
15
+ * - http://localhost:<any> and http://127.0.0.1:<any>
16
+ * - https://<anything>.repoburg.com (tunnel machine hostnames)
17
+ * - extra origins from REPOBURG_ALLOWED_ORIGINS (comma-separated)
18
+ */
19
+ const REPORG_HOSTNAME_SUFFIX = '.repoburg.com';
20
+ const extraOrigins = (process.env.REPOBURG_ALLOWED_ORIGINS ?? '')
21
+ .split(',')
22
+ .map((value) => value.trim())
23
+ .filter(Boolean);
24
+ function isLocalOrigin(origin) {
25
+ return (origin.protocol === 'http:' &&
26
+ (origin.hostname === 'localhost' || origin.hostname === '127.0.0.1'));
27
+ }
28
+ function isTunnelOrigin(origin) {
29
+ return origin.protocol === 'https:' && origin.hostname.endsWith(REPORG_HOSTNAME_SUFFIX);
30
+ }
31
+ /** CORS origin callback. `false` = do not emit CORS headers for this origin. */
32
+ function corsOrigin(origin, callback) {
33
+ // Same-origin requests and non-browser clients send no Origin header.
34
+ if (origin === undefined) {
35
+ callback(null, true);
36
+ return;
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = new URL(origin);
41
+ }
42
+ catch {
43
+ callback(null, false);
44
+ return;
45
+ }
46
+ const allowed = isLocalOrigin(parsed) || isTunnelOrigin(parsed) || extraOrigins.includes(origin);
47
+ callback(null, allowed);
48
+ }
49
+ /** Exposed for tests. */
50
+ function setExtraOriginsForTest(origins) {
51
+ extraOrigins.length = 0;
52
+ extraOrigins.push(...origins);
53
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const corsOrigin_1 = require("./corsOrigin");
4
+ function evaluate(origin) {
5
+ let result = false;
6
+ (0, corsOrigin_1.corsOrigin)(origin, (err, allow) => {
7
+ if (err)
8
+ throw err;
9
+ result = !!allow;
10
+ });
11
+ return result;
12
+ }
13
+ describe('corsOrigin', () => {
14
+ afterEach(() => (0, corsOrigin_1.setExtraOriginsForTest)([]));
15
+ it('allows requests without an Origin header (same-origin / curl)', () => {
16
+ expect(evaluate(undefined)).toBe(true);
17
+ });
18
+ it('allows localhost and 127.0.0.1 on any port', () => {
19
+ expect(evaluate('http://localhost:3000')).toBe(true);
20
+ expect(evaluate('http://localhost:9998')).toBe(true);
21
+ expect(evaluate('http://127.0.0.1:5173')).toBe(true);
22
+ });
23
+ it('allows tunnel machine hostnames under repoburg.com (https only)', () => {
24
+ expect(evaluate('https://workstation.repoburg.com')).toBe(true);
25
+ expect(evaluate('https://a-b.repoburg.com')).toBe(true);
26
+ });
27
+ it('rejects unknown origins', () => {
28
+ expect(evaluate('https://evil.example.com')).toBe(false);
29
+ expect(evaluate('http://evil.com')).toBe(false);
30
+ });
31
+ it('rejects repoburg.com hostnames over http (tunnels are https)', () => {
32
+ expect(evaluate('http://workstation.repoburg.com')).toBe(false);
33
+ });
34
+ it('rejects lookalike suffixes', () => {
35
+ expect(evaluate('https://workstation.repoburg.com.evil.com')).toBe(false);
36
+ expect(evaluate('https://evilrepoburg.com')).toBe(false);
37
+ });
38
+ it('rejects malformed origins', () => {
39
+ expect(evaluate('not a url')).toBe(false);
40
+ });
41
+ it('allows extra origins configured via env list', () => {
42
+ (0, corsOrigin_1.setExtraOriginsForTest)(['https://staging.example.com']);
43
+ expect(evaluate('https://staging.example.com')).toBe(true);
44
+ expect(evaluate('https://other.example.com')).toBe(false);
45
+ });
46
+ });
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.corsOptions = void 0;
4
+ exports.hostnameOf = hostnameOf;
4
5
  exports.isLoopbackHost = isLoopbackHost;
6
+ exports.isTunnelHost = isTunnelHost;
7
+ exports.isExtraOriginHost = isExtraOriginHost;
5
8
  exports.isAllowedRequest = isAllowedRequest;
6
9
  exports.originGuard = originGuard;
7
10
  exports.setExtraOriginsForTest = setExtraOriginsForTest;
@@ -54,6 +57,15 @@ function hostnameOf(host) {
54
57
  function isLoopbackHost(host) {
55
58
  return LOOPBACK_HOSTNAMES.has(hostnameOf(host) ?? '');
56
59
  }
60
+ /** A tunnel hostname (`<mahlas>.repoburg.com`): the request came through Cloudflare. */
61
+ function isTunnelHost(host) {
62
+ return (hostnameOf(host) ?? '').endsWith(TUNNEL_SUFFIX);
63
+ }
64
+ /** A host the owner trusts through REPOBURG_ALLOWED_ORIGINS (their own proxy). */
65
+ function isExtraOriginHost(host) {
66
+ const hostname = hostnameOf(host);
67
+ return hostname !== null && extraOrigins.some((origin) => parseUrl(origin)?.hostname === hostname);
68
+ }
57
69
  function isAllowedHost(host) {
58
70
  const hostname = hostnameOf(host);
59
71
  if (hostname === null)
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scheduleEdgeGateMove = scheduleEdgeGateMove;
4
+ /**
5
+ * Moves this machine's tunnel from Cloudflare Access to the account server's
6
+ * edge gate (MUH-108), in the background: soon after the daemon starts, then
7
+ * every few hours until it worked (no device token yet, account server
8
+ * unreachable). A tunnel without Access fields has nothing to move.
9
+ */
10
+ const provisioner_1 = require("./provisioner");
11
+ const FIRST_TRY_MS = 15000;
12
+ const RETRY_MS = 6 * 60 * 60 * 1000;
13
+ /** Starts the attempts; the returned function stops them. Timers never keep the process alive. */
14
+ function scheduleEdgeGateMove(deps = {}) {
15
+ const move = deps.move ?? (() => (0, provisioner_1.moveTunnelToEdgeGate)());
16
+ const log = deps.log ?? ((message) => console.log(message));
17
+ let timer = null;
18
+ let stopped = false;
19
+ const attempt = async () => {
20
+ try {
21
+ if (await move())
22
+ log('[remote] Tunnel moved from Cloudflare Access to the Repoburg sign-in gate.');
23
+ return; // moved, or nothing to move
24
+ }
25
+ catch (error) {
26
+ log(`[remote] Could not move the tunnel to the Repoburg sign-in gate yet: ${error.message}`);
27
+ }
28
+ if (!stopped) {
29
+ timer = setTimeout(() => void attempt(), deps.retryMs ?? RETRY_MS);
30
+ timer.unref();
31
+ }
32
+ };
33
+ timer = setTimeout(() => void attempt(), deps.firstTryMs ?? FIRST_TRY_MS);
34
+ timer.unref();
35
+ return () => {
36
+ stopped = true;
37
+ if (timer)
38
+ clearTimeout(timer);
39
+ };
40
+ }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const edge_gate_move_1 = require("./edge-gate-move");
4
+ jest.useFakeTimers();
5
+ const flush = async () => {
6
+ for (let i = 0; i < 5; i++)
7
+ await Promise.resolve();
8
+ };
9
+ describe('scheduleEdgeGateMove', () => {
10
+ it('tries soon after start and stops once moved or nothing to move', async () => {
11
+ const move = jest.fn(async () => true);
12
+ const log = jest.fn();
13
+ (0, edge_gate_move_1.scheduleEdgeGateMove)({ move, log, firstTryMs: 1000, retryMs: 5000 });
14
+ expect(move).not.toHaveBeenCalled();
15
+ await jest.advanceTimersByTimeAsync(1000);
16
+ expect(move).toHaveBeenCalledTimes(1);
17
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/moved from Cloudflare Access/));
18
+ await jest.advanceTimersByTimeAsync(20000);
19
+ expect(move).toHaveBeenCalledTimes(1);
20
+ });
21
+ it('tries again later while it fails, until it works', async () => {
22
+ const move = jest
23
+ .fn()
24
+ .mockRejectedValueOnce(new Error('Not logged in'))
25
+ .mockRejectedValueOnce(new Error('offline'))
26
+ .mockResolvedValue(true);
27
+ (0, edge_gate_move_1.scheduleEdgeGateMove)({ move, log: jest.fn(), firstTryMs: 1000, retryMs: 5000 });
28
+ await jest.advanceTimersByTimeAsync(1000);
29
+ await jest.advanceTimersByTimeAsync(5000);
30
+ await jest.advanceTimersByTimeAsync(5000);
31
+ await flush();
32
+ expect(move).toHaveBeenCalledTimes(3);
33
+ await jest.advanceTimersByTimeAsync(50000);
34
+ expect(move).toHaveBeenCalledTimes(3);
35
+ });
36
+ it('stops when told to', async () => {
37
+ const move = jest.fn().mockRejectedValue(new Error('offline'));
38
+ const stop = (0, edge_gate_move_1.scheduleEdgeGateMove)({ move, log: jest.fn(), firstTryMs: 1000, retryMs: 5000 });
39
+ await jest.advanceTimersByTimeAsync(1000);
40
+ stop();
41
+ await jest.advanceTimersByTimeAsync(50000);
42
+ expect(move).toHaveBeenCalledTimes(1);
43
+ });
44
+ });
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.EDGE_AUTH_HEADER = void 0;
37
+ exports.edgeAudience = edgeAudience;
38
+ exports.verifyEdgeJwt = verifyEdgeJwt;
39
+ /**
40
+ * Edge token verification for requests arriving through the tunnel.
41
+ *
42
+ * The account server's edge gate (account-server/src/edge/gate.ts) signs in
43
+ * the machine's owner with Google and adds a short-lived EdDSA JWT to every
44
+ * request it lets through, in the `X-Repoburg-Edge-Auth` header. It is signed
45
+ * with the account server's key, the one device tokens use (its public half
46
+ * is built into the daemon, PUBLIC_KEY), and differs from a device token in
47
+ * its audience: `tunnel:<hostname>`, the one machine it is for.
48
+ *
49
+ * Checked: signature, issuer, audience = this machine's hostname, expiry, and
50
+ * the signed `email` = the owner email pinned in remote.json.
51
+ */
52
+ const jose = __importStar(require("jose"));
53
+ const authManager_1 = require("../auth/authManager");
54
+ exports.EDGE_AUTH_HEADER = 'x-repoburg-edge-auth';
55
+ const ISSUER = 'repoburg.com';
56
+ /** Machines' clocks drift; the gate's tokens live five minutes. */
57
+ const CLOCK_TOLERANCE_SECONDS = 120;
58
+ function edgeAudience(hostname) {
59
+ return `tunnel:${hostname}`;
60
+ }
61
+ let builtInKey = null;
62
+ /** The verification key: the built-in one, or REPOBURG_EDGE_PUBLIC_KEY (a dev account server's). */
63
+ function verificationKey() {
64
+ const override = process.env.REPOBURG_EDGE_PUBLIC_KEY;
65
+ if (override)
66
+ return jose.importSPKI(override.replace(/\\n/g, '\n'), 'EdDSA');
67
+ builtInKey ?? (builtInKey = jose.importSPKI(authManager_1.PUBLIC_KEY, 'EdDSA'));
68
+ return builtInKey;
69
+ }
70
+ async function verifyEdgeJwt(token, options) {
71
+ const key = options.key ?? (await verificationKey());
72
+ const { payload } = await jose.jwtVerify(token, key, {
73
+ issuer: ISSUER,
74
+ audience: edgeAudience(options.hostname),
75
+ algorithms: ['EdDSA'],
76
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
77
+ requiredClaims: ['exp', 'sub'],
78
+ });
79
+ const email = typeof payload.email === 'string' ? payload.email : '';
80
+ if (email.toLowerCase() !== options.ownerEmail.toLowerCase()) {
81
+ throw new Error(`Edge token email does not match the machine owner (${email} !== ${options.ownerEmail}).`);
82
+ }
83
+ }
@@ -20,8 +20,6 @@ const STATE = {
20
20
  hostname: 'zz.repoburg.com',
21
21
  accountTunnelId: 'acc-1',
22
22
  tunnelToken: 'TUNNELSECRET',
23
- accessTeamDomain: 'team.cloudflareaccess.com',
24
- accessAud: 'aud',
25
23
  ownerEmail: 'o@x.com',
26
24
  installedAt: '2026-01-01T00:00:00Z',
27
25
  };