opencode-m365-copilot 0.3.0 → 0.3.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.
@@ -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-Buz1ZIg5.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-BGVW-hOf.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-Buz1ZIg5.mjs";
2
+ import { t as getOrCreateAgent } from "./agent-C28PfLXM.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
  });