# Authentication

Keep a registry private with a private network or a secret URL.

Source: https://webjs.dev/ui/docs/registry/authentication

A private registry keeps internal components to the people allowed to install them. This guide shows how to protect a registry the WebJs UI CLI installs from.

Protect the registry, not the request.

The CLI fetches `<url>/<name>.json` with a plain `fetch`, so protect the registry by where it is reachable, or by the URL itself.

## Common Patterns

### Private Network

Serve the registry where only your team can reach it: on an internal network, behind a VPN, or behind an IP allowlist at your proxy or host. The CLI needs no change, since the registry answers anyone who can connect.

```bash
npx @webjsdev/ui add auth-utils --registry https://registry.internal.acme.com/r
```

### Secret Path Segment

The base URL is any prefix the CLI appends `/<name>.json` to, so it can carry a long random segment that the server checks. Anyone without the segment gets a `404`.

```bash title=".env"
REGISTRY_URL=https://registry.acme.com/r/9f2c6b1e4d8a7f03c5e9b2d1a6f4e8c7
```

Treat the full URL as the secret. It appears in shell history, in CI logs when a command echoes it, and in the CLI's own error messages, which print the URL they requested. Keep it in `REGISTRY_URL` from a secret store rather than in a committed script.

### Query Parameters

Put a token in the path rather than in a query string. The CLI appends the item path after the base URL, so `https://registry.acme.com/r?token=abc` requests `https://registry.acme.com/r?token=abc/auth-utils.json`.

## Server-Side Implementation

A WebJs route handler can check the segment in constant time and serve the files `webjsui build` wrote.

### WebJs Route Example

```ts title="app/r/[token]/[name]/route.ts"
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { timingSafeEqual } from 'node:crypto';

const OUT = join(process.cwd(), 'registry-out');
const SECRET = Buffer.from(process.env.REGISTRY_SECRET ?? '');

function allowed(token: string): boolean {
  const given = Buffer.from(token);
  return SECRET.length > 0 && given.length === SECRET.length && timingSafeEqual(given, SECRET);
}

export async function GET(_req: Request, { params }: { params: { token: string; name: string } }) {
  const name = params.name.replace(/\.json$/, '');
  // The same 404 for a wrong token and a missing item, so a probe learns nothing.
  if (!allowed(params.token) || !/^[a-z0-9-]+$/.test(name)) {
    return Response.json({ error: 'Not found.' }, { status: 404 });
  }
  try {
    const body = await readFile(join(OUT, `${name}.json`), 'utf8');
    return new Response(body, {
      headers: { 'content-type': 'application/json', 'cache-control': 'private, no-store' },
    });
  } catch {
    return Response.json({ error: 'Not found.' }, { status: 404 });
  }
}
```

Users then install with the full URL.

```bash
npx @webjsdev/ui add auth-utils --registry https://registry.acme.com/r/<secret>
```

## Team-Based Access

Give each team its own secret segment and its own output folder, so a team's URL serves only the items built for it. Revoking a team is removing its segment.

## Security Best Practices

### Use Environment Variables

Keep the registry URL in `REGISTRY_URL`, set from your secret store or CI secrets, never committed. Every command reads it when there is no `--registry` flag.

### Use HTTPS

The secret travels in the request line, so serve the registry over HTTPS only.

### Add Rate Limiting

A WebJs app has a rate limiter built in. Put it in the middleware for the registry's segment so guessing segments is slow.

```ts title="app/r/middleware.ts"
import { rateLimit } from '@webjsdev/server';

export default rateLimit({ window: '1m', max: 60 });
```

### Rotate Secrets

Change the segment when someone leaves or a URL leaks, and send the new URL to the people who still need it.

### Log Access

Log which items are fetched and when, without logging the full URL, which carries the secret.

## Testing Authentication

```bash
# Test with curl.
curl https://registry.acme.com/r/<secret>/auth-utils.json

# Test with the CLI.
npx @webjsdev/ui view auth-utils --registry https://registry.acme.com/r/<secret>
```

## Error Handling

The CLI reports a failed request with its status and the URL it requested, for example `HTTP 404` or `HTTP 401`. Document the expected URL format where your users get the URL, since the status and the URL are what they see.

## Next Steps

- Read [Getting Started](https://webjs.dev/ui/docs/registry/getting-started) to build and serve a registry.
- Read [Namespaces](https://webjs.dev/ui/docs/registry/namespace) for working with more than one registry.
