devframe 0.6.0-beta.1 → 0.6.0-beta.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.
Files changed (62) hide show
  1. package/dist/adapters/build.d.mts +1 -1
  2. package/dist/adapters/build.mjs +2 -2
  3. package/dist/adapters/cli.d.mts +1 -1
  4. package/dist/adapters/cli.mjs +1 -1
  5. package/dist/adapters/dev.d.mts +2 -2
  6. package/dist/adapters/dev.mjs +1 -1
  7. package/dist/adapters/embedded.d.mts +1 -1
  8. package/dist/adapters/mcp.d.mts +1 -1
  9. package/dist/adapters/mcp.mjs +3 -3
  10. package/dist/client/index.d.mts +2 -2
  11. package/dist/client/index.mjs +56 -22
  12. package/dist/constants.d.mts +24 -1
  13. package/dist/constants.mjs +26 -1
  14. package/dist/{context-o-TwncyP.d.mts → context-B_I9fMBc.d.mts} +1 -1
  15. package/dist/{context-3x_bgBgZ.mjs → context-CKJheEtf.mjs} +2 -2
  16. package/dist/{dev-CSpLSEVh.mjs → dev-DSxKFn-v.mjs} +4 -4
  17. package/dist/{devframe-BwfavB78.d.mts → devframe-DgvncQy2.d.mts} +20 -4
  18. package/dist/{dump-DoXkj4ku.mjs → dump-D09PZb7T.mjs} +14 -4
  19. package/dist/{hash-DFc5WwhO.mjs → hash-PAfnyu2k.mjs} +1 -1
  20. package/dist/helpers/vite.d.mts +1 -1
  21. package/dist/helpers/vite.mjs +2 -2
  22. package/dist/{host-h3-C5SZlk03.mjs → host-h3-Dsf-Tgwx.mjs} +37 -11
  23. package/dist/index-B4lNDq5v.d.mts +107 -0
  24. package/dist/{index-CxaPKDXX.d.mts → index-Dy6GFDRf.d.mts} +1 -0
  25. package/dist/index.d.mts +3 -3
  26. package/dist/{launch-editor-CgXBgviI.mjs → launch-editor-DIzaS5EG.mjs} +146 -56
  27. package/dist/node/auth.d.mts +2 -64
  28. package/dist/node/auth.mjs +2 -100
  29. package/dist/node/hub-internals.d.mts +2 -2
  30. package/dist/node/hub-internals.mjs +1 -1
  31. package/dist/node/index.d.mts +4 -4
  32. package/dist/node/index.mjs +3 -3
  33. package/dist/recipes/interactive-auth.d.mts +53 -0
  34. package/dist/recipes/interactive-auth.mjs +132 -0
  35. package/dist/recipes/open-helpers.mjs +2 -2
  36. package/dist/{revoke-ENfxWkFK.mjs → revoke-BtQDKTp7.mjs} +1 -1
  37. package/dist/rpc/dump.mjs +1 -1
  38. package/dist/rpc/index.d.mts +2 -2
  39. package/dist/rpc/index.mjs +4 -1
  40. package/dist/rpc/transports/ws-client.mjs +21 -8
  41. package/dist/rpc/transports/ws-server.d.mts +2 -2
  42. package/dist/rpc/transports/ws-server.mjs +36 -7
  43. package/dist/{server-wyY3zh67.mjs → server-BdN41ckC.mjs} +37 -4
  44. package/dist/server-DXPq8q0K.d.mts +121 -0
  45. package/dist/{shared-state-D4PPieA0.mjs → shared-state-QtMas0NG.mjs} +34 -4
  46. package/dist/state-WX3HT5a3.mjs +101 -0
  47. package/dist/{storage-l2ezeend.mjs → storage-yrUZaiib.mjs} +55 -6
  48. package/dist/types/index.d.mts +3 -3
  49. package/dist/utils/crypto-token.mjs +1 -1
  50. package/dist/utils/events.d.mts +1 -1
  51. package/dist/utils/hash.mjs +1 -1
  52. package/dist/utils/launch-editor.mjs +1 -1
  53. package/dist/utils/open.mjs +1 -1
  54. package/dist/utils/serve-static.mjs +2 -1
  55. package/dist/utils/shared-state.d.mts +1 -1
  56. package/dist/utils/shared-state.mjs +1 -1
  57. package/dist/utils/streaming-channel.d.mts +1 -1
  58. package/dist/utils/when.d.mts +1 -1
  59. package/dist/{ws-server-BVVMDo2n.d.mts → ws-server-Bc2wBHl-.d.mts} +17 -1
  60. package/package.json +10 -9
  61. package/dist/server-oju7PTi2.d.mts +0 -82
  62. package/dist/{open-Dusa2Zzd.mjs → open-Deb5xmIT.mjs} +1 -1
@@ -0,0 +1,121 @@
1
+ import { d as ConnectionMeta, h as DevframeNodeRpcSession, it as DevframeRpcServerFunctions, m as DevframeNodeContext, rt as DevframeRpcClientFunctions } from "./devframe-DgvncQy2.mjs";
2
+ import { c as DevframeAuthHandler } from "./index-B4lNDq5v.mjs";
3
+ import { BirpcGroup } from "birpc";
4
+ import { Peer } from "crossws";
5
+ import { NodeAdapter } from "crossws/adapters/node";
6
+ import { Server } from "node:http";
7
+ import { H3 } from "h3";
8
+
9
+ //#region src/node/server.d.ts
10
+ interface StartHttpAndWsOptions {
11
+ context: DevframeNodeContext;
12
+ host?: string;
13
+ port: number;
14
+ /**
15
+ * Optional h3 app to mount on. When omitted a fresh one is created;
16
+ * when provided, callers can add their own routes (static handlers,
17
+ * auth middleware, etc.) first.
18
+ */
19
+ app?: H3;
20
+ /**
21
+ * Bind the WS endpoint to a single upgrade route (e.g. `/__devframe_ws`) instead of
22
+ * claiming every upgrade on the port. This lets the socket share a server
23
+ * with other upgrade handlers (Vite HMR, a host framework's own sockets)
24
+ * and is what the SPA's `__connection.json` points at. When omitted, the WS
25
+ * server handles every upgrade on the port (legacy behaviour).
26
+ */
27
+ path?: string;
28
+ /**
29
+ * Bind the WS endpoint on its own port instead of sharing the HTTP server's.
30
+ * The HTTP/SPA server still listens on `port`; the socket gets a dedicated
31
+ * `ws` server on `wsPort` (same `host`). Use this for the "different port"
32
+ * connection scenario. Ignored when a `server` is supplied.
33
+ */
34
+ wsPort?: number;
35
+ /**
36
+ * Mount the WS endpoint onto an existing HTTP server, sharing its port,
37
+ * rather than creating and listening on a fresh one. Use this to embed
38
+ * devframe's RPC socket inside a host server (e.g. a Vite dev server) — pair
39
+ * it with `path` so it coexists with the host's routes. The caller owns the
40
+ * server's lifecycle: {@link StartedServer.close} detaches devframe's upgrade
41
+ * listener but leaves the host server running. When set, `host`/`port` are
42
+ * only used to report the resolved origin.
43
+ */
44
+ server?: Server;
45
+ /**
46
+ * Authentication for the server:
47
+ *
48
+ * - `true` (default) — no gate; every registered method is callable
49
+ * regardless of trust (today's behavior, unchanged).
50
+ * - `false` — the RPC server is started without a trust handshake.
51
+ * Intended for single-user localhost tools where an auth round-trip
52
+ * would only get in the way. A noop `anonymous:devframe:auth` handler
53
+ * is registered so the browser client's unconditional handshake call
54
+ * succeeds and auto-trusts.
55
+ * - A {@link DevframeAuthHandler} (e.g. from
56
+ * `devframe/recipes/interactive-auth`'s `createInteractiveAuth`) —
57
+ * registers its `rpcFunctions`, wires its `authorize` as the resolver
58
+ * gate, and wires its `onConnect` on every new peer. This is the
59
+ * fully-authenticated server: an untrusted caller can only reach
60
+ * `anonymous:`-prefixed methods (see `isAnonymousRpcMethod`).
61
+ */
62
+ auth?: boolean | DevframeAuthHandler;
63
+ /**
64
+ * Lower-level escape hatch: gate individual RPC calls by method name and
65
+ * session without a full {@link DevframeAuthHandler}. Ignored when `auth`
66
+ * is a handler object (its own `authorize` is used); combine with `auth:
67
+ * true` to layer a custom policy on top of an otherwise ungated server.
68
+ */
69
+ authorize?: (methodName: string, session: DevframeNodeRpcSession) => boolean;
70
+ /**
71
+ * Called once per new WS connection, right after its session is created
72
+ * (before any RPC call is dispatched). Runs after the auth handler's own
73
+ * `onConnect` (when `auth` is a {@link DevframeAuthHandler}), so it can
74
+ * observe — but not override — the connect-time trust decision.
75
+ */
76
+ onPeerConnect?: (peer: Peer, session: DevframeNodeRpcSession) => void;
77
+ /**
78
+ * Extra origins to accept on the WS upgrade beyond the loopback default
79
+ * (`localhost`/`127.0.0.1`/`::1` and any `Origin`-less request from a
80
+ * native client). Add your LAN/tunnel origin here when reaching the tool
81
+ * from another host. Pass `false` to disable origin checking entirely
82
+ * (not recommended). Default: loopback-only.
83
+ */
84
+ allowedOrigins?: readonly string[] | false;
85
+ /**
86
+ * Called once the WS server is bound so callers can mount static
87
+ * handlers whose origin depends on the resolved port, or print their
88
+ * own startup banner. Devframe does not print one itself.
89
+ */
90
+ onReady?: (info: {
91
+ origin: string;
92
+ port: number;
93
+ app: H3;
94
+ }) => void | Promise<void>;
95
+ }
96
+ interface StartedServer {
97
+ /** Listening origin, e.g. `http://localhost:9999`. */
98
+ origin: string;
99
+ port: number;
100
+ app: H3;
101
+ /** The crossws node adapter driving the RPC socket (connected peers, pub/sub). */
102
+ ws: NodeAdapter;
103
+ rpcGroup: BirpcGroup<DevframeRpcClientFunctions, DevframeRpcServerFunctions, false>;
104
+ /**
105
+ * The {@link ConnectionMeta} descriptor for this server — the same shape
106
+ * a `__connection.json` route should serve so a devframe client's
107
+ * `resolveWsUrl` can dial back in. Reflects the `path` / `wsPort` this
108
+ * server was started with and the `jsonSerializable` methods currently
109
+ * registered on `context.rpc`.
110
+ */
111
+ connectionMeta: () => ConnectionMeta;
112
+ close: () => Promise<void>;
113
+ }
114
+ /**
115
+ * Compose an h3 + WebSocket server for a devframe context. The RPC
116
+ * group is bound to `context.rpc.functions`; the WS endpoint lives on
117
+ * the same port as the HTTP server.
118
+ */
119
+ declare function startHttpAndWs(options: StartHttpAndWsOptions): Promise<StartedServer>;
120
+ //#endregion
121
+ export { StartedServer as n, startHttpAndWs as r, StartHttpAndWsOptions as t };
@@ -1,6 +1,6 @@
1
1
  import { createEventEmitter } from "./utils/events.mjs";
2
2
  import { nanoid } from "./utils/nanoid.mjs";
3
- //#region ../../node_modules/.pnpm/immer@11.1.8/node_modules/immer/dist/immer.mjs
3
+ //#region ../../node_modules/.pnpm/immer@11.1.11/node_modules/immer/dist/immer.mjs
4
4
  var NOTHING = Symbol.for("immer-nothing");
5
5
  var DRAFTABLE = Symbol.for("immer-draftable");
6
6
  var DRAFT_STATE = Symbol.for("immer-state");
@@ -350,6 +350,21 @@ function createProxyProxy(base, parent) {
350
350
  var objectTraps = {
351
351
  get(state, prop) {
352
352
  if (prop === DRAFT_STATE) return state;
353
+ if (prop === "constructor" || prop === "__proto__") {
354
+ const value2 = latest(state)[prop];
355
+ return new Proxy(value2 || {}, {
356
+ get: (target, key) => {
357
+ if (key === "__proto__" || key === "prototype") return Object.freeze(/* @__PURE__ */ Object.create(null));
358
+ return Reflect.get(target, key);
359
+ },
360
+ set: () => {
361
+ return true;
362
+ },
363
+ apply: (target, thisArg, args) => {
364
+ return Reflect.apply(target, thisArg, args);
365
+ }
366
+ });
367
+ }
353
368
  let arrayPlugin = state.scope_.arrayMethodsPlugin_;
354
369
  const isArrayWithStringProp = state.type_ === 1 && typeof prop === "string";
355
370
  if (isArrayWithStringProp) {
@@ -369,12 +384,14 @@ var objectTraps = {
369
384
  return value;
370
385
  },
371
386
  has(state, prop) {
387
+ if (prop === "constructor" || prop === "__proto__" || prop === "prototype") return false;
372
388
  return prop in latest(state);
373
389
  },
374
390
  ownKeys(state) {
375
391
  return Reflect.ownKeys(latest(state));
376
392
  },
377
393
  set(state, prop, value) {
394
+ if (prop === "constructor" || prop === "__proto__" || prop === "prototype") return true;
378
395
  const desc = getDescriptorFromProto(latest(state), prop);
379
396
  if (desc?.set) {
380
397
  desc.set.call(state.draft_, value);
@@ -392,7 +409,7 @@ var objectTraps = {
392
409
  prepareCopy(state);
393
410
  markChanged(state);
394
411
  }
395
- if (state.copy_[prop] === value && (value !== void 0 || prop in state.copy_) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
412
+ if (state.copy_[prop] === value && (value !== void 0 || has(state.copy_, prop, state.type_)) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
396
413
  state.copy_[prop] = value;
397
414
  state.assigned_.set(prop, true);
398
415
  handleCrossReference(state, prop, value);
@@ -894,6 +911,19 @@ var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(immer);
894
911
  var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
895
912
  //#endregion
896
913
  //#region src/utils/shared-state.ts
914
+ /**
915
+ * Upper bound on retained syncIds. Loop echoes arrive near-immediately, so a
916
+ * generous window preserves de-dup while capping memory on long-lived,
917
+ * frequently-mutated states (e.g. a 1s terminal poll).
918
+ */
919
+ const MAX_SYNC_IDS = 1e3;
920
+ function rememberSyncId(syncIds, syncId) {
921
+ syncIds.add(syncId);
922
+ if (syncIds.size > MAX_SYNC_IDS) {
923
+ const oldest = syncIds.values().next().value;
924
+ if (oldest !== void 0) syncIds.delete(oldest);
925
+ }
926
+ }
897
927
  function createSharedState(options) {
898
928
  const { enablePatches: enablePatches$1 = false } = options;
899
929
  const events = createEventEmitter();
@@ -906,12 +936,12 @@ function createSharedState(options) {
906
936
  if (syncIds.has(syncId)) return;
907
937
  enablePatches();
908
938
  state = applyPatches(state, patches);
909
- syncIds.add(syncId);
939
+ rememberSyncId(syncIds, syncId);
910
940
  events.emit("updated", state, void 0, syncId);
911
941
  },
912
942
  mutate: (fn, syncId = nanoid()) => {
913
943
  if (syncIds.has(syncId)) return;
914
- syncIds.add(syncId);
944
+ rememberSyncId(syncIds, syncId);
915
945
  if (enablePatches$1) {
916
946
  const [newState, patches] = produceWithPatches(state, fn);
917
947
  state = newState;
@@ -0,0 +1,101 @@
1
+ import { DEVFRAME_OTP_URL_PARAM } from "./constants.mjs";
2
+ import { a as timingSafeEqual, i as randomToken, r as randomDigits } from "./revoke-BtQDKTp7.mjs";
3
+ //#region src/node/auth/state.ts
4
+ /** Number of decimal digits in a human-typed one-time authentication code. */
5
+ const TEMP_AUTH_CODE_LENGTH = 6;
6
+ /**
7
+ * How long an authentication code stays valid after it is (re)generated. A
8
+ * 6-digit code only has ~20 bits of entropy, so a short lifetime plus the
9
+ * attempt cap below are what keep it brute-force resistant.
10
+ */
11
+ const TEMP_AUTH_CODE_TTL = 5 * 6e4;
12
+ /** Failed attempts allowed against a single code before it is rotated. */
13
+ const TEMP_AUTH_MAX_ATTEMPTS = 5;
14
+ let tempAuthCode = generateTempCode();
15
+ let tempAuthCodeExpiresAt = Date.now() + TEMP_AUTH_CODE_TTL;
16
+ let tempAuthFailedAttempts = 0;
17
+ function generateTempCode() {
18
+ return randomDigits(TEMP_AUTH_CODE_LENGTH);
19
+ }
20
+ /**
21
+ * The current one-time authentication code. Display this to the user (e.g. in
22
+ * the dev-server terminal) so they can type it into the browser to authenticate.
23
+ */
24
+ function getTempAuthCode() {
25
+ return tempAuthCode;
26
+ }
27
+ /**
28
+ * Rotate the authentication code, resetting its expiry window and failed-attempt
29
+ * counter. Call this when a new authentication flow begins (e.g. when an
30
+ * untrusted client starts authenticating) so the displayed code is freshly
31
+ * valid for its full TTL.
32
+ */
33
+ function refreshTempAuthCode() {
34
+ tempAuthCode = generateTempCode();
35
+ tempAuthCodeExpiresAt = Date.now() + TEMP_AUTH_CODE_TTL;
36
+ tempAuthFailedAttempts = 0;
37
+ return tempAuthCode;
38
+ }
39
+ /**
40
+ * Build a "magic link" authentication URL that embeds a one-time code (OTP) as
41
+ * a query parameter. Opening it authenticates the client without typing — print
42
+ * it on startup (devframe stays headless, so the host prints its own banner).
43
+ * Defaults to the current code; the link is subject to the same TTL.
44
+ */
45
+ function buildOtpAuthUrl(baseUrl, code = tempAuthCode) {
46
+ const url = new URL(baseUrl);
47
+ url.searchParams.set(DEVFRAME_OTP_URL_PARAM, code);
48
+ return url.href;
49
+ }
50
+ /**
51
+ * Re-authenticate a connection that presents a previously-issued bearer token.
52
+ * Returns `true` and marks the session trusted when the token is known.
53
+ *
54
+ * Used by the `anonymous:devframe:auth` handler so a client that already
55
+ * authenticated (token persisted in the browser) is trusted on reconnect
56
+ * without entering the code again.
57
+ */
58
+ function verifyAuthToken(token, session, storage) {
59
+ if (!token || !storage.value().trusted[token]) return false;
60
+ session.meta.clientAuthToken = token;
61
+ session.meta.isTrusted = true;
62
+ return true;
63
+ }
64
+ /**
65
+ * Exchange a one-time authentication code for a fresh, node-issued bearer token.
66
+ *
67
+ * On success this mints a high-entropy token, records it in the trusted store,
68
+ * marks the calling session trusted, rotates the code, and returns the token
69
+ * for the client to persist. Returns `null` on any failure.
70
+ *
71
+ * Because the code is short and human-typed, verification is hardened against
72
+ * brute force: it enforces a time-to-live, compares in constant time, and
73
+ * rotates the code after {@link TEMP_AUTH_MAX_ATTEMPTS} failed attempts so an
74
+ * attacker cannot keep guessing against the same code.
75
+ */
76
+ function exchangeTempAuthCode(code, session, info, storage) {
77
+ if (Date.now() > tempAuthCodeExpiresAt) {
78
+ refreshTempAuthCode();
79
+ return null;
80
+ }
81
+ if (!timingSafeEqual(code, tempAuthCode)) {
82
+ tempAuthFailedAttempts += 1;
83
+ if (tempAuthFailedAttempts >= TEMP_AUTH_MAX_ATTEMPTS) refreshTempAuthCode();
84
+ return null;
85
+ }
86
+ const authToken = randomToken();
87
+ storage.mutate((state) => {
88
+ state.trusted[authToken] = {
89
+ authToken,
90
+ ua: info.ua,
91
+ origin: info.origin,
92
+ timestamp: Date.now()
93
+ };
94
+ });
95
+ session.meta.clientAuthToken = authToken;
96
+ session.meta.isTrusted = true;
97
+ refreshTempAuthCode();
98
+ return authToken;
99
+ }
100
+ //#endregion
101
+ export { verifyAuthToken as a, refreshTempAuthCode as i, exchangeTempAuthCode as n, getTempAuthCode as r, buildOtpAuthUrl as t };
@@ -2,6 +2,7 @@ import { t as devframeReporter } from "./diagnostics-reporter-CsIG85Q5.mjs";
2
2
  import { defineDiagnostics } from "nostics";
3
3
  import fs from "node:fs";
4
4
  import { dirname } from "pathe";
5
+ import process$1 from "node:process";
5
6
  import { destr } from "destr";
6
7
  //#region src/node/diagnostics.ts
7
8
  const diagnostics = defineDiagnostics({
@@ -46,6 +47,14 @@ const diagnostics = defineDiagnostics({
46
47
  DF0034: {
47
48
  why: (p) => `Scoped RPC registration for namespace "${p.namespace}" received an already-namespaced function name "${p.name}".`,
48
49
  fix: "A scoped context auto-namespaces ids. Pass a bare name without a \":\" separator (e.g. `register({ name: \"get-cwd\" })`), or use the unscoped `ctx.base.rpc.register` for a fully-qualified name."
50
+ },
51
+ DF0035: {
52
+ why: (p) => `Failed to persist storage file: ${p.filepath}`,
53
+ fix: "Check that the storage directory is writable and has free space."
54
+ },
55
+ DF0036: {
56
+ why: (p) => `RPC call to "${p.name}" was rejected: the caller is not authorized.`,
57
+ fix: "Complete the auth handshake (or connect with a static/pre-shared token) before calling a trusted method. Untrusted callers may only call `anonymous:`-prefixed methods — see `isAnonymousRpcMethod`."
49
58
  }
50
59
  }
51
60
  });
@@ -89,7 +98,7 @@ function createEventEmitter() {
89
98
  };
90
99
  }
91
100
  //#endregion
92
- //#region ../../node_modules/.pnpm/immer@11.1.8/node_modules/immer/dist/immer.mjs
101
+ //#region ../../node_modules/.pnpm/immer@11.1.11/node_modules/immer/dist/immer.mjs
93
102
  var NOTHING = Symbol.for("immer-nothing");
94
103
  var DRAFTABLE = Symbol.for("immer-draftable");
95
104
  var DRAFT_STATE = Symbol.for("immer-state");
@@ -439,6 +448,21 @@ function createProxyProxy(base, parent) {
439
448
  var objectTraps = {
440
449
  get(state, prop) {
441
450
  if (prop === DRAFT_STATE) return state;
451
+ if (prop === "constructor" || prop === "__proto__") {
452
+ const value2 = latest(state)[prop];
453
+ return new Proxy(value2 || {}, {
454
+ get: (target, key) => {
455
+ if (key === "__proto__" || key === "prototype") return Object.freeze(/* @__PURE__ */ Object.create(null));
456
+ return Reflect.get(target, key);
457
+ },
458
+ set: () => {
459
+ return true;
460
+ },
461
+ apply: (target, thisArg, args) => {
462
+ return Reflect.apply(target, thisArg, args);
463
+ }
464
+ });
465
+ }
442
466
  let arrayPlugin = state.scope_.arrayMethodsPlugin_;
443
467
  const isArrayWithStringProp = state.type_ === 1 && typeof prop === "string";
444
468
  if (isArrayWithStringProp) {
@@ -458,12 +482,14 @@ var objectTraps = {
458
482
  return value;
459
483
  },
460
484
  has(state, prop) {
485
+ if (prop === "constructor" || prop === "__proto__" || prop === "prototype") return false;
461
486
  return prop in latest(state);
462
487
  },
463
488
  ownKeys(state) {
464
489
  return Reflect.ownKeys(latest(state));
465
490
  },
466
491
  set(state, prop, value) {
492
+ if (prop === "constructor" || prop === "__proto__" || prop === "prototype") return true;
467
493
  const desc = getDescriptorFromProto(latest(state), prop);
468
494
  if (desc?.set) {
469
495
  desc.set.call(state.draft_, value);
@@ -481,7 +507,7 @@ var objectTraps = {
481
507
  prepareCopy(state);
482
508
  markChanged(state);
483
509
  }
484
- if (state.copy_[prop] === value && (value !== void 0 || prop in state.copy_) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
510
+ if (state.copy_[prop] === value && (value !== void 0 || has(state.copy_, prop, state.type_)) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
485
511
  state.copy_[prop] = value;
486
512
  state.assigned_.set(prop, true);
487
513
  handleCrossReference(state, prop, value);
@@ -992,6 +1018,19 @@ function nanoid(size = 21) {
992
1018
  }
993
1019
  //#endregion
994
1020
  //#region src/utils/shared-state.ts
1021
+ /**
1022
+ * Upper bound on retained syncIds. Loop echoes arrive near-immediately, so a
1023
+ * generous window preserves de-dup while capping memory on long-lived,
1024
+ * frequently-mutated states (e.g. a 1s terminal poll).
1025
+ */
1026
+ const MAX_SYNC_IDS = 1e3;
1027
+ function rememberSyncId(syncIds, syncId) {
1028
+ syncIds.add(syncId);
1029
+ if (syncIds.size > MAX_SYNC_IDS) {
1030
+ const oldest = syncIds.values().next().value;
1031
+ if (oldest !== void 0) syncIds.delete(oldest);
1032
+ }
1033
+ }
995
1034
  function createSharedState(options) {
996
1035
  const { enablePatches: enablePatches$1 = false } = options;
997
1036
  const events = createEventEmitter();
@@ -1004,12 +1043,12 @@ function createSharedState(options) {
1004
1043
  if (syncIds.has(syncId)) return;
1005
1044
  enablePatches();
1006
1045
  state = applyPatches(state, patches);
1007
- syncIds.add(syncId);
1046
+ rememberSyncId(syncIds, syncId);
1008
1047
  events.emit("updated", state, void 0, syncId);
1009
1048
  },
1010
1049
  mutate: (fn, syncId = nanoid()) => {
1011
1050
  if (syncIds.has(syncId)) return;
1012
- syncIds.add(syncId);
1051
+ rememberSyncId(syncIds, syncId);
1013
1052
  if (enablePatches$1) {
1014
1053
  const [newState, patches] = produceWithPatches(state, fn);
1015
1054
  state = newState;
@@ -1132,8 +1171,18 @@ function createStorage(options) {
1132
1171
  enablePatches: false
1133
1172
  });
1134
1173
  state.on("updated", debounce((newState) => {
1135
- fs.mkdirSync(dirname(options.filepath), { recursive: true });
1136
- fs.writeFileSync(options.filepath, `${JSON.stringify(newState, null, 2)}\n`);
1174
+ try {
1175
+ const dir = dirname(options.filepath);
1176
+ fs.mkdirSync(dir, { recursive: true });
1177
+ const tmp = `${options.filepath}.${process$1.pid}.tmp`;
1178
+ fs.writeFileSync(tmp, `${JSON.stringify(newState, null, 2)}\n`);
1179
+ fs.renameSync(tmp, options.filepath);
1180
+ } catch (error) {
1181
+ diagnostics.DF0035({
1182
+ filepath: options.filepath,
1183
+ cause: error
1184
+ }, { method: "error" });
1185
+ }
1137
1186
  }, debounceTime));
1138
1187
  return state;
1139
1188
  }
@@ -1,4 +1,4 @@
1
- import { $ as ScopedServerFunctions, G as DevframeScopedNodeContext, H as EntriesToObject, J as DevframeSettings, K as DevframeScopedNodeRpc, Q as ScopedClientFunctions, S as RpcStreamingHost, St as EventsMap, U as PartialWithoutId, W as Thenable, X as DevframeSettingsStore, Y as DevframeSettingsRegistry, Z as ScopedBroadcastOptions, _ as RpcFunctionsHost, _t as AgentToolInput, a as DevframeDuplicationStrategy, at as DevframeRpcSharedStates, b as RpcStreamingChannel, bt as EventEmitter, c as DevframeSpaOptions, ct as DevframeDiagnosticsDefinition, d as ConnectionMeta, dt as AgentHandle, et as ScopedSharedStates, f as ConnectionMetaWebsocket, ft as AgentManifest, g as RpcBroadcastOptions, gt as AgentTool, h as DevframeNodeRpcSession, ht as AgentResourceInput, i as DevframeDeploymentKind, it as DevframeRpcServerFunctions, l as DevframeWsOptions, lt as DevframeDiagnosticsHost, m as DevframeNodeContext, mt as AgentResourceContent, n as DevframeCliOptions, nt as DevframeViewHost, o as DevframeRuntime, ot as DevframeHost, p as DevframeCapabilities, pt as AgentResource, q as DevframeScopedStreamingHost, r as DevframeDefinition, rt as DevframeRpcClientFunctions, s as DevframeSetupInfo, st as DevframeDefineDiagnosticsOptions, t as DevframeBrowserContext, tt as SettingsForNamespace, u as defineDevframe, ut as DevframeDiagnosticsLogger, v as RpcSharedStateGetOptions, vt as DevframeAgentHost, x as RpcStreamingChannelOptions, xt as EventUnsubscribe, y as RpcSharedStateHost, yt as DevframeAgentHostEvents } from "../devframe-BwfavB78.mjs";
1
+ import { $ as ScopedServerFunctions, G as DevframeScopedNodeContext, H as EntriesToObject, J as DevframeSettings, K as DevframeScopedNodeRpc, Q as ScopedClientFunctions, S as RpcStreamingHost, St as EventsMap, U as PartialWithoutId, W as Thenable, X as DevframeSettingsStore, Y as DevframeSettingsRegistry, Z as ScopedBroadcastOptions, _ as RpcFunctionsHost, _t as AgentToolInput, a as DevframeDuplicationStrategy, at as DevframeRpcSharedStates, b as RpcStreamingChannel, bt as EventEmitter, c as DevframeSpaOptions, ct as DevframeDiagnosticsDefinition, d as ConnectionMeta, dt as AgentHandle, et as ScopedSharedStates, f as ConnectionMetaWebsocket, ft as AgentManifest, g as RpcBroadcastOptions, gt as AgentTool, h as DevframeNodeRpcSession, ht as AgentResourceInput, i as DevframeDeploymentKind, it as DevframeRpcServerFunctions, l as DevframeWsOptions, lt as DevframeDiagnosticsHost, m as DevframeNodeContext, mt as AgentResourceContent, n as DevframeCliOptions, nt as DevframeViewHost, o as DevframeRuntime, ot as DevframeHost, p as DevframeCapabilities, pt as AgentResource, q as DevframeScopedStreamingHost, r as DevframeDefinition, rt as DevframeRpcClientFunctions, s as DevframeSetupInfo, st as DevframeDefineDiagnosticsOptions, t as DevframeBrowserContext, tt as SettingsForNamespace, u as defineDevframe, ut as DevframeDiagnosticsLogger, v as RpcSharedStateGetOptions, vt as DevframeAgentHost, x as RpcStreamingChannelOptions, xt as EventUnsubscribe, y as RpcSharedStateHost, yt as DevframeAgentHostEvents } from "../devframe-DgvncQy2.mjs";
2
2
  import { g as RpcFunctionAgentOptions } from "../types-DZEx4ffs.mjs";
3
- import { t as DevframeNodeRpcSessionMeta } from "../ws-server-BVVMDo2n.mjs";
4
- export { AgentHandle, AgentManifest, AgentResource, AgentResourceContent, AgentResourceInput, AgentTool, AgentToolInput, ConnectionMeta, ConnectionMetaWebsocket, DevframeAgentHost, DevframeAgentHostEvents, DevframeBrowserContext, DevframeCapabilities, DevframeCliOptions, DevframeDefineDiagnosticsOptions, DevframeDefinition, DevframeDeploymentKind, DevframeDiagnosticsDefinition, DevframeDiagnosticsHost, DevframeDiagnosticsLogger, DevframeDuplicationStrategy, DevframeHost, DevframeNodeContext, DevframeNodeRpcSession, DevframeNodeRpcSessionMeta, DevframeRpcClientFunctions, DevframeRpcServerFunctions, DevframeRpcSharedStates, DevframeRuntime, DevframeScopedNodeContext, DevframeScopedNodeRpc, DevframeScopedStreamingHost, DevframeSettings, DevframeSettingsRegistry, DevframeSettingsStore, DevframeSetupInfo, DevframeSpaOptions, DevframeViewHost, DevframeWsOptions, EntriesToObject, EventEmitter, EventUnsubscribe, EventsMap, PartialWithoutId, RpcBroadcastOptions, RpcFunctionAgentOptions, RpcFunctionsHost, RpcSharedStateGetOptions, RpcSharedStateHost, RpcStreamingChannel, RpcStreamingChannelOptions, RpcStreamingHost, ScopedBroadcastOptions, ScopedClientFunctions, ScopedServerFunctions, ScopedSharedStates, SettingsForNamespace, Thenable, defineDevframe };
3
+ import { t as DevframeNodeRpcSessionMeta } from "../ws-server-Bc2wBHl-.mjs";
4
+ export { AgentHandle, AgentManifest, AgentResource, AgentResourceContent, AgentResourceInput, AgentTool, AgentToolInput, ConnectionMeta, ConnectionMetaWebsocket, DevframeAgentHost, DevframeAgentHostEvents, DevframeBrowserContext, DevframeCapabilities, DevframeCliOptions, DevframeDefineDiagnosticsOptions, DevframeDefinition, DevframeDeploymentKind, DevframeDiagnosticsDefinition, DevframeDiagnosticsHost, DevframeDiagnosticsLogger, DevframeDuplicationStrategy, DevframeHost, DevframeNodeContext, DevframeNodeRpcSession, type DevframeNodeRpcSessionMeta, DevframeRpcClientFunctions, DevframeRpcServerFunctions, DevframeRpcSharedStates, DevframeRuntime, DevframeScopedNodeContext, DevframeScopedNodeRpc, DevframeScopedStreamingHost, DevframeSettings, DevframeSettingsRegistry, DevframeSettingsStore, DevframeSetupInfo, DevframeSpaOptions, DevframeViewHost, DevframeWsOptions, EntriesToObject, EventEmitter, EventUnsubscribe, EventsMap, PartialWithoutId, RpcBroadcastOptions, type RpcFunctionAgentOptions, RpcFunctionsHost, RpcSharedStateGetOptions, RpcSharedStateHost, RpcStreamingChannel, RpcStreamingChannelOptions, RpcStreamingHost, ScopedBroadcastOptions, ScopedClientFunctions, ScopedServerFunctions, ScopedSharedStates, SettingsForNamespace, Thenable, defineDevframe };
@@ -19,7 +19,7 @@ function randomToken(byteLength = 16) {
19
19
  */
20
20
  function randomDigits(length) {
21
21
  const limit = 250;
22
- const buf = new Uint8Array(1);
22
+ const buf = /* @__PURE__ */ new Uint8Array(1);
23
23
  let out = "";
24
24
  while (out.length < length) {
25
25
  globalThis.crypto.getRandomValues(buf);
@@ -1,4 +1,4 @@
1
- import { St as EventsMap, bt as EventEmitter } from "../devframe-BwfavB78.mjs";
1
+ import { St as EventsMap, bt as EventEmitter } from "../devframe-DgvncQy2.mjs";
2
2
 
3
3
  //#region src/utils/events.d.ts
4
4
  /**
@@ -1,2 +1,2 @@
1
- import { t as hash } from "../hash-DFc5WwhO.mjs";
1
+ import { t as hash } from "../hash-PAfnyu2k.mjs";
2
2
  export { hash };
@@ -1,2 +1,2 @@
1
- import { t as launchEditor } from "../launch-editor-CgXBgviI.mjs";
1
+ import { t as launchEditor } from "../launch-editor-DIzaS5EG.mjs";
2
2
  export { launchEditor };
@@ -1,2 +1,2 @@
1
- import { t as open } from "../open-Dusa2Zzd.mjs";
1
+ import { t as open } from "../open-Deb5xmIT.mjs";
2
2
  export { open };
@@ -143,7 +143,8 @@ function serveStaticNodeMiddleware(dir, options) {
143
143
  res.end();
144
144
  return;
145
145
  }
146
- const file = await resolveTarget(absDir, req.url ?? "/", opts.indexNames, opts.single);
146
+ const url = req.url ?? "/";
147
+ const file = await resolveTarget(absDir, url, opts.indexNames, opts.single);
147
148
  if (!file) {
148
149
  if (next) {
149
150
  next();
@@ -1,2 +1,2 @@
1
- import { B as SharedStatePatch, F as ImmutableObject, I as ImmutableSet, L as SharedState, M as Immutable, N as ImmutableArray, P as ImmutableMap, R as SharedStateEvents, V as createSharedState, z as SharedStateOptions } from "../devframe-BwfavB78.mjs";
1
+ import { B as SharedStatePatch, F as ImmutableObject, I as ImmutableSet, L as SharedState, M as Immutable, N as ImmutableArray, P as ImmutableMap, R as SharedStateEvents, V as createSharedState, z as SharedStateOptions } from "../devframe-DgvncQy2.mjs";
2
2
  export { Immutable, ImmutableArray, ImmutableMap, ImmutableObject, ImmutableSet, SharedState, SharedStateEvents, SharedStateOptions, SharedStatePatch, createSharedState };
@@ -1,2 +1,2 @@
1
- import { t as createSharedState } from "../shared-state-D4PPieA0.mjs";
1
+ import { t as createSharedState } from "../shared-state-QtMas0NG.mjs";
2
2
  export { createSharedState };
@@ -1,2 +1,2 @@
1
- import { A as createStreamReader, C as BufferedChunk, D as StreamReader, E as StreamErrorPayload, O as StreamSink, T as CreateStreamSinkOptions, j as createStreamSink, k as StreamSinkEvents, w as CreateStreamReaderOptions } from "../devframe-BwfavB78.mjs";
1
+ import { A as createStreamReader, C as BufferedChunk, D as StreamReader, E as StreamErrorPayload, O as StreamSink, T as CreateStreamSinkOptions, j as createStreamSink, k as StreamSinkEvents, w as CreateStreamReaderOptions } from "../devframe-DgvncQy2.mjs";
2
2
  export { BufferedChunk, CreateStreamReaderOptions, CreateStreamSinkOptions, StreamErrorPayload, StreamReader, StreamSink, StreamSinkEvents, createStreamReader, createStreamSink };
@@ -381,4 +381,4 @@ declare function evaluateWhen<T extends object, const E extends string>(expressi
381
381
  */
382
382
  declare function resolveContextValue<T extends Record<string, unknown>>(key: string, context: T): unknown;
383
383
  //#endregion
384
- export { EvaluateWhenOptions, WhenContext, type WhenExpression, evaluateWhen, resolveContextValue };
384
+ export { EvaluateWhenOptions, WhenContext, WhenExpression, evaluateWhen, resolveContextValue };
@@ -57,6 +57,13 @@ interface WsRpcTransportOptions {
57
57
  destroyUnmatched?: boolean;
58
58
  /** When set, a new https.Server is created and the WS endpoint is attached to it. */
59
59
  https?: ServerOptions;
60
+ /**
61
+ * Extra origins to accept on the WS upgrade beyond the loopback default.
62
+ * Add your LAN/tunnel origin here when reaching the tool from another host.
63
+ * Pass `false` to disable origin checking entirely (not recommended).
64
+ * Default: loopback-only.
65
+ */
66
+ allowedOrigins?: readonly string[] | false;
60
67
  /**
61
68
  * RPC function definitions, used by the per-call wire serializer to
62
69
  * dispatch between strict-JSON and structured-clone encoding based
@@ -88,6 +95,15 @@ interface WsRpcTransport {
88
95
  */
89
96
  close: () => Promise<void>;
90
97
  }
98
+ declare function isLoopbackHostname(hostname: string): boolean;
99
+ /**
100
+ * Default origin policy for a localhost dev tool: allow requests with no
101
+ * `Origin` header (native, non-browser clients), allow any loopback origin
102
+ * (so cross-port localhost dev setups keep working), and allow explicitly
103
+ * configured origins. Everything else — a real remote page in the dev's
104
+ * browser — is rejected.
105
+ */
106
+ declare function isAllowedOrigin(origin: string | undefined, allowedOrigins: readonly string[]): boolean;
91
107
  /**
92
108
  * Attach a WebSocket transport to an existing RPC group, powered by
93
109
  * [crossws](https://crossws.h3.dev). Either attach to an existing HTTP(S)
@@ -100,4 +116,4 @@ interface WsRpcTransport {
100
116
  */
101
117
  declare function attachWsRpcTransport<ClientFunctions extends object, ServerFunctions extends object>(rpcGroup: BirpcGroup<ClientFunctions, ServerFunctions, false>, options?: WsRpcTransportOptions): WsRpcTransport;
102
118
  //#endregion
103
- export { attachWsRpcTransport as i, WsRpcTransport as n, WsRpcTransportOptions as r, DevframeNodeRpcSessionMeta as t };
119
+ export { isAllowedOrigin as a, attachWsRpcTransport as i, WsRpcTransport as n, isLoopbackHostname as o, WsRpcTransportOptions as r, DevframeNodeRpcSessionMeta as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "devframe",
3
3
  "type": "module",
4
- "version": "0.6.0-beta.1",
4
+ "version": "0.6.0-beta.3",
5
5
  "description": "Framework for building generic devframes",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -31,6 +31,7 @@
31
31
  "./node": "./dist/node/index.mjs",
32
32
  "./node/auth": "./dist/node/auth.mjs",
33
33
  "./node/hub-internals": "./dist/node/hub-internals.mjs",
34
+ "./recipes/interactive-auth": "./dist/recipes/interactive-auth.mjs",
34
35
  "./recipes/open-helpers": "./dist/recipes/open-helpers.mjs",
35
36
  "./rpc": "./dist/rpc/index.mjs",
36
37
  "./rpc/client": "./dist/rpc/client.mjs",
@@ -69,32 +70,32 @@
69
70
  }
70
71
  },
71
72
  "dependencies": {
72
- "@valibot/to-json-schema": "^1.7.0",
73
+ "@valibot/to-json-schema": "^1.7.1",
73
74
  "birpc": "^4.0.0",
74
75
  "cac": "^7.0.0",
75
- "crossws": "^0.4.8",
76
+ "crossws": "^0.4.9",
76
77
  "destr": "^2.0.5",
77
78
  "h3": "2.0.1-rc.22",
78
79
  "mrmime": "^2.0.1",
79
80
  "nostics": "^1.1.4",
80
81
  "pathe": "^2.0.3",
81
82
  "ufo": "^1.6.4",
82
- "valibot": "^1.4.1"
83
+ "valibot": "^1.4.2"
83
84
  },
84
85
  "devDependencies": {
85
86
  "@modelcontextprotocol/sdk": "^1.29.0",
86
87
  "get-port-please": "^3.2.0",
87
- "immer": "^11.1.8",
88
- "launch-editor": "^2.13.2",
88
+ "immer": "^11.1.11",
89
+ "launch-editor": "^2.14.1",
89
90
  "mlly": "^1.8.2",
90
- "obug": "^2.1.1",
91
+ "obug": "^2.1.3",
91
92
  "ohash": "^2.0.11",
92
93
  "open": "^11.0.0",
93
94
  "p-limit": "^7.3.0",
94
95
  "perfect-debounce": "^2.1.0",
95
96
  "structured-clone-es": "^2.0.0",
96
- "tinyglobby": "^0.2.16",
97
- "tsdown": "^0.22.0",
97
+ "tinyglobby": "^0.2.17",
98
+ "tsdown": "^0.22.3",
98
99
  "ua-parser-modern": "^0.1.1",
99
100
  "whenexpr": "^0.1.2",
100
101
  "ws": "^8.21.0"