hmcp-core 0.0.1 → 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.
Files changed (76) hide show
  1. package/README.md +19 -3
  2. package/dist/approvals.d.ts +508 -0
  3. package/dist/approvals.js +1445 -0
  4. package/dist/argpath.d.ts +75 -0
  5. package/dist/argpath.js +189 -0
  6. package/dist/audit.d.ts +289 -0
  7. package/dist/audit.js +512 -0
  8. package/dist/canonical.d.ts +78 -0
  9. package/dist/canonical.js +146 -0
  10. package/dist/classify-held.d.ts +47 -0
  11. package/dist/classify-held.js +60 -0
  12. package/dist/classify-name.d.ts +55 -0
  13. package/dist/classify-name.js +255 -0
  14. package/dist/decide.d.ts +168 -0
  15. package/dist/decide.js +518 -0
  16. package/dist/egress.d.ts +123 -0
  17. package/dist/egress.js +544 -0
  18. package/dist/enforce.d.ts +78 -0
  19. package/dist/enforce.js +231 -0
  20. package/dist/exposure-apply.d.ts +51 -0
  21. package/dist/exposure-apply.js +69 -0
  22. package/dist/exposure.d.ts +81 -0
  23. package/dist/exposure.js +65 -0
  24. package/dist/file-lock.d.ts +70 -0
  25. package/dist/file-lock.js +165 -0
  26. package/dist/glob.d.ts +11 -0
  27. package/dist/glob.js +55 -0
  28. package/dist/grants.d.ts +204 -0
  29. package/dist/grants.js +372 -0
  30. package/dist/http-util.d.ts +52 -0
  31. package/dist/http-util.js +81 -0
  32. package/dist/index.d.ts +35 -0
  33. package/dist/index.js +36 -0
  34. package/dist/inventory.d.ts +100 -0
  35. package/dist/inventory.js +88 -0
  36. package/dist/ip.d.ts +15 -0
  37. package/dist/ip.js +186 -0
  38. package/dist/jwt.d.ts +57 -0
  39. package/dist/jwt.js +199 -0
  40. package/dist/live-state.d.ts +76 -0
  41. package/dist/live-state.js +57 -0
  42. package/dist/migrate.d.ts +22 -0
  43. package/dist/migrate.js +318 -0
  44. package/dist/pins.d.ts +119 -0
  45. package/dist/pins.js +125 -0
  46. package/dist/policy-batch.d.ts +89 -0
  47. package/dist/policy-batch.js +340 -0
  48. package/dist/policy-source.d.ts +161 -0
  49. package/dist/policy-source.js +299 -0
  50. package/dist/policy-write.d.ts +627 -0
  51. package/dist/policy-write.js +1697 -0
  52. package/dist/policy.d.ts +456 -0
  53. package/dist/policy.js +448 -0
  54. package/dist/redact.d.ts +65 -0
  55. package/dist/redact.js +191 -0
  56. package/dist/registry.d.ts +41 -0
  57. package/dist/registry.js +121 -0
  58. package/dist/remember-defaults.d.ts +9 -0
  59. package/dist/remember-defaults.js +9 -0
  60. package/dist/remember.d.ts +91 -0
  61. package/dist/remember.js +371 -0
  62. package/dist/resolve.d.ts +22 -0
  63. package/dist/resolve.js +34 -0
  64. package/dist/runtime-state.d.ts +65 -0
  65. package/dist/runtime-state.js +35 -0
  66. package/dist/secrets.d.ts +159 -0
  67. package/dist/secrets.js +361 -0
  68. package/dist/tenant.d.ts +83 -0
  69. package/dist/tenant.js +182 -0
  70. package/dist/unicode.d.ts +40 -0
  71. package/dist/unicode.js +103 -0
  72. package/dist/within-host.d.ts +33 -0
  73. package/dist/within-host.js +91 -0
  74. package/dist/within-real.d.ts +7 -0
  75. package/dist/within-real.js +28 -0
  76. package/package.json +33 -4
@@ -0,0 +1,159 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The locked-keys file: `~/.hmcp/secrets.json`, mode 0600.
4
+ *
5
+ * gateway.yaml never holds a key the console wrote. It holds a reference,
6
+ * `{ secret: "github_token" }`, and the value lives here, readable only by the
7
+ * owner. That makes gateway.yaml safe to share, back up or paste into a bug
8
+ * report, and it gives sign-in (OAuth) tokens -- which rotate -- somewhere to
9
+ * be rewritten without touching the gateway's config.
10
+ *
11
+ * Several gateway processes read this file at once (each AI app starts its
12
+ * own), and OAuth refresh rewrites it, so every write is taken under a lock
13
+ * and re-reads the file after taking it.
14
+ *
15
+ * CONTRACT (phase 0). Types and signatures are fixed; the bodies of
16
+ * `SecretStore` are implemented by workstream A.
17
+ */
18
+ export declare const SECRET_NAME: RegExp;
19
+ export declare const SecretNameSchema: z.ZodString;
20
+ /** A reference to a stored value, as it appears in gateway.yaml. */
21
+ export declare const SecretRefSchema: z.ZodObject<{
22
+ secret: z.ZodString;
23
+ prefix: z.ZodOptional<z.ZodString>;
24
+ }, z.core.$strict>;
25
+ export type SecretRef = z.infer<typeof SecretRefSchema>;
26
+ /** An env or header value: a literal string (as before), or a reference. */
27
+ export declare const SecretValueSchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
28
+ secret: z.ZodString;
29
+ prefix: z.ZodOptional<z.ZodString>;
30
+ }, z.core.$strict>]>;
31
+ export type SecretValue = z.infer<typeof SecretValueSchema>;
32
+ export declare const isSecretRef: (v: unknown) => v is SecretRef;
33
+ export interface OAuthServerMetadata {
34
+ issuer: string;
35
+ authorization_endpoint: string;
36
+ token_endpoint: string;
37
+ registration_endpoint?: string;
38
+ token_endpoint_auth_methods_supported?: string[];
39
+ scopes_supported?: string[];
40
+ }
41
+ export interface OAuthClientRegistration {
42
+ client_id: string;
43
+ client_secret?: string;
44
+ client_secret_expires_at?: number;
45
+ redirect_uris: string[];
46
+ token_endpoint_auth_method?: string;
47
+ }
48
+ export interface OAuthTokens {
49
+ access_token: string;
50
+ token_type: string;
51
+ refresh_token?: string;
52
+ /** Epoch milliseconds. */
53
+ expires_at?: number;
54
+ scope?: string;
55
+ }
56
+ export type OAuthStatus = "signed-in" | "needs-sign-in";
57
+ export interface SecretValueEntry {
58
+ kind: "value";
59
+ value: string;
60
+ label?: string;
61
+ created_at: string;
62
+ updated_at: string;
63
+ }
64
+ export interface SecretOAuthEntry {
65
+ kind: "oauth";
66
+ label?: string;
67
+ created_at: string;
68
+ updated_at: string;
69
+ /** The MCP server this sign-in is for. */
70
+ server_url: string;
71
+ /** RFC 8707 resource indicator sent with every token request. */
72
+ resource?: string;
73
+ scopes?: string[];
74
+ authorization_server: string;
75
+ metadata: OAuthServerMetadata;
76
+ client: OAuthClientRegistration;
77
+ tokens?: OAuthTokens;
78
+ status: OAuthStatus;
79
+ last_error?: string;
80
+ }
81
+ export type SecretEntry = SecretValueEntry | SecretOAuthEntry;
82
+ export interface SecretsFileV1 {
83
+ version: 1;
84
+ secrets: Record<string, SecretEntry>;
85
+ }
86
+ /** What may be shown about a secret: never its value or tokens. */
87
+ export interface SecretSummary {
88
+ name: string;
89
+ kind: SecretEntry["kind"];
90
+ label?: string;
91
+ /** oauth only. */
92
+ status?: OAuthStatus;
93
+ /** oauth only: when the current access token expires, epoch ms. */
94
+ expires_at?: number;
95
+ /** oauth only: the MCP server URL. */
96
+ server_url?: string;
97
+ updated_at: string;
98
+ }
99
+ /** Plain-words failures. `name` is the secret's name, never its value. */
100
+ export declare class SecretMissing extends Error {
101
+ readonly secretName: string;
102
+ constructor(secretName: string);
103
+ }
104
+ export declare class SecretsFileExposed extends Error {
105
+ readonly path: string;
106
+ constructor(path: string);
107
+ }
108
+ export declare class SecretsFileBroken extends Error {
109
+ readonly path: string;
110
+ constructor(path: string, reason: string);
111
+ }
112
+ /** A comparable stamp of the file, for watchers. `null` when it does not exist. */
113
+ export type FileStamp = {
114
+ mtimeMs: number;
115
+ size: number;
116
+ ino: number;
117
+ } | null;
118
+ export declare function defaultSecretsPath(): string;
119
+ /**
120
+ * The store. Every read goes to disk (the file is small, and another process
121
+ * may have just refreshed a token); every write is locked, re-read, atomic.
122
+ */
123
+ export declare class SecretStore {
124
+ readonly path: string;
125
+ constructor(path?: string);
126
+ /** Names and kinds only. A missing file is an empty list. */
127
+ list(): SecretSummary[];
128
+ get(name: string): SecretEntry | undefined;
129
+ has(name: string): boolean;
130
+ /**
131
+ * The value a reference stands for, with its prefix. A `value` entry gives
132
+ * its value; an `oauth` entry gives its current access token (no refresh --
133
+ * that is the token source's job). Throws SecretMissing.
134
+ */
135
+ resolve(ref: SecretRef): string;
136
+ set(name: string, entry: SecretEntry): void;
137
+ delete(name: string): boolean;
138
+ /** Read-modify-write under the lock; `fn` sees the freshly re-read entry. */
139
+ update(name: string, fn: (current: SecretEntry | undefined) => SecretEntry | undefined): SecretEntry | undefined;
140
+ stamp(): FileStamp;
141
+ private locked;
142
+ /** `~/.hmcp`, private to its owner, when it does not exist yet. An existing one is left as it is. */
143
+ private ensureDir;
144
+ private read;
145
+ /**
146
+ * A temporary file at 0600 beside the real one, flushed, then renamed over
147
+ * it. A reader sees the old file or the new one, never half of either, and
148
+ * the new one is private from the first byte it holds.
149
+ */
150
+ private write;
151
+ }
152
+ /**
153
+ * Turn an env/header record into plain strings. Literals pass through; a
154
+ * reference needs a store and throws SecretMissing when absent. Used by the
155
+ * gateway at connect time and by the console's "Test it" -- nowhere else.
156
+ */
157
+ export declare function resolveSecretRecord(record: Record<string, SecretValue>, store?: SecretStore): Record<string, string>;
158
+ /** The secret names a record refers to. */
159
+ export declare function secretRefsIn(record: Record<string, SecretValue> | undefined): string[];
@@ -0,0 +1,361 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { z } from "zod";
6
+ import { assertPrivateFile, withFileLock } from "./file-lock.js";
7
+ /**
8
+ * The locked-keys file: `~/.hmcp/secrets.json`, mode 0600.
9
+ *
10
+ * gateway.yaml never holds a key the console wrote. It holds a reference,
11
+ * `{ secret: "github_token" }`, and the value lives here, readable only by the
12
+ * owner. That makes gateway.yaml safe to share, back up or paste into a bug
13
+ * report, and it gives sign-in (OAuth) tokens -- which rotate -- somewhere to
14
+ * be rewritten without touching the gateway's config.
15
+ *
16
+ * Several gateway processes read this file at once (each AI app starts its
17
+ * own), and OAuth refresh rewrites it, so every write is taken under a lock
18
+ * and re-reads the file after taking it.
19
+ *
20
+ * CONTRACT (phase 0). Types and signatures are fixed; the bodies of
21
+ * `SecretStore` are implemented by workstream A.
22
+ */
23
+ export const SECRET_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
24
+ export const SecretNameSchema = z.string().regex(SECRET_NAME, "a key name must be lower-case letters, digits, _ . or -");
25
+ /** A reference to a stored value, as it appears in gateway.yaml. */
26
+ export const SecretRefSchema = z
27
+ .object({
28
+ secret: SecretNameSchema,
29
+ /** Text put before the value, such as "Bearer ". */
30
+ prefix: z.string().max(32).optional()
31
+ })
32
+ .strict();
33
+ /** An env or header value: a literal string (as before), or a reference. */
34
+ export const SecretValueSchema = z.union([z.string(), SecretRefSchema]);
35
+ export const isSecretRef = (v) => typeof v === "object" && v !== null && typeof v.secret === "string";
36
+ /** Plain-words failures. `name` is the secret's name, never its value. */
37
+ export class SecretMissing extends Error {
38
+ secretName;
39
+ constructor(secretName) {
40
+ super(`the locked key "${secretName}" is not in the locked-keys file`);
41
+ this.secretName = secretName;
42
+ this.name = "SecretMissing";
43
+ }
44
+ }
45
+ export class SecretsFileExposed extends Error {
46
+ path;
47
+ constructor(path) {
48
+ super(`the locked-keys file ${path} can be read by other people on this computer. ` +
49
+ `Make it private (chmod 600 "${path}") and try again.`);
50
+ this.path = path;
51
+ this.name = "SecretsFileExposed";
52
+ }
53
+ }
54
+ export class SecretsFileBroken extends Error {
55
+ path;
56
+ constructor(path, reason) {
57
+ super(`the locked-keys file ${path} could not be read: ${reason}`);
58
+ this.path = path;
59
+ this.name = "SecretsFileBroken";
60
+ }
61
+ }
62
+ export function defaultSecretsPath() {
63
+ return process.env.HMCP_SECRETS_FILE || join(homedir(), ".hmcp", "secrets.json");
64
+ }
65
+ /* ------------------------------------------------------------ file format */
66
+ /*
67
+ * The file is validated on every read, because it is written by more than one
68
+ * process and may have been edited by hand. Unknown keys are kept rather than
69
+ * stripped (`loose`), so a file written by a newer build survives being
70
+ * rewritten by this one.
71
+ */
72
+ const OAuthServerMetadataSchema = z
73
+ .object({
74
+ issuer: z.string(),
75
+ authorization_endpoint: z.string(),
76
+ token_endpoint: z.string(),
77
+ registration_endpoint: z.string().optional(),
78
+ token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
79
+ scopes_supported: z.array(z.string()).optional()
80
+ })
81
+ .loose();
82
+ const OAuthClientRegistrationSchema = z
83
+ .object({
84
+ client_id: z.string(),
85
+ client_secret: z.string().optional(),
86
+ client_secret_expires_at: z.number().optional(),
87
+ redirect_uris: z.array(z.string()),
88
+ token_endpoint_auth_method: z.string().optional()
89
+ })
90
+ .loose();
91
+ const OAuthTokensSchema = z
92
+ .object({
93
+ access_token: z.string(),
94
+ token_type: z.string(),
95
+ refresh_token: z.string().optional(),
96
+ expires_at: z.number().optional(),
97
+ scope: z.string().optional()
98
+ })
99
+ .loose();
100
+ const SecretValueEntrySchema = z
101
+ .object({
102
+ kind: z.literal("value"),
103
+ value: z.string(),
104
+ label: z.string().optional(),
105
+ created_at: z.string(),
106
+ updated_at: z.string()
107
+ })
108
+ .loose();
109
+ const SecretOAuthEntrySchema = z
110
+ .object({
111
+ kind: z.literal("oauth"),
112
+ label: z.string().optional(),
113
+ created_at: z.string(),
114
+ updated_at: z.string(),
115
+ server_url: z.string(),
116
+ resource: z.string().optional(),
117
+ scopes: z.array(z.string()).optional(),
118
+ authorization_server: z.string(),
119
+ metadata: OAuthServerMetadataSchema,
120
+ client: OAuthClientRegistrationSchema,
121
+ tokens: OAuthTokensSchema.optional(),
122
+ status: z.enum(["signed-in", "needs-sign-in"]),
123
+ last_error: z.string().optional()
124
+ })
125
+ .loose();
126
+ const SecretEntrySchema = z.discriminatedUnion("kind", [SecretValueEntrySchema, SecretOAuthEntrySchema]);
127
+ const SecretsFileSchema = z
128
+ .object({
129
+ version: z.literal(1),
130
+ // Keys checked against the name rule, which also keeps `__proto__` and
131
+ // friends out of the record.
132
+ secrets: z.record(SecretNameSchema, SecretEntrySchema)
133
+ })
134
+ .loose();
135
+ /**
136
+ * Where a zod failure went wrong, without the value. Zod's messages name types
137
+ * and options, not the data, but the path is all a person needs to find the
138
+ * line -- and it is a secret's *name* at most.
139
+ */
140
+ function describeIssues(error) {
141
+ const first = error.issues.slice(0, 3).map((i) => {
142
+ const at = i.path.map(String).join(".") || "(top level)";
143
+ return `${at}: ${i.message}`;
144
+ });
145
+ return first.join("; ");
146
+ }
147
+ const emptyFile = () => ({ version: 1, secrets: {} });
148
+ /**
149
+ * The store. Every read goes to disk (the file is small, and another process
150
+ * may have just refreshed a token); every write is locked, re-read, atomic.
151
+ */
152
+ export class SecretStore {
153
+ path;
154
+ constructor(path) {
155
+ this.path = path ?? defaultSecretsPath();
156
+ }
157
+ /** Names and kinds only. A missing file is an empty list. */
158
+ list() {
159
+ const file = this.read();
160
+ return Object.keys(file.secrets)
161
+ .sort()
162
+ .map((name) => summarize(name, file.secrets[name]));
163
+ }
164
+ get(name) {
165
+ const secrets = this.read().secrets;
166
+ return Object.hasOwn(secrets, name) ? secrets[name] : undefined;
167
+ }
168
+ has(name) {
169
+ return this.get(name) !== undefined;
170
+ }
171
+ /**
172
+ * The value a reference stands for, with its prefix. A `value` entry gives
173
+ * its value; an `oauth` entry gives its current access token (no refresh --
174
+ * that is the token source's job). Throws SecretMissing.
175
+ */
176
+ resolve(ref) {
177
+ const entry = this.get(ref.secret);
178
+ if (!entry)
179
+ throw new SecretMissing(ref.secret);
180
+ const raw = entry.kind === "value" ? entry.value : entry.tokens?.access_token;
181
+ // A sign-in with no token yet is as missing as a key never stored: there is
182
+ // nothing to send, and sending the prefix alone would be a wrong credential.
183
+ if (raw === undefined || raw === "")
184
+ throw new SecretMissing(ref.secret);
185
+ return `${ref.prefix ?? ""}${raw}`;
186
+ }
187
+ set(name, entry) {
188
+ checkName(name);
189
+ const valid = checkEntry(name, entry);
190
+ this.locked(() => {
191
+ const file = this.read();
192
+ file.secrets[name] = valid;
193
+ this.write(file);
194
+ });
195
+ }
196
+ delete(name) {
197
+ return this.locked(() => {
198
+ const file = this.read();
199
+ if (!Object.hasOwn(file.secrets, name))
200
+ return false;
201
+ delete file.secrets[name];
202
+ this.write(file);
203
+ return true;
204
+ });
205
+ }
206
+ /** Read-modify-write under the lock; `fn` sees the freshly re-read entry. */
207
+ update(name, fn) {
208
+ checkName(name);
209
+ return this.locked(() => {
210
+ const file = this.read();
211
+ const had = Object.hasOwn(file.secrets, name);
212
+ // A copy, so a callback that mutates what it was given and then throws
213
+ // leaves nothing half-changed behind.
214
+ const current = had ? structuredClone(file.secrets[name]) : undefined;
215
+ const next = fn(current);
216
+ if (next === undefined) {
217
+ if (had) {
218
+ delete file.secrets[name];
219
+ this.write(file);
220
+ }
221
+ return undefined;
222
+ }
223
+ file.secrets[name] = checkEntry(name, next);
224
+ this.write(file);
225
+ return file.secrets[name];
226
+ });
227
+ }
228
+ stamp() {
229
+ try {
230
+ const s = statSync(this.path);
231
+ return { mtimeMs: s.mtimeMs, size: s.size, ino: Number(s.ino) };
232
+ }
233
+ catch {
234
+ return null;
235
+ }
236
+ }
237
+ /* ------------------------------------------------------------ private */
238
+ locked(fn) {
239
+ this.ensureDir();
240
+ return withFileLock(this.path, fn, { what: "the locked-keys file" });
241
+ }
242
+ /** `~/.hmcp`, private to its owner, when it does not exist yet. An existing one is left as it is. */
243
+ ensureDir() {
244
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
245
+ }
246
+ read() {
247
+ let text;
248
+ try {
249
+ // Checked before the read, so an exposed file's contents are never
250
+ // loaded into a process that is about to refuse them.
251
+ assertPrivateFile(this.path, { error: (path) => new SecretsFileExposed(path) });
252
+ text = readFileSync(this.path, "utf8");
253
+ }
254
+ catch (err) {
255
+ if (err.code === "ENOENT")
256
+ return emptyFile();
257
+ if (err instanceof SecretsFileExposed)
258
+ throw err;
259
+ throw new SecretsFileBroken(this.path, err.message);
260
+ }
261
+ if (text.trim() === "")
262
+ return emptyFile();
263
+ let raw;
264
+ try {
265
+ raw = JSON.parse(text);
266
+ }
267
+ catch {
268
+ /*
269
+ * Never the parser's message: V8 quotes the text around the fault, and
270
+ * in this file the text around any fault is somebody's key.
271
+ */
272
+ throw new SecretsFileBroken(this.path, "it is not valid JSON");
273
+ }
274
+ const parsed = SecretsFileSchema.safeParse(raw);
275
+ if (!parsed.success)
276
+ throw new SecretsFileBroken(this.path, describeIssues(parsed.error));
277
+ return parsed.data;
278
+ }
279
+ /**
280
+ * A temporary file at 0600 beside the real one, flushed, then renamed over
281
+ * it. A reader sees the old file or the new one, never half of either, and
282
+ * the new one is private from the first byte it holds.
283
+ */
284
+ write(file) {
285
+ const dir = dirname(this.path);
286
+ const tmp = join(dir, `.${basename(this.path)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
287
+ const fd = openSync(tmp, "wx", 0o600);
288
+ try {
289
+ writeSync(fd, `${JSON.stringify(file, null, 2)}\n`);
290
+ fsyncSync(fd);
291
+ }
292
+ catch (err) {
293
+ closeSync(fd);
294
+ rmSync(tmp, { force: true });
295
+ throw err;
296
+ }
297
+ closeSync(fd);
298
+ try {
299
+ // `open`'s mode is filtered through the umask; a umask can only remove
300
+ // bits, but say 0600 explicitly rather than rely on that.
301
+ if (process.platform !== "win32")
302
+ chmodSync(tmp, 0o600);
303
+ renameSync(tmp, this.path);
304
+ }
305
+ catch (err) {
306
+ rmSync(tmp, { force: true });
307
+ throw err;
308
+ }
309
+ }
310
+ }
311
+ function checkName(name) {
312
+ const result = SecretNameSchema.safeParse(name);
313
+ if (!result.success)
314
+ throw new Error(`"${name}" cannot be a locked key's name: ${result.error.issues[0].message}`);
315
+ }
316
+ function checkEntry(name, entry) {
317
+ const result = SecretEntrySchema.safeParse(entry);
318
+ // The issue's path and message, never the entry: it may carry the value.
319
+ if (!result.success)
320
+ throw new Error(`the locked key "${name}" is not valid: ${describeIssues(result.error)}`);
321
+ return result.data;
322
+ }
323
+ function summarize(name, entry) {
324
+ // Built field by field rather than by removing fields, so nothing added to
325
+ // an entry later can reach a summary without being named here.
326
+ const out = { name, kind: entry.kind, updated_at: entry.updated_at };
327
+ if (entry.label !== undefined)
328
+ out.label = entry.label;
329
+ if (entry.kind === "oauth") {
330
+ out.status = entry.status;
331
+ out.server_url = entry.server_url;
332
+ if (entry.tokens?.expires_at !== undefined)
333
+ out.expires_at = entry.tokens.expires_at;
334
+ }
335
+ return out;
336
+ }
337
+ /**
338
+ * Turn an env/header record into plain strings. Literals pass through; a
339
+ * reference needs a store and throws SecretMissing when absent. Used by the
340
+ * gateway at connect time and by the console's "Test it" -- nowhere else.
341
+ */
342
+ export function resolveSecretRecord(record, store) {
343
+ const out = {};
344
+ for (const [key, value] of Object.entries(record)) {
345
+ if (typeof value === "string")
346
+ out[key] = value;
347
+ else if (!store)
348
+ throw new SecretMissing(value.secret);
349
+ else
350
+ out[key] = store.resolve(value);
351
+ }
352
+ return out;
353
+ }
354
+ /** The secret names a record refers to. */
355
+ export function secretRefsIn(record) {
356
+ if (!record)
357
+ return [];
358
+ return Object.values(record)
359
+ .filter(isSecretRef)
360
+ .map((r) => r.secret);
361
+ }
@@ -0,0 +1,83 @@
1
+ import { type TenantConfig } from "./policy.js";
2
+ export declare class TenantError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export interface TenantResolverOptions {
6
+ /** Request headers, for the `header` source. Supplied per-call by the gateway. */
7
+ readonly headers?: Record<string, string | string[] | undefined>;
8
+ readonly env?: NodeJS.ProcessEnv;
9
+ /**
10
+ * Where the tenant is allowed to come from.
11
+ *
12
+ * `"process"` (the default) is a server bound to one tenant at startup.
13
+ * `"request"` is a hosted deployment resolving it per call, where the
14
+ * sources that trust their input are refused outright.
15
+ */
16
+ readonly trust?: "process" | "request";
17
+ /** The already-verified tenant, for the `jwt-verified` source. */
18
+ readonly verified?: string | undefined;
19
+ }
20
+ /**
21
+ * Produces the tenant identifier bound to the running credential. This value is
22
+ * never taken from agent input - that is the whole point of tenant scoping, and
23
+ * why a tenant argument in an agent-facing schema is a finding (HMCP002) rather
24
+ * than a parameter the gateway fills in.
25
+ *
26
+ * Note the `jwt-claim` source reads the claim without verifying the token's
27
+ * signature. The token is our own credential, not attacker-supplied input, so
28
+ * there is nothing to forge here; it is a way to avoid duplicating the tenant
29
+ * id in a second environment variable.
30
+ */
31
+ export declare function resolveTenant(config: TenantConfig, options?: TenantResolverOptions): string | undefined;
32
+ /** Resolves and fails loudly when the policy marks tenant scoping required. */
33
+ export declare function requireTenant(config: TenantConfig, options?: TenantResolverOptions): string | undefined;
34
+ export interface TenantInjection {
35
+ readonly path: Record<string, string>;
36
+ readonly query: Record<string, string>;
37
+ readonly body: Record<string, string>;
38
+ readonly headers: Record<string, string>;
39
+ }
40
+ /**
41
+ * Builds the server-side values to splice into an upstream request. The agent
42
+ * never supplies these and cannot see them in a tool schema.
43
+ */
44
+ export declare function tenantInjection(config: TenantConfig, value: string): TenantInjection;
45
+ /**
46
+ * The reserved tenant key for "this deployment has no tenant configured".
47
+ *
48
+ * Empty string rather than NULL, because SQLite permits several NULLs in a
49
+ * non-rowid PRIMARY KEY column — `tool_exposure` would quietly stop being
50
+ * unique. Rather than a sentinel like "-", which a real tenant could be
51
+ * called, because `resolveTenant` already rejects an empty value on both the
52
+ * env and header branches, so no real tenant can ever be "".
53
+ */
54
+ export declare const NO_TENANT = "";
55
+ /**
56
+ * Canonicalises a resolved tenant before it is used as a storage key.
57
+ *
58
+ * Single-tenant deployments read this value from their own environment and it
59
+ * is whatever the operator typed. Once a hosted gateway resolves it per
60
+ * request it is attacker-influenced, and a key that can be spelled two ways is
61
+ * a key that can be made to collide or to split: `acme` and `acme ` must not
62
+ * become two scopes, and two different-looking strings must not become one.
63
+ *
64
+ * So: NFC, because the same name composed two ways in Unicode must compare
65
+ * equal; trimmed; length-capped; and restricted to an unambiguous alphabet. A
66
+ * control character has no business in an identifier and is how a value gets
67
+ * smuggled past a log line or a terminal.
68
+ */
69
+ export declare function normalizeTenantKey(raw: string): string;
70
+ /**
71
+ * What a row in the approvals database belongs to.
72
+ *
73
+ * Two axes, because they answer different questions and neither implies the
74
+ * other. `component` is which server ("generated:Billing"), and is the same
75
+ * string for every deployment of that server. `tenant` is whose data the call
76
+ * touches. One database holds rows for many of both.
77
+ */
78
+ export interface Scope {
79
+ readonly component: string;
80
+ readonly tenant: string;
81
+ }
82
+ /** A scope for a deployment with no tenant configured. */
83
+ export declare function componentScope(component: string): Scope;