mdedit-cli 0.3.1 → 0.3.3

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/dist/index.js CHANGED
@@ -934,6 +934,372 @@ ${chalk.bold.underline(text)}
934
934
  }
935
935
  });
936
936
 
937
+ // ../node-auth/dist/index.js
938
+ import { timingSafeEqual } from "crypto";
939
+ import { createServer } from "http";
940
+ import { Entry } from "@napi-rs/keyring";
941
+ import { createHash, randomBytes } from "crypto";
942
+ function required(value, name) {
943
+ const normalized = value?.trim();
944
+ if (!normalized) throw new TypeError(`${name} is required`);
945
+ return normalized;
946
+ }
947
+ async function responsePayload(response) {
948
+ const payload = await response.json().catch(() => ({}));
949
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
950
+ }
951
+ function stringField(payload, name) {
952
+ const value = payload[name];
953
+ return typeof value === "string" ? value : "";
954
+ }
955
+ function statesMatch(actual, expected) {
956
+ const actualBuffer = Buffer.from(actual);
957
+ const expectedBuffer = Buffer.from(expected);
958
+ return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
959
+ }
960
+ async function startLoopbackCallback({
961
+ redirectUri,
962
+ state,
963
+ listenPort,
964
+ timeoutMs = 12e4
965
+ }) {
966
+ const redirect = new URL(redirectUri);
967
+ if (redirect.protocol !== "http:" || redirect.hostname !== "localhost") {
968
+ throw new TypeError("OAuth redirect URI must use http://localhost");
969
+ }
970
+ const port = listenPort ?? Number(redirect.port);
971
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
972
+ throw new TypeError("OAuth redirect URI must include a valid port");
973
+ }
974
+ let resolveResult;
975
+ let rejectResult;
976
+ const result = new Promise((resolve2, reject) => {
977
+ resolveResult = resolve2;
978
+ rejectResult = reject;
979
+ });
980
+ let settled = false;
981
+ let timeout;
982
+ const server = createServer((request, response) => {
983
+ const url = new URL(request.url || "/", "http://localhost");
984
+ if (request.method !== "GET" || url.pathname !== redirect.pathname) {
985
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
986
+ response.end("Not found");
987
+ return;
988
+ }
989
+ const finish = (error, code2) => {
990
+ if (settled) return;
991
+ settled = true;
992
+ if (timeout) clearTimeout(timeout);
993
+ response.writeHead(error ? 400 : 200, {
994
+ "content-type": "text/plain; charset=utf-8"
995
+ });
996
+ response.end(error ? "OAuth login failed. Return to the terminal." : "OAuth login complete. You can close this window.");
997
+ server.close();
998
+ if (error) rejectResult(error);
999
+ else resolveResult(code2);
1000
+ };
1001
+ const actualState = url.searchParams.get("state") || "";
1002
+ if (!statesMatch(actualState, state)) {
1003
+ finish(new OAuthClientError(
1004
+ "OAuth callback state did not match",
1005
+ "OAUTH_STATE_MISMATCH"
1006
+ ));
1007
+ return;
1008
+ }
1009
+ const oauthError = url.searchParams.get("error");
1010
+ if (oauthError) {
1011
+ finish(new OAuthClientError(
1012
+ `OAuth authorization failed: ${oauthError}`,
1013
+ "OAUTH_AUTHORIZATION_DENIED"
1014
+ ));
1015
+ return;
1016
+ }
1017
+ const code = url.searchParams.get("code");
1018
+ if (!code) {
1019
+ finish(new OAuthClientError(
1020
+ "OAuth callback did not include an authorization code",
1021
+ "OAUTH_CALLBACK_INVALID"
1022
+ ));
1023
+ return;
1024
+ }
1025
+ finish(void 0, code);
1026
+ });
1027
+ await new Promise((resolve2, reject) => {
1028
+ server.once("error", (error) => {
1029
+ if (error.code === "EADDRINUSE") {
1030
+ reject(new OAuthClientError(
1031
+ `OAuth callback port ${port} is already in use`,
1032
+ "OAUTH_CALLBACK_PORT_IN_USE",
1033
+ { port }
1034
+ ));
1035
+ return;
1036
+ }
1037
+ reject(error);
1038
+ });
1039
+ server.listen(port, "127.0.0.1", resolve2);
1040
+ });
1041
+ const address = server.address();
1042
+ const boundPort = typeof address === "object" && address ? address.port : port;
1043
+ timeout = setTimeout(() => {
1044
+ if (settled) return;
1045
+ settled = true;
1046
+ server.close();
1047
+ rejectResult(new OAuthClientError(
1048
+ "OAuth callback timed out",
1049
+ "OAUTH_CALLBACK_TIMEOUT"
1050
+ ));
1051
+ }, timeoutMs);
1052
+ return {
1053
+ port: boundPort,
1054
+ result,
1055
+ close: () => new Promise((resolve2) => {
1056
+ if (timeout) clearTimeout(timeout);
1057
+ if (!server.listening) {
1058
+ resolve2();
1059
+ return;
1060
+ }
1061
+ server.close(() => resolve2());
1062
+ })
1063
+ };
1064
+ }
1065
+ function normalizeProfiles(profiles) {
1066
+ return [...new Set(profiles.map((profile) => profile.trim()).filter(Boolean))].sort();
1067
+ }
1068
+ function createPkcePair() {
1069
+ const verifier = randomBytes(48).toString("base64url");
1070
+ return {
1071
+ verifier,
1072
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
1073
+ method: "S256"
1074
+ };
1075
+ }
1076
+ var OAuthClientError, refreshesByCredentialStore, NodeOAuthClient, DEFAULT_SERVICE, OsCredentialStore;
1077
+ var init_dist2 = __esm({
1078
+ "../node-auth/dist/index.js"() {
1079
+ "use strict";
1080
+ OAuthClientError = class extends Error {
1081
+ constructor(message, code, details) {
1082
+ super(message);
1083
+ this.code = code;
1084
+ this.details = details;
1085
+ this.name = "OAuthClientError";
1086
+ }
1087
+ };
1088
+ refreshesByCredentialStore = /* @__PURE__ */ new WeakMap();
1089
+ NodeOAuthClient = class {
1090
+ configuration;
1091
+ credentialStore;
1092
+ fetch;
1093
+ refreshes;
1094
+ constructor({
1095
+ configuration,
1096
+ credentialStore: credentialStore2,
1097
+ fetch: fetch2 = globalThis.fetch
1098
+ }) {
1099
+ this.configuration = configuration;
1100
+ this.credentialStore = credentialStore2;
1101
+ this.fetch = fetch2;
1102
+ const existingRefreshes = refreshesByCredentialStore.get(credentialStore2);
1103
+ this.refreshes = existingRefreshes ?? /* @__PURE__ */ new Map();
1104
+ if (!existingRefreshes) {
1105
+ refreshesByCredentialStore.set(credentialStore2, this.refreshes);
1106
+ }
1107
+ }
1108
+ createAuthorizationRequest({
1109
+ challenge,
1110
+ state
1111
+ }) {
1112
+ const url = new URL(this.configuration.authorizationEndpoint);
1113
+ url.search = new URLSearchParams({
1114
+ client_id: required(this.configuration.clientId, "clientId"),
1115
+ code_challenge: required(challenge, "challenge"),
1116
+ code_challenge_method: "S256",
1117
+ redirect_uri: required(this.configuration.redirectUri, "redirectUri"),
1118
+ resource: required(this.configuration.resource, "resource"),
1119
+ response_type: "code",
1120
+ scope: this.configuration.scopes.join(" "),
1121
+ state: required(state, "state")
1122
+ }).toString();
1123
+ return { url: url.toString() };
1124
+ }
1125
+ async exchangeAuthorizationCode({
1126
+ code,
1127
+ profile,
1128
+ verifier
1129
+ }) {
1130
+ const tokenSet = await this.tokenRequest(new URLSearchParams({
1131
+ client_id: this.configuration.clientId,
1132
+ code: required(code, "code"),
1133
+ code_verifier: required(verifier, "verifier"),
1134
+ grant_type: "authorization_code",
1135
+ redirect_uri: this.configuration.redirectUri,
1136
+ resource: this.configuration.resource
1137
+ }), "OAUTH_CODE_EXCHANGE_FAILED");
1138
+ await this.credentialStore.set(required(profile, "profile"), tokenSet);
1139
+ return tokenSet;
1140
+ }
1141
+ async getAccessToken(profile, { forceRefresh = false } = {}) {
1142
+ const normalizedProfile = required(profile, "profile");
1143
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1144
+ if (!tokenSet) {
1145
+ throw new OAuthClientError(
1146
+ `OAuth profile "${normalizedProfile}" is not logged in`,
1147
+ "OAUTH_LOGIN_REQUIRED"
1148
+ );
1149
+ }
1150
+ if (!forceRefresh && tokenSet.expiresAt > Date.now() + 3e4) {
1151
+ return tokenSet.accessToken;
1152
+ }
1153
+ const refreshKey = JSON.stringify([
1154
+ this.configuration.tokenEndpoint,
1155
+ this.configuration.clientId,
1156
+ this.configuration.resource,
1157
+ normalizedProfile
1158
+ ]);
1159
+ let refresh = this.refreshes.get(refreshKey);
1160
+ if (!refresh) {
1161
+ refresh = this.refresh(normalizedProfile, tokenSet).finally(() => this.refreshes.delete(refreshKey));
1162
+ this.refreshes.set(refreshKey, refresh);
1163
+ }
1164
+ return (await refresh).accessToken;
1165
+ }
1166
+ async status(profile) {
1167
+ const normalizedProfile = required(profile, "profile");
1168
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1169
+ return tokenSet ? {
1170
+ authenticated: true,
1171
+ expiresAt: tokenSet.expiresAt,
1172
+ profile: normalizedProfile,
1173
+ scope: [...tokenSet.scope]
1174
+ } : { authenticated: false, profile: normalizedProfile };
1175
+ }
1176
+ async logout(profile) {
1177
+ const normalizedProfile = required(profile, "profile");
1178
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1179
+ if (!tokenSet) return;
1180
+ await this.revoke(tokenSet.refreshToken);
1181
+ await this.credentialStore.delete(normalizedProfile);
1182
+ }
1183
+ async logoutAll() {
1184
+ for (const profile of await this.credentialStore.listProfiles()) {
1185
+ await this.logout(profile);
1186
+ }
1187
+ }
1188
+ async refresh(profile, current) {
1189
+ const replacement = await this.tokenRequest(new URLSearchParams({
1190
+ client_id: this.configuration.clientId,
1191
+ grant_type: "refresh_token",
1192
+ refresh_token: current.refreshToken,
1193
+ resource: this.configuration.resource
1194
+ }), "OAUTH_REFRESH_FAILED", {
1195
+ refreshToken: current.refreshToken,
1196
+ scopes: current.scope
1197
+ });
1198
+ await this.credentialStore.set(profile, replacement);
1199
+ return replacement;
1200
+ }
1201
+ async revoke(refreshToken) {
1202
+ if (!this.configuration.revocationEndpoint) {
1203
+ throw new OAuthClientError(
1204
+ "OAuth revocation endpoint is not configured",
1205
+ "OAUTH_REVOCATION_UNAVAILABLE"
1206
+ );
1207
+ }
1208
+ const response = await this.fetch(this.configuration.revocationEndpoint, {
1209
+ method: "POST",
1210
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1211
+ body: new URLSearchParams({
1212
+ client_id: this.configuration.clientId,
1213
+ token: refreshToken
1214
+ })
1215
+ });
1216
+ if (!response.ok) {
1217
+ throw new OAuthClientError(
1218
+ `OAuth revocation failed with status ${response.status}`,
1219
+ "OAUTH_REVOCATION_FAILED",
1220
+ { status: response.status }
1221
+ );
1222
+ }
1223
+ }
1224
+ async tokenRequest(body, errorCode, fallback) {
1225
+ const response = await this.fetch(this.configuration.tokenEndpoint, {
1226
+ method: "POST",
1227
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1228
+ body
1229
+ });
1230
+ const payload = await responsePayload(response);
1231
+ if (!response.ok) {
1232
+ throw new OAuthClientError(
1233
+ `OAuth token request failed with status ${response.status}`,
1234
+ errorCode,
1235
+ {
1236
+ error: stringField(payload, "error") || void 0,
1237
+ status: response.status
1238
+ }
1239
+ );
1240
+ }
1241
+ const accessToken = stringField(payload, "access_token");
1242
+ const refreshToken = stringField(payload, "refresh_token") || fallback?.refreshToken || "";
1243
+ const tokenType = stringField(payload, "token_type") || "Bearer";
1244
+ const expiresIn = Number(payload.expires_in);
1245
+ if (!accessToken || !refreshToken || !Number.isFinite(expiresIn) || expiresIn <= 0) {
1246
+ throw new OAuthClientError("OAuth token response is incomplete", errorCode);
1247
+ }
1248
+ const returnedScopes = stringField(payload, "scope").split(/\s+/).filter(Boolean);
1249
+ return {
1250
+ accessToken,
1251
+ expiresAt: Date.now() + expiresIn * 1e3,
1252
+ refreshToken,
1253
+ scope: returnedScopes.length > 0 ? returnedScopes : [...fallback?.scopes || []],
1254
+ tokenType
1255
+ };
1256
+ }
1257
+ };
1258
+ DEFAULT_SERVICE = "ai.mdedit.oauth";
1259
+ OsCredentialStore = class {
1260
+ createEntry;
1261
+ loadProfileIndex;
1262
+ saveProfileIndex;
1263
+ service;
1264
+ constructor({
1265
+ createEntry = (service2, account) => new Entry(service2, account),
1266
+ loadProfileIndex,
1267
+ saveProfileIndex,
1268
+ service = DEFAULT_SERVICE
1269
+ }) {
1270
+ this.createEntry = createEntry;
1271
+ this.loadProfileIndex = loadProfileIndex;
1272
+ this.saveProfileIndex = saveProfileIndex;
1273
+ this.service = service;
1274
+ }
1275
+ async delete(profile) {
1276
+ this.createEntry(this.service, profile).deletePassword();
1277
+ const profiles = (await this.listProfiles()).filter((item) => item !== profile);
1278
+ await this.saveProfileIndex(profiles);
1279
+ }
1280
+ async get(profile) {
1281
+ const serialized = this.createEntry(this.service, profile).getPassword();
1282
+ if (!serialized) return null;
1283
+ const parsed = JSON.parse(serialized);
1284
+ if (!parsed || typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.expiresAt !== "number" || !Array.isArray(parsed.scope)) {
1285
+ throw new Error(`Stored OAuth profile "${profile}" is invalid`);
1286
+ }
1287
+ return parsed;
1288
+ }
1289
+ async listProfiles() {
1290
+ return normalizeProfiles(await this.loadProfileIndex());
1291
+ }
1292
+ async set(profile, tokenSet) {
1293
+ this.createEntry(this.service, profile).setPassword(JSON.stringify(tokenSet));
1294
+ await this.saveProfileIndex(normalizeProfiles([
1295
+ ...await this.loadProfileIndex(),
1296
+ profile
1297
+ ]));
1298
+ }
1299
+ };
1300
+ }
1301
+ });
1302
+
937
1303
  // src/utils/oauth.ts
938
1304
  var oauth_exports = {};
939
1305
  __export(oauth_exports, {
@@ -943,14 +1309,8 @@ __export(oauth_exports, {
943
1309
  qualifyOAuthScopes: () => qualifyOAuthScopes,
944
1310
  storedOAuthAccessToken: () => storedOAuthAccessToken
945
1311
  });
946
- import { randomBytes } from "crypto";
1312
+ import { randomBytes as randomBytes2 } from "crypto";
947
1313
  import { spawn } from "child_process";
948
- import {
949
- NodeOAuthClient,
950
- OsCredentialStore,
951
- createPkcePair,
952
- startLoopbackCallback
953
- } from "@mdedit/node-auth";
954
1314
  function activeProfile(profile) {
955
1315
  return profile?.trim() || configManager.get("oauthProfile") || DEFAULT_PROFILE;
956
1316
  }
@@ -1041,7 +1401,7 @@ async function loginWithOAuth({
1041
1401
  const normalizedProfile = activeProfile(profile);
1042
1402
  const client = await oauthClient(scopes);
1043
1403
  const pkce = createPkcePair();
1044
- const state = randomBytes(32).toString("base64url");
1404
+ const state = randomBytes2(32).toString("base64url");
1045
1405
  const callback = await startLoopbackCallback({
1046
1406
  redirectUri: FIXED_REDIRECT_URI,
1047
1407
  state
@@ -1101,6 +1461,7 @@ var DEFAULT_PROFILE, FIXED_REDIRECT_URI, oauthClientsByConfiguration;
1101
1461
  var init_oauth = __esm({
1102
1462
  "src/utils/oauth.ts"() {
1103
1463
  "use strict";
1464
+ init_dist2();
1104
1465
  init_config();
1105
1466
  init_api();
1106
1467
  init_output();
@@ -1230,7 +1591,7 @@ import { Command } from "commander";
1230
1591
  import inquirer from "inquirer";
1231
1592
  import { v4 as uuidv4 } from "uuid";
1232
1593
  import { readFile, writeFile } from "fs/promises";
1233
- import { createHash } from "crypto";
1594
+ import { createHash as createHash2 } from "crypto";
1234
1595
  import { basename, extname } from "path";
1235
1596
  import {
1236
1597
  openArticleSession
@@ -1423,7 +1784,7 @@ async function writeBlobToFile(blob, filePath) {
1423
1784
  await writeFile(filePath, buffer);
1424
1785
  }
1425
1786
  function sha256Hex(content) {
1426
- return createHash("sha256").update(content).digest("hex");
1787
+ return createHash2("sha256").update(content).digest("hex");
1427
1788
  }
1428
1789
  function inferFileTitle(filePath, content) {
1429
1790
  const firstHeading = content?.match(/^\s*#\s+(.+?)\s*$/m)?.[1]?.trim();
@@ -2198,58 +2559,12 @@ function presentApiKeyListRow(key) {
2198
2559
  }
2199
2560
 
2200
2561
  // src/commands/apikey.ts
2201
- var DEFAULT_API_KEY_SCOPES = ["articles:read", "articles:write"];
2202
2562
  function createApiKeyCommands() {
2203
2563
  const apiKey = new Command5("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
2204
- apiKey.command("create").description("Create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").option("--scopes <scopes>", "Comma-separated least-privilege scopes").action(async (options) => {
2205
- requireApiKey();
2206
- const client = getApiClient();
2207
- let name = options.name;
2208
- if (!name) {
2209
- const answers = await inquirer5.prompt([
2210
- {
2211
- type: "input",
2212
- name: "name",
2213
- message: "API key name:",
2214
- validate: (input) => input.length > 0 || "Name is required"
2215
- }
2216
- ]);
2217
- name = String(answers.name);
2218
- }
2219
- const expiresRaw = options.expires;
2220
- let expiresInDays = void 0;
2221
- if (expiresRaw !== void 0) {
2222
- const days = Number.parseInt(String(expiresRaw), 10);
2223
- if (!Number.isFinite(days) || days <= 0) {
2224
- throw new Error("--expires must be a positive integer (number of days).");
2225
- }
2226
- expiresInDays = days;
2227
- }
2228
- const scopesRaw = options.scopes;
2229
- const scopes = scopesRaw === void 0 ? DEFAULT_API_KEY_SCOPES : [...new Set(scopesRaw.split(",").map((scope) => scope.trim()).filter(Boolean))];
2230
- if (scopesRaw !== void 0 && scopes?.length === 0) {
2231
- throw new Error("--scopes must contain at least one scope.");
2232
- }
2233
- output.info("Creating API key...");
2234
- const req = { name };
2235
- if (options.description) req.description = options.description;
2236
- if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
2237
- req.scopes = scopes;
2238
- const result = await client.apiKeys.create(req);
2239
- output.success("API key created successfully!");
2240
- output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
2241
- output.output({
2242
- keyId: result.keyId,
2243
- keyPrefix: result.keyPrefix,
2244
- name: result.name,
2245
- createdAt: result.createdAt,
2246
- expiresAt: result.expiresAt,
2247
- key: result.key
2248
- });
2249
- output.info("\nTo use this key with the CLI:");
2250
- output.info(` mdedit config set apiKey ${result.key}`);
2251
- output.info("\nOr set environment variable:");
2252
- output.info(` export MDEDIT_API_KEY="${result.key}"`);
2564
+ apiKey.command("create").description("Open the web app to create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").option("--scopes <scopes>", "Comma-separated least-privilege scopes").action(async () => {
2565
+ throw new Error(
2566
+ "API key creation is no longer supported in the CLI. Create scoped keys in mdedit.ai Settings -> Integrations -> API Keys, then configure the CLI with `mdedit config login --api-key <key>` or MDEDIT_API_KEY."
2567
+ );
2253
2568
  });
2254
2569
  apiKey.command("list").description("List your API keys").option("--full", "Show full API key objects (all fields)").action(async (options) => {
2255
2570
  requireApiKey();
@@ -2262,7 +2577,7 @@ function createApiKeyCommands() {
2262
2577
  }
2263
2578
  if (result.keys.length === 0) {
2264
2579
  output.output([]);
2265
- output.info("No API keys found. Create one with: mdedit apikey create");
2580
+ output.info("No API keys found. Create one in mdedit.ai Settings -> Integrations -> API Keys.");
2266
2581
  return;
2267
2582
  }
2268
2583
  output.output(result.keys.map(presentApiKeyListRow));