copilot-agents-mcp 0.1.0 → 0.2.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.
@@ -0,0 +1,159 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import * as https from "node:https";
3
+ import { isIP } from "node:net";
4
+ import { webhookPayloadId } from "./delivery.js";
5
+ const VALIDATION_ERRORS = {
6
+ input: "Invalid webhook URL. Provide an absolute URL without embedded credentials.",
7
+ https: "Webhook URL must use HTTPS. Change the URL scheme to https.",
8
+ nonPublic: "Webhook URL resolves to a non-public address. Use a host whose addresses are all public.",
9
+ allowedHost: "Webhook host is outside COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS. Use an allowed host or update that setting.",
10
+ dns: "Webhook DNS lookup failed. Check the hostname and DNS configuration, then retry.",
11
+ };
12
+ export class WebhookValidationError extends Error {
13
+ constructor(reason) {
14
+ super(VALIDATION_ERRORS[reason]);
15
+ this.name = "WebhookValidationError";
16
+ }
17
+ }
18
+ const DELIVERY_FAILED = "Webhook delivery failed.";
19
+ const TIMEOUT_MS = 10_000;
20
+ function publicIpv4(address) {
21
+ const octets = address.split(".").map(Number);
22
+ const [a = 0, b = 0, c = 0] = octets;
23
+ return !(a === 0 || a === 10 || a === 127 || a >= 224
24
+ || (a === 100 && b >= 64 && b <= 127)
25
+ || (a === 169 && b === 254)
26
+ || (a === 172 && b >= 16 && b <= 31)
27
+ || (a === 192 && (b === 168 || (b === 0 && (c === 0 || c === 2)) || (b === 88 && c === 99)))
28
+ || (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100)))
29
+ || (a === 203 && b === 0 && c === 113));
30
+ }
31
+ function ipv6Value(address) {
32
+ const expanded = address.replace(/\d+\.\d+\.\d+\.\d+$/, (ipv4) => {
33
+ const octets = ipv4.split(".").map(Number);
34
+ return `${((octets[0] ?? 0) * 256 + (octets[1] ?? 0)).toString(16)}:${((octets[2] ?? 0) * 256 + (octets[3] ?? 0)).toString(16)}`;
35
+ });
36
+ const [left = "", right] = expanded.split("::");
37
+ const head = left ? left.split(":") : [];
38
+ const tail = right ? right.split(":") : [];
39
+ const words = right === undefined ? head : [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail];
40
+ return words.reduce((value, word) => (value << 16n) | BigInt(`0x${word}`), 0n);
41
+ }
42
+ function publicAddress(address) {
43
+ const family = isIP(address);
44
+ if (family === 4)
45
+ return publicIpv4(address);
46
+ if (family !== 6)
47
+ return false;
48
+ const value = ipv6Value(address);
49
+ if (value >> 32n === 0xffffn) {
50
+ const ipv4 = [24n, 16n, 8n, 0n].map((shift) => Number((value >> shift) & 255n)).join(".");
51
+ return publicIpv4(ipv4);
52
+ }
53
+ // Only global unicast; exclude documentation and transition ranges.
54
+ return value >> 125n === 1n
55
+ && value >> 96n !== 0x20010db8n
56
+ && value >> 96n !== 0x20010000n
57
+ && value >> 80n !== 0x200100020000n
58
+ && value >> 100n !== 0x2001001n
59
+ && value >> 100n !== 0x2001002n
60
+ && value >> 108n !== 0x3fff0n
61
+ && value >> 112n !== 0x2002n;
62
+ }
63
+ const resolveWebhook = (hostname) => lookup(hostname, { all: true, verbatim: true });
64
+ export async function validateWebhookUrl(input, env = process.env, resolver = resolveWebhook) {
65
+ let url;
66
+ try {
67
+ url = new URL(input);
68
+ }
69
+ catch {
70
+ throw new WebhookValidationError("input");
71
+ }
72
+ if (url.protocol !== "https:")
73
+ throw new WebhookValidationError("https");
74
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
75
+ if (url.username || url.password || !hostname)
76
+ throw new WebhookValidationError("input");
77
+ if (hostname.toLowerCase().replace(/\.$/, "") === "metadata.google.internal") {
78
+ throw new WebhookValidationError("nonPublic");
79
+ }
80
+ const allowed = env.COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS;
81
+ if (allowed !== undefined && !allowed.split(",").some((host) => host.trim().toLowerCase() === hostname.toLowerCase())) {
82
+ throw new WebhookValidationError("allowedHost");
83
+ }
84
+ const family = isIP(hostname);
85
+ let addresses;
86
+ try {
87
+ addresses = family ? [{ address: hostname, family }] : await resolver(hostname);
88
+ }
89
+ catch {
90
+ throw new WebhookValidationError("dns");
91
+ }
92
+ if (!addresses.length)
93
+ throw new WebhookValidationError("dns");
94
+ if (addresses.some(({ address, family: resolvedFamily }) => (!publicAddress(address) || isIP(address) !== resolvedFamily)))
95
+ throw new WebhookValidationError("nonPublic");
96
+ return { url, addresses };
97
+ }
98
+ export function webhookPost(notice, authorization) {
99
+ const headers = {
100
+ "Content-Type": "application/json",
101
+ "Idempotency-Key": webhookPayloadId(notice.task_id, notice.state),
102
+ };
103
+ if (authorization)
104
+ headers.Authorization = authorization;
105
+ return {
106
+ body: JSON.stringify({
107
+ task_id: notice.task_id,
108
+ state: notice.state,
109
+ repo: notice.repo,
110
+ pr_url: notice.pull_request?.html_url ?? null,
111
+ }),
112
+ headers,
113
+ };
114
+ }
115
+ export async function postOwnerNotice(input, notice, authorization, env = process.env) {
116
+ try {
117
+ const { url, addresses } = await validateWebhookUrl(input, env);
118
+ const [pinned] = addresses;
119
+ const pinnedLookup = (_hostname, options, callback) => {
120
+ if (options.all)
121
+ callback(null, [{ address: pinned.address, family: pinned.family }]);
122
+ else
123
+ callback(null, pinned.address, pinned.family);
124
+ };
125
+ const { body, headers } = webhookPost(notice, authorization);
126
+ await new Promise((resolve, reject) => {
127
+ const request = https.request(url, {
128
+ method: "POST",
129
+ agent: false,
130
+ lookup: pinnedLookup,
131
+ servername: isIP(url.hostname.replace(/^\[|\]$/g, "")) ? "" : url.hostname,
132
+ headers: {
133
+ ...headers,
134
+ Host: url.host,
135
+ "Content-Length": Buffer.byteLength(body),
136
+ },
137
+ timeout: TIMEOUT_MS,
138
+ }, (response) => {
139
+ response.on("error", () => reject(new Error(DELIVERY_FAILED)));
140
+ response.resume();
141
+ if (response.statusCode && response.statusCode >= 200 && response.statusCode < 300)
142
+ resolve();
143
+ else
144
+ reject(new Error(DELIVERY_FAILED));
145
+ });
146
+ const timer = setTimeout(() => request.destroy(new Error(DELIVERY_FAILED)), TIMEOUT_MS);
147
+ request.on("close", () => clearTimeout(timer));
148
+ request.on("error", () => {
149
+ clearTimeout(timer);
150
+ reject(new Error(DELIVERY_FAILED));
151
+ });
152
+ request.on("timeout", () => request.destroy(new Error(DELIVERY_FAILED)));
153
+ request.end(body);
154
+ });
155
+ }
156
+ catch {
157
+ throw new Error(DELIVERY_FAILED);
158
+ }
159
+ }
@@ -0,0 +1,102 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, rename, rm } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { readState, withStateLock } from "./state.js";
6
+ import { validateOwner } from "./tasks.js";
7
+ import { validateWebhookUrl, WebhookValidationError } from "./webhook-http.js";
8
+ export const WEBHOOK_ERROR = "Could not complete webhook operation.";
9
+ export const WEBHOOK_INPUT_ERROR = "Invalid webhook input. Use a valid --owner, secret files (--url-file and --auth-file) or hidden terminal prompts, and a nonempty single-line Authorization value.";
10
+ export function webhookKeyPath(statePath, owner) {
11
+ const digest = createHash("sha256").update(validateOwner(owner)).digest("hex");
12
+ return join(dirname(statePath), digest);
13
+ }
14
+ export function ownerWebhook(state, task) {
15
+ if (!task.owner || !task.created_at || !Object.hasOwn(state.webhooks ?? {}, task.owner))
16
+ return undefined;
17
+ const registration = state.webhooks?.[task.owner];
18
+ if (registration && Date.parse(task.created_at) > Date.parse(registration.registeredAt))
19
+ return registration;
20
+ return undefined;
21
+ }
22
+ export async function registerWebhook(statePath, owner, url, authorization, options) {
23
+ try {
24
+ owner = validateOwner(owner);
25
+ }
26
+ catch {
27
+ throw new Error(WEBHOOK_INPUT_ERROR);
28
+ }
29
+ if (!authorization.trim() || /[\r\n]/.test(authorization))
30
+ throw new Error(WEBHOOK_INPUT_ERROR);
31
+ try {
32
+ await validateWebhookUrl(url, options?.env ?? process.env);
33
+ await withStateLock(statePath, async (state) => {
34
+ const keyFilePath = webhookKeyPath(statePath, owner);
35
+ const staging = `${keyFilePath}.${randomUUID()}`;
36
+ try {
37
+ const file = await open(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
38
+ try {
39
+ await file.chmod(0o600);
40
+ await file.writeFile(authorization, "utf8");
41
+ await file.sync();
42
+ }
43
+ finally {
44
+ await file.close();
45
+ }
46
+ await rename(staging, keyFilePath);
47
+ }
48
+ finally {
49
+ await rm(staging, { force: true });
50
+ }
51
+ state.webhooks ??= {};
52
+ Object.defineProperty(state.webhooks, owner, {
53
+ value: { url, keyFilePath, registeredAt: new Date((options?.now ?? Date.now)()).toISOString() },
54
+ enumerable: true,
55
+ writable: true,
56
+ configurable: true,
57
+ });
58
+ });
59
+ }
60
+ catch (error) {
61
+ if (error instanceof WebhookValidationError)
62
+ throw error;
63
+ throw new Error(WEBHOOK_ERROR);
64
+ }
65
+ }
66
+ export async function removeWebhook(statePath, owner) {
67
+ try {
68
+ owner = validateOwner(owner);
69
+ await withStateLock(statePath, async (state) => {
70
+ await rm(webhookKeyPath(statePath, owner), { force: true });
71
+ if (state.webhooks)
72
+ Reflect.deleteProperty(state.webhooks, owner);
73
+ });
74
+ }
75
+ catch {
76
+ throw new Error(WEBHOOK_ERROR);
77
+ }
78
+ }
79
+ export async function listWebhooks(statePath) {
80
+ try {
81
+ const state = await readState(statePath);
82
+ return await Promise.all(Object.entries(state.webhooks ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(async ([owner, registration]) => {
83
+ let keyPresent = false;
84
+ let keyMode0600 = false;
85
+ const keyFilePath = webhookKeyPath(statePath, owner);
86
+ if (registration.keyFilePath === keyFilePath) {
87
+ try {
88
+ const stat = await lstat(keyFilePath);
89
+ keyPresent = stat.isFile();
90
+ keyMode0600 = keyPresent && (stat.mode & 0o777) === 0o600;
91
+ }
92
+ catch {
93
+ // A missing or inaccessible key is a diagnostic, not a secret read.
94
+ }
95
+ }
96
+ return { owner, host: new URL(registration.url).hostname, keyFilePath, registeredAt: registration.registeredAt, keyPresent, keyMode0600 };
97
+ }));
98
+ }
99
+ catch {
100
+ throw new Error(WEBHOOK_ERROR);
101
+ }
102
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilot-agents-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Local MCP server for launching GitHub Copilot cloud agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",