@aura-labs-ai/mcp-server-admission 0.1.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/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @aura-labs-ai/mcp-server-admission
2
+
3
+ The local action layer of AURA agent admission. An agent installs this MCP
4
+ server in its own environment; the server holds the agent's Ed25519 keys and
5
+ signs every admission request itself. The private keys never leave the machine —
6
+ only signatures do. Discovery stays on the hosted AURA MCP; authority lives here.
7
+
8
+ ## Install
9
+
10
+ ```json
11
+ {
12
+ "mcpServers": {
13
+ "aura-admission": {
14
+ "command": "npx",
15
+ "args": ["-y", "@aura-labs-ai/mcp-server-admission"]
16
+ }
17
+ }
18
+ }
19
+ ```
20
+
21
+ Environment:
22
+
23
+ - `AURA_BENCH_URL` — the certification bench (default `https://sandbox.aura-labs.ai`)
24
+ - `AURA_KEY_PATH` — key file location override (default: macOS Keychain, else `~/.aura/keys.json` at 0600)
25
+
26
+ ## The tools, in recorded-run order
27
+
28
+ Provision opens the recorded conformance run, and registrations are captured
29
+ into it only when the sandbox key is presented — so the order below matters.
30
+ Registering before provisioning still succeeds, but the transcript never
31
+ captures it.
32
+
33
+ 1. `get_admission_guide` — read the admission chain from the bench.
34
+ 2. `mint_sandbox_key` — two-phase. The first call generates and holds a
35
+ dedicated domain signing key and returns the exact domain-control proof to
36
+ publish (DNS TXT `_aura-agent-key.<domain>` = `aura-key=<public_key>`, or the
37
+ HTTPS document `https://<domain>/.well-known/aura-agent-key` containing
38
+ `{"public_key":"<base64>"}`). Publish it, call again: the tool attempts the
39
+ mint and, until the proof is visible, returns the bench's `looked_for` /
40
+ `found` verbatim. On success the bearer key is held locally.
41
+ 3. `provision_sandbox` — the seeded market, the manifest, and the opened
42
+ `run_id`. Idempotent.
43
+ 4. `register_principal` — signed locally with the held principal key.
44
+ 5. `register_agent` — signed locally with the held agent key.
45
+ 6. `reset_sandbox` — opens a fresh run (not idempotent; spends run quota).
46
+
47
+ ## Key custody
48
+
49
+ Three Ed25519 keypairs (principal, agent, domain — the bench enforces
50
+ fingerprint uniqueness, so they are distinct by construction) plus the chain
51
+ state (`sandbox_key`, `principal_id`, `agent_id`, `namespace_id`, `run_id`)
52
+ persist across restarts via the platform storage adapter. Nothing sensitive is
53
+ ever written to stdout (the MCP channel) or included in tool results.
54
+
55
+ ## Publishing (maintainers)
56
+
57
+ The package publishes over npm OIDC trusted publishing from the repository
58
+ workflow. A brand-new package name requires a one-time bootstrap publish via
59
+ traditional auth, then registering its Trusted Publisher on npmjs.com, before
60
+ the workflow can publish it.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@aura-labs-ai/mcp-server-admission",
3
+ "version": "0.1.0",
4
+ "description": "AURA admission MCP server: the local action layer that onboards an agent onto the AURA certification bench. Holds the agent's Ed25519 keys and signs every admission request locally — keys never leave the machine.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "bin": {
8
+ "mcp-server-admission": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "src/index.js",
12
+ "src/tools.js",
13
+ "src/wallet.js",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test src/tests/*.test.js"
18
+ },
19
+ "dependencies": {
20
+ "@aura-labs-ai/sdk-common": "^0.2.0",
21
+ "@modelcontextprotocol/sdk": "^1.0.0"
22
+ },
23
+ "overrides": {
24
+ "fast-uri": "^3.1.3",
25
+ "hono": "^4.12.28",
26
+ "path-to-regexp": "^8.4.2"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "keywords": [
32
+ "aura",
33
+ "mcp",
34
+ "admission",
35
+ "agent",
36
+ "ed25519",
37
+ "sandbox"
38
+ ],
39
+ "license": "MIT",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }
package/src/index.js ADDED
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * AURA Admission MCP Server (ADR-017, DEC-176)
5
+ *
6
+ * The local action layer of agent admission: an agent installs this server in
7
+ * its own environment, and it holds the agent's Ed25519 keys and signs every
8
+ * admission request itself — the private keys never leave the machine. The
9
+ * hosted AURA MCP stays read/discover-only; authority lives here.
10
+ *
11
+ * Tools (recorded-run order):
12
+ * get_admission_guide — read the admission chain from the bench
13
+ * mint_sandbox_key — two-phase domain-proof mint of the sandbox key
14
+ * provision_sandbox — provision the namespace; opens the recorded run
15
+ * register_principal — register the principal (signed locally)
16
+ * register_agent — register this agent (signed locally)
17
+ * reset_sandbox — open a fresh run
18
+ *
19
+ * Key custody: three Ed25519 slots (principal / agent / domain) plus the chain
20
+ * state, persisted via @aura-labs-ai/sdk-common createStorage() — the macOS
21
+ * Keychain, else ~/.aura/keys.json at 0600 (AURA_KEY_PATH overrides).
22
+ *
23
+ * @see docs/decisions/ADR-017-MCP-ACTION-ARCHITECTURE.md
24
+ */
25
+
26
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
27
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
28
+ import {
29
+ CallToolRequestSchema,
30
+ ListToolsRequestSchema,
31
+ } from '@modelcontextprotocol/sdk/types.js';
32
+
33
+ import { createStorage } from '@aura-labs-ai/sdk-common';
34
+ import { AdmissionWallet } from './wallet.js';
35
+ import { TOOL_DEFINITIONS, TOOL_HANDLERS } from './tools.js';
36
+
37
+ // The certification bench: all six admission operations serve there; the
38
+ // production host does not register them.
39
+ const BENCH_URL = process.env.AURA_BENCH_URL || 'https://sandbox.aura-labs.ai';
40
+
41
+ // stdout is the MCP channel; all logging goes to stderr.
42
+ function log(message) {
43
+ console.error(`[aura-admission] ${message}`);
44
+ }
45
+
46
+ async function main() {
47
+ const storage = createStorage();
48
+ const wallet = new AdmissionWallet(storage);
49
+ const deps = { wallet, fetch: globalThis.fetch, baseUrl: BENCH_URL };
50
+
51
+ const server = new Server(
52
+ { name: 'aura-admission', version: '0.1.0' },
53
+ { capabilities: { tools: {} } },
54
+ );
55
+
56
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
57
+ tools: TOOL_DEFINITIONS,
58
+ }));
59
+
60
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
61
+ const { name, arguments: args } = request.params;
62
+ const handler = TOOL_HANDLERS[name];
63
+ if (!handler) {
64
+ return {
65
+ content: [{ type: 'text', text: JSON.stringify({ status: 'error', error: 'unknown_tool', message: `Unknown tool: ${name}` }) }],
66
+ isError: true,
67
+ };
68
+ }
69
+ let result;
70
+ try {
71
+ result = await handler(args || {}, deps);
72
+ } catch (e) {
73
+ log(`tool ${name} failed: ${e.message}`);
74
+ result = { status: 'error', error: 'tool_failed', message: e.message };
75
+ }
76
+ return {
77
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
78
+ isError: result.status === 'error',
79
+ };
80
+ });
81
+
82
+ const transport = new StdioServerTransport();
83
+ await server.connect(transport);
84
+ log(`ready — bench ${BENCH_URL}, keys via ${process.platform === 'darwin' ? 'Keychain' : 'file storage'}`);
85
+ }
86
+
87
+ main().catch((e) => {
88
+ log(`fatal: ${e.message}`);
89
+ process.exit(1);
90
+ });
package/src/tools.js ADDED
@@ -0,0 +1,331 @@
1
+ /**
2
+ * The six admission action tools (ADR-017, DEC-176).
3
+ *
4
+ * Pure, dependency-injected handlers: every tool is (args, deps) -> result where
5
+ * deps = { wallet, fetch, baseUrl }. No module-level I/O and no imports beyond
6
+ * node builtins, so the handlers unit-test with an in-memory wallet + scripted
7
+ * fetch, and the bench integration suite drives them against the real routes
8
+ * through an injected fetch shim.
9
+ *
10
+ * Auth surfaces (each tool signs locally; keys never leave the wallet):
11
+ * register_principal X-Signature principal key, over JSON.stringify(body)
12
+ * register_agent X-Agent-Signature agent key, over JSON.stringify(body)
13
+ * mint_sandbox_key X-Signature domain key, over JSON.stringify(body)
14
+ * provision_sandbox / reset_sandbox bearer X-AURA-Sandbox-Key, no signature
15
+ * get_admission_guide unauthenticated read
16
+ *
17
+ * ORDERING: the recorded-run happy path is guide -> mint -> provision ->
18
+ * register_principal -> register_agent. Provision opens the conformance run and
19
+ * the recorder attributes registrations to it only when the sandbox key is
20
+ * presented, so registering before provisioning yields identities the transcript
21
+ * never captures. The tool descriptions carry this so an autonomous agent is not
22
+ * misled by the admission phases' ordinal order.
23
+ */
24
+
25
+ const ORDER_NOTE = 'Recorded-run order: get_admission_guide -> mint_sandbox_key -> provision_sandbox -> register_principal -> register_agent (-> reset_sandbox for a fresh run). Provision opens the recorded run; register before provisioning and the transcript never captures the identity.';
26
+
27
+ /** Tool name -> the openapi.json operationId it drives. get_admission_guide reads
28
+ * the bench guide resource, which is deliberately absent from the contract paths
29
+ * (a runtime projection of x-aura-agent-admission), so it maps to null. */
30
+ export const TOOL_OPERATIONS = {
31
+ get_admission_guide: null,
32
+ mint_sandbox_key: 'mintSandboxKey',
33
+ provision_sandbox: 'provisionSandbox',
34
+ register_principal: 'registerPrincipal',
35
+ register_agent: 'registerAgent',
36
+ reset_sandbox: 'resetSandbox',
37
+ };
38
+
39
+ export const TOOL_DEFINITIONS = [
40
+ {
41
+ name: 'get_admission_guide',
42
+ description: `Read the admission guide (GET /v1/admission on the certification bench): the ten phases, their status, and the live operation links. Start here. ${ORDER_NOTE}`,
43
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
44
+ },
45
+ {
46
+ name: 'mint_sandbox_key',
47
+ description: `Mint the sandbox key for a domain you control (POST /v1/sandbox/keys). Two-phase: the first call generates and holds the domain signing key locally and returns the exact domain-control proof to publish (a DNS TXT record, or a well-known HTTPS document); call again once published and the tool attempts the mint, returning the server's looked_for/found verbatim while the proof is still missing. The minted bearer key is held locally for provision/reset/registration. ${ORDER_NOTE}`,
48
+ inputSchema: {
49
+ type: 'object',
50
+ properties: {
51
+ domain: { type: 'string', description: 'The domain you control (no scheme, port, path, or wildcard).' },
52
+ verification_method: { type: 'string', enum: ['dns_txt', 'well_known'], description: 'How you will prove control: a DNS TXT record, or an HTTPS well-known document.' },
53
+ },
54
+ required: ['domain', 'verification_method'],
55
+ additionalProperties: false,
56
+ },
57
+ },
58
+ {
59
+ name: 'provision_sandbox',
60
+ description: `Provision the sandbox namespace (POST /v1/sandbox/namespaces, bearer sandbox key): a seeded market, the manifest, and the OPENED CONFORMANCE RUN (run_id) the transcript records into. Idempotent: a repeat call replays the same namespace and run. Run this BEFORE registering identities so they are recorded. ${ORDER_NOTE}`,
61
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
62
+ },
63
+ {
64
+ name: 'register_principal',
65
+ description: `Register the principal you act for (POST /v1/principals), signed locally with the held principal key (X-Signature). Attaches the held sandbox key so the registration is namespace-stamped and recorded into the open run — provision first, or nothing is recorded. Returns and holds principal_id. ${ORDER_NOTE}`,
66
+ inputSchema: {
67
+ type: 'object',
68
+ properties: {
69
+ principal_type: { type: 'string', enum: ['organization', 'individual'] },
70
+ legal_name: { type: 'string' },
71
+ jurisdiction: { type: 'string', description: 'ISO country code, e.g. US.' },
72
+ contact: {
73
+ type: 'object',
74
+ properties: { name: { type: 'string' }, email: { type: 'string' }, role: { type: 'string' } },
75
+ additionalProperties: false,
76
+ },
77
+ },
78
+ required: ['principal_type', 'legal_name', 'jurisdiction'],
79
+ additionalProperties: false,
80
+ },
81
+ },
82
+ {
83
+ name: 'register_agent',
84
+ description: `Register this agent under the held principal (POST /v1/agents/register), signed locally with the held agent key (X-Agent-Signature). Attaches the held sandbox key so the registration is recorded into the open run. Returns and holds agent_id. ${ORDER_NOTE}`,
85
+ inputSchema: {
86
+ type: 'object',
87
+ properties: {
88
+ type: { type: 'string', enum: ['scout', 'beacon'], description: 'The agent role to register.' },
89
+ principal_id: { type: 'string', description: 'Optional override; defaults to the principal_id held from register_principal.' },
90
+ },
91
+ required: ['type'],
92
+ additionalProperties: false,
93
+ },
94
+ },
95
+ {
96
+ name: 'reset_sandbox',
97
+ description: `Reset the namespace and open a FRESH conformance run (POST /v1/sandbox/namespaces/current/reset, bearer sandbox key). NOT idempotent: each success is a new run boundary and spends run quota; an in-flight flow refuses with sandbox_run_active (let it quiesce), and the tier run quota can refuse with 429. Returns and holds the new run_id. ${ORDER_NOTE}`,
98
+ inputSchema: {
99
+ type: 'object',
100
+ properties: { reason: { type: 'string', description: 'Optional note recorded with the reset.' } },
101
+ additionalProperties: false,
102
+ },
103
+ },
104
+ ];
105
+
106
+ // --- wire helpers ---------------------------------------------------------
107
+
108
+ const DEFAULT_BASE_URL = 'https://sandbox.aura-labs.ai';
109
+
110
+ async function call(deps, method, path, { body, headers } = {}) {
111
+ const baseUrl = (deps.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, '');
112
+ // Byte-frozen: the body is serialized exactly once; signatures are computed by
113
+ // callers over this same string, and this same string is sent.
114
+ const bodyString = body === undefined ? undefined : JSON.stringify(body);
115
+ const res = await deps.fetch(`${baseUrl}/v1${path}`, {
116
+ method,
117
+ headers: {
118
+ ...(bodyString !== undefined && { 'content-type': 'application/json' }),
119
+ ...headers,
120
+ },
121
+ ...(bodyString !== undefined && { body: bodyString }),
122
+ });
123
+ let json = null;
124
+ try { json = await res.json(); } catch { /* non-JSON body */ }
125
+ return { status: res.status, json };
126
+ }
127
+
128
+ /** Serialize once, sign that string with a wallet slot, return both. */
129
+ async function signBody(deps, slot, body) {
130
+ const bodyString = JSON.stringify(body);
131
+ const signature = await deps.wallet.sign(slot, bodyString);
132
+ return { bodyString, signature };
133
+ }
134
+
135
+ async function callSigned(deps, path, body, signatureHeader, slot) {
136
+ const baseUrl = (deps.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, '');
137
+ const { bodyString, signature } = await signBody(deps, slot, body);
138
+ const sandboxKey = await deps.wallet.getState('sandbox_key');
139
+ const res = await deps.fetch(`${baseUrl}/v1${path}`, {
140
+ method: 'POST',
141
+ headers: {
142
+ 'content-type': 'application/json',
143
+ [signatureHeader]: signature,
144
+ ...(sandboxKey && { 'x-aura-sandbox-key': sandboxKey }),
145
+ },
146
+ body: bodyString,
147
+ });
148
+ let json = null;
149
+ try { json = await res.json(); } catch { /* non-JSON body */ }
150
+ return { status: res.status, json, sandboxKeyAttached: Boolean(sandboxKey) };
151
+ }
152
+
153
+ const apiError = (r) => ({
154
+ status: 'error',
155
+ http: r.status,
156
+ error: r.json?.error ?? 'unknown_error',
157
+ message: r.json?.message ?? 'The bench returned a non-success response.',
158
+ });
159
+
160
+ // --- the domain-control proof the mint requires (mirrors Core's derivation) ---
161
+
162
+ export function domainProof(domain, method, publicKeyBase64) {
163
+ if (method === 'dns_txt') {
164
+ return {
165
+ type: 'dns_txt',
166
+ record_name: `_aura-agent-key.${domain}`,
167
+ record_type: 'TXT',
168
+ record_value: `aura-key=${publicKeyBase64}`,
169
+ };
170
+ }
171
+ return {
172
+ type: 'well_known',
173
+ url: `https://${domain}/.well-known/aura-agent-key`,
174
+ body: { public_key: publicKeyBase64 },
175
+ };
176
+ }
177
+
178
+ // --- handlers --------------------------------------------------------------
179
+
180
+ export async function handleGetAdmissionGuide(args, deps) {
181
+ const r = await call(deps, 'GET', '/admission');
182
+ if (r.status !== 200) return apiError(r);
183
+ return {
184
+ status: 'ok',
185
+ recommended_tool_order: ['get_admission_guide', 'mint_sandbox_key', 'provision_sandbox', 'register_principal', 'register_agent', 'reset_sandbox'],
186
+ ordering_note: ORDER_NOTE,
187
+ guide: r.json,
188
+ };
189
+ }
190
+
191
+ export async function handleMintSandboxKey(args, deps) {
192
+ const { domain, verification_method: method } = args;
193
+ const existing = await deps.wallet.getState('sandbox_key');
194
+ if (existing) {
195
+ return {
196
+ status: 'already_minted',
197
+ message: 'A sandbox key is already held; provision_sandbox uses it. A re-mint would revoke it and orphan any provisioned namespace.',
198
+ };
199
+ }
200
+
201
+ // Phase one: the domain key did not exist yet, so the proof cannot have been
202
+ // published. Generate + hold the key and return exactly what to publish.
203
+ const firstCall = !(await deps.wallet.hasKey('domain'));
204
+ const publicKey = await deps.wallet.publicKey('domain');
205
+ const proof = domainProof(domain, method, publicKey);
206
+ if (firstCall) {
207
+ return {
208
+ status: 'proof_required',
209
+ publish: proof,
210
+ next: 'Publish the proof above (you control the domain), then call mint_sandbox_key again with the same arguments.',
211
+ };
212
+ }
213
+
214
+ // Phase two: attempt the mint, signing the exact bytes we send.
215
+ const body = { domain, public_key: publicKey, verification_method: method };
216
+ const r = await callSigned(deps, '/sandbox/keys', body, 'x-signature', 'domain');
217
+ if (r.status === 201) {
218
+ await deps.wallet.setState('sandbox_key', r.json.sandbox_key);
219
+ return {
220
+ status: 'minted',
221
+ display_prefix: r.json.display_prefix,
222
+ domain: r.json.domain,
223
+ note: 'The bearer key is held locally and attached to provision/reset/registration automatically. It is shown once by the server and never again.',
224
+ };
225
+ }
226
+ if (r.status === 403 && r.json?.error === 'sandbox_identity_not_verified') {
227
+ return {
228
+ status: 'proof_pending',
229
+ looked_for: r.json.looked_for,
230
+ found: r.json.found,
231
+ publish: proof,
232
+ next: 'The proof is not visible to the bench yet (publication or propagation). Verify it, then call mint_sandbox_key again.',
233
+ };
234
+ }
235
+ return apiError(r);
236
+ }
237
+
238
+ export async function handleProvisionSandbox(args, deps) {
239
+ const sandboxKey = await deps.wallet.getState('sandbox_key');
240
+ if (!sandboxKey) return { status: 'error', error: 'no_sandbox_key', message: 'Mint a sandbox key first: mint_sandbox_key.' };
241
+ const r = await call(deps, 'POST', '/sandbox/namespaces', { headers: { 'x-aura-sandbox-key': sandboxKey } });
242
+ if (r.status === 201 || r.status === 200) {
243
+ await deps.wallet.setState('namespace_id', r.json.namespace_id);
244
+ if (r.json.run_id) await deps.wallet.setState('run_id', r.json.run_id);
245
+ return {
246
+ status: r.status === 201 ? 'provisioned' : 'already_provisioned',
247
+ namespace_id: r.json.namespace_id,
248
+ run_id: r.json.run_id ?? null,
249
+ scenario_version: r.json.scenario_version,
250
+ quotas: r.json.quotas,
251
+ counterparties: r.json.counterparties,
252
+ note: 'The conformance run is open; registrations from here on are recorded into it.',
253
+ };
254
+ }
255
+ return apiError(r);
256
+ }
257
+
258
+ export async function handleRegisterPrincipal(args, deps) {
259
+ const body = {
260
+ principal_type: args.principal_type,
261
+ legal_name: args.legal_name,
262
+ jurisdiction: args.jurisdiction,
263
+ ...(args.contact && { contact: args.contact }),
264
+ public_key: await deps.wallet.publicKey('principal'),
265
+ };
266
+ const r = await callSigned(deps, '/principals', body, 'x-signature', 'principal');
267
+ if (r.status === 201 || r.status === 200) {
268
+ await deps.wallet.setState('principal_id', r.json.principal_id);
269
+ return {
270
+ status: 'registered',
271
+ principal_id: r.json.principal_id,
272
+ verification_level: r.json.verification_level,
273
+ ...(!r.sandboxKeyAttached && { warning: 'No sandbox key was held, so this registration is not namespace-stamped and was NOT recorded into any run. Mint and provision first for a recorded onboarding.' }),
274
+ };
275
+ }
276
+ return apiError(r);
277
+ }
278
+
279
+ export async function handleRegisterAgent(args, deps) {
280
+ const principalId = args.principal_id ?? (await deps.wallet.getState('principal_id'));
281
+ if (!principalId) return { status: 'error', error: 'no_principal', message: 'Register the principal first: register_principal.' };
282
+ const body = {
283
+ public_key: await deps.wallet.publicKey('agent'),
284
+ type: args.type,
285
+ principal_id: principalId,
286
+ capacity: 'agent_for_principal',
287
+ manifest: {},
288
+ };
289
+ const r = await callSigned(deps, '/agents/register', body, 'x-agent-signature', 'agent');
290
+ if (r.status === 201 || r.status === 200) {
291
+ await deps.wallet.setState('agent_id', r.json.agent_id);
292
+ return {
293
+ status: 'registered',
294
+ agent_id: r.json.agent_id,
295
+ principal_id: r.json.principal_id,
296
+ ...(!r.sandboxKeyAttached && { warning: 'No sandbox key was held, so this registration is not namespace-stamped and was NOT recorded into any run. Mint and provision first for a recorded onboarding.' }),
297
+ };
298
+ }
299
+ return apiError(r);
300
+ }
301
+
302
+ export async function handleResetSandbox(args, deps) {
303
+ const sandboxKey = await deps.wallet.getState('sandbox_key');
304
+ if (!sandboxKey) return { status: 'error', error: 'no_sandbox_key', message: 'Mint a sandbox key first: mint_sandbox_key.' };
305
+ const r = await call(deps, 'POST', '/sandbox/namespaces/current/reset', {
306
+ headers: { 'x-aura-sandbox-key': sandboxKey },
307
+ ...(args.reason && { body: { reason: args.reason } }),
308
+ });
309
+ if (r.status === 200) {
310
+ await deps.wallet.setState('run_id', r.json.run_id);
311
+ return {
312
+ status: 'reset',
313
+ run_id: r.json.run_id,
314
+ namespace_id: r.json.namespace_id,
315
+ scenario_version: r.json.scenario_version,
316
+ note: 'A fresh run is open; prior runs and their transcripts survive.',
317
+ };
318
+ }
319
+ if (r.status === 409) return { status: 'run_active', error: r.json?.error, message: r.json?.message };
320
+ if (r.status === 429) return { status: 'quota_exhausted', error: r.json?.error, message: r.json?.message, quota: r.json?.quota, tier: r.json?.tier };
321
+ return apiError(r);
322
+ }
323
+
324
+ export const TOOL_HANDLERS = {
325
+ get_admission_guide: handleGetAdmissionGuide,
326
+ mint_sandbox_key: handleMintSandboxKey,
327
+ provision_sandbox: handleProvisionSandbox,
328
+ register_principal: handleRegisterPrincipal,
329
+ register_agent: handleRegisterAgent,
330
+ reset_sandbox: handleResetSandbox,
331
+ };
package/src/wallet.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * AdmissionWallet — local custody for the admission chain (ADR-017).
3
+ *
4
+ * The birth chain needs three distinct Ed25519 identities (Core's mint route
5
+ * enforces fingerprint uniqueness across principals, agents, key history, and
6
+ * sandbox keys, so the domain key can never be the principal or agent key):
7
+ *
8
+ * principal — signs the principal registration (X-Signature)
9
+ * agent — signs the agent registration (X-Agent-Signature)
10
+ * domain — signs the sandbox-key mint (X-Signature)
11
+ *
12
+ * plus a state record for what the chain returns (the bearer sandbox key,
13
+ * principal_id, agent_id, namespace_id, run_id), so identity survives across
14
+ * tool calls and process restarts.
15
+ *
16
+ * Keys are generated locally and persisted through an injected storage adapter
17
+ * (in production wiring, @aura-labs-ai/sdk-common createStorage(): macOS
18
+ * Keychain, else ~/.aura/keys.json at 0600). Private keys never leave this
19
+ * module except as signatures. The raw<->KeyObject conversion mirrors the
20
+ * scout SDK KeyManager byte-for-byte.
21
+ */
22
+
23
+ import crypto from 'node:crypto';
24
+
25
+ // Ed25519 DER prefixes for raw key <-> KeyObject conversion (same constants the
26
+ // scout SDK KeyManager uses).
27
+ const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
28
+ const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
29
+
30
+ const SLOTS = ['principal', 'agent', 'domain'];
31
+ const STATE_FIELDS = ['sandbox_key', 'principal_id', 'agent_id', 'namespace_id', 'run_id'];
32
+ const PREFIX = 'aura:admission:';
33
+
34
+ export class AdmissionWallet {
35
+ #storage;
36
+ #keys = new Map(); // slot -> { publicKeyBase64, privateKeyObject }
37
+
38
+ /**
39
+ * @param {{ get: Function, set: Function }} storage - storage adapter (sdk-common shape)
40
+ */
41
+ constructor(storage) {
42
+ if (!storage) throw new Error('AdmissionWallet requires a storage adapter');
43
+ this.#storage = storage;
44
+ }
45
+
46
+ /**
47
+ * Load or generate the keypair for a slot. Returns the base64 raw public key.
48
+ * @param {'principal'|'agent'|'domain'} slot
49
+ * @returns {Promise<string>}
50
+ */
51
+ async publicKey(slot) {
52
+ const k = await this.#load(slot);
53
+ return k.publicKeyBase64;
54
+ }
55
+
56
+ /**
57
+ * Whether a slot's keypair already exists (without generating one). Lets the
58
+ * mint tool distinguish its first call (generate + return the proof to
59
+ * publish) from later calls (attempt the mint).
60
+ * @param {'principal'|'agent'|'domain'} slot
61
+ * @returns {Promise<boolean>}
62
+ */
63
+ async hasKey(slot) {
64
+ if (this.#keys.has(slot)) return true;
65
+ return Boolean(await this.#storage.get(`${PREFIX}${slot}:publicKey`));
66
+ }
67
+
68
+ /**
69
+ * Sign a string with a slot's private key. The signature is the only thing
70
+ * that ever leaves the wallet.
71
+ * @param {'principal'|'agent'|'domain'} slot
72
+ * @param {string} data
73
+ * @returns {Promise<string>} base64 Ed25519 signature
74
+ */
75
+ async sign(slot, data) {
76
+ const k = await this.#load(slot);
77
+ return crypto.sign(null, Buffer.from(data), k.privateKeyObject).toString('base64');
78
+ }
79
+
80
+ /** @param {string} field @returns {Promise<string|null>} */
81
+ async getState(field) {
82
+ this.#assertStateField(field);
83
+ return (await this.#storage.get(`${PREFIX}state:${field}`)) ?? null;
84
+ }
85
+
86
+ /** @param {string} field @param {string} value */
87
+ async setState(field, value) {
88
+ this.#assertStateField(field);
89
+ await this.#storage.set(`${PREFIX}state:${field}`, value);
90
+ }
91
+
92
+ #assertStateField(field) {
93
+ if (!STATE_FIELDS.includes(field)) throw new Error(`unknown wallet state field: ${field}`);
94
+ }
95
+
96
+ async #load(slot) {
97
+ if (!SLOTS.includes(slot)) throw new Error(`unknown wallet key slot: ${slot}`);
98
+ if (this.#keys.has(slot)) return this.#keys.get(slot);
99
+
100
+ const storedPublic = await this.#storage.get(`${PREFIX}${slot}:publicKey`);
101
+ const storedPrivate = await this.#storage.get(`${PREFIX}${slot}:privateKey`);
102
+ if (storedPublic && storedPrivate) {
103
+ const loaded = {
104
+ publicKeyBase64: storedPublic,
105
+ privateKeyObject: crypto.createPrivateKey({
106
+ key: Buffer.concat([PKCS8_PREFIX, Buffer.from(storedPrivate, 'base64')]),
107
+ format: 'der',
108
+ type: 'pkcs8',
109
+ }),
110
+ };
111
+ this.#keys.set(slot, loaded);
112
+ return loaded;
113
+ }
114
+
115
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
116
+ const spkiDer = publicKey.export({ type: 'spki', format: 'der' });
117
+ const publicKeyBase64 = spkiDer.subarray(spkiDer.length - 32).toString('base64');
118
+ const pkcs8Der = privateKey.export({ type: 'pkcs8', format: 'der' });
119
+ const rawPrivateBase64 = pkcs8Der.subarray(pkcs8Der.length - 32).toString('base64');
120
+
121
+ await this.#storage.set(`${PREFIX}${slot}:publicKey`, publicKeyBase64);
122
+ await this.#storage.set(`${PREFIX}${slot}:privateKey`, rawPrivateBase64);
123
+
124
+ const generated = { publicKeyBase64, privateKeyObject: privateKey };
125
+ this.#keys.set(slot, generated);
126
+ return generated;
127
+ }
128
+ }
129
+
130
+ /** The raw public key as a KeyObject — exported for verification in tests. */
131
+ export function rawPublicToKeyObject(publicKeyBase64) {
132
+ return crypto.createPublicKey({
133
+ key: Buffer.concat([SPKI_PREFIX, Buffer.from(publicKeyBase64, 'base64')]),
134
+ format: 'der',
135
+ type: 'spki',
136
+ });
137
+ }