@capsulos/provider-namespace 0.0.0-stage → 0.9.0

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.
package/src/index.ts ADDED
@@ -0,0 +1,401 @@
1
+ // Provider for Namespace. One capsule = one Namespace instance: a virtual
2
+ // machine of its own that runs the template's image as a container (Linux)
3
+ // or its files and capsulod directly on the machine (macOS, where there are
4
+ // no containers). The SDK talks to Namespace's API with a workspace token
5
+ // and to capsulod through the instance's ingress for a port
6
+ // (https://capsulod-<id>.<region>.nscluster.cloud), which Namespace only
7
+ // opens to whoever carries a token of the workspace.
8
+ //
9
+ // Verified on the service (2026-11-17, docs/providers.md):
10
+ // - CreateInstance takes the image by reference from the workspace's
11
+ // registry (nscr.io/<workspace>/...), and runs its command: capsulod
12
+ // starts with the machine. Its token arrives in the boot hook (/run on
13
+ // port 9000, exported like 8080), which this provider calls the way
14
+ // Lambda MicroVMs does by itself; nothing of the capsule is left in the
15
+ // instance's description
16
+ // - the life of an instance is its deadline
17
+ // - no pause in the public API (2026-11-17)
18
+ import {
19
+ CapsuleError,
20
+ HOOKS_PORT,
21
+ callHook,
22
+ deliverBoot,
23
+ type CapsuleHandle,
24
+ type CapsuleInfo,
25
+ type CapsuleSpec,
26
+ type CapsuleState,
27
+ type Connection,
28
+ type CreateOptions,
29
+ type Provider,
30
+ type ProviderCapabilities,
31
+ } from '@capsulos/sdk';
32
+ import { Registry, splitImage, type ImageConfig } from './registry.js';
33
+
34
+ export { Registry, splitImage, type ImageConfig, type RegistryOptions } from './registry.js';
35
+
36
+ export interface NamespaceProviderOptions {
37
+ /** A token of the workspace. Default: the NSC_TOKEN variable (`nsc auth generate-dev-token`, or a token made in the dashboard). */
38
+ token?: string;
39
+ /** The region's API (default the NSC_ENDPOINT variable, or https://us.compute.namespaceapis.com). */
40
+ endpoint?: string;
41
+ /** Default hard limit per capsule, in seconds (default one hour). */
42
+ maxDurationSeconds?: number;
43
+ /** CPUs of a capsule (default 2). */
44
+ cpu?: number;
45
+ /** Memory of a capsule whose image does not say how much it asks for (default 4096 MiB). */
46
+ memoryMiB?: number;
47
+ /**
48
+ * Also close the network outside the machine for capsules created with
49
+ * `network.internet: 'deny'`: Namespace then blocks what is not on the
50
+ * allow list, on top of what the daemon enforces inside. On macOS it is
51
+ * the only enforcement there is. Default true.
52
+ */
53
+ enforceNetworkOutside?: boolean;
54
+ /**
55
+ * How to ask the registry about an image (its memory, whether it is macOS).
56
+ * Default: the token, which only works when it may use the registry; a
57
+ * revocable token may not (Namespace does not grant it), and then an image
58
+ * is taken as Linux with the default memory.
59
+ */
60
+ registryAuth?: { username: string; password: string };
61
+ fetch?: typeof fetch;
62
+ }
63
+
64
+ const CAPSULOD_PORT = 8080;
65
+ const SERVICE = 'namespace.cloud.compute.v1beta.ComputeService';
66
+ const INGRESS_AUTH = 'x-nsc-ingress-auth';
67
+ const LABEL = 'capsulos';
68
+ /** The labels of an image built from a capsule.yaml (the same ones the Docker target writes). */
69
+ export const IMAGE_LABEL = 'dev.capsulos';
70
+ const PORT_NAMES: Record<number, string> = { [CAPSULOD_PORT]: 'capsulod', [HOOKS_PORT]: 'hooks' };
71
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
72
+
73
+ /**
74
+ * What Namespace gives a capsule: Linux in a container of a VM, and macOS
75
+ * (arm64) on the machine itself, from a template built with the macOS recipe.
76
+ */
77
+ export const NAMESPACE_CAPABILITIES: ProviderCapabilities = {
78
+ os: ['linux', 'macos'],
79
+ arch: ['amd64', 'arm64'],
80
+ isolation: 'vm',
81
+ maxMemoryMiB: 65536,
82
+ maxCpu: 32,
83
+ gpu: false,
84
+ pause: false,
85
+ snapshot: false,
86
+ mounts: true,
87
+ networkPolicy: true,
88
+ agentHarness: true,
89
+ templateVersions: true,
90
+ typicalStartMs: 25000,
91
+ };
92
+
93
+ interface Label {
94
+ name: string;
95
+ value: string;
96
+ }
97
+
98
+ export interface NamespaceInstance {
99
+ instanceId: string;
100
+ createdAt?: string;
101
+ destroyedAt?: string;
102
+ deadline?: string;
103
+ status?: string;
104
+ ingressDomain?: string;
105
+ labels?: Label[];
106
+ }
107
+
108
+ interface Described {
109
+ metadata?: NamespaceInstance;
110
+ containers?: Array<{ name?: string; exportedPort?: Array<{ containerPort?: number; fqdn?: string }> }>;
111
+ shutdownReasons?: Array<{ message?: string }>;
112
+ }
113
+
114
+ export class NamespaceProvider implements Provider {
115
+ readonly name = 'namespace';
116
+ readonly capabilities = NAMESPACE_CAPABILITIES;
117
+ private readonly token: string;
118
+ private readonly endpoint: string;
119
+ private readonly fetchImpl: typeof fetch;
120
+ private readonly domains = new Map<string, string>();
121
+ private readonly images = new Map<string, ImageConfig | null>();
122
+
123
+ constructor(private readonly opts: NamespaceProviderOptions = {}) {
124
+ const token = opts.token ?? process.env.NSC_TOKEN;
125
+ if (!token) throw new CapsuleError('Namespace needs a workspace token: set NSC_TOKEN (https://cloud.namespace.so, or `nsc auth generate-dev-token`)');
126
+ this.token = token;
127
+ this.endpoint = (opts.endpoint ?? process.env.NSC_ENDPOINT ?? 'https://us.compute.namespaceapis.com').replace(/\/+$/, '');
128
+ this.fetchImpl = opts.fetch ?? fetch;
129
+ }
130
+
131
+ /** The registry of images, with the provider's token. */
132
+ registry(host?: string): Registry {
133
+ return new Registry({ ...(this.opts.registryAuth ? { basic: this.opts.registryAuth } : { token: this.token }), ...(host ? { host } : {}), fetch: this.fetchImpl });
134
+ }
135
+
136
+ /** A call to Namespace's API (Connect, as JSON). `ok` lists the statuses that are not errors besides 2xx. */
137
+ async rpc<T>(method: string, body: unknown, ok: number[] = []): Promise<{ status: number; data: T | null }> {
138
+ let res: Response;
139
+ try {
140
+ res = await this.fetchImpl(`${this.endpoint}/${SERVICE}/${method}`, {
141
+ method: 'POST',
142
+ headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json' },
143
+ body: JSON.stringify(body ?? {}),
144
+ signal: AbortSignal.timeout(120_000),
145
+ });
146
+ } catch (err) {
147
+ throw new CapsuleError(`Namespace ${method}: ${err instanceof Error ? err.message : String(err)}`);
148
+ }
149
+ const text = await res.text();
150
+ if (!res.ok && !ok.includes(res.status)) {
151
+ let message = text.slice(0, 300);
152
+ try {
153
+ message = (JSON.parse(text) as { message?: string }).message ?? message;
154
+ } catch {
155
+ // not JSON: the text is the message
156
+ }
157
+ throw new CapsuleError(`Namespace ${method}: ${res.status} ${message}`, res.status);
158
+ }
159
+ let data: T | null = null;
160
+ try {
161
+ data = text ? (JSON.parse(text) as T) : null;
162
+ } catch {
163
+ data = null;
164
+ }
165
+ return { status: res.status, data };
166
+ }
167
+
168
+ /**
169
+ * `template` is an image of the workspace's registry
170
+ * (`nscr.io/<workspace>/capsulos/<name>` for one built from a
171
+ * capsule.yaml); the version is its tag.
172
+ */
173
+ async create(spec: CapsuleSpec, opts: CreateOptions = {}): Promise<CapsuleHandle> {
174
+ if (spec.clientToken) {
175
+ const again = (await this.instances([{ name: `${LABEL}-client-token`, value: spec.clientToken }]))[0];
176
+ if (again) return { ...this.infoOf(again), connection: await this.connect(again.instanceId) };
177
+ }
178
+ const maxDurationSeconds = spec.maxDurationSeconds ?? this.opts.maxDurationSeconds ?? 3600;
179
+ const timeoutMs = opts.timeoutMs ?? 180_000;
180
+ const imageRef = spec.templateVersion ? `${spec.template}:${spec.templateVersion}` : spec.template;
181
+ const image = await this.imageConfig(spec.template, spec.templateVersion ?? 'latest');
182
+ const macos = image?.os === 'darwin';
183
+ const memoryMiB = Number(image?.labels[`${IMAGE_LABEL}.memory-mib`]) || this.opts.memoryMiB || 4096;
184
+ const ports = [CAPSULOD_PORT, HOOKS_PORT];
185
+ const cpu = this.opts.cpu ?? 2;
186
+ const deny = spec.network?.internet === 'deny';
187
+ const { data } = await this.rpc<Described>('CreateInstance', {
188
+ shape: {
189
+ // A Mac comes in fixed shapes: the smallest one that gives what is asked.
190
+ virtualCpu: macos ? macShape(this.opts.cpu ?? 0, memoryMiB).cpu : cpu,
191
+ // Linux: Namespace takes memory in whole GiB, and more of them than CPUs (its smallest shapes give 2 GiB per CPU).
192
+ memoryMegabytes: macos ? macShape(this.opts.cpu ?? 0, memoryMiB).memoryGiB * 1024 : Math.max(Math.ceil(memoryMiB / 1024), cpu * 2) * 1024,
193
+ machineArch: macos ? 'arm64' : (image?.architecture ?? 'amd64'),
194
+ os: macos ? 'macos' : 'linux',
195
+ },
196
+ documentedPurpose: `capsulos capsule of ${spec.template}`,
197
+ labels: [
198
+ { name: LABEL, value: '1' },
199
+ { name: `${LABEL}-template`, value: spec.template },
200
+ ...(spec.templateVersion ? [{ name: `${LABEL}-version`, value: spec.templateVersion }] : []),
201
+ ...(spec.clientToken ? [{ name: `${LABEL}-client-token`, value: spec.clientToken }] : []),
202
+ ],
203
+ deadline: new Date(Date.now() + maxDurationSeconds * 1000).toISOString(),
204
+ ...(macos
205
+ ? {
206
+ // No containers on macOS: the image's files are put on the machine and its boot script runs there.
207
+ applications: [{ name: 'capsule', imageRef, command: './capsulos-boot.sh' }],
208
+ ingresses: ports.map((port) => ({ name: PORT_NAMES[port], mode: 'HTTP', port })),
209
+ }
210
+ : {
211
+ containers: [
212
+ {
213
+ name: 'capsule',
214
+ imageRef,
215
+ args: ['capsulod'],
216
+ exportPorts: ports.map((containerPort) => ({ proto: 'HTTP', containerPort, name: PORT_NAMES[containerPort] })),
217
+ // capsulod is root with every capability: it mounts, locks the routes and drops each service to its user.
218
+ privileged: true,
219
+ },
220
+ ],
221
+ }),
222
+ ...(deny && this.opts.enforceNetworkOutside !== false
223
+ ? { networkPolicy: { egress: { mode: 'BLOCK', rules: outsideRules(spec.network?.allow ?? [], splitImage(spec.template).host) } } }
224
+ : {}),
225
+ });
226
+ const id = data?.metadata?.instanceId;
227
+ if (!id) throw new CapsuleError('Namespace created an instance without an id');
228
+ if (data?.metadata?.ingressDomain) this.domains.set(id, data.metadata.ingressDomain);
229
+ try {
230
+ const deadline = Date.now() + timeoutMs;
231
+ for (;;) {
232
+ const { data: now } = await this.rpc<Described>('DescribeInstance', { instanceId: id });
233
+ const status = now?.metadata?.status;
234
+ if (now?.metadata?.ingressDomain) this.domains.set(id, now.metadata.ingressDomain);
235
+ if (status === 'RUNNING') break;
236
+ if (status === 'ERROR' || status === 'DESTROYED' || status === 'DESTROYING') {
237
+ const why = now?.shutdownReasons?.map((r) => r.message).filter(Boolean).join('; ');
238
+ throw new CapsuleError(`Namespace could not start instance ${id}: ${status}${why ? ` (${why})` : ''}`);
239
+ }
240
+ if (opts.signal?.aborted) throw new CapsuleError(`creation of instance ${id} aborted`);
241
+ if (Date.now() > deadline) throw new CapsuleError(`instance ${id} was still ${status ?? 'not running'} after ${Math.round(timeoutMs / 1000)} s`);
242
+ await sleep(750);
243
+ }
244
+ // On a Mac the daemon cannot lock the routes: it is told that Namespace's egress policy is the block.
245
+ const boot = macos && deny && this.opts.enforceNetworkOutside !== false ? { ...spec, network: { ...spec.network!, outside: true } } : spec;
246
+ await deliverBoot(await this.portConnection(id, HOOKS_PORT), id, boot, { timeoutMs: Math.max(15_000, deadline - Date.now()), signal: opts.signal, fetch: this.fetchImpl });
247
+ } catch (err) {
248
+ await this.terminate(id).catch(() => undefined);
249
+ const e = err instanceof Error ? err : new Error(String(err));
250
+ throw new CapsuleError(`${e.message}; terminated instance ${id}`, err instanceof CapsuleError ? err.status : undefined, { capsuleId: id });
251
+ }
252
+ const connection = await this.portConnection(id, CAPSULOD_PORT);
253
+ return {
254
+ id,
255
+ provider: this.name,
256
+ state: 'running',
257
+ template: spec.template,
258
+ templateVersion: spec.templateVersion ?? null,
259
+ createdAt: data?.metadata?.createdAt ? new Date(data.metadata.createdAt) : new Date(),
260
+ endpoint: connection.baseUrl,
261
+ maxDurationSeconds,
262
+ connection,
263
+ };
264
+ }
265
+
266
+ async get(id: string): Promise<CapsuleInfo | null> {
267
+ const { status, data } = await this.rpc<Described>('DescribeInstance', { instanceId: id }, [404]);
268
+ if (status === 404 || !data?.metadata) return null;
269
+ if (data.metadata.ingressDomain) this.domains.set(id, data.metadata.ingressDomain);
270
+ return this.infoOf(data.metadata);
271
+ }
272
+
273
+ /** The capsules of the workspace, optionally those of one template (its image, without the tag). */
274
+ async list(template?: string): Promise<CapsuleInfo[]> {
275
+ return (await this.instances(template ? [{ name: `${LABEL}-template`, value: template }] : [])).map((i) => this.infoOf(i));
276
+ }
277
+
278
+ async terminate(id: string): Promise<void> {
279
+ // Best effort: a service that asked for the notice gets it before the machine goes.
280
+ if (this.domains.has(id)) {
281
+ await callHook(await this.portConnection(id, HOOKS_PORT), 'terminate', {}, { timeoutMs: 0, requestTimeoutMs: 4_000, fetch: this.fetchImpl }).catch(() => undefined);
282
+ }
283
+ await this.rpc('DestroyInstance', { instanceId: id, reason: 'capsulos: capsule terminated' }, [404]);
284
+ this.domains.delete(id);
285
+ }
286
+
287
+ async connect(id: string): Promise<Connection> {
288
+ return this.portConnection(id, CAPSULOD_PORT);
289
+ }
290
+
291
+ /** The address of capsulod (8080) or of its hooks (9000): the only two ports an instance exports. Everything else goes through capsulod's /proxy. */
292
+ async portUrl(id: string, port: number): Promise<string> {
293
+ const name = PORT_NAMES[port];
294
+ if (!name) throw new CapsuleError(`a Namespace capsule exports ports ${Object.keys(PORT_NAMES).join(' and ')}; reach port ${port} through the capsule (capsule.ports)`);
295
+ let domain = this.domains.get(id);
296
+ if (!domain) {
297
+ const { status, data } = await this.rpc<Described>('DescribeInstance', { instanceId: id }, [404]);
298
+ domain = data?.metadata?.ingressDomain;
299
+ if (status === 404 || !domain) throw new CapsuleError(`Namespace has no instance ${id} (it ended, or it never existed)`, 404, { capsuleId: id });
300
+ this.domains.set(id, domain);
301
+ }
302
+ return `https://${name}-${id}.${domain}`;
303
+ }
304
+
305
+ /** What the ingress asks for: a token of the workspace. It is not the `Authorization` header, which stays free for the service behind. */
306
+ portHeaders(): Record<string, string> {
307
+ return { [INGRESS_AUTH]: `Bearer ${this.token}` };
308
+ }
309
+
310
+ private async portConnection(id: string, port: number): Promise<Connection> {
311
+ return { baseUrl: await this.portUrl(id, port), headers: async () => this.portHeaders() };
312
+ }
313
+
314
+ /** What the registry says of an image: its system, its architecture and its labels. Null when it cannot be read (an image of another registry). */
315
+ private async imageConfig(template: string, tag: string): Promise<ImageConfig | null> {
316
+ const key = `${template}:${tag}`;
317
+ if (this.images.has(key)) return this.images.get(key) ?? null;
318
+ let config: ImageConfig | null = null;
319
+ try {
320
+ const { host, repository } = splitImage(template);
321
+ config = (await this.registry(host).image(repository, tag))?.config ?? null;
322
+ } catch {
323
+ config = null;
324
+ }
325
+ this.images.set(key, config);
326
+ return config;
327
+ }
328
+
329
+ private async instances(filter: Label[]): Promise<NamespaceInstance[]> {
330
+ const out: NamespaceInstance[] = [];
331
+ let paginationCursor: string | undefined;
332
+ do {
333
+ const { data } = await this.rpc<{ instances?: NamespaceInstance[]; paginationCursor?: string }>('ListInstances', {
334
+ labelFilter: [{ name: LABEL, value: '1', op: 'EQUAL' }, ...filter.map((f) => ({ ...f, op: 'EQUAL' }))],
335
+ ...(paginationCursor ? { paginationCursor } : {}),
336
+ });
337
+ out.push(...(data?.instances ?? []));
338
+ paginationCursor = data?.instances?.length ? data.paginationCursor : undefined;
339
+ } while (paginationCursor);
340
+ return out;
341
+ }
342
+
343
+ private infoOf(i: NamespaceInstance): CapsuleInfo {
344
+ const label = (name: string) => i.labels?.find((l) => l.name === name)?.value ?? null;
345
+ const created = i.createdAt ? new Date(i.createdAt) : null;
346
+ const end = i.deadline ? new Date(i.deadline) : null;
347
+ if (i.ingressDomain) this.domains.set(i.instanceId, i.ingressDomain);
348
+ return {
349
+ id: i.instanceId,
350
+ provider: this.name,
351
+ state: toState(i.status),
352
+ template: label(`${LABEL}-template`),
353
+ templateVersion: label(`${LABEL}-version`),
354
+ createdAt: created,
355
+ terminatedAt: i.destroyedAt ? new Date(i.destroyedAt) : null,
356
+ endpoint: i.ingressDomain ? `https://${PORT_NAMES[CAPSULOD_PORT]}-${i.instanceId}.${i.ingressDomain}` : null,
357
+ maxDurationSeconds: created && end ? Math.round((end.getTime() - created.getTime()) / 1000) : null,
358
+ };
359
+ }
360
+ }
361
+
362
+ export function toState(s: string | undefined): CapsuleState {
363
+ switch (s) {
364
+ case 'RUNNING':
365
+ return 'running';
366
+ case 'PENDING':
367
+ case 'CREATING':
368
+ return 'pending';
369
+ case 'SUSPENDING':
370
+ case 'SUSPENDED':
371
+ return 'suspended';
372
+ case 'DESTROYING':
373
+ case 'DESTROYED':
374
+ case 'ERROR':
375
+ return 'terminated';
376
+ default:
377
+ return 'unknown';
378
+ }
379
+ }
380
+
381
+ /** The macOS machines Namespace offers (CPUs x GiB), as its API listed them on 2026-11-17. */
382
+ export const MAC_SHAPES: ReadonlyArray<{ cpu: number; memoryGiB: number }> = [[4, 7], [4, 14], [6, 14], [6, 28], [8, 14], [8, 28], [12, 28], [12, 56], [16, 28], [16, 56]].map(([cpu, memoryGiB]) => ({ cpu: cpu!, memoryGiB: memoryGiB! }));
383
+ /** The smallest Mac with at least these CPUs and this memory; the biggest when none has both. */
384
+ export function macShape(cpu: number, memoryMiB: number): { cpu: number; memoryGiB: number } {
385
+ return MAC_SHAPES.find((s) => s.cpu >= cpu && s.memoryGiB * 1024 >= memoryMiB) ?? MAC_SHAPES.at(-1)!;
386
+ }
387
+
388
+ /**
389
+ * capsulos's allow list ('host', '*.domain', 'host:port') as Namespace's
390
+ * egress rules take it (domains, no ports): Namespace's is the coarser net,
391
+ * the daemon's proxy inside still checks the port. The registry of the image
392
+ * is always let through at this layer: the machine pulls the image under the
393
+ * same policy, and with the registry blocked the capsule never starts. Inside,
394
+ * the daemon still refuses it unless the allow list names it.
395
+ */
396
+ export function outsideRules(allow: string[], registry?: string): Array<{ op: 'ALLOW'; matcher: { matchDomains: string[] }; allow: Record<string, never> }> {
397
+ const pull = registry ? [registry, ...(/(^|\.)nscr\.io$/.test(registry) ? ['*.nscr.io', '*.namespaceblobs.com'] : [])] : [];
398
+ const domains = [...new Set([...allow.map((a) => a.replace(/:\d+$/, '')).filter(Boolean), ...pull])];
399
+ return domains.length ? [{ op: 'ALLOW', matcher: { matchDomains: domains }, allow: {} }] : [];
400
+ }
401
+ export * from './templates.js';
@@ -0,0 +1,148 @@
1
+ // The Namespace provider against a stubbed fetch: what it asks of Namespace
2
+ // for a Linux image and for a macOS one, and how it reads an image from the
3
+ // registry. The service itself is exercised by the conformance suite.
4
+ import { describe, expect, it } from 'vitest';
5
+ import { CapsuleError } from '@capsulos/sdk';
6
+ import { NamespaceProvider, outsideRules, toState } from './index.js';
7
+
8
+ interface Call {
9
+ method: string;
10
+ url: string;
11
+ headers: Record<string, string>;
12
+ body: unknown;
13
+ }
14
+
15
+ const RPC = 'https://us.compute.namespaceapis.com/namespace.cloud.compute.v1beta.ComputeService';
16
+ const IMAGE = 'nscr.io/ws1/capsulos/base';
17
+
18
+ function stub(image: { os: string; architecture: string; labels?: Record<string, string> } | null, extra: (c: Call) => { status?: number; body?: unknown } | undefined = () => undefined) {
19
+ const calls: Call[] = [];
20
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
21
+ const call: Call = {
22
+ method: init?.method ?? 'GET',
23
+ url: String(input),
24
+ headers: Object.fromEntries(Object.entries((init?.headers ?? {}) as Record<string, string>).map(([k, v]) => [k.toLowerCase(), v])),
25
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
26
+ };
27
+ calls.push(call);
28
+ const answer = (): { status?: number; body?: unknown; headers?: Record<string, string> } => {
29
+ const more = extra(call);
30
+ if (more) return more;
31
+ if (call.url === 'https://nscr.io/v2/ws1/capsulos/base/manifests/2.0.0') {
32
+ return image ? { body: { config: { digest: 'sha256:cfg' } }, headers: { 'docker-content-digest': 'sha256:man' } } : { status: 404, body: {} };
33
+ }
34
+ if (call.url === 'https://nscr.io/v2/ws1/capsulos/base/blobs/sha256:cfg') return { body: { os: image!.os, architecture: image!.architecture, config: { Labels: image!.labels ?? {} } } };
35
+ if (call.url === `${RPC}/CreateInstance`) return { body: { metadata: { instanceId: 'i1', ingressDomain: 'fra1.namespaced.app', status: 'CREATING' } } };
36
+ if (call.url === `${RPC}/DescribeInstance`) return { body: { metadata: { instanceId: 'i1', ingressDomain: 'fra1.namespaced.app', status: 'RUNNING' } } };
37
+ if (call.url === `${RPC}/DestroyInstance`) return { body: {} };
38
+ if (call.url.startsWith('https://hooks-i1.fra1.namespaced.app/')) return { body: { ok: true } };
39
+ return { status: 404, body: { message: 'not stubbed' } };
40
+ };
41
+ const res = answer();
42
+ return new Response(res.body === undefined ? null : JSON.stringify(res.body), { status: res.status ?? 200, headers: res.headers });
43
+ }) as typeof fetch;
44
+ return { calls, provider: new NamespaceProvider({ token: 'nsc_token', fetch: fetchImpl }) };
45
+ }
46
+
47
+ const created = (calls: Call[]) => calls.find((c) => c.url === `${RPC}/CreateInstance`)!.body as Record<string, any>;
48
+
49
+ describe('NamespaceProvider.create', () => {
50
+ it('runs a Linux image as a privileged container with the memory its labels ask for', async () => {
51
+ const { calls, provider } = stub({ os: 'linux', architecture: 'amd64', labels: { 'dev.capsulos.memory-mib': '2048' } });
52
+ const handle = await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789', maxDurationSeconds: 600 });
53
+ expect(handle).toMatchObject({ id: 'i1', provider: 'namespace', state: 'running', endpoint: 'https://capsulod-i1.fra1.namespaced.app', templateVersion: '2.0.0' });
54
+
55
+ const body = created(calls);
56
+ // Whole GiB, and at least two per CPU.
57
+ expect(body.shape).toEqual({ virtualCpu: 2, memoryMegabytes: 4096, machineArch: 'amd64', os: 'linux' });
58
+ expect(body.containers).toEqual([
59
+ {
60
+ name: 'capsule',
61
+ imageRef: `${IMAGE}:2.0.0`,
62
+ args: ['capsulod'],
63
+ exportPorts: [
64
+ { proto: 'HTTP', containerPort: 8080, name: 'capsulod' },
65
+ { proto: 'HTTP', containerPort: 9000, name: 'hooks' },
66
+ ],
67
+ privileged: true,
68
+ },
69
+ ]);
70
+ expect(body.applications).toBeUndefined();
71
+ expect(body.networkPolicy).toBeUndefined();
72
+ expect(Date.parse(body.deadline) - Date.now()).toBeGreaterThan(590_000);
73
+ // Nothing of the capsule's token is left in the instance's description.
74
+ expect(JSON.stringify(body)).not.toContain('capsule-token');
75
+
76
+ const hook = calls.find((c) => c.url.endsWith('/run'))!;
77
+ expect(hook.url).toBe('https://hooks-i1.fra1.namespaced.app/aws/lambda-microvms/runtime/v1/run');
78
+ expect(hook.headers['x-nsc-ingress-auth']).toBe('Bearer nsc_token');
79
+ expect(hook.headers.authorization).toBeUndefined();
80
+ expect(await handle.connection.headers()).toEqual({ 'x-nsc-ingress-auth': 'Bearer nsc_token' });
81
+ // The registry is asked with the token as a password, the API with it as a bearer.
82
+ expect(calls[0]!.headers.authorization).toBe(`Basic ${Buffer.from('token:nsc_token').toString('base64')}`);
83
+ });
84
+
85
+ it('runs a macOS image as an application on the machine, with ingresses instead of container ports', async () => {
86
+ const { calls, provider } = stub({ os: 'darwin', architecture: 'arm64' });
87
+ await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' });
88
+ const body = created(calls);
89
+ expect(body.shape).toMatchObject({ machineArch: 'arm64', os: 'macos' });
90
+ expect(body.containers).toBeUndefined();
91
+ expect(body.applications).toEqual([{ name: 'capsule', imageRef: `${IMAGE}:2.0.0`, command: './capsulos-boot.sh' }]);
92
+ expect(body.ingresses).toEqual([
93
+ { name: 'capsulod', mode: 'HTTP', port: 8080 },
94
+ { name: 'hooks', mode: 'HTTP', port: 9000 },
95
+ ]);
96
+ });
97
+
98
+ it('blocks what the allow list does not name when the capsule denies the internet', async () => {
99
+ const { calls, provider } = stub({ os: 'linux', architecture: 'amd64' });
100
+ await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789', network: { internet: 'deny', allow: ['api.example.com:443'] } });
101
+ expect(created(calls).networkPolicy).toEqual({ egress: { mode: 'BLOCK', rules: [{ op: 'ALLOW', matcher: { matchDomains: ['api.example.com', 'nscr.io', '*.nscr.io', '*.namespaceblobs.com'] }, allow: {} }] } });
102
+ });
103
+
104
+ it('destroys an instance that ended in error, and names it', async () => {
105
+ const { calls, provider } = stub({ os: 'linux', architecture: 'amd64' }, (c) =>
106
+ c.url === `${RPC}/DescribeInstance` ? { body: { metadata: { instanceId: 'i1', status: 'ERROR' }, shutdownReasons: [{ message: 'image not found' }] } } : undefined,
107
+ );
108
+ const err = await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' }).catch((e: unknown) => e);
109
+ expect(err).toBeInstanceOf(CapsuleError);
110
+ expect((err as CapsuleError).message).toMatch(/image not found.*terminated instance i1/);
111
+ expect(calls.some((c) => c.url === `${RPC}/DestroyInstance`)).toBe(true);
112
+ });
113
+
114
+ it('an image the registry does not have is taken as Linux with the default memory', async () => {
115
+ const { calls, provider } = stub(null);
116
+ await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' });
117
+ expect(created(calls).shape).toEqual({ virtualCpu: 2, memoryMegabytes: 4096, machineArch: 'amd64', os: 'linux' });
118
+ });
119
+ });
120
+
121
+ describe('Registry', () => {
122
+ it('follows an index to the image and reads its labels', async () => {
123
+ const { provider } = stub(null, (c) => {
124
+ if (c.url.endsWith('/manifests/1.0.0')) return { body: { manifests: [{ digest: 'sha256:att', platform: { os: 'unknown', architecture: 'unknown' } }, { digest: 'sha256:img', platform: { os: 'linux', architecture: 'arm64' } }] } };
125
+ if (c.url.endsWith('/manifests/sha256:img')) return { body: { config: { digest: 'sha256:c2' } } };
126
+ if (c.url.endsWith('/blobs/sha256:c2')) return { body: { os: 'linux', architecture: 'arm64', created: '2026-11-17T00:00:00Z', config: { Labels: { a: 'b' } } } };
127
+ if (c.url.endsWith('/x/tags/list?n=1000')) return { body: { name: 'ws1/capsulos/x', tags: ['1.0.0', 'latest'] } };
128
+ return undefined;
129
+ });
130
+ const registry = provider.registry();
131
+ expect(await registry.tags('ws1/capsulos/x')).toEqual(['1.0.0', 'latest']);
132
+ expect((await registry.image('ws1/capsulos/x', '1.0.0'))?.config).toEqual({ os: 'linux', architecture: 'arm64', created: '2026-11-17T00:00:00Z', labels: { a: 'b' } });
133
+ expect(await registry.tags('ws1/capsulos/none')).toEqual([]);
134
+ });
135
+ });
136
+
137
+ describe('states and rules', () => {
138
+ it('maps Namespace states', () => {
139
+ expect(toState('RUNNING')).toBe('running');
140
+ expect(toState('CREATING')).toBe('pending');
141
+ expect(toState('DESTROYED')).toBe('terminated');
142
+ });
143
+ it('an empty allow list blocks everything but the registry the machine pulls its image from', () => {
144
+ expect(outsideRules([])).toEqual([]);
145
+ expect(outsideRules([], 'nscr.io')).toEqual([{ op: 'ALLOW', matcher: { matchDomains: ['nscr.io', '*.nscr.io', '*.namespaceblobs.com'] }, allow: {} }]);
146
+ expect(outsideRules(['api.github.com:443'], 'ghcr.io')[0]!.matcher.matchDomains).toEqual(['api.github.com', 'ghcr.io']);
147
+ });
148
+ });
@@ -0,0 +1,114 @@
1
+ // The workspace's image registry (nscr.io), spoken to with the plain OCI
2
+ // distribution API: a template version is an image there, and what capsulos
3
+ // needs to know about it (which declaration it is, how much memory it asks
4
+ // for, which system it runs on) is in the image's own configuration.
5
+ import { createHash } from 'node:crypto';
6
+ import { CapsuleError } from '@capsulos/sdk';
7
+
8
+ export interface ImageConfig {
9
+ os: string;
10
+ architecture: string;
11
+ created?: string;
12
+ labels: Record<string, string>;
13
+ }
14
+
15
+ export interface RegistryOptions {
16
+ /** The registry's host (default nscr.io). */
17
+ host?: string;
18
+ /** A token of the workspace that may use the registry: sent as the password of the user `token`. */
19
+ token?: string;
20
+ /** A user and password instead (what `nsc docker login` left in Docker's configuration). */
21
+ basic?: { username: string; password: string };
22
+ fetch?: typeof fetch;
23
+ }
24
+
25
+ const ACCEPT = [
26
+ 'application/vnd.oci.image.index.v1+json',
27
+ 'application/vnd.docker.distribution.manifest.list.v2+json',
28
+ 'application/vnd.oci.image.manifest.v1+json',
29
+ 'application/vnd.docker.distribution.manifest.v2+json',
30
+ ].join(', ');
31
+
32
+ interface Manifest {
33
+ config?: { digest: string };
34
+ manifests?: Array<{ digest: string; platform?: { os?: string; architecture?: string } }>;
35
+ }
36
+
37
+ export class Registry {
38
+ readonly host: string;
39
+ private readonly auth: string;
40
+ private readonly fetchImpl: typeof fetch;
41
+
42
+ constructor(opts: RegistryOptions) {
43
+ this.host = opts.host ?? 'nscr.io';
44
+ // The registry takes a workspace token as the password of the user `token`.
45
+ const { username, password } = opts.basic ?? { username: 'token', password: opts.token ?? '' };
46
+ this.auth = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
47
+ this.fetchImpl = opts.fetch ?? fetch;
48
+ }
49
+
50
+ private async call(method: string, path: string, accept?: string): Promise<Response> {
51
+ try {
52
+ return await this.fetchImpl(`https://${this.host}/v2/${path}`, {
53
+ method,
54
+ headers: { authorization: this.auth, ...(accept ? { accept } : {}) },
55
+ signal: AbortSignal.timeout(60_000),
56
+ });
57
+ } catch (err) {
58
+ throw new CapsuleError(`registry ${this.host} ${method} ${path}: ${err instanceof Error ? err.message : String(err)}`);
59
+ }
60
+ }
61
+
62
+ /** The tags of a repository (`<workspace>/capsulos/<name>`); none when it does not exist. */
63
+ async tags(repository: string): Promise<string[]> {
64
+ const out: string[] = [];
65
+ let path: string | null = `${repository}/tags/list?n=1000`;
66
+ while (path) {
67
+ const res: Response = await this.call('GET', path);
68
+ if (res.status === 404) return out;
69
+ if (!res.ok) throw new CapsuleError(`registry ${this.host}: listing the tags of ${repository}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
70
+ out.push(...(((await res.json()) as { tags?: string[] | null }).tags ?? []));
71
+ const next = /<([^>]+)>;\s*rel="next"/.exec(res.headers.get('link') ?? '')?.[1];
72
+ path = next ? next.replace(/^\/v2\//, '') : null;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** The digest a tag names, and the image's configuration; null when the registry has no such image. */
78
+ async image(repository: string, reference: string): Promise<{ digest: string; config: ImageConfig } | null> {
79
+ let res = await this.call('GET', `${repository}/manifests/${reference}`, ACCEPT);
80
+ if (res.status === 404) return null;
81
+ if (!res.ok) throw new CapsuleError(`registry ${this.host}: ${repository}:${reference}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
82
+ // The digest of a manifest is the hash of its bytes: a registry that does not say it in a header (nscr.io on GET) still has it.
83
+ const body = Buffer.from(await res.arrayBuffer());
84
+ const digest = res.headers.get('docker-content-digest') || `sha256:${createHash('sha256').update(body).digest('hex')}`;
85
+ let manifest = JSON.parse(body.toString('utf8')) as Manifest;
86
+ if (manifest.manifests?.length) {
87
+ // An index (docker buildx adds an attestation next to the image): the image is the entry with a real platform.
88
+ const entry = manifest.manifests.find((m) => m.platform?.os && m.platform.os !== 'unknown') ?? manifest.manifests[0]!;
89
+ res = await this.call('GET', `${repository}/manifests/${entry.digest}`, ACCEPT);
90
+ if (!res.ok) return null;
91
+ manifest = (await res.json()) as Manifest;
92
+ }
93
+ if (!manifest.config?.digest) return null;
94
+ const blob = await this.call('GET', `${repository}/blobs/${manifest.config.digest}`);
95
+ if (!blob.ok) return null;
96
+ const cfg = (await blob.json()) as { os?: string; architecture?: string; created?: string; config?: { Labels?: Record<string, string> | null } };
97
+ return { digest, config: { os: cfg.os ?? 'linux', architecture: cfg.architecture ?? 'amd64', ...(cfg.created ? { created: cfg.created } : {}), labels: cfg.config?.Labels ?? {} } };
98
+ }
99
+
100
+ /** Remove what a tag names (the registry deletes by digest). */
101
+ async remove(repository: string, reference: string): Promise<void> {
102
+ const found = await this.image(repository, reference);
103
+ if (!found?.digest) return;
104
+ const res = await this.call('DELETE', `${repository}/manifests/${found.digest}`);
105
+ if (!res.ok && res.status !== 404) throw new CapsuleError(`registry ${this.host}: removing ${repository}:${reference}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
106
+ }
107
+ }
108
+
109
+ /** `nscr.io/<workspace>/capsulos/<name>` → its registry host and repository. */
110
+ export function splitImage(ref: string): { host: string; repository: string } {
111
+ const slash = ref.indexOf('/');
112
+ if (slash < 0) throw new CapsuleError(`${ref} is not an image of a registry: it names no host`);
113
+ return { host: ref.slice(0, slash), repository: ref.slice(slash + 1) };
114
+ }