@mmon-co/ncept-local 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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 mmon-co
3
+ Copyright (c) 2026 mmon Co.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/dist/host.d.ts CHANGED
@@ -139,6 +139,7 @@ export interface Host {
139
139
  mission: string;
140
140
  title: string;
141
141
  visibility?: "public" | "unlisted";
142
+ signIn?: false;
142
143
  }>): Promise<HubRelease>;
143
144
  exportTo(destination: "web"): Promise<void>;
144
145
  importFrom(source: "web"): Promise<ImportResult>;
@@ -1,6 +1,18 @@
1
1
  import { type OAuthClientProvider, type OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js";
2
2
  import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
3
3
  import type { HubOptions } from "./host.js";
4
+ export declare function hubBaseUrl(value?: string): string;
5
+ export declare function hasHubCredentials(options: HubOptions): Promise<boolean>;
6
+ export declare function beginHubBrowserSignIn(options: HubOptions): Promise<HubBrowserSignIn>;
7
+ export declare class HubSignInRequired extends Error {
8
+ constructor();
9
+ }
10
+ export interface HubBrowserSignIn {
11
+ readonly url: string;
12
+ readonly expiresAt: number;
13
+ /** True once consent has been exchanged for locally stored Hub credentials. */
14
+ poll(): Promise<boolean>;
15
+ }
4
16
  /** SDK owns discovery, issuer/resource binding, dynamic registration, PKCE and refresh. */
5
17
  export declare class HubAuth implements OAuthClientProvider {
6
18
  readonly resource: string;
@@ -11,6 +23,7 @@ export declare class HubAuth implements OAuthClientProvider {
11
23
  private verifier?;
12
24
  private authorize?;
13
25
  private nonce;
26
+ private transient;
14
27
  private constructor();
15
28
  static open(resource: string, options: HubOptions): Promise<HubAuth>;
16
29
  get redirectUrl(): string | undefined;
@@ -42,5 +55,7 @@ export declare class HubAuth implements OAuthClientProvider {
42
55
  redirectToAuthorization(url: URL): Promise<void>;
43
56
  invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
44
57
  private save;
58
+ /** The browser can be on another machine. Keep the PKCE verifier and claim secret in this process. */
59
+ beginBrowserSignIn(): Promise<HubBrowserSignIn>;
45
60
  signIn(): Promise<void>;
46
61
  }
package/dist/hub-auth.js CHANGED
@@ -1,11 +1,34 @@
1
1
  import { createServer } from "node:http";
2
2
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
- import { randomBytes, randomUUID } from "node:crypto";
4
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { execFile } from "node:child_process";
6
- import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
6
+ import { auth, UnauthorizedError, } from "@modelcontextprotocol/sdk/client/auth.js";
7
7
  import { credentialsPath } from "./directory.js";
8
8
  const scopes = "patches publish learn";
9
+ const defaultHub = "https://co.mmon.co/ncept";
10
+ export function hubBaseUrl(value = defaultHub) {
11
+ const url = new URL(value);
12
+ if ((url.protocol !== "https:" &&
13
+ !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
14
+ url.username ||
15
+ url.password ||
16
+ url.search ||
17
+ url.hash)
18
+ throw new Error("Hub URL must use HTTPS (or loopback HTTP)");
19
+ return url.href.replace(/\/$/, "");
20
+ }
21
+ export async function hasHubCredentials(options) {
22
+ return Boolean((await HubAuth.open(hubBaseUrl(options.url) + "/mcp", options)).tokens());
23
+ }
24
+ export async function beginHubBrowserSignIn(options) {
25
+ return (await HubAuth.open(hubBaseUrl(options.url) + "/mcp", options)).beginBrowserSignIn();
26
+ }
27
+ export class HubSignInRequired extends Error {
28
+ constructor() {
29
+ super("Sign in to Common Concept first");
30
+ }
31
+ }
9
32
  async function load(path) {
10
33
  try {
11
34
  const stored = JSON.parse(await readFile(path, "utf8"));
@@ -34,6 +57,7 @@ export class HubAuth {
34
57
  verifier;
35
58
  authorize;
36
59
  nonce = "";
60
+ transient = false;
37
61
  constructor(resource, path, openUrl, clientMetadataUrl) {
38
62
  this.resource = resource;
39
63
  this.path = path;
@@ -96,7 +120,7 @@ export class HubAuth {
96
120
  }
97
121
  async redirectToAuthorization(url) {
98
122
  if (!this.authorize)
99
- throw new Error("Sign in first with host.hub.signIn()");
123
+ throw new UnauthorizedError("Sign in to Common Concept first");
100
124
  await this.authorize(url);
101
125
  }
102
126
  async invalidateCredentials(scope) {
@@ -110,12 +134,82 @@ export class HubAuth {
110
134
  }
111
135
  async save(change) {
112
136
  this.credentials = { ...this.credentials, ...change };
137
+ if (this.transient)
138
+ return;
113
139
  const all = { ...(await load(this.path)), [this.resource]: this.credentials };
114
140
  await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
115
141
  const temporary = this.path + "." + randomUUID() + ".tmp";
116
142
  await writeFile(temporary, JSON.stringify(all) + "\n", { mode: 0o600, flag: "wx" });
117
143
  await rename(temporary, this.path);
118
144
  }
145
+ /** The browser can be on another machine. Keep the PKCE verifier and claim secret in this process. */
146
+ async beginBrowserSignIn() {
147
+ const path = this.resource.replace(/\/mcp$/, "/bb-sign-in");
148
+ const attempt = new HubAuth(this.resource, this.path, this.openUrl);
149
+ attempt.transient = true;
150
+ const state = (attempt.nonce = randomBytes(32).toString("base64url"));
151
+ const secret = randomBytes(32).toString("base64url");
152
+ const claimHash = createHash("sha256").update(secret).digest("hex");
153
+ const send = (body) => fetch(path, {
154
+ method: "POST",
155
+ headers: { "Content-Type": "application/json" },
156
+ body: JSON.stringify({ state, ...body }),
157
+ redirect: "error",
158
+ signal: AbortSignal.timeout(10_000),
159
+ });
160
+ const startedAt = Date.now();
161
+ const started = await send({ claimHash });
162
+ if (!started.ok)
163
+ throw new Error("Common Concept sign-in is unavailable");
164
+ const config = await started.json();
165
+ if (!config ||
166
+ typeof config !== "object" ||
167
+ !("clientId" in config) ||
168
+ typeof config.clientId !== "string" ||
169
+ !("redirect" in config) ||
170
+ config.redirect !== path ||
171
+ !path.startsWith("https://") ||
172
+ !("expiresIn" in config) ||
173
+ typeof config.expiresIn !== "number")
174
+ throw new Error("Invalid Common Concept sign-in configuration");
175
+ attempt.credentials = { client: { client_id: config.clientId }, redirect: config.redirect };
176
+ let url;
177
+ attempt.authorize = async (authorization) => {
178
+ url = authorization.href;
179
+ };
180
+ const settings = {
181
+ serverUrl: this.resource,
182
+ resourceMetadataUrl: new URL(this.resource.replace(/\/mcp$/, "/.well-known/oauth-protected-resource")),
183
+ scope: scopes + " offline_access",
184
+ fetchFn: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(10_000) }),
185
+ };
186
+ await auth(attempt, settings);
187
+ if (!url)
188
+ throw new Error("Common Concept did not open sign-in");
189
+ const expiresAt = startedAt + config.expiresIn;
190
+ return {
191
+ url,
192
+ expiresAt,
193
+ poll: async () => {
194
+ const response = await send({ secret });
195
+ if (response.status === 410)
196
+ throw new Error("Sign-in expired. Try again.");
197
+ if (!response.ok)
198
+ throw new Error("Common Concept sign-in is unavailable");
199
+ const result = await response.json();
200
+ if (!result || typeof result !== "object")
201
+ throw new Error("Invalid Common Concept sign-in response");
202
+ if (!("code" in result))
203
+ return false;
204
+ if (typeof result.code !== "string")
205
+ throw new Error("Sign-in declined");
206
+ await auth(attempt, { ...settings, authorizationCode: result.code });
207
+ attempt.transient = false;
208
+ await attempt.save({});
209
+ return true;
210
+ },
211
+ };
212
+ }
119
213
  async signIn() {
120
214
  this.nonce = randomBytes(32).toString("base64url");
121
215
  let accept;
package/dist/hub.js CHANGED
@@ -5,7 +5,8 @@ import metadata from "../package.json" with { type: "json" };
5
5
  import { attachmentDigest, canonicalJson, contentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isMission, isMissionRevision, isPatchId, migrateTheoryPatchClosure, notebookSelection, reifyView, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, selectGraph, } from "@mmon-co/ncept-core";
6
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
- import { HubAuth } from "./hub-auth.js";
8
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
9
+ import { hubBaseUrl, HubAuth, HubSignInRequired } from "./hub-auth.js";
9
10
  import { unpackDirectory } from "./directory.js";
10
11
  import { object, parsePiSession } from "./sessions.js";
11
12
  import { validate, unpack } from "./exchange.js";
@@ -94,17 +95,6 @@ function suggestedMissions(revision, contents) {
94
95
  return { mission, preselected: preselected === true };
95
96
  });
96
97
  }
97
- function baseUrl(value) {
98
- const url = new URL(value);
99
- if ((url.protocol !== "https:" &&
100
- !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
101
- url.username ||
102
- url.password ||
103
- url.search ||
104
- url.hash)
105
- throw new Error("Hub URL must use HTTPS (or loopback HTTP)");
106
- return url.href.replace(/\/$/, "");
107
- }
108
98
  function releaseAddress(value, base) {
109
99
  const page = value.match(/^(https?:\/\/.+)\/hub\/([^/]+)\/releases\/([^/?#]+)(?:[?#].*)?$/);
110
100
  const api = value.match(/^(https?:\/\/.+)\/hub\/v1\/releases\/([^/]+)\/([^/?#]+)(?:[?#].*)?$/);
@@ -115,7 +105,7 @@ function releaseAddress(value, base) {
115
105
  if (!isPatchId(patchId) || !version)
116
106
  throw new Error("Use a Hub release page URL or patch-id@version");
117
107
  releasePrecedenceKey(version);
118
- return { base: match ? baseUrl(match[1] ?? "") : base, patchId, version };
108
+ return { base: match ? hubBaseUrl(match[1] ?? "") : base, patchId, version };
119
109
  }
120
110
  function releasePath(patchId, version) {
121
111
  return "/hub/v1/releases/" + encodeURIComponent(patchId) + "/" + encodeURIComponent(version);
@@ -180,16 +170,23 @@ function theoryRequirement(value) {
180
170
  return { theory: value.theory, range: value.range };
181
171
  }
182
172
  export function connectHub(profile, theories, confirm, createMission, options = {}) {
183
- const base = baseUrl(options.url ?? "https://co.mmon.co/ncept");
173
+ const base = hubBaseUrl(options.url);
184
174
  const resource = base + "/mcp";
185
175
  const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + metadata.version };
186
176
  async function connected(operation) {
187
177
  const provider = await HubAuth.open(resource, options);
188
178
  if (!provider.tokens())
189
- throw new Error("Sign in first with host.hub.signIn()");
179
+ throw new HubSignInRequired();
190
180
  const client = new Client({ name: metadata.name, version: metadata.version });
191
181
  try {
192
- await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
182
+ try {
183
+ await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
184
+ }
185
+ catch (error) {
186
+ if (error instanceof UnauthorizedError)
187
+ throw new HubSignInRequired();
188
+ throw error;
189
+ }
193
190
  return await operation(async (name, args) => {
194
191
  const result = await client.callTool({ name, arguments: args });
195
192
  const text = Array.isArray(result.content)
@@ -384,8 +381,11 @@ export function connectHub(profile, theories, confirm, createMission, options =
384
381
  })))
385
382
  throw new Error("Share declined");
386
383
  const provider = await HubAuth.open(resource, options);
387
- if (!provider.tokens())
384
+ if (!provider.tokens()) {
385
+ if (input.signIn === false)
386
+ throw new HubSignInRequired();
388
387
  await provider.signIn();
388
+ }
389
389
  return release(bundle, current.blobs, "0.1.0", visibility);
390
390
  },
391
391
  async exportTo() {
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { beginHubBrowserSignIn, hasHubCredentials, HubSignInRequired, type HubBrowserSignIn } from "./hub-auth.js";
5
6
  export { openLearningReader } from "./learning.js";
package/dist/index.js CHANGED
@@ -2,4 +2,5 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { beginHubBrowserSignIn, hasHubCredentials, HubSignInRequired } from "./hub-auth.js";
5
6
  export { openLearningReader } from "./learning.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmon-co/ncept-local",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,12 +36,12 @@
36
36
  "prepack": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@mmon-co/ncept-core": "^0.3.0",
39
+ "@mmon-co/ncept-core": "^0.4.0",
40
40
  "@modelcontextprotocol/sdk": "1.32.1",
41
41
  "proper-lockfile": "4.1.2"
42
42
  },
43
43
  "devDependencies": {
44
- "@mmon-co/ncept-default-theory": "^2.0.0",
44
+ "@mmon-co/ncept-default-theory": "^3.0.0",
45
45
  "@types/proper-lockfile": "^4.1.4",
46
46
  "bun-types": "^1.3.14",
47
47
  "typescript": "5.9.3"