Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/npm-credentials-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@thatopen/services": minor
---

CLI: auto-configure `.npmrc` for private beta packages.

`thatopen create --beta` (and `thatopen login` inside a beta project) now fetch
read-only npm credentials from the platform and write a project `.npmrc`, so
`npm install` of the private `@thatopen-platform/*-beta` packages just works for
Founding members — no manual token setup. Adds
`EngineServicesClient.getNpmCredentials()` and exports the `NpmCredentials` type.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ To use beta engine libraries instead of the stable ones, see:

Once scaffolded, open `AGENTS.md` in the scaffolded project root — it has everything needed to start building.

## Beta engine libraries (Founding Members)

Founding Members get early access to the private beta engine libraries (`@thatopen-platform/*-beta`). The CLI configures access automatically — no npm account or manual token needed.

```bash
thatopen login --token <your-token> # API token from the dashboard → Data → API Tokens
thatopen create my-app --beta # new project on the beta libraries
# or, in an existing project:
thatopen swap --beta # toggle the current project to beta
```

On `--beta`, the CLI fetches your read-only beta npm credentials and writes them to the project's `.npmrc`, so `npm install` resolves the private packages. The `.npmrc` is gitignored — it carries a credential, so don't commit or share it. Access is tied to your membership; non-Founding accounts get a clear message and the project is still created.

## What's in this repository

- **Library** — `EngineServicesClient` and `PlatformClient` for interacting with the That Open API (files, folders, apps, cloud components, executions, permissions).
Expand Down
9 changes: 6 additions & 3 deletions src/cli/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { basename, join, resolve } from 'node:path';
import { execSync } from 'node:child_process';
import { updateLocalConfig } from '../lib/config';
import { BETA_ALIASES } from '../lib/beta';
import { configureBetaNpmrc } from '../lib/npmrc';

const TEMPLATES = ['app', 'cloud-component'] as const;
type Template = (typeof TEMPLATES)[number];
Expand Down Expand Up @@ -93,12 +94,14 @@ export const createCommand = new Command('create')
updateLocalConfig({ beta: true }, targetDir);
}

// ── Beta: authenticate private installs via .npmrc ───────────
if (opts.beta) {
await configureBetaNpmrc(targetDir);
}

// Install dependencies automatically
console.log('');
console.log('Installing dependencies...');
if (opts.beta) {
console.log('(Beta packages are private — if this fails with 401/403, configure your beta npm token.)');
}
try {
execSync('npm install', { cwd: targetDir, stdio: 'inherit' });
} catch {
Expand Down
15 changes: 13 additions & 2 deletions src/cli/commands/login.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Command } from 'commander';
import { writeConfig, updateLocalConfig } from '../lib/config';
import { writeConfig, updateLocalConfig, readLocalConfig } from '../lib/config';
import { EngineServicesClient } from '../../core/client';
import { setupNpmrc } from '../lib/npmrc';

export const loginCommand = new Command('login')
.description('Authenticate with the ThatOpen platform')
Expand Down Expand Up @@ -37,8 +38,9 @@ export const loginCommand = new Command('login')

console.log('Validating token...');

const client = new EngineServicesClient(opts.token, apiUrl);

try {
const client = new EngineServicesClient(opts.token, apiUrl);
await client.listApps();
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
Expand All @@ -56,4 +58,13 @@ export const loginCommand = new Command('login')
'Logged in successfully. Config saved to ~/.thatopen/config.json',
);
}

// In a beta project, refresh .npmrc so a rotated Founders token propagates
// on the next login. Best-effort — never blocks login.
if (readLocalConfig()?.beta) {
const result = await setupNpmrc(client, process.cwd());
if (result.status === 'written') {
console.log(`Beta access refreshed — updated .npmrc for ${result.scope}.`);
}
}
});
7 changes: 4 additions & 3 deletions src/cli/commands/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from 'node:path';
import { execSync } from 'node:child_process';
import { readLocalConfig, updateLocalConfig } from '../lib/config';
import { BETA_ALIASES } from '../lib/beta';
import { configureBetaNpmrc } from '../lib/npmrc';

export const swapCommand = new Command('swap')
.description('Toggle between stable public and beta engine libraries')
Expand Down Expand Up @@ -63,10 +64,10 @@ export const swapCommand = new Command('swap')
updateLocalConfig({ beta: targetBeta }, cwd);

console.log(`Switched to ${targetBeta ? 'beta' : 'stable'} libraries.`);

// Beta packages are private — write an authenticated .npmrc before install.
if (targetBeta) {
console.log(
'Beta packages are private — make sure your beta npm token is configured.',
);
await configureBetaNpmrc(cwd);
}

console.log('');
Expand Down
116 changes: 116 additions & 0 deletions src/cli/lib/npmrc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
mkdtempSync,
rmSync,
existsSync,
readFileSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setupNpmrc } from './npmrc';
import { RequestError } from '../../core/request-error';
import type { EngineServicesClient } from '../../core/client';

function fakeClient(getNpmCredentials: () => Promise<unknown>): EngineServicesClient {
return { getNpmCredentials } as unknown as EngineServicesClient;
}

describe('setupNpmrc', () => {
let dir: string;

beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'npmrc-test-'));
});

afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});

it('writes .npmrc and returns written on success', async () => {
const npmrc =
'@thatopen-platform:registry=https://registry.npmjs.org/\n' +
'//registry.npmjs.org/:_authToken=npm_ro\n';
const client = fakeClient(async () => ({
registry: 'https://registry.npmjs.org/',
scope: '@thatopen-platform',
token: 'npm_ro',
npmrc,
}));

const result = await setupNpmrc(client, dir);

expect(result).toEqual({ status: 'written', scope: '@thatopen-platform' });
expect(readFileSync(join(dir, '.npmrc'), 'utf-8')).toBe(npmrc);
});

it('returns forbidden and writes nothing on a 403', async () => {
const client = fakeClient(async () => {
throw new RequestError(
403,
'Forbidden',
JSON.stringify({ message: 'Community membership required' }),
);
});

const result = await setupNpmrc(client, dir);

expect(result).toEqual({ status: 'forbidden' });
expect(existsSync(join(dir, '.npmrc'))).toBe(false);
});

it('returns error (and writes nothing) on any other failure', async () => {
const client = fakeClient(async () => {
throw new Error('network down');
});

const result = await setupNpmrc(client, dir);

expect(result.status).toBe('error');
expect(existsSync(join(dir, '.npmrc'))).toBe(false);
});

describe('.gitignore protection (Sergio review #19)', () => {
const okClient = () =>
fakeClient(async () => ({
registry: 'https://registry.npmjs.org/',
scope: '@thatopen-platform',
token: 'npm_ro',
npmrc: '//registry.npmjs.org/:_authToken=npm_ro\n',
}));

const gitignore = () =>
readFileSync(join(dir, '.gitignore'), 'utf-8');

it('creates .gitignore ignoring .npmrc when none exists', async () => {
await setupNpmrc(okClient(), dir);
expect(gitignore()).toBe('.npmrc\n');
});

it('appends .npmrc to an existing .gitignore that lacks it', async () => {
writeFileSync(join(dir, '.gitignore'), 'node_modules\ndist\n');
await setupNpmrc(okClient(), dir);
expect(gitignore()).toBe('node_modules\ndist\n.npmrc\n');
});

it('adds a newline before appending when the file has no trailing newline', async () => {
writeFileSync(join(dir, '.gitignore'), 'node_modules');
await setupNpmrc(okClient(), dir);
expect(gitignore()).toBe('node_modules\n.npmrc\n');
});

it('does not duplicate .npmrc when already ignored', async () => {
writeFileSync(join(dir, '.gitignore'), 'node_modules\n.npmrc\ndist\n');
await setupNpmrc(okClient(), dir);
expect(gitignore()).toBe('node_modules\n.npmrc\ndist\n');
});

it('does not write .gitignore when the account is forbidden', async () => {
const client = fakeClient(async () => {
throw new RequestError(403, 'Forbidden', '{}');
});
await setupNpmrc(client, dir);
expect(existsSync(join(dir, '.gitignore'))).toBe(false);
});
});
});
97 changes: 97 additions & 0 deletions src/cli/lib/npmrc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import {
appendFileSync,
existsSync,
readFileSync,
writeFileSync,
} from 'node:fs';
import { join } from 'node:path';
import { EngineServicesClient } from '../../core/client';
import { RequestError } from '../../core/request-error';
import { resolveConfig } from './config';

export type NpmrcResult =
| { status: 'written'; scope: string }
| { status: 'forbidden' }
| { status: 'error'; message: string };

/**
* Make sure `<dir>/.gitignore` ignores `.npmrc` before we write a credential
* into it. The scaffold template already covers this for `create`, but
* `swap`/`login` run in existing projects whose `.gitignore` we don't own — so
* without this the token could be committed. Creates `.gitignore` if absent.
*/
function ensureNpmrcIgnored(dir: string): void {
const gitignorePath = join(dir, '.gitignore');
if (!existsSync(gitignorePath)) {
writeFileSync(gitignorePath, '.npmrc\n');
return;
}
const content = readFileSync(gitignorePath, 'utf-8');
const alreadyIgnored = content
.split(/\r?\n/)
.some((line) => line.trim() === '.npmrc');
if (alreadyIgnored) return;
const prefix = content.length === 0 || content.endsWith('\n') ? '' : '\n';
appendFileSync(gitignorePath, `${prefix}.npmrc\n`);
}

/**
* Fetches the Founders npm credentials and writes them to `<dir>/.npmrc`, so
* `npm install` can resolve the private `@thatopen-platform` beta packages.
*
* Best-effort by design — it never throws, so scaffolding and login keep
* flowing:
* - `forbidden`: the account isn't a FOUNDING member (backend 403); no file.
* - `error`: any other failure (network, misconfig); no file.
* - `written`: `.npmrc` created (mode 0600, it carries a credential).
*/
export async function setupNpmrc(
client: EngineServicesClient,
dir: string,
): Promise<NpmrcResult> {
try {
const creds = await client.getNpmCredentials();
ensureNpmrcIgnored(dir);
writeFileSync(join(dir, '.npmrc'), creds.npmrc, { mode: 0o600 });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we make sure that .npmrc is included in .gitignore before entering the token here? In swap/login for existing projects, it might not be included (only the create command covers it by default), and we could end up pushing the credentials to the repo.

return { status: 'written', scope: creds.scope };
} catch (err) {
if (err instanceof RequestError && err.status === 403) {
return { status: 'forbidden' };
}
const message = err instanceof Error ? err.message : String(err);
return { status: 'error', message };
}
}

/**
* CLI glue for the `--beta` flows (`create` and `swap`): resolves the logged-in
* config, writes an authenticated `.npmrc` into `dir`, and prints a
* human-readable status. Best-effort — never throws, so the install still runs.
*/
export async function configureBetaNpmrc(dir: string): Promise<void> {
const config = resolveConfig(dir);
if (!config) {
console.log(
' Beta libraries are private. Run `thatopen login --token <token>`,',
);
console.log(
' then `npm install`, or add your beta npm token to .npmrc manually.',
);
return;
}
const client = new EngineServicesClient(config.accessToken, config.apiUrl);
const result = await setupNpmrc(client, dir);
if (result.status === 'written') {
console.log(` Beta access configured — wrote .npmrc for ${result.scope}.`);
} else if (result.status === 'forbidden') {
console.log(
' Your account is not a Founding member — beta libraries need Founding',
);
console.log(' access, so the install will fail until you have it.');
} else {
console.log(
` Could not fetch beta npm credentials (${result.message}). Set your`,
);
console.log(' token in .npmrc manually if the install fails.');
}
}
1 change: 1 addition & 0 deletions src/cli/templates/shared/_gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
dist
*.zip
.thatopen
.npmrc
30 changes: 30 additions & 0 deletions src/core/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,4 +407,34 @@ describe('EngineServicesClient — HTTP contract', () => {
);
});
});

describe('getNpmCredentials', () => {
it('GETs /api/npm-registry/credentials with the access token', async () => {
fetchMock.mockResolvedValue(
okResponse({
registry: 'https://registry.npmjs.org/',
scope: '@thatopen-platform',
token: 'npm_ro',
npmrc: '@thatopen-platform:registry=https://registry.npmjs.org/\n',
}),
);
const client = new EngineServicesClient(TOKEN, API);
const creds = await client.getNpmCredentials();
const { url } = getCall(fetchMock);
const { pathname, params } = parseUrl(url);
expect(pathname).toBe('/api/npm-registry/credentials');
expect(params.get('accessToken')).toBe(TOKEN);
expect(creds.scope).toBe('@thatopen-platform');
});

it('throws a RequestError with status 403 for non-Founding accounts', async () => {
fetchMock.mockResolvedValue(
errorResponse(403, 'Community membership required'),
);
const client = new EngineServicesClient(TOKEN, API);
await expect(client.getNpmCredentials()).rejects.toMatchObject({
status: 403,
});
});
});
});
Loading
Loading