iit-mcp-autotask 0.54.2

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 (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
package/dist/doctor.js ADDED
@@ -0,0 +1,154 @@
1
+ import { serverCredentialDefaults, unrecognisedAutotaskVars } from './config/load.js';
2
+ import {} from './config/schema.js';
3
+ import { credentialShapeProblem } from 'node-autotask';
4
+ import { SECRET_MARKER, SECRET_VARIABLE } from './credential.js';
5
+ import { assertPlanHash, BUILT_AGAINST_PLAN_HASH } from './tools/catalog-data.js';
6
+ /** Check one credential-shaped value without ever carrying it out of this function. */
7
+ function credentialCheck(name, value, required) {
8
+ if (value === undefined || value.trim() === '') {
9
+ // "not set", never "length 0": the boot schema normalises a blank the same way, and a blank is
10
+ // the `.env.example` placeholder rather than a credential the vendor would see.
11
+ return { name, status: 'absent', shapeOk: false, blocks: required };
12
+ }
13
+ const problem = credentialShapeProblem(value);
14
+ const malformed = problem !== undefined;
15
+ return {
16
+ name,
17
+ status: malformed ? 'malformed' : 'ok',
18
+ length: value.length,
19
+ // The SECRET's first two characters are the one place a credential character could cross this
20
+ // boundary: `GET /doctor` is pre-auth and the CLI writes to stdout, while every other surface of
21
+ // this package emits zero characters of a secret (value-scrub to `[REDACTED]`, boot message =
22
+ // length only, envelopes never carry prefixes). The secret is therefore masked with the
23
+ // package's own marker; the identifiers (integration code, username, impersonation id) are not
24
+ // secrets and keep their format prefix, which is what makes the report useful.
25
+ // `<1>` for a one-character value, so the report never implies a one-character secret.
26
+ prefix2: name === SECRET_VARIABLE ? SECRET_MARKER : value.length >= 2 ? value.slice(0, 2) : '<1>',
27
+ shapeOk: !malformed,
28
+ // The SDK's value-free problem string (its first problem only), or none.
29
+ anomalies: malformed ? [problem] : [],
30
+ // `blocks` is "this field would be refused": an absent-and-required field and a malformed one,
31
+ // and nothing else. A present, well-shaped value never blocks, however much the deployment needs it.
32
+ blocks: malformed,
33
+ };
34
+ }
35
+ /**
36
+ * Check one origin value: does it parse, and what origin would actually be dialed?
37
+ *
38
+ * An origin is not a secret (the operator wrote it), but only its origin crosses into the report: a
39
+ * URL with userinfo (`https://user:pass@host`) would otherwise carry a credential into every log
40
+ * sink this report reaches, so the origin is derived and the raw value is dropped.
41
+ */
42
+ function baseCheck(name, value, required) {
43
+ if (value === undefined || value.trim() === '')
44
+ return { name, present: false, resolvable: false, blocks: required };
45
+ let url;
46
+ try {
47
+ url = new URL(value);
48
+ }
49
+ catch {
50
+ return { name, present: true, resolvable: false, blocks: true };
51
+ }
52
+ // `https:` and an origin-only path are the config's own rules; a value that breaks them fails
53
+ // boot, so a doctor report on a live config sees them already enforced. Still reported here, so a
54
+ // doctor run against a hand-built config cannot print green for something the server would refuse.
55
+ const ok = url.protocol === 'https:' && (url.pathname === '' || url.pathname === '/' || url.pathname === '/atservicesrest');
56
+ return { name, present: true, origin: url.origin, resolvable: ok, blocks: !ok };
57
+ }
58
+ /** The host policy mode name for the operator (never a credential, never a caller value). */
59
+ function hostPolicyOf(config) {
60
+ const list = config.AUTOTASK_ALLOWED_BASE_HOSTS;
61
+ const hasDefault = config.AUTOTASK_BASE_URL !== undefined;
62
+ const mode = list !== undefined
63
+ ? hasDefault
64
+ ? 'default_and_list'
65
+ : 'allow_list'
66
+ : hasDefault
67
+ ? 'default_only'
68
+ : config.AUTOTASK_ALLOW_ANY_BASE_HOST
69
+ ? 'any'
70
+ : 'none';
71
+ return {
72
+ allowedBaseHosts: list ?? [],
73
+ mode,
74
+ allowAnyBaseHost: config.AUTOTASK_ALLOW_ANY_BASE_HOST,
75
+ };
76
+ }
77
+ /**
78
+ * Build the doctor report for an already-validated config.
79
+ *
80
+ * Takes the parsed `Config` rather than a raw environment on purpose: `loadConfig` has already
81
+ * refused a blank/missing/origin-invalid configuration — and, at boot, a malformed credential — so
82
+ * reaching here means every structural question is settled and only the SHAPE facts remain.
83
+ *
84
+ * `surface` is the effective tool surface (built by `describeSurface` in `tools/surface.ts`,
85
+ * passed in so this module keeps its zero tool-layer imports): profile, advertised tools, the
86
+ * exposure filters, the policy hash and where the write gate is served.
87
+ *
88
+ * `env` is the environment the config was parsed from, used only to report a variable the operator
89
+ * SET on the non-required path (an `http` deployment's optional credential defaults) without putting
90
+ * its value anywhere. Nothing here reads the network.
91
+ */
92
+ export function runDoctor(config, env = {}, surface) {
93
+ const isStdio = config.MCP_TRANSPORT === 'stdio';
94
+ const defaults = serverCredentialDefaults(config);
95
+ const names = [
96
+ ['AUTOTASK_API_INTEGRATION_CODE', config.AUTOTASK_API_INTEGRATION_CODE ?? env.AUTOTASK_API_INTEGRATION_CODE, isStdio || defaults !== undefined],
97
+ ['AUTOTASK_USERNAME', config.AUTOTASK_USERNAME ?? env.AUTOTASK_USERNAME, isStdio || defaults !== undefined],
98
+ ['AUTOTASK_SECRET', config.AUTOTASK_SECRET ?? env.AUTOTASK_SECRET, isStdio || defaults !== undefined],
99
+ ];
100
+ const credentials = [
101
+ ...names.map(([name, value, required]) => credentialCheck(name, value, required)),
102
+ // Impersonation is optional on every path; an absent one never blocks, a malformed one always does.
103
+ credentialCheck('AUTOTASK_IMPERSONATION_RESOURCE_ID', config.AUTOTASK_IMPERSONATION_RESOURCE_ID ?? env.AUTOTASK_IMPERSONATION_RESOURCE_ID, false),
104
+ ];
105
+ const bases = [
106
+ baseCheck('AUTOTASK_BASE_URL', config.AUTOTASK_BASE_URL, isStdio),
107
+ ];
108
+ const notes = [
109
+ 'zero vendor requests: this report is computed from the environment alone (this module imports no Autotask client)',
110
+ 'shape facts only (length, two-character prefix — masked for the secret — and anomaly names) — a credential value is never read out',
111
+ 'a green doctor means any later 401 is vendor-side (rotated, revoked or role-restricted credential), not a mangled load',
112
+ ];
113
+ // #73: the stale-variable note (diagnostics only — a clean env adds nothing, byte-identical).
114
+ const unrecognised = unrecognisedAutotaskVars(env);
115
+ if (unrecognised.length > 0) {
116
+ notes.push(`unrecognised AUTOTASK_* env vars (ignored by this server): ${unrecognised.join(', ')} — they are not config errors; check the server version if they were copied from another deployment; a known legacy rename is AUTOTASK_API_CODE -> AUTOTASK_API_INTEGRATION_CODE`);
117
+ }
118
+ if (!isStdio) {
119
+ notes.push('http transport: the tool-call credential arrives per request in the X-Autotask-* headers and is checked at that boundary, not here');
120
+ }
121
+ let planHash;
122
+ try {
123
+ assertPlanHash();
124
+ planHash = { builtAgainst: BUILT_AGAINST_PLAN_HASH, installed: BUILT_AGAINST_PLAN_HASH, ok: true };
125
+ }
126
+ catch (err) {
127
+ // The boot gate still refuses; the report says the same thing in structured form. The message
128
+ // names plan hashes, never a credential.
129
+ planHash = {
130
+ builtAgainst: BUILT_AGAINST_PLAN_HASH,
131
+ installed: 'mismatch',
132
+ ok: false,
133
+ problem: err instanceof Error ? err.message : String(err),
134
+ };
135
+ notes.push('the installed SDK plan does not match the one this surface was built against: the server would refuse to boot (see planHash.problem)');
136
+ }
137
+ if (credentials.some((c) => c.blocks)) {
138
+ notes.push('a credential-bearing variable would be refused by the server: fix the load recipe before any live session (a 401 costs a real vendor auth failure, and repeated ones risk an account lock)');
139
+ }
140
+ return {
141
+ ok: !credentials.some((c) => c.blocks) &&
142
+ bases.every((b) => b.blocks !== true) &&
143
+ planHash.ok,
144
+ transport: config.MCP_TRANSPORT,
145
+ dialed: 0,
146
+ credentials,
147
+ bases,
148
+ hostPolicy: hostPolicyOf(config),
149
+ planHash,
150
+ ...(surface !== undefined ? { surface } : {}),
151
+ notes,
152
+ };
153
+ }
154
+ //# sourceMappingURL=doctor.js.map
@@ -0,0 +1,57 @@
1
+ import * as z from 'zod';
2
+ import { type Config } from './config/schema.js';
3
+ /** The request body cap on the HTTP transport (M10). */
4
+ export declare const MAX_BODY_BYTES: number;
5
+ /**
6
+ * One entry of the tokens file. `runScope` is the company scope an operator principal may write in
7
+ * this run; the write path intersects it with the policy on every preview and apply, and boot
8
+ * refuses an operator token without one (`src/write/runtime.ts`).
9
+ */
10
+ declare const TOKEN_ENTRY: z.ZodObject<{
11
+ principal: z.ZodString;
12
+ profile: z.ZodEnum<{
13
+ readonly: "readonly";
14
+ operator: "operator";
15
+ }>;
16
+ toolsets: z.ZodOptional<z.ZodArray<z.ZodEnum<{
17
+ [x: string]: string;
18
+ }>>>;
19
+ runScope: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
20
+ all: z.ZodLiteral<true>;
21
+ }, z.core.$strict>, z.ZodObject<{
22
+ companyIds: z.ZodArray<z.ZodNumber>;
23
+ }, z.core.$strict>]>>;
24
+ }, z.core.$strict>;
25
+ export type TokenEntry = z.infer<typeof TOKEN_ENTRY>;
26
+ /** The loaded tokens file: entries by their SHA-256 key (the token itself is never held). */
27
+ export interface TokenStore {
28
+ /** The entry for a presented bearer token, or undefined (constant-time over every key). */
29
+ verify(bearer: string): TokenEntry | undefined;
30
+ readonly size: number;
31
+ /** Every entry (boot checks: operator tokens and their run scopes). */
32
+ readonly entries: readonly TokenEntry[];
33
+ }
34
+ /** Load and validate `AUTOTASK_HTTP_TOKENS_FILE` once at boot (a bad file fails boot, naming no token). */
35
+ export declare function loadTokenStore(path: string): TokenStore;
36
+ /** The bearer token of a request (`Authorization: Bearer <token>`), or undefined. */
37
+ export declare function bearerOf(request: Request): string | undefined;
38
+ /** The per-request config a token selects: its own profile and toolsets. */
39
+ export declare function configForToken(config: Config, entry: TokenEntry): Config;
40
+ /**
41
+ * The per-principal token bucket: `perMinute` requests a minute, refilled continuously.
42
+ * ponytail: in-process and per replica; a shared limiter (or the gateway) is the upgrade when
43
+ * tokens mode runs more than one replica.
44
+ */
45
+ export declare function createRateLimiter(perMinute: number, now?: () => number): {
46
+ /** 0 when the request may proceed, else the seconds until it may. */
47
+ take(principal: string): number;
48
+ };
49
+ export interface McpGuard {
50
+ /** A refusal response, or the token entry (tokens mode) / null (gateway or loopback) to proceed. */
51
+ check(request: Request): Response | {
52
+ entry: TokenEntry | null;
53
+ };
54
+ }
55
+ /** Build the `/mcp` guard for this deployment. */
56
+ export declare function createMcpGuard(config: Config, tokens?: TokenStore): McpGuard;
57
+ export {};
@@ -0,0 +1,134 @@
1
+ /**
2
+ * http-guard.ts — what stands in front of `/mcp` on the HTTP transport (0.6.0, A12):
3
+ *
4
+ * - Host and Origin validation (DNS-rebinding defence; the spec's Origin MUST) with the SDK's own
5
+ * helpers: on a loopback bind the localhost allowlists apply (plus any configured names); off
6
+ * loopback the configured `AUTOTASK_HTTP_ALLOWED_HOSTS` is required at boot. A request without an
7
+ * `Origin` passes (a non-browser client); a present but unlisted one, or an unlisted `Host`, is 403.
8
+ * - Caller auth in `tokens` mode: a bearer token whose SHA-256 is a key of the tokens file, compared
9
+ * in constant time against every key, names the principal and its own fixed profile and toolsets
10
+ * (so each token sees its own tool list). A missing or unknown token is 401 and sees no list.
11
+ * In `gateway` mode the gateway authenticates callers and this layer does not.
12
+ * - Rate limiting in `tokens` mode: an in-process token bucket per principal
13
+ * (`AUTOTASK_HTTP_RATE_PER_MIN`, default 60), 429 with `Retry-After`. `gateway` mode delegates it.
14
+ *
15
+ * The request body cap (1 MiB, 413) is enforced where the body is read (`http.ts`).
16
+ */
17
+ import { createHash, timingSafeEqual } from 'node:crypto';
18
+ import { readFileSync } from 'node:fs';
19
+ import { hostHeaderValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins, originValidationResponse, } from '@modelcontextprotocol/server';
20
+ import * as z from 'zod';
21
+ import { ConfigError, PROFILES, TOOLSETS, RUN_SCOPE, isLoopbackHost } from './config/schema.js';
22
+ /** The request body cap on the HTTP transport (M10). */
23
+ export const MAX_BODY_BYTES = 1024 * 1024;
24
+ /**
25
+ * One entry of the tokens file. `runScope` is the company scope an operator principal may write in
26
+ * this run; the write path intersects it with the policy on every preview and apply, and boot
27
+ * refuses an operator token without one (`src/write/runtime.ts`).
28
+ */
29
+ const TOKEN_ENTRY = z
30
+ .object({
31
+ principal: z.string().min(1).max(200),
32
+ profile: z.enum(PROFILES),
33
+ toolsets: z.array(z.enum([...TOOLSETS, 'all'])).optional(),
34
+ runScope: RUN_SCOPE.optional(),
35
+ })
36
+ .strict();
37
+ const TOKENS_FILE = z.record(z.string().regex(/^[0-9a-f]{64}$/, 'keys are the lowercase hex SHA-256 of a token'), TOKEN_ENTRY);
38
+ /** Load and validate `AUTOTASK_HTTP_TOKENS_FILE` once at boot (a bad file fails boot, naming no token). */
39
+ export function loadTokenStore(path) {
40
+ let parsed;
41
+ try {
42
+ parsed = TOKENS_FILE.parse(JSON.parse(readFileSync(path, 'utf8')));
43
+ }
44
+ catch (err) {
45
+ const detail = err instanceof z.ZodError ? err.issues.map((i) => `${i.path.join('.') || '(file)'}: ${i.message}`).join('; ') : 'unreadable or not JSON';
46
+ throw new ConfigError(`AUTOTASK_HTTP_TOKENS_FILE is invalid: ${detail}`);
47
+ }
48
+ const entries = Object.entries(parsed).map(([hash, entry]) => ({ key: Buffer.from(hash, 'hex'), entry }));
49
+ if (entries.length === 0)
50
+ throw new ConfigError('AUTOTASK_HTTP_TOKENS_FILE lists no token');
51
+ // One principal, one token (review F6): two tokens under one name would share plans, idempotency
52
+ // keys and a rate bucket while carrying different profiles or run scopes.
53
+ const seen = new Set();
54
+ const repeated = new Set();
55
+ for (const { entry } of entries)
56
+ (seen.has(entry.principal) ? repeated : seen).add(entry.principal);
57
+ if (repeated.size > 0)
58
+ throw new ConfigError(`AUTOTASK_HTTP_TOKENS_FILE is invalid: principal(s) ${[...repeated].join(', ')} appear on more than one token`);
59
+ return {
60
+ size: entries.length,
61
+ entries: entries.map((e) => e.entry),
62
+ verify(bearer) {
63
+ const digest = createHash('sha256').update(bearer, 'utf8').digest();
64
+ let found;
65
+ // Every key is compared, match or not: the time taken does not depend on which one matched.
66
+ for (const { key, entry } of entries)
67
+ if (timingSafeEqual(key, digest))
68
+ found = entry;
69
+ return found;
70
+ },
71
+ };
72
+ }
73
+ /** The bearer token of a request (`Authorization: Bearer <token>`), or undefined. */
74
+ export function bearerOf(request) {
75
+ const m = /^Bearer\s+(\S+)$/i.exec(request.headers.get('authorization') ?? '');
76
+ return m?.[1];
77
+ }
78
+ /** The per-request config a token selects: its own profile and toolsets. */
79
+ export function configForToken(config, entry) {
80
+ const toolsets = entry.toolsets === undefined ? config.AUTOTASK_TOOLSETS : entry.toolsets.includes('all') ? [...TOOLSETS] : entry.toolsets;
81
+ return { ...config, AUTOTASK_PROFILE: entry.profile, AUTOTASK_TOOLSETS: [...toolsets] };
82
+ }
83
+ /**
84
+ * The per-principal token bucket: `perMinute` requests a minute, refilled continuously.
85
+ * ponytail: in-process and per replica; a shared limiter (or the gateway) is the upgrade when
86
+ * tokens mode runs more than one replica.
87
+ */
88
+ export function createRateLimiter(perMinute, now = Date.now) {
89
+ const buckets = new Map();
90
+ const perMs = perMinute / 60_000;
91
+ return {
92
+ /** 0 when the request may proceed, else the seconds until it may. */
93
+ take(principal) {
94
+ const t = now();
95
+ const b = buckets.get(principal) ?? { tokens: perMinute, at: t };
96
+ b.tokens = Math.min(perMinute, b.tokens + (t - b.at) * perMs);
97
+ b.at = t;
98
+ buckets.set(principal, b);
99
+ if (b.tokens >= 1) {
100
+ b.tokens -= 1;
101
+ return 0;
102
+ }
103
+ return Math.ceil((1 - b.tokens) / perMs / 1000);
104
+ },
105
+ };
106
+ }
107
+ function refusal(status, message, headers = {}) {
108
+ return Response.json({ jsonrpc: '2.0', error: { code: -32000, message }, id: null }, { status, headers });
109
+ }
110
+ /** Build the `/mcp` guard for this deployment. */
111
+ export function createMcpGuard(config, tokens) {
112
+ const loopback = isLoopbackHost(config.MCP_HOST);
113
+ const hosts = [...(loopback ? localhostAllowedHostnames() : []), ...(config.AUTOTASK_HTTP_ALLOWED_HOSTS ?? [])];
114
+ const origins = [...(loopback ? localhostAllowedOrigins() : []), ...(config.AUTOTASK_HTTP_ALLOWED_ORIGINS ?? [])];
115
+ const limiter = tokens === undefined ? undefined : createRateLimiter(config.AUTOTASK_HTTP_RATE_PER_MIN);
116
+ return {
117
+ check(request) {
118
+ const rejected = hostHeaderValidationResponse(request, hosts) ?? originValidationResponse(request, origins);
119
+ if (rejected !== undefined)
120
+ return rejected;
121
+ if (tokens === undefined)
122
+ return { entry: null };
123
+ const bearer = bearerOf(request);
124
+ const entry = bearer === undefined ? undefined : tokens.verify(bearer);
125
+ if (entry === undefined)
126
+ return refusal(401, 'Unauthorized: a valid bearer token is required', { 'WWW-Authenticate': 'Bearer' });
127
+ const wait = limiter.take(entry.principal);
128
+ if (wait > 0)
129
+ return refusal(429, 'Too many requests for this principal', { 'Retry-After': String(wait) });
130
+ return { entry };
131
+ },
132
+ };
133
+ }
134
+ //# sourceMappingURL=http-guard.js.map
package/dist/http.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { type Server } from 'node:http';
2
+ import { type Config } from './config/schema.js';
3
+ import type { Logger } from './logger.js';
4
+ import { type McpGuard, type TokenStore } from './http-guard.js';
5
+ /** A fetch-shaped MCP handler, as returned by the SDK's `createMcpHandler`. */
6
+ export interface FetchHandler {
7
+ fetch(request: Request): Promise<Response>;
8
+ }
9
+ /** The orchestrator probe paths (the published contract — none of them call the vendor). */
10
+ export declare const HEALTH_PATH = "/health";
11
+ export declare const READY_PATH = "/ready";
12
+ export declare const METADATA_PATH = "/metadata";
13
+ /**
14
+ * The zero-wire credential preflight route (issue #5).
15
+ *
16
+ * Same trust model as {@link READY_PATH}: answered before the MCP handler, never authenticated, and
17
+ * never touching Autotask. It reports the shape of the SERVER-HELD credential only — the caller's
18
+ * own per-request credential is checked at the tool boundary, one request at a time, and is
19
+ * deliberately not echoed back to the caller that sent it. Reporting shape facts (a length, a
20
+ * two-character prefix — masked for the secret — and anomaly names) about the server's own
21
+ * environment is therefore not a disclosure: the caller that can reach this listener is the operator
22
+ * who set that environment.
23
+ */
24
+ export declare const DOCTOR_PATH = "/doctor";
25
+ /**
26
+ * The `/metadata` payload: the server identity + the MCP protocol baseline + the capability
27
+ * manifest reference, read from `server.json` (the machine-readable surface file) when present.
28
+ * Served verbatim — it is the documented identity, not a re-derivation.
29
+ */
30
+ export declare function loadMetadata(fallback: {
31
+ name: string;
32
+ version: string;
33
+ mcpProtocolBaseline: string;
34
+ legacyProtocolFallback: string;
35
+ }, config?: Pick<Config, 'AUTOTASK_PROFILE' | 'AUTOTASK_TOOLSETS' | 'AUTOTASK_WRITE' | 'AUTOTASK_DEDUP' | 'AUTOTASK_HTTP_AUTH' | 'AUTOTASK_HTTP_RATE_PER_MIN'>): unknown;
36
+ /**
37
+ * Build the fetch-level request handler: `/health` and `/ready`, then (behind the guard, when one
38
+ * is given: Host/Origin validation, caller auth and the rate limit) `/metadata`, `/doctor` and MCP.
39
+ *
40
+ * Split out from the listener so the request path is testable without binding a port.
41
+ */
42
+ export declare function createFetchHandler(mcp: FetchHandler, metadata: unknown, doctor?: () => unknown, guard?: McpGuard, ready?: () => unknown): (request: Request) => Promise<Response>;
43
+ /**
44
+ * Bind the listener. `mcp` is supplied by the caller so this module never builds tools itself.
45
+ *
46
+ * The bind address is `config.MCP_HOST` (`--host`, default `127.0.0.1`). `tokens` is the loaded
47
+ * tokens file in `tokens` mode. `exit` is a parameter only so a test can watch a listen failure
48
+ * without killing the test runner.
49
+ */
50
+ export declare function startHttpServer(config: Config, mcp: FetchHandler, log: Logger, tokens?: TokenStore, exit?: (code: number) => void, env?: Record<string, string | undefined>, ready?: () => unknown): Server;