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
45 changes: 45 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Architecture

`solved-proxy` keeps the runtime small, but its source tree has explicit
boundaries so new v4 capabilities do not accumulate in a flat directory.

```text
src/
├── domain/ Pure gateway values and official v4 contract types
├── generated/ Deterministic artifacts derived from the pinned OpenAPI
├── application/ Route compilation and reviewed request-contract logic
├── adapters/
│ ├── http/ Inbound Node HTTP parsing, CORS, auth, and request handling
│ └── solved/ Outbound solved.ac HTTP client
├── infrastructure/ Runtime configuration and secret-file loading
└── server.ts Composition root and process lifecycle
```

## Dependency direction

- `domain` depends only on itself and platform primitives.
- `generated` may depend on `domain` types, never on runtime adapters.
- `application` may depend on `domain`, `generated`, and other application
modules.
- `infrastructure` constructs domain values but does not import application or
adapters.
- `adapters` may depend on application and domain contracts. The outbound
solved.ac adapter must not depend on the inbound HTTP adapter.
- `server.ts` is the composition root and may wire adapters and infrastructure.

`adapters/http/gateway-handler.ts` is intentionally a composition-aware inbound
adapter for this small service: it resolves the application contract and calls
the reviewed solved.ac adapter. This is the single documented adapter-to-adapter
orchestration point. It can be split into a separate use-case layer if runtime
flows become substantially more complex.

The source-layout test enforces the root shape and the lower-layer dependency
direction. Keep tests flat under `test/` so Node's test command remains simple;
their filenames mirror the production module roles.

## Generated boundaries

Files under `src/generated/` are never edited directly. The OpenAPI snapshot,
wire declarations, and operation manifest remain deterministic inputs to the
application layer. See the update and verification commands in
[`README.md`](README.md).
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ The build emits JavaScript to `dist/`. Tests use Node's built-in test runner and
stub upstream `fetch`; they need no external network access. The load-tool test
binds only an ephemeral loopback port.

## Source architecture

Runtime code is grouped into `domain`, `application`, inbound/outbound
`adapters`, and `infrastructure` layers; `src/server.ts` is the only root
TypeScript file and acts as the composition root. Generated OpenAPI artifacts
remain isolated under `src/generated`. The dependency direction and the one
documented gateway orchestration boundary are described in
[`ARCHITECTURE.md`](ARCHITECTURE.md) and enforced by an offline source-layout
test.

## Official OpenAPI contract

The complete machine-readable solved.ac v4 contract is pinned at
Expand Down
24 changes: 7 additions & 17 deletions src/authorization.ts → src/adapters/http/bearer-authorization.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import {
createBearerAuthorization,
type BearerAuthorization,
} from '../../domain/bearer-authorization.js';
import { readUniqueRawHeader } from './request-headers.js';

const MAX_BEARER_HEADER_BYTES = 4_096;
const BEARER_TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/u;
declare const bearerAuthorizationBrand: unique symbol;

export type BearerAuthorization = Readonly<{
token: string;
[bearerAuthorizationBrand]: true;
}>;

export type BearerAuthorizationResult =
| { readonly kind: 'absent' }
Expand All @@ -30,23 +27,16 @@ export function parseBearerAuthorization(
const separator = header.value.indexOf(' ');
const scheme = header.value.slice(0, separator);
const token = header.value.slice(separator + 1);
const authorization = createBearerAuthorization(token);
if (
separator < 1 ||
scheme.toLowerCase() !== 'bearer' ||
!BEARER_TOKEN.test(token)
authorization === undefined
) {
return { kind: 'invalid' };
}
return {
kind: 'valid',
authorization: Object.freeze({
token,
}) as BearerAuthorization,
authorization,
};
}

export function bearerAuthorizationHeader(
authorization: BearerAuthorization,
): string {
return `Bearer ${authorization.token}`;
}
File renamed without changes.
12 changes: 5 additions & 7 deletions src/app.ts → src/adapters/http/gateway-handler.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';

import {
parseBearerAuthorization,
type BearerAuthorization,
} from './authorization.js';
import type { BearerAuthorization } from '../../domain/bearer-authorization.js';
import { parseBearerAuthorization } from './bearer-authorization.js';
import {
ContractError,
resolveProxyRequest,
SOLVED_API_BASE_URL,
} from './contract.js';
} from '../../application/v4-request-contract.js';
import { corsDecision } from './cors-policy.js';
import {
proxyRequest,
type ProxyDependencies,
type ProxyRequestPolicy,
UpstreamError,
} from './proxy-handler.js';
} from '../solved/solved-client.js';
import { parseRequestTarget } from './request-target.js';
import { findRoute } from './routes.js';
import { findRoute } from '../../application/v4-router.js';

export const DEFAULT_MAX_CONCURRENT_REQUESTS = 8;

Expand Down
File renamed without changes.
8 changes: 2 additions & 6 deletions src/request-target.ts → src/adapters/http/request-target.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import type { ParsedRequestTarget } from '../../application/parsed-request-target.js';

export const MAX_REQUEST_TARGET_BYTES = 8_192;

const INVALID_RAW_TARGET = /[\p{Cc}\u0020]/u;
const INVALID_DECODED_COMPONENT = /\p{Cc}/u;
const VALID_PERCENT_ESCAPE = /^[0-9A-Fa-f]{2}$/u;

export interface ParsedRequestTarget {
readonly url: URL;
readonly pathname: string;
readonly decodedPathSegments: readonly string[];
}

function hasValidPercentEncoding(value: string): boolean {
for (let index = 0; index < value.length; index += 1) {
if (value[index] !== '%') {
Expand Down
6 changes: 3 additions & 3 deletions src/proxy-handler.ts → src/adapters/solved/solved-client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
bearerAuthorizationHeader,
type BearerAuthorization,
} from './authorization.js';
import type { SolvedClientCredentials } from './config.js';
import type { V4ResponseContract } from './v4-operation-contract.js';
} from '../../domain/bearer-authorization.js';
import type { SolvedClientCredentials } from '../../domain/solved-client-credentials.js';
import type { V4ResponseContract } from '../../domain/v4-operation-contract.js';

export const DEFAULT_UPSTREAM_TIMEOUT_MS = 8_000;
export const DEFAULT_MAX_RESPONSE_BYTES = 5 * 1_024 * 1_024;
Expand Down
5 changes: 5 additions & 0 deletions src/application/parsed-request-target.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface ParsedRequestTarget {
readonly url: URL;
readonly pathname: string;
readonly decodedPathSegments: readonly string[];
}
8 changes: 4 additions & 4 deletions src/contract.ts → src/application/v4-request-contract.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ParsedRequestTarget } from './request-target.js';
import { findRoute } from './routes.js';
import type { V4ResponseContract } from './v4-operation-contract.js';
import { validateUriValue } from './uri-schema.js';
import type { V4ResponseContract } from '../domain/v4-operation-contract.js';
import { validateUriValue } from '../domain/uri-schema.js';
import type { ParsedRequestTarget } from './parsed-request-target.js';
import { findRoute } from './v4-router.js';

export const SOLVED_API_BASE_URL = 'https://solved.ac/' as const;

Expand Down
6 changes: 3 additions & 3 deletions src/routes.ts → src/application/v4-router.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { V4_OPERATION_MANIFEST } from './generated/v4-operations.js';
import { V4_OPERATION_MANIFEST } from '../generated/v4-operations.js';
import type {
V4OperationContract,
V4OperationParameter,
} from './v4-operation-contract.js';
} from '../domain/v4-operation-contract.js';
import {
assertUriSchemaSupported,
validateUriValue,
} from './uri-schema.js';
} from '../domain/uri-schema.js';

const PATH_PARAMETER = /^\{([A-Za-z][A-Za-z0-9]*)\}$/u;
const EXPECTED_GET_OPERATIONS = 71;
Expand Down
26 changes: 26 additions & 0 deletions src/domain/bearer-authorization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const MAX_BEARER_TOKEN_BYTES = 4_089;
const BEARER_TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/u;
declare const bearerAuthorizationBrand: unique symbol;

export type BearerAuthorization = Readonly<{
token: string;
[bearerAuthorizationBrand]: true;
}>;

export function createBearerAuthorization(
token: string,
): BearerAuthorization | undefined {
if (
Buffer.byteLength(token, 'utf8') > MAX_BEARER_TOKEN_BYTES ||
!BEARER_TOKEN.test(token)
) {
return undefined;
}
return Object.freeze({ token }) as BearerAuthorization;
}

export function bearerAuthorizationHeader(
authorization: BearerAuthorization,
): string {
return `Bearer ${authorization.token}`;
}
4 changes: 4 additions & 0 deletions src/domain/solved-client-credentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface SolvedClientCredentials {
readonly clientId: string;
readonly clientSecret: string;
}
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/generated/v4-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Snapshot SHA-256: 312abfb4677fc67d914f6a357ff5b89d170eb65791ecb5d3ab30ab873352125d
* Do not edit directly; run npm run openapi:operations:update.
*/
import type { V4OperationManifest } from '../v4-operation-contract.js';
import type { V4OperationManifest } from '../domain/v4-operation-contract.js';

export const V4_OPERATION_SNAPSHOT_SHA256 = "312abfb4677fc67d914f6a357ff5b89d170eb65791ecb5d3ab30ab873352125d" as const;

Expand Down
7 changes: 2 additions & 5 deletions src/config.ts → src/infrastructure/runtime-config.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { readFileSync, statSync } from 'node:fs';

import type { SolvedClientCredentials } from '../domain/solved-client-credentials.js';

const MAX_CREDENTIAL_BYTES = 4_096;
const MAX_CORS_ORIGINS_BYTES = 8_192;
const MAX_CORS_ORIGINS = 32;

export interface SolvedClientCredentials {
readonly clientId: string;
readonly clientSecret: string;
}

export class ConfigurationError extends Error {
constructor(message: string) {
super(message);
Expand Down
6 changes: 3 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { pathToFileURL } from 'node:url';
import {
createRequestHandler,
DEFAULT_MAX_CONCURRENT_REQUESTS,
} from './app.js';
} from './adapters/http/gateway-handler.js';
import {
loadProtectedCorsOrigins,
loadSolvedClientCredentials,
} from './config.js';
} from './infrastructure/runtime-config.js';
import {
DEFAULT_MAX_RESPONSE_BYTES,
DEFAULT_UPSTREAM_TIMEOUT_MS,
} from './proxy-handler.js';
} from './adapters/solved/solved-client.js';

const DEFAULT_PORT = 3_000;
const DEFAULT_HOST = '0.0.0.0';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import assert from 'node:assert/strict';
import test from 'node:test';

import {
bearerAuthorizationHeader,
parseBearerAuthorization,
} from '../src/authorization.js';
import { parseBearerAuthorization } from '../src/adapters/http/bearer-authorization.js';
import { bearerAuthorizationHeader } from '../src/domain/bearer-authorization.js';

test('parses one bounded RFC 6750 Bearer value and normalizes the scheme', () => {
for (const value of [
Expand Down
2 changes: 1 addition & 1 deletion test/cors-policy.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';

import { corsDecision } from '../src/cors-policy.js';
import { corsDecision } from '../src/adapters/http/cors-policy.js';

const allowedOrigins = ['https://app.example', 'http://localhost:3000'];

Expand Down
5 changes: 4 additions & 1 deletion test/app.test.ts → test/gateway-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { EventEmitter, once } from 'node:events';
import type { IncomingMessage, ServerResponse } from 'node:http';
import test from 'node:test';

import { createRequestHandler, handleGatewayRequest } from '../src/app.js';
import {
createRequestHandler,
handleGatewayRequest,
} from '../src/adapters/http/gateway-handler.js';

const text = (body: Uint8Array): string => new TextDecoder().decode(body);
const credentials = Object.freeze({
Expand Down
2 changes: 1 addition & 1 deletion test/request-target.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import test from 'node:test';
import {
MAX_REQUEST_TARGET_BYTES,
parseRequestTarget,
} from '../src/request-target.js';
} from '../src/adapters/http/request-target.js';

test('parses path and query components exactly once', () => {
const parsed = parseRequestTarget(
Expand Down
2 changes: 1 addition & 1 deletion test/config.test.ts → test/runtime-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
ConfigurationError,
loadProtectedCorsOrigins,
loadSolvedClientCredentials,
} from '../src/config.js';
} from '../src/infrastructure/runtime-config.js';

function credentialFiles(
clientId = 'client-id',
Expand Down
6 changes: 3 additions & 3 deletions test/proxy-handler.test.ts → test/solved-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import assert from 'node:assert/strict';
import { ReadableStream } from 'node:stream/web';
import test from 'node:test';

import { parseBearerAuthorization } from '../src/authorization.js';
import { parseBearerAuthorization } from '../src/adapters/http/bearer-authorization.js';
import { V4_OPERATION_MANIFEST } from '../src/generated/v4-operations.js';
import {
proxyRequest as proxyUpstream,
type ProxyDependencies,
type ProxyRequestPolicy,
UpstreamError,
} from '../src/proxy-handler.js';
import type { V4ResponseContract } from '../src/v4-operation-contract.js';
} from '../src/adapters/solved/solved-client.js';
import type { V4ResponseContract } from '../src/domain/v4-operation-contract.js';

const upstreamUrl = new URL('https://solved.ac/api/v4/users/tourist');
const responsePolicy =
Expand Down
Loading
Loading