opencode-m365-copilot 0.3.0 → 0.3.1

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 CHANGED
@@ -162,11 +162,17 @@ records are checked against the real `@opencode/plugin` schema constructors. It
162
162
  "leanSystemPrompt": false, // replace opencode's prose prompt (default: false)
163
163
  "setDefaultModel": true, // set `model` if you have not (default: true)
164
164
  "setSmallModel": true, // route title generation to the local titler (default: true)
165
- "baseUrl": null // use an already-running proxy instead of an in-process one
165
+ "baseUrl": null, // use an already-running proxy instead of an in-process one
166
+ "apiKey": null // that proxy's secret (or export M365_PROXY_KEY instead)
166
167
  }]]
167
168
  }
168
169
  ```
169
170
 
171
+ The in-process proxy needs no key configured: it mints a random secret each launch and
172
+ hands it to opencode itself. Only a standalone `opencode-m365 serve` proxy needs one —
173
+ `serve` prints its key, or takes a fixed one from `M365_PROXY_KEY`. Either put that key
174
+ in `apiKey`, or export the same `M365_PROXY_KEY` to opencode and leave `apiKey` out.
175
+
170
176
  On opencode 2 the same block goes under `plugins`, as `{ "package": ..., "options": ... }`.
171
177
 
172
178
  ### Why `small_model` is redirected
@@ -211,6 +217,10 @@ Two ways to sign in:
211
217
  `~/.config/opencode-copilot/secrets.json`. `mfaSecret` is the **base32 seed** your
212
218
  authenticator derives codes from (`JBSWY3DPEHPK3PXP`), not a 6-digit code. Most password
213
219
  managers will show it; an `otpauth://` URI is accepted and the seed extracted.
220
+ That file holds **both** sign-in factors — anyone who can read it can pass MFA as you —
221
+ so keep it `chmod 600` (the CLI tightens a looser file itself and warns), keep it off
222
+ backups and synced folders, and prefer interactive sign-in if you can. It is only read
223
+ by `opencode-m365 login`; you can delete it once you have signed in.
214
224
  - **Interactive** — `opencode-m365 login --interactive` opens a window and you complete
215
225
  SSO/MFA by hand once. Required for tenants with push-only MFA, FIDO2, or a federated IdP
216
226
  (Okta/Ping/Duo), where no seed exists to extract.
@@ -231,14 +241,17 @@ which belongs to the m365-copilot-proxy project.
231
241
  opencode-m365 login [--interactive] # sign in
232
242
  opencode-m365 setup [--local] # register the plugin with opencode
233
243
  opencode-m365 serve [--port 4141] # run the proxy standalone, for any OpenAI client
244
+ # (send its key as `Authorization: Bearer`)
234
245
  opencode-m365 doctor # check auth, agent, proxy and opencode wiring
235
246
  ```
236
247
 
237
248
  ## Limits
238
249
 
239
- - **600 user messages per conversation.** The proxy reuses one conversation per task and
250
+ - **600 user messages per conversation.** The proxy reuses one conversation per task,
240
251
  sends only new messages, and reports the remaining budget in
241
- `usage.x_m365_conversation_remaining`.
252
+ `usage.x_m365_conversation_remaining`. A task is the opencode session on opencode 2,
253
+ or the system prompt plus the first user message otherwise; turns within one task run
254
+ one at a time.
242
255
  - **Account-level throttling** exists and is keyed to your identity, so re-authenticating
243
256
  does not clear it. It self-heals after a lull.
244
257
  - **Streaming** works for tool-less turns. A tool turn is buffered, because a fenced call
@@ -1,7 +1,6 @@
1
- import { c as POWERPLATFORM_SCOPE, h as AGENT_FILE, m as createLogger, o as BAP_SCOPE } from "./server-DuHBfcPQ.mjs";
1
+ import { _ as createLogger, b as AGENT_FILE, d as POWERPLATFORM_SCOPE, l as BAP_SCOPE, y as writePrivateFile } from "./server-DO0_u884.mjs";
2
2
  import { createHash } from "node:crypto";
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
- import { dirname } from "node:path";
3
+ import { readFileSync } from "node:fs";
5
4
  //#region src/agent.ts
6
5
  /**
7
6
  * The Copilot Studio declarative agent.
@@ -205,8 +204,7 @@ function readCache(file) {
205
204
  }
206
205
  function writeCache(file, cache) {
207
206
  try {
208
- mkdirSync(dirname(file), { recursive: true });
209
- writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`);
207
+ writePrivateFile(file, `${JSON.stringify(cache, null, 2)}\n`);
210
208
  } catch (error) {
211
209
  log.warn("could not write the agent cache", String(error));
212
210
  }
package/dist/cli.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { D as LOCAL_TITLE_MODEL, E as DEFAULT_MODEL, _ as CONFIG_DIR, b as PROVIDER_ID, g as CACHE_FILE, h as AGENT_FILE, n as startServer, p as createTokenClient, v as SECRETS_FILE, w as mergeOpencodeConfig } from "./server-DuHBfcPQ.mjs";
3
- import { t as getOrCreateAgent } from "./agent-BDA00x1V.mjs";
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
2
+ import { C as SECRETS_FILE, M as LOCAL_TITLE_MODEL, S as CONFIG_DIR, T as PROVIDER_ID, a as startServer, b as AGENT_FILE, g as createTokenClient, j as DEFAULT_MODEL, k as mergeOpencodeConfig, x as CACHE_FILE } from "./server-DO0_u884.mjs";
3
+ import { t as getOrCreateAgent } from "./agent-C3DxtJPy.mjs";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
5
  import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  //#region src/cli.ts
9
9
  /**
@@ -36,6 +36,7 @@ function printHelp() {
36
36
  login [--interactive] Sign in to Microsoft 365 and store the token cache
37
37
  setup [--local] Add the plugin to ~/.config/opencode/opencode.json
38
38
  serve [--port <n>] Run the OpenAI-compatible proxy standalone
39
+ (key from M365_PROXY_KEY, else printed)
39
40
  doctor Check auth, the agent, and the proxy
40
41
 
41
42
  Config lives in ${CONFIG_DIR}
@@ -45,7 +46,7 @@ to complete SSO/MFA by hand once — the only option on tenants with push-only
45
46
  MFA, FIDO2, or a federated IdP.`);
46
47
  }
47
48
  async function doLogin(args) {
48
- const { login } = await import("./login-Cb_rQQHO.mjs");
49
+ const { login } = await import("./login-_9JzoRK8.mjs");
49
50
  const interactive = args.includes("--interactive");
50
51
  try {
51
52
  const account = await login({
@@ -84,11 +85,16 @@ async function doSetup(args) {
84
85
  }
85
86
  const merged = mergeOpencodeConfig(existing, {
86
87
  pluginRef,
87
- pluginDir
88
+ pluginDir,
89
+ inspect: inspectPluginPath
88
90
  });
89
91
  mkdirSync(dirname(OPENCODE_CONFIG), { recursive: true });
92
+ const backup = `${OPENCODE_CONFIG}.bak`;
93
+ const hadConfig = existsSync(OPENCODE_CONFIG);
94
+ if (hadConfig) copyFileSync(OPENCODE_CONFIG, backup);
90
95
  writeFileSync(OPENCODE_CONFIG, `${JSON.stringify(merged, null, 2)}\n`);
91
96
  console.log(`Added ${pluginRef} to ${OPENCODE_CONFIG}`);
97
+ if (hadConfig) console.log(`(previous version saved as ${backup})`);
92
98
  console.log(`\nThe plugin registers the provider itself on startup, so there is nothing`);
93
99
  console.log(`else to configure. Models appear as ${PROVIDER_ID}/<model>, defaulting to`);
94
100
  console.log(`${PROVIDER_ID}/${DEFAULT_MODEL}.`);
@@ -97,19 +103,43 @@ async function doSetup(args) {
97
103
  console.log(`README. Pass { "lean": false } in the plugin options to opt out.`);
98
104
  console.log(`\nCheck it with: opencode models | grep ${PROVIDER_ID}`);
99
105
  }
106
+ /** Which package owns a local plugin path: its own dir or the one above (`dist/`). */
107
+ function inspectPluginPath(path) {
108
+ if (!existsSync(path)) return { exists: false };
109
+ const start = path.endsWith(".mjs") || path.endsWith(".js") ? dirname(path) : path;
110
+ for (const dir of [start, dirname(start)]) try {
111
+ const name = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))?.name;
112
+ if (typeof name === "string") return {
113
+ exists: true,
114
+ packageName: name
115
+ };
116
+ } catch {}
117
+ return { exists: true };
118
+ }
100
119
  async function doServe(args) {
101
120
  const portIndex = args.indexOf("--port");
102
121
  const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 4141;
103
122
  const tokens = createTokenClient();
123
+ const fixedKey = process.env.M365_PROXY_KEY || void 0;
104
124
  const proxy = await startServer({
105
125
  getToken: () => tokens.getToken(),
106
126
  resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
107
- port
127
+ port,
128
+ ...fixedKey ? { apiKey: fixedKey } : {}
108
129
  });
109
130
  console.log(`M365 Copilot proxy listening on ${proxy.url}`);
110
131
  console.log(` models: ${proxy.url}/v1/models`);
111
132
  console.log(` completions: ${proxy.url}/v1/chat/completions`);
112
- console.log("\nUnauthenticated and loopback-only. Ctrl+C to stop.");
133
+ console.log("\nLoopback-only. Every request must send `Authorization: Bearer <key>`;");
134
+ console.log("browser origins and CORS are refused.");
135
+ if (fixedKey) console.log(" key: from M365_PROXY_KEY");
136
+ else {
137
+ console.log(` key: ${proxy.apiKey}`);
138
+ console.log(" (new every launch — set M365_PROXY_KEY to keep one)");
139
+ }
140
+ console.log(`\nPoint the plugin here with { "baseUrl": "${proxy.url}/v1", "apiKey": "<key>" },`);
141
+ console.log("or leave apiKey out and export the same M365_PROXY_KEY to opencode.");
142
+ console.log("Ctrl+C to stop.");
113
143
  process.on("SIGINT", () => {
114
144
  proxy.close().then(() => process.exit(0));
115
145
  });
@@ -150,7 +180,8 @@ async function doDoctor() {
150
180
  port: 0
151
181
  });
152
182
  check("starts and serves /health", (await fetch(`${proxy.url}/health`)).ok, proxy.url);
153
- const models = await (await fetch(`${proxy.url}/v1/models`)).json();
183
+ check("refuses a request without the secret", (await fetch(`${proxy.url}/v1/models`)).status === 401);
184
+ const models = await (await fetch(`${proxy.url}/v1/models`, { headers: { Authorization: `Bearer ${proxy.apiKey}` } })).json();
154
185
  check("advertises models", models.data?.length > 0, `${models.data?.length ?? 0} models`);
155
186
  check("local titler present", models.data?.some((m) => m.id === LOCAL_TITLE_MODEL));
156
187
  await proxy.close();
@@ -1,4 +1,4 @@
1
- import { A as __require, j as __toESM, k as __commonJSMin } from "./server-DuHBfcPQ.mjs";
1
+ import { F as __require, I as __toESM, P as __commonJSMin } from "./server-DO0_u884.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import http from "http";
4
4
  import crypto, { createHash as createHash$1 } from "crypto";
@@ -1,5 +1,5 @@
1
- import { _ as CONFIG_DIR, a as AUTHORITY, d as authCodeFromUrl, f as createCachePlugin, i as string, l as REDIRECT_URI, m as createLogger, r as object, s as CLIENT_ID, u as SYDNEY_SCOPES, v as SECRETS_FILE } from "./server-DuHBfcPQ.mjs";
2
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
1
+ import { C as SECRETS_FILE, S as CONFIG_DIR, _ as createLogger, c as AUTHORITY, f as REDIRECT_URI, h as createCachePlugin, m as authCodeFromUrl, o as object, p as SYDNEY_SCOPES, s as string, u as CLIENT_ID, v as ensurePrivateDir } from "./server-DO0_u884.mjs";
2
+ import { chmodSync, existsSync, readFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  //#region src/login.ts
5
5
  /**
@@ -29,9 +29,15 @@ const SecretsSchema = object({
29
29
  */
30
30
  mfaSecret: string().optional()
31
31
  });
32
- /** Read stored credentials, if any. Returns undefined when the file is absent. */
33
- function loadSecrets(file = SECRETS_FILE) {
32
+ /**
33
+ * Read stored credentials, if any. Returns undefined when the file is absent.
34
+ *
35
+ * The file holds both sign-in factors, so a copy other local users can read is
36
+ * tightened to 0600 on the spot, with a warning. A file we cannot tighten is refused.
37
+ */
38
+ function loadSecrets(file = SECRETS_FILE, { warn = (message) => console.warn(message) } = {}) {
34
39
  if (!existsSync(file)) return void 0;
40
+ guardSecretsMode(file, warn);
35
41
  let parsed;
36
42
  try {
37
43
  parsed = JSON.parse(readFileSync(file, "utf8"));
@@ -42,6 +48,17 @@ function loadSecrets(file = SECRETS_FILE) {
42
48
  if (!result.success) throw new Error(`${file} is missing required fields: ${result.error.issues.map((i) => i.path.join(".")).join(", ")}`);
43
49
  return result.data;
44
50
  }
51
+ function guardSecretsMode(file, warn) {
52
+ if (process.platform === "win32") return;
53
+ const mode = statSync(file).mode & 511;
54
+ if ((mode & 63) === 0) return;
55
+ try {
56
+ chmodSync(file, 384);
57
+ } catch (error) {
58
+ throw new Error(`${file} is readable by other users (mode ${mode.toString(8)}) and could not be tightened: ${String(error)}. Run \`chmod 600 ${file}\`.`);
59
+ }
60
+ warn(`${file} was readable by other users (mode ${mode.toString(8)}); it holds your password and TOTP seed, so it has been changed to 0600.`);
61
+ }
45
62
  /**
46
63
  * Validate a TOTP seed before we try to use it.
47
64
  *
@@ -62,7 +79,7 @@ function normaliseTotpSecret(raw) {
62
79
  }
63
80
  /** Current 6-digit code for a base32 seed. */
64
81
  async function totpCode(secret) {
65
- const { TOTP, Secret } = await import("./otpauth.node-BaAHzqxj.mjs");
82
+ const { TOTP, Secret } = await import("./otpauth.node-CBOz_1IZ.mjs");
66
83
  return new TOTP({
67
84
  secret: Secret.fromBase32(normaliseTotpSecret(secret)),
68
85
  digits: 6,
@@ -79,7 +96,7 @@ async function login(options = {}) {
79
96
  const secrets = loadSecrets(options.secretsFile);
80
97
  const interactive = options.interactive ?? !secrets?.mfaSecret;
81
98
  if (!interactive && !secrets) throw new Error(`No credentials at ${options.secretsFile ?? SECRETS_FILE}. Create it with { "email", "password", "mfaSecret" }, or sign in interactively with --interactive.`);
82
- const { PublicClientApplication, CryptoProvider } = await import("./dist-C8jy_NH0.mjs");
99
+ const { PublicClientApplication, CryptoProvider } = await import("./dist-CBYT-Zyt.mjs");
83
100
  const app = new PublicClientApplication({
84
101
  auth: {
85
102
  clientId: CLIENT_ID,
@@ -112,8 +129,9 @@ async function login(options = {}) {
112
129
  async function captureAuthCode(authUrl, options) {
113
130
  const playwright = await importPlaywright();
114
131
  const timeout = options.timeoutMs ?? (options.interactive ? 6e5 : 12e4);
115
- mkdirSync(CONFIG_DIR, { recursive: true });
132
+ ensurePrivateDir(CONFIG_DIR);
116
133
  const profileDir = process.env.M365_BROWSER_PROFILE || join(CONFIG_DIR, "browser-profile");
134
+ ensurePrivateDir(profileDir);
117
135
  const context = await playwright.chromium.launchPersistentContext(profileDir, {
118
136
  headless: !options.interactive,
119
137
  executablePath: process.env.CHROMIUM_PATH || void 0,
@@ -201,7 +201,7 @@ import * as crypto from "node:crypto";
201
201
  * Returns random bytes.
202
202
  * @param {number} size Size.
203
203
  * @returns {Uint8Array} Random bytes.
204
- */ const randomBytes = (size) => {
204
+ */ const randomBytes$1 = (size) => {
205
205
  if (crypto?.randomBytes) return crypto.randomBytes(size);
206
206
  else if (globalScope.crypto?.getRandomValues) return globalScope.crypto.getRandomValues(new Uint8Array(size));
207
207
  else throw new Error("Cryptography API not available");
@@ -302,7 +302,7 @@ import * as crypto from "node:crypto";
302
302
  * Secret key.
303
303
  * @type {Uint8Array}
304
304
  * @readonly
305
- */ this.bytes = typeof buffer === "undefined" ? randomBytes(size) : new Uint8Array(buffer);
305
+ */ this.bytes = typeof buffer === "undefined" ? randomBytes$1(size) : new Uint8Array(buffer);
306
306
  Object.defineProperty(this, "bytes", {
307
307
  enumerable: true,
308
308
  writable: false,
@@ -316,7 +316,7 @@ import * as crypto from "node:crypto";
316
316
  * @param {string} a String a.
317
317
  * @param {string} b String b.
318
318
  * @returns {boolean} Equality result.
319
- */ const timingSafeEqual = (a, b) => {
319
+ */ const timingSafeEqual$1 = (a, b) => {
320
320
  if (crypto?.timingSafeEqual) return crypto.timingSafeEqual(globalScope.Buffer.from(a), globalScope.Buffer.from(b));
321
321
  else {
322
322
  if (a.length !== b.length) throw new TypeError("Input strings must have the same length");
@@ -404,7 +404,7 @@ import * as crypto from "node:crypto";
404
404
  counter: i,
405
405
  hmac
406
406
  });
407
- if (timingSafeEqual(token, generatedToken)) delta = i - counter;
407
+ if (timingSafeEqual$1(token, generatedToken)) delta = i - counter;
408
408
  };
409
409
  check(counter);
410
410
  for (let i = 1; i <= window && delta === null; ++i) {
package/dist/plugin.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { C as buildProviderInfo, E as DEFAULT_MODEL, O as isLocalModel, S as buildModelInfos, T as resolveOptions, b as PROVIDER_ID, m as createLogger, n as startServer, p as createTokenClient, t as AUX_REQUEST_KIND_HEADER, x as applyPluginConfig, y as PLUGIN_ID } from "./server-DuHBfcPQ.mjs";
2
- import { t as getOrCreateAgent } from "./agent-BDA00x1V.mjs";
1
+ import { A as resolveOptions, D as buildModelInfos, E as applyPluginConfig, N as isLocalModel, O as buildProviderInfo, T as PROVIDER_ID, _ as createLogger, a as startServer, g as createTokenClient, j as DEFAULT_MODEL, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER, w as PLUGIN_ID } from "./server-DO0_u884.mjs";
2
+ import { t as getOrCreateAgent } from "./agent-C3DxtJPy.mjs";
3
3
  //#region src/runtime.ts
4
4
  /**
5
5
  * The part of the plugin that is the same under both opencode plugin APIs.
@@ -50,21 +50,29 @@ const LEAN_SYSTEM_PROMPT = [
50
50
  */
51
51
  async function startRuntime(rawOptions) {
52
52
  const options = resolveOptions(rawOptions);
53
- if (options.baseUrl) return {
54
- baseUrl: options.baseUrl,
55
- options,
56
- close: async () => {}
57
- };
53
+ const sharedKey = process.env.M365_PROXY_KEY || void 0;
54
+ if (options.baseUrl) {
55
+ const apiKey = options.apiKey ?? sharedKey;
56
+ if (!apiKey) log$1.warn("baseUrl is set but no proxy secret is: pass the key `opencode-m365 serve` printed as the `apiKey` plugin option, or set M365_PROXY_KEY");
57
+ return {
58
+ baseUrl: options.baseUrl,
59
+ apiKey: apiKey ?? "missing-proxy-secret",
60
+ options,
61
+ close: async () => {}
62
+ };
63
+ }
58
64
  const tokens = createTokenClient();
59
65
  const proxy = await startServer({
60
66
  getToken: () => tokens.getToken(),
61
67
  resolveAgent: () => getOrCreateAgent({ getTokenForScope: (scopes) => tokens.getTokenForScope(scopes) }),
62
68
  lean: options.lean,
69
+ ...sharedKey ? { apiKey: sharedKey } : {},
63
70
  ...options.leanSystemPrompt ? { leanSystemPrompt: LEAN_SYSTEM_PROMPT } : {}
64
71
  });
65
72
  log$1.info(`M365 Copilot proxy listening on ${proxy.url}`);
66
73
  return {
67
74
  baseUrl: `${proxy.url}/v1`,
75
+ apiKey: proxy.apiKey,
68
76
  options,
69
77
  close: () => proxy.close()
70
78
  };
@@ -81,7 +89,7 @@ async function server(input, rawOptions) {
81
89
  } }).catch(() => {});
82
90
  return {
83
91
  async config(config) {
84
- applyPluginConfig(config, runtime.baseUrl, runtime.options);
92
+ applyPluginConfig(config, runtime, runtime.options);
85
93
  },
86
94
  async dispose() {
87
95
  await runtime.close();
@@ -93,7 +101,7 @@ async function server(input, rawOptions) {
93
101
  const log = createLogger("plugin");
94
102
  const setup = async (ctx) => {
95
103
  const runtime = await startRuntime(ctx.options);
96
- const info = buildProviderInfo(runtime.baseUrl);
104
+ const info = buildProviderInfo(runtime.baseUrl, runtime.apiKey);
97
105
  const models = buildModelInfos();
98
106
  await ctx.provider.transform((editor) => {
99
107
  editor.add({
@@ -105,9 +113,14 @@ const setup = async (ctx) => {
105
113
  if (editor.default.get()) return;
106
114
  editor.default.set(PROVIDER_ID, DEFAULT_MODEL);
107
115
  });
108
- if (runtime.options.setSmallModel) await ctx.session.hook("model.request", (event) => {
109
- if (event.kind !== "title") return;
116
+ await ctx.session.hook("model.request", (event) => {
110
117
  if (event.model.providerID !== "m365") return;
118
+ if (event.kind === "primary" && event.sessionID) {
119
+ event.headers[SESSION_ID_HEADER] = String(event.sessionID);
120
+ return;
121
+ }
122
+ if (!runtime.options.setSmallModel) return;
123
+ if (event.kind !== "title") return;
111
124
  if (isLocalModel(event.model.id)) return;
112
125
  event.headers[AUX_REQUEST_KIND_HEADER] = event.kind;
113
126
  });
@@ -1,8 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
- import { randomUUID } from "node:crypto";
3
- import { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
- import { dirname, join } from "node:path";
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { appendFileSync, chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
5
4
  import { homedir } from "node:os";
5
+ import { dirname, join, parse, resolve, sep } from "node:path";
6
6
  import { createServer } from "node:http";
7
7
  //#region \0rolldown/runtime.js
8
8
  var __create = Object.create;
@@ -567,7 +567,8 @@ function resolveOptions(raw) {
567
567
  setDefaultModel: bool(options.setDefaultModel, true),
568
568
  setSmallModel: bool(options.setSmallModel, true),
569
569
  leanSystemPrompt: bool(options.leanSystemPrompt, false),
570
- baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0
570
+ baseUrl: typeof options.baseUrl === "string" ? options.baseUrl : void 0,
571
+ apiKey: typeof options.apiKey === "string" && options.apiKey !== "" ? options.apiKey : void 0
571
572
  };
572
573
  }
573
574
  /** `{ bash: true, ..., webfetch: false, ... }` — opencode's `tools` config shape. */
@@ -578,7 +579,7 @@ function buildToolProfile() {
578
579
  return profile;
579
580
  }
580
581
  /** The `provider.m365` entry pointing opencode at our local OpenAI-compatible proxy. */
581
- function buildProviderConfig(baseUrl) {
582
+ function buildProviderConfig(baseUrl, apiKey) {
582
583
  const models = {};
583
584
  for (const model of MODELS) models[model.id] = {
584
585
  name: model.name,
@@ -598,14 +599,14 @@ function buildProviderConfig(baseUrl) {
598
599
  name: "Microsoft 365 Copilot",
599
600
  options: {
600
601
  baseURL: baseUrl,
601
- apiKey: "m365-local",
602
+ apiKey,
602
603
  timeout: 9e5
603
604
  },
604
605
  models
605
606
  };
606
607
  }
607
608
  /** The opencode 2 provider record pointing at our local OpenAI-compatible proxy. */
608
- function buildProviderInfo(baseUrl) {
609
+ function buildProviderInfo(baseUrl, apiKey) {
609
610
  return {
610
611
  id: PROVIDER_ID,
611
612
  name: "Microsoft 365 Copilot",
@@ -613,7 +614,7 @@ function buildProviderInfo(baseUrl) {
613
614
  package: "@opencode/ai/providers/openai-compatible",
614
615
  settings: {
615
616
  baseURL: baseUrl,
616
- apiKey: "m365-local",
617
+ apiKey,
617
618
  timeout: 9e5
618
619
  }
619
620
  };
@@ -665,9 +666,9 @@ function buildModelInfos() {
665
666
  * Deliberately additive: anything the user set explicitly wins. We are a plugin
666
667
  * making someone else's config work, not the owner of it.
667
668
  */
668
- function applyPluginConfig(config, baseUrl, options) {
669
+ function applyPluginConfig(config, endpoint, options) {
669
670
  config.provider ??= {};
670
- config.provider[PROVIDER_ID] = buildProviderConfig(baseUrl);
671
+ config.provider[PROVIDER_ID] = buildProviderConfig(endpoint.baseUrl, endpoint.apiKey);
671
672
  if (options.setDefaultModel && !config.model) config.model = `${PROVIDER_ID}/${DEFAULT_MODEL}`;
672
673
  if (options.setSmallModel && !config.small_model) config.small_model = `${PROVIDER_ID}/${LOCAL_TITLE_MODEL}`;
673
674
  if (options.lean && usesOurProvider(config)) config.tools = {
@@ -678,31 +679,24 @@ function applyPluginConfig(config, baseUrl, options) {
678
679
  function usesOurProvider(config) {
679
680
  return typeof config.model === "string" && config.model.startsWith(`m365/`);
680
681
  }
681
- /**
682
- * Merge our plugin reference into an on-disk `opencode.json`, non-destructively.
683
- *
684
- * `pluginRef` is either the npm package name or an absolute path to the built
685
- * plugin — the CLI uses the latter for a local checkout.
686
- *
687
- * Both keys are written. They are genuinely different settings: opencode 1 reads
688
- * `plugin`, opencode 2 reads `plugins`, and the entry forms differ too — v1 takes a
689
- * `[spec, options]` tuple where v2 takes `{ package, options }`. Each version drops
690
- * the key it does not know rather than complaining, verified against 1.18.31, which
691
- * resolved a config carrying `plugins` with no diagnostic and simply left it out. So
692
- * one file can serve both, which is the whole point of the dual entry in `plugin.ts`.
693
- *
694
- * They also need different *references* for a local checkout. opencode 1 wants the
695
- * built entrypoint; opencode 2 insists on a directory and drops a file path with
696
- * `configured plugin path must be a directory` — measured against 2.0.11, and since
697
- * v2 swallows plugin load failures nothing else reports it. `pluginDir` is that
698
- * directory. An npm install needs neither, because the package name serves both.
699
- */
682
+ /** The npm name this package publishes under — what a checkout's package.json says. */
683
+ const PACKAGE_NAME = "opencode-m365-copilot";
684
+ /** Every option key this plugin reads; anything else belongs to another plugin. */
685
+ const OUR_OPTION_KEYS = /* @__PURE__ */ new Set([
686
+ "lean",
687
+ "setDefaultModel",
688
+ "setSmallModel",
689
+ "leanSystemPrompt",
690
+ "baseUrl",
691
+ "apiKey"
692
+ ]);
700
693
  function mergeOpencodeConfig(existing, opts) {
701
694
  const merged = { ...existing };
702
695
  merged.$schema ??= "https://opencode.ai/config.json";
703
696
  const pluginDir = opts.pluginDir ?? opts.pluginRef;
704
- const v1 = withOurRef(merged.plugin, opts.pluginRef);
705
- const v2 = withOurRef(merged.plugins, pluginDir, v1.dropped);
697
+ const inspect = opts.inspect ?? (() => ({ exists: false }));
698
+ const v1 = withOurRef(merged.plugin, opts.pluginRef, inspect);
699
+ const v2 = withOurRef(merged.plugins, pluginDir, inspect, v1.dropped);
706
700
  merged.plugin = [...v1.kept, v1.options ? [opts.pluginRef, v1.options] : opts.pluginRef];
707
701
  merged.plugins = [...v2.kept, v2.options ? {
708
702
  package: pluginDir,
@@ -717,14 +711,14 @@ function mergeOpencodeConfig(existing, opts) {
717
711
  * build path — is what stops a re-run of setup, after the checkout moved, from
718
712
  * leaving opencode trying to load a file that no longer exists.
719
713
  */
720
- function withOurRef(existing, pluginRef, containing = []) {
714
+ function withOurRef(existing, pluginRef, inspect, containing = []) {
721
715
  const entries = Array.isArray(existing) ? [...existing] : [];
722
716
  const kept = [];
723
717
  const dropped = [];
724
718
  let options;
725
719
  for (const entry of entries) {
726
720
  const spec = specifierOf(entry);
727
- if (!(isOurPluginRef(spec, pluginRef) || containing.some((path) => isWithin(spec, path)))) {
721
+ if (!(isOurPluginRef(spec, pluginRef, optionsOf(entry), inspect) || containing.some((path) => isWithin(spec, path)))) {
728
722
  kept.push(entry);
729
723
  continue;
730
724
  }
@@ -760,14 +754,24 @@ function specifierOf(entry) {
760
754
  /**
761
755
  * Does `ref` point at this plugin?
762
756
  *
763
- * Three ways it can: the npm package name, this repo's directory name, or the same
764
- * build artifact at a different location — a local install is an absolute path to
765
- * `.../dist/plugin.mjs`, and only the directory changes when the checkout moves.
757
+ * Certain when it is the npm package name or this repo's directory name. A local
758
+ * install is an absolute path to `.../dist/plugin.mjs`, but that layout is common to
759
+ * many plugins, so a shared path tail alone proves nothing:
760
+ *
761
+ * - a path that exists is ours only if its package.json names this package;
762
+ * - a path that no longer exists (the usual moved-checkout case) is taken as a stale
763
+ * copy of us when it carries no options, or only ours — so another plugin's options
764
+ * are never swallowed. An option-less vanished entry is taken even if it was someone
765
+ * else's: setup writes a bare entry by default, so that is what a moved checkout of
766
+ * ours usually leaves, and a foreign one was already failing to load.
766
767
  */
767
- function isOurPluginRef(ref, incoming) {
768
+ function isOurPluginRef(ref, incoming, options, inspect) {
768
769
  if (ref === incoming) return true;
769
770
  if (ref.includes("opencode-m365-copilot") || ref.includes("opencode-copilot-plugin")) return true;
770
- return tail(ref) !== "" && tail(ref) === tail(incoming);
771
+ if (tail(ref) === "" || tail(ref) !== tail(incoming)) return false;
772
+ const info = inspect(ref);
773
+ if (info.exists) return info.packageName === PACKAGE_NAME;
774
+ return Object.keys(options ?? {}).every((key) => OUR_OPTION_KEYS.has(key));
771
775
  }
772
776
  /** The last two path segments, which for a local install are `dist/plugin.mjs`. */
773
777
  function tail(ref) {
@@ -789,11 +793,125 @@ const SECRETS_FILE = process.env.M365_SECRETS_FILE || join(CONFIG_DIR, "secrets.
789
793
  const AGENT_FILE = process.env.M365_AGENT_FILE || join(CONFIG_DIR, "agent-id.json");
790
794
  const LOG_FILE = join(CONFIG_DIR, "debug.log");
791
795
  //#endregion
796
+ //#region src/private-fs.ts
797
+ /**
798
+ * Owner-only filesystem writes for everything under the config directory.
799
+ *
800
+ * That directory holds the SSO browser profile, the MSAL cache, optional stored
801
+ * credentials (password *and* TOTP seed) and a debug log that under `M365_TRACE`
802
+ * contains the access token. None of it should be readable by other local users,
803
+ * whatever the umask was when it was first created — so each helper also tightens
804
+ * a file or directory that already exists with looser permissions.
805
+ */
806
+ const DIR_MODE = 448;
807
+ const FILE_MODE = 384;
808
+ /** Best effort: Windows ignores POSIX modes, and a file we do not own cannot be changed. */
809
+ function tighten(path, mode) {
810
+ if (process.platform === "win32") return;
811
+ try {
812
+ chmodSync(path, mode);
813
+ } catch {}
814
+ }
815
+ /** The canonical path, following symlinks — or the plain resolved one if it does not exist. */
816
+ function canonical(path) {
817
+ try {
818
+ return realpathSync(path);
819
+ } catch {
820
+ return resolve(path);
821
+ }
822
+ }
823
+ /**
824
+ * Is `dir` the user's home directory, one of its ancestors, or the filesystem root?
825
+ *
826
+ * Those are shared with every other tool the user runs, so they are never ours to
827
+ * chmod — even when `M365_CONFIG_DIR=$HOME` makes one of them our config directory.
828
+ * Compared by real path, so a symlink on either side cannot slip past.
829
+ */
830
+ function isHomeOrAbove(dir) {
831
+ const target = canonical(dir);
832
+ if (target === parse(target).root) return true;
833
+ const home = canonical(homedir());
834
+ return home === target || home.startsWith(target.endsWith(sep) ? target : `${target}${sep}`);
835
+ }
836
+ /**
837
+ * Create `dir` (and parents) owner-only, and tighten `dir` itself if it already
838
+ * existed — unless it is the home directory or above, which stays as it is.
839
+ */
840
+ function ensurePrivateDir(dir) {
841
+ mkdirSync(dir, {
842
+ recursive: true,
843
+ mode: DIR_MODE
844
+ });
845
+ if (!isHomeOrAbove(dir)) tighten(dir, DIR_MODE);
846
+ }
847
+ /**
848
+ * Make sure `file`'s directory exists. A directory we create is owner-only; an
849
+ * existing one is tightened only when it is our config directory — a path
850
+ * overridden to `~/cache.json` must not chmod the user's home.
851
+ */
852
+ function preparePrivateParent(file) {
853
+ const dir = dirname(file);
854
+ if (resolve(dir) === resolve(CONFIG_DIR)) ensurePrivateDir(dir);
855
+ else mkdirSync(dir, {
856
+ recursive: true,
857
+ mode: DIR_MODE
858
+ });
859
+ }
860
+ /** Write `file` owner-only, creating its directory owner-only too. */
861
+ function writePrivateFile(file, contents) {
862
+ preparePrivateParent(file);
863
+ writeFileSync(file, contents, { mode: FILE_MODE });
864
+ tighten(file, FILE_MODE);
865
+ }
866
+ /** Append to `file` owner-only, creating its directory owner-only too. */
867
+ function appendPrivateFile(file, contents) {
868
+ preparePrivateParent(file);
869
+ appendFileSync(file, contents, { mode: FILE_MODE });
870
+ tighten(file, FILE_MODE);
871
+ }
872
+ /**
873
+ * An appender for a file written often, like the debug log.
874
+ *
875
+ * The first write goes through `appendPrivateFile` — directory created, both
876
+ * tightened. Later writes only append, so a log line per stream delta does not pay
877
+ * for a mkdir and two chmods each time on opencode's event loop. If the file has
878
+ * disappeared since (a user clearing the log), the next write does the full setup
879
+ * again rather than recreating it with whatever the umask allows.
880
+ */
881
+ function createPrivateAppender(file) {
882
+ let ready = false;
883
+ return (contents) => {
884
+ if (ready) {
885
+ let fd;
886
+ try {
887
+ fd = openSync(file, constants.O_WRONLY | constants.O_APPEND);
888
+ } catch {
889
+ ready = false;
890
+ }
891
+ if (fd !== void 0) {
892
+ try {
893
+ writeSync(fd, contents);
894
+ } finally {
895
+ closeSync(fd);
896
+ }
897
+ return;
898
+ }
899
+ }
900
+ appendPrivateFile(file, contents);
901
+ ready = true;
902
+ };
903
+ }
904
+ //#endregion
792
905
  //#region src/log.ts
793
906
  const DEBUG = process.env.M365_DEBUG === "1" || process.env.M365_TRACE === "1";
794
907
  const TRACE = process.env.M365_TRACE === "1";
795
908
  const TO_STDOUT = process.env.M365_LOG_STDOUT === "1";
796
- let ready = false;
909
+ /**
910
+ * One appender for every scope, since they all share the file. Owner-only (under
911
+ * M365_TRACE this log carries the access token), with the mkdir and chmods paid on
912
+ * the first line only — this runs per stream delta on opencode's event loop.
913
+ */
914
+ const appendLog = createPrivateAppender(LOG_FILE);
797
915
  /** Truncate a payload for the log unless full tracing is on. */
798
916
  function trunc(value, max = 400) {
799
917
  const text = typeof value === "string" ? value : JSON.stringify(value);
@@ -812,11 +930,7 @@ function createLogger(scope) {
812
930
  const line = `${(/* @__PURE__ */ new Date()).toISOString()} [${level}] [${scope}] ${parts.map((p) => trunc(p)).join(" ")}`;
813
931
  if (TO_STDOUT) process.stdout.write(`${line}\n`);
814
932
  try {
815
- if (!ready) {
816
- mkdirSync(dirname(LOG_FILE) || CONFIG_DIR, { recursive: true });
817
- ready = true;
818
- }
819
- appendFileSync(LOG_FILE, `${line}\n`);
933
+ appendLog(`${line}\n`);
820
934
  } catch {}
821
935
  };
822
936
  return {
@@ -878,9 +992,7 @@ function createCachePlugin(file = CACHE_FILE) {
878
992
  async afterCacheAccess(context) {
879
993
  if (!context.cacheHasChanged) return;
880
994
  try {
881
- mkdirSync(dirname(file), { recursive: true });
882
- writeFileSync(file, context.tokenCache.serialize(), { mode: 384 });
883
- chmodSync(file, 384);
995
+ writePrivateFile(file, context.tokenCache.serialize());
884
996
  } catch (error) {
885
997
  log$2.warn("could not persist the token cache", String(error));
886
998
  }
@@ -892,7 +1004,7 @@ function createTokenClient(options = {}) {
892
1004
  const cache = /* @__PURE__ */ new Map();
893
1005
  async function client() {
894
1006
  if (app) return app;
895
- const { PublicClientApplication } = await import("./dist-C8jy_NH0.mjs");
1007
+ const { PublicClientApplication } = await import("./dist-CBYT-Zyt.mjs");
896
1008
  app = new PublicClientApplication({
897
1009
  auth: {
898
1010
  clientId: CLIENT_ID,
@@ -3007,7 +3119,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3007
3119
  const http$1 = __require("http");
3008
3120
  const net = __require("net");
3009
3121
  const tls = __require("tls");
3010
- const { randomBytes, createHash: createHash$2 } = __require("crypto");
3122
+ const { randomBytes: randomBytes$1, createHash: createHash$2 } = __require("crypto");
3011
3123
  const { Duplex: Duplex$2, Readable } = __require("stream");
3012
3124
  const { URL: URL$1 } = __require("url");
3013
3125
  const PerMessageDeflate = require_permessage_deflate();
@@ -3576,7 +3688,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3576
3688
  }
3577
3689
  }
3578
3690
  const defaultPort = isSecure ? 443 : 80;
3579
- const key = randomBytes(16).toString("base64");
3691
+ const key = randomBytes$1(16).toString("base64");
3580
3692
  const request = isSecure ? https.request : http$1.request;
3581
3693
  const protocolSet = /* @__PURE__ */ new Set();
3582
3694
  let perMessageDeflate;
@@ -9299,7 +9411,7 @@ const initializer = (inst, issues) => {
9299
9411
  const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
9300
9412
  //#endregion
9301
9413
  //#region node_modules/zod/v4/classic/parse.js
9302
- const parse = /* @__PURE__ */ _parse(ZodRealError);
9414
+ const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
9303
9415
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
9304
9416
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
9305
9417
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -9431,7 +9543,7 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
9431
9543
  own(this, "~standard", value);
9432
9544
  },
9433
9545
  parse: function _parse(data, params) {
9434
- return parse(this, data, params, { callee: _parse });
9546
+ return parse$1(this, data, params, { callee: _parse });
9435
9547
  },
9436
9548
  parseAsync: async function _parseAsync(data, params) {
9437
9549
  return await parseAsync(this, data, params, { callee: _parseAsync });
@@ -10232,8 +10344,11 @@ const ChatCompletionRequest = object({
10232
10344
  /**
10233
10345
  * Maps an OpenAI client's stateless history onto stateful M365 conversations.
10234
10346
  *
10235
- * Identity is the first user message: an agent loop keeps resending the same opening
10236
- * turn, so it is a stable handle for "this is still the same task".
10347
+ * Identity is the harness's session id when it names one (the opencode 2 plugin
10348
+ * does). Otherwise it is a sha256 of the system prompt plus the first user message:
10349
+ * an agent loop keeps resending both, so together they are a stable handle for "this
10350
+ * is still the same task" — and the system prompt carries the working directory, so
10351
+ * the same opener in two repos stays apart.
10237
10352
  */
10238
10353
  var ConversationPool = class {
10239
10354
  conversations = /* @__PURE__ */ new Map();
@@ -10241,9 +10356,9 @@ var ConversationPool = class {
10241
10356
  constructor(options = {}) {
10242
10357
  this.maxIdleMs = options.maxIdleMs ?? 36e5;
10243
10358
  }
10244
- resolve(messages) {
10359
+ resolve(messages, options = {}) {
10245
10360
  this.evictStale();
10246
- const key = fingerprint(messages);
10361
+ const key = options.sessionId ? `s:${createHash("sha256").update(options.sessionId).digest("hex")}` : fingerprint(messages);
10247
10362
  const existing = this.conversations.get(key);
10248
10363
  if (existing) {
10249
10364
  if (messages.length < existing.sentMessageCount) existing.sentMessageCount = 0;
@@ -10267,11 +10382,11 @@ var ConversationPool = class {
10267
10382
  }
10268
10383
  };
10269
10384
  function fingerprint(messages) {
10385
+ const system = messages.filter((message) => message.role === "system" || message.role === "developer").map(contentOf).join("\n");
10270
10386
  const firstUser = messages.find((message) => message.role === "user");
10271
- const text = firstUser ? contentOf(firstUser) : "";
10272
- let hash = 0;
10273
- for (let i = 0; i < text.length; i += 1) hash = (hash << 5) - hash + text.charCodeAt(i) | 0;
10274
- return `c${hash}`;
10387
+ const hash = createHash("sha256");
10388
+ for (const part of [system, firstUser ? contentOf(firstUser) : ""]) hash.update(`${part.length}:${part}`);
10389
+ return `c:${hash.digest("hex")}`;
10275
10390
  }
10276
10391
  /** Message content as plain text, flattening the array-of-parts form. */
10277
10392
  function contentOf(message) {
@@ -10537,8 +10652,11 @@ function firstLine(text) {
10537
10652
  *
10538
10653
  * Small on purpose: `node:http` rather than a framework, because this runs inside
10539
10654
  * opencode's own process and every dependency here is one opencode has to install.
10540
- * It binds loopback only — the proxy is unauthenticated and speaks to a paid account
10541
- * with your credentials.
10655
+ * It binds loopback only, and loopback is not a trust boundary: every browser tab on
10656
+ * the machine can reach it too. So every request must also carry a per-launch secret
10657
+ * (`Authorization: Bearer <apiKey>`), must name a loopback `Host` (DNS rebinding), and
10658
+ * must not come from a browser `Origin` the caller did not allow. No CORS headers are
10659
+ * ever sent — opencode is a server-side client and needs none.
10542
10660
  */
10543
10661
  const log = createLogger("server");
10544
10662
  /** See the warning in `handleChatCompletion`; this keeps it to once per process. */
@@ -10553,9 +10671,33 @@ let warnedAboutToolSelection = false;
10553
10671
  * M365 conversation per session, which is precisely the throttle signature.
10554
10672
  */
10555
10673
  const AUX_REQUEST_KIND_HEADER = "x-m365-request-kind";
10674
+ /**
10675
+ * Header a harness uses to name the session a request belongs to, so two sessions
10676
+ * that happen to open with the same message never share an M365 conversation.
10677
+ * Lowercase for the same reason as {@link AUX_REQUEST_KIND_HEADER}.
10678
+ */
10679
+ const SESSION_ID_HEADER = "x-m365-session-id";
10680
+ /** Generous: a long agent history is a few MB of JSON; this only stops abuse. */
10681
+ const DEFAULT_MAX_BODY_BYTES = 33554432;
10682
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
10683
+ "127.0.0.1",
10684
+ "::1",
10685
+ "localhost"
10686
+ ]);
10687
+ /** A fresh per-launch secret: 32 random bytes, base64url. */
10688
+ function generateApiKey() {
10689
+ return randomBytes(32).toString("base64url");
10690
+ }
10556
10691
  async function startServer(deps) {
10557
10692
  const pool = new ConversationPool();
10558
10693
  const host = deps.host ?? "127.0.0.1";
10694
+ if (!LOOPBACK_HOSTS.has(host)) throw new Error(`Refusing to bind ${host}: the proxy only listens on loopback (127.0.0.1, ::1, localhost)`);
10695
+ const apiKey = deps.apiKey || generateApiKey();
10696
+ if (deps.allowedOrigins !== void 0) process.emitWarning("startServer's allowedOrigins option is ignored: the proxy refuses every request carrying an Origin, since browsers cannot use it.", {
10697
+ type: "DeprecationWarning",
10698
+ code: "M365_ALLOWED_ORIGINS"
10699
+ });
10700
+ const maxBodyBytes = deps.maxBodyBytes ?? 33554432;
10559
10701
  let agentPromise;
10560
10702
  const agentId = async () => {
10561
10703
  if (!deps.resolveAgent) return null;
@@ -10565,11 +10707,15 @@ async function startServer(deps) {
10565
10707
  });
10566
10708
  return agentPromise;
10567
10709
  };
10710
+ const portOf = () => server.address().port;
10568
10711
  const server = createServer((request, response) => {
10569
10712
  handle(request, response, {
10570
10713
  deps,
10571
10714
  pool,
10572
- agentId
10715
+ agentId,
10716
+ apiKey,
10717
+ maxBodyBytes,
10718
+ port: portOf()
10573
10719
  }).catch((error) => {
10574
10720
  log.error("unhandled request failure", String(error));
10575
10721
  sendError(response, 500, "internal_error", String(error));
@@ -10581,25 +10727,60 @@ async function startServer(deps) {
10581
10727
  });
10582
10728
  const { port } = server.address();
10583
10729
  return {
10584
- url: `http://${host}:${port}`,
10730
+ url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
10585
10731
  port,
10732
+ apiKey,
10586
10733
  close: () => new Promise((resolve) => {
10587
10734
  server.closeAllConnections?.();
10588
10735
  server.close(() => resolve());
10589
10736
  })
10590
10737
  };
10591
10738
  }
10739
+ var PayloadTooLargeError = class extends Error {};
10740
+ /**
10741
+ * Is `Host` one of the names this listener is actually reachable by?
10742
+ *
10743
+ * A DNS-rebound page talks to 127.0.0.1 while its `Host` still names the attacker's
10744
+ * domain, so anything but a loopback name on our own port is refused.
10745
+ */
10746
+ function isLoopbackHost(header, port) {
10747
+ if (!header) return false;
10748
+ const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(header.trim().toLowerCase());
10749
+ if (!match) return false;
10750
+ const name = match[1].replace(/^\[|\]$/g, "");
10751
+ return LOOPBACK_HOSTS.has(name) && Number(match[2] ?? 80) === port;
10752
+ }
10753
+ /** Constant-time check of `Authorization: Bearer <key>`. */
10754
+ function hasApiKey(header, apiKey) {
10755
+ const match = /^Bearer\s+(.+)$/i.exec(header ?? "");
10756
+ if (!match) return false;
10757
+ const given = Buffer.from(match[1].trim());
10758
+ const expected = Buffer.from(apiKey);
10759
+ return given.length === expected.length && timingSafeEqual(given, expected);
10760
+ }
10592
10761
  async function handle(request, response, context) {
10593
10762
  const url = new URL(request.url ?? "/", "http://localhost");
10594
10763
  const method = (request.method ?? "GET").toUpperCase();
10764
+ if (!isLoopbackHost(request.headers.host, context.port)) {
10765
+ sendError(response, 403, "forbidden", "Host must be a loopback address");
10766
+ return;
10767
+ }
10768
+ if (request.headers.origin !== void 0) {
10769
+ sendError(response, 403, "forbidden", "Browser origins may not use this proxy");
10770
+ return;
10771
+ }
10595
10772
  if (method === "OPTIONS") {
10596
- response.writeHead(204, corsHeaders()).end();
10773
+ sendError(response, 403, "forbidden", "CORS is not supported");
10597
10774
  return;
10598
10775
  }
10599
10776
  if (method === "GET" && url.pathname === "/health") {
10600
10777
  sendJson(response, 200, { status: "ok" });
10601
10778
  return;
10602
10779
  }
10780
+ if (!hasApiKey(request.headers.authorization, context.apiKey)) {
10781
+ sendError(response, 401, "invalid_api_key", "Missing or wrong proxy secret. Send `Authorization: Bearer <key>` with the key the proxy printed or was given (M365_PROXY_KEY).");
10782
+ return;
10783
+ }
10603
10784
  if (method === "GET" && url.pathname === "/v1/models") {
10604
10785
  sendJson(response, 200, {
10605
10786
  object: "list",
@@ -10621,8 +10802,13 @@ async function handle(request, response, context) {
10621
10802
  async function handleChatCompletion(request, response, context) {
10622
10803
  let body;
10623
10804
  try {
10624
- body = ChatCompletionRequest.parse(JSON.parse(await readBody(request)));
10805
+ body = ChatCompletionRequest.parse(JSON.parse(await readBody(request, context.maxBodyBytes)));
10625
10806
  } catch (error) {
10807
+ if (error instanceof PayloadTooLargeError) {
10808
+ sendError(response, 413, "request_too_large", error.message);
10809
+ request.resume();
10810
+ return;
10811
+ }
10626
10812
  sendError(response, 400, "invalid_request_error", String(error?.message ?? error));
10627
10813
  return;
10628
10814
  }
@@ -10641,7 +10827,22 @@ async function handleChatCompletion(request, response, context) {
10641
10827
  respondWithTitle(response, body, model.id);
10642
10828
  return;
10643
10829
  }
10644
- const conversation = context.pool.resolve(body.messages);
10830
+ const sessionHeader = request.headers[SESSION_ID_HEADER];
10831
+ const sessionId = typeof sessionHeader === "string" && sessionHeader !== "" ? sessionHeader : void 0;
10832
+ const conversation = context.pool.resolve(body.messages, sessionId ? { sessionId } : {});
10833
+ const previous = conversation.turn ?? Promise.resolve();
10834
+ let release;
10835
+ const current = new Promise((resolve) => release = resolve);
10836
+ conversation.turn = previous.then(() => current);
10837
+ await previous;
10838
+ try {
10839
+ await runTurn(request, response, context, body, conversation, model, tools);
10840
+ } finally {
10841
+ release();
10842
+ }
10843
+ }
10844
+ async function runTurn(request, response, context, body, conversation, model, tools) {
10845
+ if (body.messages.length < conversation.sentMessageCount) conversation.sentMessageCount = 0;
10645
10846
  conversation.session ??= new CopilotSession({
10646
10847
  getToken: context.deps.getToken,
10647
10848
  ...context.deps.endpoint ? { endpoint: context.deps.endpoint } : {}
@@ -10663,7 +10864,7 @@ async function handleChatCompletion(request, response, context) {
10663
10864
  signal: abort.signal,
10664
10865
  ...canStreamText ? { onDelta: (chunk) => response.write(streamChunk(streamId, model.id, { content: chunk })) } : {}
10665
10866
  });
10666
- conversation.sentMessageCount = body.messages.length;
10867
+ conversation.sentMessageCount = body.messages.length + 1;
10667
10868
  if (!streaming) {
10668
10869
  sendJson(response, 200, buildCompletion(result, {
10669
10870
  model: model.id,
@@ -10753,23 +10954,12 @@ function startSse(response) {
10753
10954
  response.writeHead(200, {
10754
10955
  "Content-Type": "text/event-stream",
10755
10956
  "Cache-Control": "no-cache",
10756
- Connection: "keep-alive",
10757
- ...corsHeaders()
10957
+ Connection: "keep-alive"
10758
10958
  });
10759
10959
  }
10760
- function corsHeaders() {
10761
- return {
10762
- "Access-Control-Allow-Origin": "*",
10763
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
10764
- "Access-Control-Allow-Headers": "Content-Type, Authorization"
10765
- };
10766
- }
10767
10960
  function sendJson(response, status, body) {
10768
10961
  const payload = JSON.stringify(body);
10769
- response.writeHead(status, {
10770
- "Content-Type": "application/json",
10771
- ...corsHeaders()
10772
- });
10962
+ response.writeHead(status, { "Content-Type": "application/json" });
10773
10963
  response.end(payload);
10774
10964
  }
10775
10965
  function sendError(response, status, code, message) {
@@ -10780,10 +10970,17 @@ function sendError(response, status, code, message) {
10780
10970
  code
10781
10971
  } });
10782
10972
  }
10783
- async function readBody(request) {
10973
+ async function readBody(request, limit) {
10974
+ const declared = Number(request.headers["content-length"]);
10975
+ if (Number.isFinite(declared) && declared > limit) throw new PayloadTooLargeError(`Request body exceeds ${limit} bytes`);
10784
10976
  const chunks = [];
10785
- for await (const chunk of request) chunks.push(chunk);
10977
+ let size = 0;
10978
+ for await (const chunk of request) {
10979
+ size += chunk.length;
10980
+ if (size > limit) throw new PayloadTooLargeError(`Request body exceeds ${limit} bytes`);
10981
+ chunks.push(chunk);
10982
+ }
10786
10983
  return Buffer.concat(chunks).toString("utf8");
10787
10984
  }
10788
10985
  //#endregion
10789
- export { __require as A, buildProviderInfo as C, LOCAL_TITLE_MODEL as D, DEFAULT_MODEL as E, isLocalModel as O, buildModelInfos as S, resolveOptions as T, CONFIG_DIR as _, AUTHORITY as a, PROVIDER_ID as b, POWERPLATFORM_SCOPE as c, authCodeFromUrl as d, createCachePlugin as f, CACHE_FILE as g, AGENT_FILE as h, string as i, __toESM as j, __commonJSMin as k, REDIRECT_URI as l, createLogger as m, startServer as n, BAP_SCOPE as o, createTokenClient as p, object as r, CLIENT_ID as s, AUX_REQUEST_KIND_HEADER as t, SYDNEY_SCOPES as u, SECRETS_FILE as v, mergeOpencodeConfig as w, applyPluginConfig as x, PLUGIN_ID as y };
10986
+ export { resolveOptions as A, SECRETS_FILE as C, buildModelInfos as D, applyPluginConfig as E, __require as F, __toESM as I, LOCAL_TITLE_MODEL as M, isLocalModel as N, buildProviderInfo as O, __commonJSMin as P, CONFIG_DIR as S, PROVIDER_ID as T, createLogger as _, startServer as a, AGENT_FILE as b, AUTHORITY as c, POWERPLATFORM_SCOPE as d, REDIRECT_URI as f, createTokenClient as g, createCachePlugin as h, generateApiKey as i, DEFAULT_MODEL as j, mergeOpencodeConfig as k, BAP_SCOPE as l, authCodeFromUrl as m, DEFAULT_MAX_BODY_BYTES as n, object as o, SYDNEY_SCOPES as p, SESSION_ID_HEADER as r, string as s, AUX_REQUEST_KIND_HEADER as t, CLIENT_ID as u, ensurePrivateDir as v, PLUGIN_ID as w, CACHE_FILE as x, writePrivateFile as y };
package/dist/server.d.mts CHANGED
@@ -21,6 +21,12 @@ export declare const DEFAULT_MODEL = "gpt-5.5-think-deeper";
21
21
  * M365 conversation per session, which is precisely the throttle signature.
22
22
  */
23
23
  export declare const AUX_REQUEST_KIND_HEADER = "x-m365-request-kind";
24
+ /**
25
+ * Header a harness uses to name the session a request belongs to, so two sessions
26
+ * that happen to open with the same message never share an M365 conversation.
27
+ * Lowercase for the same reason as {@link AUX_REQUEST_KIND_HEADER}.
28
+ */
29
+ export declare const SESSION_ID_HEADER = "x-m365-session-id";
24
30
  export interface ServerDeps {
25
31
  /** Supplies a Sydney chat token. */
26
32
  getToken: () => Promise<string>;
@@ -49,12 +55,35 @@ export interface ServerDeps {
49
55
  */
50
56
  leanSystemPrompt?: string;
51
57
  port?: number;
58
+ /** Loopback only: `127.0.0.1` (the default), `::1` or `localhost`. Anything else throws. */
52
59
  host?: string;
60
+ /**
61
+ * The bearer secret every request must carry. Omit it and a fresh 32-byte random
62
+ * one is generated per launch, which is what the in-process plugin wants: it hands
63
+ * the key straight to opencode's provider config and nobody else ever sees it.
64
+ */
65
+ apiKey?: string;
66
+ /**
67
+ * @deprecated Ignored, with a warning. Every request carrying an `Origin` is refused:
68
+ * opencode sends none, so one means a web page — and no allowlist could have made
69
+ * the proxy usable from a page anyway, since the bearer header forces a CORS
70
+ * preflight and preflights are always refused. Kept only so an old caller that
71
+ * still passes it keeps starting.
72
+ */
73
+ allowedOrigins?: readonly string[];
74
+ /** Largest request body accepted, in bytes. */
75
+ maxBodyBytes?: number;
53
76
  }
54
77
  export interface ProxyHandle {
55
78
  url: string;
56
79
  port: number;
80
+ /** The bearer secret a client must send. */
81
+ apiKey: string;
57
82
  close(): Promise<void>;
58
83
  }
84
+ /** Generous: a long agent history is a few MB of JSON; this only stops abuse. */
85
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
86
+ /** A fresh per-launch secret: 32 random bytes, base64url. */
87
+ export declare function generateApiKey(): string;
59
88
  export declare function startServer(deps: ServerDeps): Promise<ProxyHandle>;
60
89
  //#endregion
package/dist/server.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { E as DEFAULT_MODEL, n as startServer, t as AUX_REQUEST_KIND_HEADER } from "./server-DuHBfcPQ.mjs";
2
- export { AUX_REQUEST_KIND_HEADER, DEFAULT_MODEL, startServer };
1
+ import { a as startServer, i as generateApiKey, j as DEFAULT_MODEL, n as DEFAULT_MAX_BODY_BYTES, r as SESSION_ID_HEADER, t as AUX_REQUEST_KIND_HEADER } from "./server-DO0_u884.mjs";
2
+ export { AUX_REQUEST_KIND_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_MODEL, SESSION_ID_HEADER, generateApiKey, startServer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-m365-copilot",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Use your org's Microsoft 365 Copilot as the model backend for opencode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -31,19 +31,21 @@
31
31
  "test:watch": "vitest",
32
32
  "typecheck": "tsc --noEmit"
33
33
  },
34
- "devDependencies": {
34
+ "dependencies": {
35
35
  "@azure/msal-node": "^6.0.0",
36
+ "otpauth": "^9.5.0",
37
+ "ws": "^8.20.0",
38
+ "zod": "^4.3.6"
39
+ },
40
+ "devDependencies": {
36
41
  "@opencode-ai/plugin": "^1.18.18",
37
42
  "@opencode/plugin": "^2.0.11",
38
43
  "@types/node": "^26.2.0",
39
44
  "@types/ws": "^8.18.1",
40
- "otpauth": "^9.5.0",
41
45
  "playwright": "^1.62.1",
42
46
  "tsdown": "^0.23.0",
43
47
  "typescript": "^7.0.2",
44
- "vitest": "^5.0.0",
45
- "ws": "^8.20.0",
46
- "zod": "^4.3.6"
48
+ "vitest": "^5.0.0"
47
49
  },
48
50
  "publishConfig": {
49
51
  "access": "public"