runwork 0.10.1 → 0.10.2

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,44 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { normalizeCloneArgs } from '../clone.js';
3
+ describe('normalizeCloneArgs', () => {
4
+ it('passes through both args unchanged when --app is not provided', () => {
5
+ expect(normalizeCloneArgs('app-id', 'C:/dir', undefined)).toEqual({
6
+ appId: 'app-id',
7
+ directory: 'C:/dir',
8
+ });
9
+ expect(normalizeCloneArgs('app-id', 'C:/dir', {})).toEqual({
10
+ appId: 'app-id',
11
+ directory: 'C:/dir',
12
+ });
13
+ });
14
+ it('passes through both args unchanged when --app is set but directory is also explicit', () => {
15
+ expect(normalizeCloneArgs('app-id', 'C:/dir', { app: 'foo' })).toEqual({ appId: 'app-id', directory: 'C:/dir' });
16
+ });
17
+ it('shifts the first positional to directory when --app is set and only one positional arg is present', () => {
18
+ // The reproducer from the field:
19
+ // runwork clone --app academic-grade-conversion C:\Users\Oytun\Desktop\agc-test
20
+ // commander binds rawAppId = "C:\Users\..." and rawDirectory = undefined.
21
+ expect(normalizeCloneArgs('C:\\Users\\Oytun\\Desktop\\agc-test', undefined, {
22
+ app: 'academic-grade-conversion',
23
+ })).toEqual({
24
+ appId: undefined,
25
+ directory: 'C:\\Users\\Oytun\\Desktop\\agc-test',
26
+ });
27
+ });
28
+ it('does not shift when --app is set and no positional args are provided', () => {
29
+ expect(normalizeCloneArgs(undefined, undefined, { app: 'foo' })).toEqual({
30
+ appId: undefined,
31
+ directory: undefined,
32
+ });
33
+ });
34
+ it('does not shift when --app is set with only the directory positional (rawAppId already undefined)', () => {
35
+ // commander binds positional arguments left-to-right; if only one is
36
+ // given, it's always rawAppId. So this case shouldn't arise in practice
37
+ // -- but if a future commander upgrade changes that, we should leave
38
+ // already-correct args alone.
39
+ expect(normalizeCloneArgs(undefined, 'C:/dir', { app: 'foo' })).toEqual({
40
+ appId: undefined,
41
+ directory: 'C:/dir',
42
+ });
43
+ });
44
+ });
@@ -10,4 +10,18 @@ export interface CloneResult {
10
10
  workspaceName: string;
11
11
  }
12
12
  export declare function execClone(client: ApiClient, app: AppInfo, directory?: string, creds?: Credentials | null): Promise<CloneResult>;
13
+ /**
14
+ * Reconcile positional args with --app. When --app is provided, the first
15
+ * positional argument is intended as the *directory* -- not another appId
16
+ * -- because the app is already disambiguated by the option. Without this,
17
+ * `runwork clone --app foo C:\path\to\dir` ends up parsing `C:\path\to\dir`
18
+ * as `appId` (which is then ignored because `--app` wins), leaving
19
+ * `directory` undefined and silently cloning into the slug under cwd.
20
+ */
21
+ export declare function normalizeCloneArgs(appId: string | undefined, directory: string | undefined, options: {
22
+ app?: string;
23
+ } | undefined): {
24
+ appId: string | undefined;
25
+ directory: string | undefined;
26
+ };
13
27
  export declare const cloneCommand: Command;
@@ -109,13 +109,28 @@ export async function execClone(client, app, directory, creds) {
109
109
  workspaceName: app.workspaceName,
110
110
  };
111
111
  }
112
+ /**
113
+ * Reconcile positional args with --app. When --app is provided, the first
114
+ * positional argument is intended as the *directory* -- not another appId
115
+ * -- because the app is already disambiguated by the option. Without this,
116
+ * `runwork clone --app foo C:\path\to\dir` ends up parsing `C:\path\to\dir`
117
+ * as `appId` (which is then ignored because `--app` wins), leaving
118
+ * `directory` undefined and silently cloning into the slug under cwd.
119
+ */
120
+ export function normalizeCloneArgs(appId, directory, options) {
121
+ if (options?.app && appId && !directory) {
122
+ return { appId: undefined, directory: appId };
123
+ }
124
+ return { appId, directory };
125
+ }
112
126
  export const cloneCommand = new Command('clone')
113
127
  .description('Clone a Runwork app to local development')
114
128
  .argument('[appId]', 'App ID to clone (interactive if omitted)')
115
129
  .argument('[directory]', 'Target directory')
116
130
  .option('--app <name-or-id>', 'App name or ID (skips interactive selection)')
117
- .action(async (appId, directory, options) => {
131
+ .action(async (rawAppId, rawDirectory, options) => {
118
132
  requireGit('clone');
133
+ const { appId, directory } = normalizeCloneArgs(rawAppId, rawDirectory, options);
119
134
  const creds = requireAuth();
120
135
  const client = new ApiClient(creds);
121
136
  const useJson = shouldOutputJson(undefined);
@@ -151,7 +166,10 @@ export const cloneCommand = new Command('clone')
151
166
  jsonOut(response);
152
167
  return;
153
168
  }
154
- console.log(`\nApp "${cloneResult.appName}" cloned to ${cloneResult.directory}/`);
169
+ // No trailing separator: cloneResult.directory is already an absolute
170
+ // path. Appending '/' here mixed with Windows '\' separators produced
171
+ // confusing output like `C:\Users\...\app/` on Windows.
172
+ console.log(`\nApp "${cloneResult.appName}" cloned to ${cloneResult.directory}`);
155
173
  console.log(`Remote: ${client.getGitRemoteUrl(cloneResult.workspaceId, cloneResult.appId)}`);
156
174
  await runAgentWizard(cloneResult.directory);
157
175
  console.log(`Next: cd ${cloneResult.slug} && runwork dev`);
@@ -1 +1 @@
1
- export declare const VERSION = "0.10.1";
1
+ export declare const VERSION = "0.10.2";
@@ -1,2 +1,2 @@
1
1
  // Auto-generated by scripts/embed-types.ts -- do not edit
2
- export const VERSION = "0.10.1";
2
+ export const VERSION = "0.10.2";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * End-to-end auth test.
3
+ *
4
+ * Spins up a tiny HTTP server that mimics the runwork.ai git endpoint's
5
+ * auth contract (HTTP Basic, any username, password = API key) and runs a
6
+ * real `git ls-remote` against it through a credential-helper script. This
7
+ * verifies the entire chain we depend on:
8
+ *
9
+ * git -> credential.<origin>.helper -> our helper script -> our helper's
10
+ * protocol output -> git constructs Basic auth -> server accepts it.
11
+ *
12
+ * Catches the class of bugs we've burned hours on (Pass 1's PATH issues,
13
+ * Pass 2's "logged in but no helper registered") *before* a user hits them.
14
+ *
15
+ * Note: this test exercises the contract our credential helper depends on,
16
+ * not the helper function itself -- credentials.test.ts already covers
17
+ * `handleGitCredentialRequest()` in isolation. Together they prove that
18
+ * (a) the helper produces the right protocol output and (b) git+server
19
+ * accept that output as Basic auth.
20
+ */
21
+ export {};
@@ -0,0 +1,195 @@
1
+ /**
2
+ * End-to-end auth test.
3
+ *
4
+ * Spins up a tiny HTTP server that mimics the runwork.ai git endpoint's
5
+ * auth contract (HTTP Basic, any username, password = API key) and runs a
6
+ * real `git ls-remote` against it through a credential-helper script. This
7
+ * verifies the entire chain we depend on:
8
+ *
9
+ * git -> credential.<origin>.helper -> our helper script -> our helper's
10
+ * protocol output -> git constructs Basic auth -> server accepts it.
11
+ *
12
+ * Catches the class of bugs we've burned hours on (Pass 1's PATH issues,
13
+ * Pass 2's "logged in but no helper registered") *before* a user hits them.
14
+ *
15
+ * Note: this test exercises the contract our credential helper depends on,
16
+ * not the helper function itself -- credentials.test.ts already covers
17
+ * `handleGitCredentialRequest()` in isolation. Together they prove that
18
+ * (a) the helper produces the right protocol output and (b) git+server
19
+ * accept that output as Basic auth.
20
+ */
21
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
22
+ import { execFile } from 'child_process';
23
+ import { promisify } from 'util';
24
+ import { mkdtempSync, writeFileSync, rmSync, chmodSync, existsSync } from 'fs';
25
+ import { join } from 'path';
26
+ import { tmpdir } from 'os';
27
+ import { createServer } from 'http';
28
+ import { probeGit } from '../preflight.js';
29
+ const execFileAsync = promisify(execFile);
30
+ const EXPECTED_API_KEY = 'test-api-key-abcd1234';
31
+ /**
32
+ * Minimal HTTP server that:
33
+ * - Returns 401 + WWW-Authenticate when no Basic auth is supplied
34
+ * - Returns 401 when password (the API key) is wrong; username is ignored
35
+ * - Returns 200 + a valid empty-refs pkt-line response when auth is correct
36
+ *
37
+ * The pkt-line response is the smallest valid output for `info/refs?
38
+ * service=git-upload-pack` -- the service announcement plus a flush packet.
39
+ * That's enough for `git ls-remote` to terminate successfully.
40
+ */
41
+ function createBasicAuthGitServer(attempts) {
42
+ return new Promise((resolve) => {
43
+ const server = createServer((req, res) => {
44
+ const authHeader = req.headers['authorization'];
45
+ if (!authHeader || !authHeader.startsWith('Basic ')) {
46
+ attempts.push({ hasAuthHeader: false });
47
+ res.writeHead(401, {
48
+ 'WWW-Authenticate': 'Basic realm="Test"',
49
+ 'Content-Type': 'text/plain',
50
+ });
51
+ res.end('Authentication required');
52
+ return;
53
+ }
54
+ const decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf-8');
55
+ const colonIdx = decoded.indexOf(':');
56
+ const username = colonIdx >= 0 ? decoded.slice(0, colonIdx) : decoded;
57
+ const password = colonIdx >= 0 ? decoded.slice(colonIdx + 1) : '';
58
+ attempts.push({ hasAuthHeader: true, username, password });
59
+ if (password !== EXPECTED_API_KEY) {
60
+ res.writeHead(401, {
61
+ 'WWW-Authenticate': 'Basic realm="Test"',
62
+ 'Content-Type': 'text/plain',
63
+ });
64
+ res.end('Invalid API key');
65
+ return;
66
+ }
67
+ // Minimal valid info/refs response for git-upload-pack with no refs.
68
+ // Shape:
69
+ // 001e# service=git-upload-pack\n
70
+ // 0000
71
+ // 0000 (no refs)
72
+ const service = '# service=git-upload-pack\n';
73
+ const pktServiceLength = (service.length + 4).toString(16).padStart(4, '0');
74
+ const flush = '0000';
75
+ const body = `${pktServiceLength}${service}${flush}${flush}`;
76
+ res.writeHead(200, {
77
+ 'Content-Type': 'application/x-git-upload-pack-advertisement',
78
+ 'Cache-Control': 'no-cache',
79
+ });
80
+ res.end(body);
81
+ });
82
+ server.listen(0, '127.0.0.1', () => resolve(server));
83
+ });
84
+ }
85
+ /**
86
+ * Write a credential helper script into `dir` and return its path. The
87
+ * script ignores stdin (test fixtures don't need to honour git's
88
+ * action/host inputs) and prints the test's API key. Bash on macOS/Linux
89
+ * and Git Bash on Windows both run the resulting `!"<path>"` invocation
90
+ * the same way.
91
+ */
92
+ function writeHelperScript(dir, apiKey) {
93
+ const scriptPath = join(dir, 'fake-helper.sh');
94
+ const body = [
95
+ '#!/usr/bin/env bash',
96
+ '# Test fixture: emits the git credential helper "get" protocol output',
97
+ '# with a hardcoded API key. The "get" arg is the only one git invokes',
98
+ '# during a fetch; "store"/"erase" are no-ops.',
99
+ 'if [ "$1" != "get" ]; then exit 0; fi',
100
+ '# Drain stdin so git\'s pipe doesn\'t stall.',
101
+ 'cat > /dev/null',
102
+ 'echo "username=runwork"',
103
+ `echo "password=${apiKey}"`,
104
+ '',
105
+ ].join('\n');
106
+ writeFileSync(scriptPath, body, { mode: 0o755 });
107
+ // chmod is no-op on Windows but won't error.
108
+ chmodSync(scriptPath, 0o755);
109
+ return scriptPath;
110
+ }
111
+ describe('git credential helper e2e (Basic auth contract)', () => {
112
+ const gitProbe = probeGit();
113
+ const skipReason = !gitProbe.installed ? 'git not installed' : null;
114
+ let tmpDir;
115
+ let homeDir;
116
+ let xdgConfigHome;
117
+ let scriptPath;
118
+ let server;
119
+ let serverUrl;
120
+ let attempts = [];
121
+ beforeAll(async () => {
122
+ if (skipReason)
123
+ return;
124
+ tmpDir = mkdtempSync(join(tmpdir(), 'runwork-helper-e2e-'));
125
+ homeDir = join(tmpDir, 'home');
126
+ xdgConfigHome = join(homeDir, '.config');
127
+ // git -c gc.auto=0 needs ~/.gitconfig to exist when GIT_CONFIG_GLOBAL is
128
+ // pointed at a path that doesn't yet exist; pre-create the dir and
129
+ // empty file.
130
+ const gitConfigGlobal = join(homeDir, '.gitconfig');
131
+ require('fs').mkdirSync(homeDir, { recursive: true });
132
+ writeFileSync(gitConfigGlobal, '');
133
+ scriptPath = writeHelperScript(tmpDir, EXPECTED_API_KEY);
134
+ server = await createBasicAuthGitServer(attempts);
135
+ const addr = server.address();
136
+ serverUrl = `http://127.0.0.1:${addr.port}`;
137
+ // Register the credential helper globally in the isolated git config.
138
+ // We use the unscoped `credential.helper` (not `credential.<url>.helper`)
139
+ // because (a) the test config is fully isolated so we don't risk
140
+ // bleeding into other host auth flows and (b) git's URL matching for
141
+ // scoped helpers has subtleties that aren't what we're testing here --
142
+ // we're testing the helper *contract*, not git's URL matcher.
143
+ const gitBin = gitProbe.path ?? 'git';
144
+ await execFileAsync(gitBin, [
145
+ 'config', '--file', gitConfigGlobal,
146
+ 'credential.helper', `!"${scriptPath}"`,
147
+ ]);
148
+ });
149
+ afterAll(() => {
150
+ if (server)
151
+ server.close();
152
+ if (tmpDir && existsSync(tmpDir))
153
+ rmSync(tmpDir, { recursive: true, force: true });
154
+ });
155
+ it.skipIf(skipReason)('git ls-remote authenticates via the credential helper end-to-end', async () => {
156
+ const gitBin = gitProbe.path ?? 'git';
157
+ // Use GIT_CONFIG_GLOBAL to isolate from the user's real ~/.gitconfig
158
+ // (which may have an auth helper registered for some other host).
159
+ const env = {
160
+ ...process.env,
161
+ GIT_CONFIG_GLOBAL: join(homeDir, '.gitconfig'),
162
+ GIT_CONFIG_SYSTEM: '/dev/null',
163
+ XDG_CONFIG_HOME: xdgConfigHome,
164
+ HOME: homeDir,
165
+ // Force git to never prompt -- if the helper fails, we want the
166
+ // command to exit non-zero, not hang.
167
+ GIT_TERMINAL_PROMPT: '0',
168
+ };
169
+ const path = '/test-workspace/test-app';
170
+ const url = `${serverUrl}${path}`;
171
+ // ls-remote against the fake server. Should exit 0 (server accepted
172
+ // auth and returned a valid -- empty -- ref advertisement).
173
+ const result = await execFileAsync(gitBin, ['ls-remote', url], { env });
174
+ expect(result.stdout).toBe('');
175
+ // No refs in the test response, so stdout is empty.
176
+ // Verify the server actually saw a Basic-auth attempt with our key.
177
+ const successAttempt = attempts.find((a) => a.hasAuthHeader && a.password === EXPECTED_API_KEY);
178
+ expect(successAttempt).toBeDefined();
179
+ expect(successAttempt.username).toBe('runwork');
180
+ }, 20_000);
181
+ it.skipIf(skipReason)('server rejects requests with no auth (sanity: contract is enforced)', async () => {
182
+ // Direct fetch with no Authorization header should 401.
183
+ const response = await fetch(`${serverUrl}/whatever`);
184
+ expect(response.status).toBe(401);
185
+ expect(response.headers.get('www-authenticate')).toContain('Basic');
186
+ });
187
+ it.skipIf(skipReason)('server rejects requests with the wrong API key (sanity: contract is enforced)', async () => {
188
+ const response = await fetch(`${serverUrl}/whatever`, {
189
+ headers: {
190
+ authorization: `Basic ${Buffer.from('runwork:wrong-key').toString('base64')}`,
191
+ },
192
+ });
193
+ expect(response.status).toBe(401);
194
+ });
195
+ });
@@ -5,38 +5,51 @@ vi.mock('../../auth/store.js', () => ({
5
5
  }));
6
6
  const mockExecFileSync = (await import('child_process')).execFileSync;
7
7
  const { getCredentials: mockGetCredentials } = await import('../../auth/store.js');
8
- const { configureGitCredentials, removeGitCredentials, handleGitCredentialRequest, } = await import('../credentials.js');
8
+ const { configureGitCredentials, removeGitCredentials, handleGitCredentialRequest, buildHelperValue, } = await import('../credentials.js');
9
9
  describe('git/credentials', () => {
10
10
  beforeEach(() => {
11
11
  vi.clearAllMocks();
12
12
  });
13
+ describe('buildHelperValue()', () => {
14
+ it('wraps the execPath in quotes and prefixes with !', () => {
15
+ expect(buildHelperValue('/usr/local/bin/runwork')).toBe('!"/usr/local/bin/runwork" git-credential-helper');
16
+ });
17
+ it('normalises Windows backslashes to forward slashes for .gitconfig safety', () => {
18
+ expect(buildHelperValue('C:\\Users\\test\\.runwork\\bin\\runwork.exe')).toBe('!"C:/Users/test/.runwork/bin/runwork.exe" git-credential-helper');
19
+ });
20
+ it('survives spaces in install paths via quoting', () => {
21
+ expect(buildHelperValue('C:\\Program Files\\Runwork\\runwork.exe')).toBe('!"C:/Program Files/Runwork/runwork.exe" git-credential-helper');
22
+ });
23
+ });
13
24
  describe('configureGitCredentials()', () => {
14
- it('calls git config with correct args', async () => {
25
+ it('registers the helper using process.execPath, not bare "runwork"', async () => {
15
26
  await configureGitCredentials('https://runwork.ai/api/git/ws/app');
16
- expect(mockExecFileSync).toHaveBeenCalledWith('git', [
17
- 'config',
18
- '--global',
19
- 'credential.https://runwork.ai.helper',
20
- '!runwork git-credential-helper',
21
- ], { stdio: 'pipe' });
27
+ // Don't pin process.execPath itself (varies per machine), but
28
+ // assert the value follows the absolute-path shape so PATH-relative
29
+ // regressions are caught.
30
+ const call = mockExecFileSync.mock.calls.find((c) => c[0] === 'git' && c[1]?.includes('--global'));
31
+ expect(call).toBeDefined();
32
+ const args = call[1];
33
+ expect(args).toContain('config');
34
+ expect(args).toContain('--global');
35
+ expect(args).toContain('credential.https://runwork.ai.helper');
36
+ const helperValue = args[args.length - 1];
37
+ expect(helperValue).toMatch(/^!"[^"]+" git-credential-helper$/);
38
+ expect(helperValue).not.toBe('!runwork git-credential-helper');
39
+ // The path inside the quotes should be process.execPath, normalised.
40
+ expect(helperValue).toContain(process.execPath.replace(/\\/g, '/'));
22
41
  });
23
42
  it('extracts origin from full URL', async () => {
24
43
  await configureGitCredentials('https://custom.runwork.dev/api/git/ws-1/app-1');
25
- expect(mockExecFileSync).toHaveBeenCalledWith('git', [
26
- 'config',
27
- '--global',
28
- 'credential.https://custom.runwork.dev.helper',
29
- '!runwork git-credential-helper',
30
- ], { stdio: 'pipe' });
44
+ const call = mockExecFileSync.mock.calls[0];
45
+ const args = call[1];
46
+ expect(args[2]).toBe('credential.https://custom.runwork.dev.helper');
31
47
  });
32
48
  it('handles URL with port', async () => {
33
49
  await configureGitCredentials('https://localhost:8787/api/git/ws/app');
34
- expect(mockExecFileSync).toHaveBeenCalledWith('git', [
35
- 'config',
36
- '--global',
37
- 'credential.https://localhost:8787.helper',
38
- '!runwork git-credential-helper',
39
- ], { stdio: 'pipe' });
50
+ const call = mockExecFileSync.mock.calls[0];
51
+ const args = call[1];
52
+ expect(args[2]).toBe('credential.https://localhost:8787.helper');
40
53
  });
41
54
  });
42
55
  describe('removeGitCredentials()', () => {
@@ -0,0 +1 @@
1
+ export {};