@hyperframes/core 0.9.55 → 0.9.56

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.
@@ -0,0 +1,18 @@
1
+ /** The address and port a preview accepted a connection on, or that the CLI dialed. */
2
+ export interface PreviewEndpoint {
3
+ address: string;
4
+ port: number;
5
+ }
6
+ /** The token's folder: always in the user's own home, never a cache folder another user may share. */
7
+ export declare function previewTokenDir(): string;
8
+ export declare const previewTokenPath: (dir?: string) => string;
9
+ /** This user's preview token, made on first use; null when the file is missing, unsafe or unreadable. */
10
+ export declare function previewToken(dir?: string): string | null;
11
+ export declare const newPreviewNonce: () => string;
12
+ /** Carries the CLI's challenge; a custom header also makes a browser preflight any cross-site probe. */
13
+ export declare const PREVIEW_NONCE_HEADER = "x-hyperframes-nonce";
14
+ /** The answer to `nonce` from the preview at `endpoint` serving `config`. It binds all three, so an answer
15
+ * relayed from another preview, or with its config altered, does not check out. */
16
+ export declare function previewProof(nonce: unknown, endpoint: PreviewEndpoint, config: Record<string, unknown>, token?: string | null): string | null;
17
+ /** Whether `config`, read from `endpoint` in answer to `nonce`, carries this user's proof. */
18
+ export declare function provesPreviewOwner(nonce: string, endpoint: PreviewEndpoint, config: Record<string, unknown>, token?: string | null): boolean;
@@ -0,0 +1,88 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, mkdirSync, openSync, readSync, writeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
6
+ const NONCE_SHAPE = /^[0-9a-f]{32}$/;
7
+ /** The token's folder: always in the user's own home, never a cache folder another user may share. */
8
+ export function previewTokenDir() {
9
+ if (process.platform === "win32")
10
+ return join(process.env["LOCALAPPDATA"]?.trim() || join(homedir(), "AppData", "Local"), "hyperframes");
11
+ return join(homedir(), ".local", "state", "hyperframes", "auth");
12
+ }
13
+ export const previewTokenPath = (dir = previewTokenDir()) => join(dir, "preview-token");
14
+ // ponytail: Windows relies on the user-only ACL of LOCALAPPDATA; check the ACL itself if that folder can be shared.
15
+ function isPrivateFile(fd) {
16
+ const stat = fstatSync(fd);
17
+ if (!stat.isFile() || stat.nlink !== 1)
18
+ return false;
19
+ if (process.platform === "win32")
20
+ return true;
21
+ return stat.uid === process.getuid?.() && (stat.mode & 0o077) === 0;
22
+ }
23
+ function readToken(path) {
24
+ let fd;
25
+ try {
26
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ try {
32
+ if (!isPrivateFile(fd))
33
+ return null;
34
+ const bytes = Buffer.alloc(65);
35
+ const token = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, 0)).toString("utf-8");
36
+ return TOKEN_SHAPE.test(token) ? token : null;
37
+ }
38
+ finally {
39
+ closeSync(fd);
40
+ }
41
+ }
42
+ /** This user's preview token, made on first use; null when the file is missing, unsafe or unreadable. */
43
+ export function previewToken(dir = previewTokenDir()) {
44
+ const path = previewTokenPath(dir);
45
+ const existing = readToken(path);
46
+ if (existing)
47
+ return existing;
48
+ try {
49
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
50
+ const flags = constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0);
51
+ const fd = openSync(path, flags, 0o600);
52
+ const token = randomBytes(32).toString("hex");
53
+ try {
54
+ writeSync(fd, token);
55
+ }
56
+ finally {
57
+ closeSync(fd);
58
+ }
59
+ return token;
60
+ }
61
+ catch {
62
+ // expected: the file exists (made by another process, or unsafe); only a safe one is used
63
+ return readToken(path);
64
+ }
65
+ }
66
+ export const newPreviewNonce = () => randomBytes(16).toString("hex");
67
+ /** Carries the CLI's challenge; a custom header also makes a browser preflight any cross-site probe. */
68
+ export const PREVIEW_NONCE_HEADER = "x-hyperframes-nonce";
69
+ const endpointKey = ({ address, port }) => `${address.replace(/^\[(.*)\]$/, "$1").replace(/^::ffff:/i, "")}:${port}`;
70
+ /** The answer to `nonce` from the preview at `endpoint` serving `config`. It binds all three, so an answer
71
+ * relayed from another preview, or with its config altered, does not check out. */
72
+ export function previewProof(nonce, endpoint, config, token = previewToken()) {
73
+ if (!token || typeof nonce !== "string" || !NONCE_SHAPE.test(nonce))
74
+ return null;
75
+ const { proof: _proof, ...signed } = config;
76
+ const fields = JSON.stringify(signed, Object.keys(signed).sort());
77
+ return createHmac("sha256", token)
78
+ .update(`${nonce}\n${endpointKey(endpoint)}\n${fields}`)
79
+ .digest("hex");
80
+ }
81
+ /** Whether `config`, read from `endpoint` in answer to `nonce`, carries this user's proof. */
82
+ export function provesPreviewOwner(nonce, endpoint, config, token = previewToken()) {
83
+ const expected = previewProof(nonce, endpoint, config, token);
84
+ const proof = config["proof"];
85
+ if (!expected || typeof proof !== "string" || proof.length !== expected.length)
86
+ return false;
87
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(proof));
88
+ }
@@ -1,5 +1,6 @@
1
1
  import { wallSetTimeout } from "./wallClock.js";
2
2
  import { swallow } from "./diagnostics.js";
3
+ import { isStylableElement } from "./domRealm.js";
3
4
  import { inspectRuntimeProtocol, runtimeProtocolFpsToNumber, runtimeProtocolMetadata, } from "./protocol.js";
4
5
  let runtimeProtocolFps = 30;
5
6
  export function setRuntimeProtocolFps(fps) {
@@ -14,31 +15,97 @@ export function postRuntimeMessage(payload) {
14
15
  swallow("bridge.postMessage", err);
15
16
  }
16
17
  }
18
+ const FLASH_DEFAULT_DURATION_MS = 800;
19
+ const FLASH_MAX_DURATION_MS = 5000;
20
+ const MAX_FLASH_SELECTORS = 100;
21
+ const MAX_SELECTOR_LENGTH = 1000;
22
+ function isFiniteNumber(value) {
23
+ return typeof value === "number" && Number.isFinite(value);
24
+ }
25
+ // Absent (null or undefined) yields the fallback, a finite number yields itself,
26
+ // and any other value yields null so the caller drops the message.
27
+ function readNumber(value, fallback) {
28
+ if (value == null)
29
+ return fallback;
30
+ return isFiniteNumber(value) ? value : null;
31
+ }
32
+ function isBoundedString(value) {
33
+ return typeof value === "string" && value.length <= MAX_SELECTOR_LENGTH;
34
+ }
35
+ function isOptionalBoundedString(value) {
36
+ return value == null || isBoundedString(value);
37
+ }
38
+ function isGradingTarget(value) {
39
+ if (value === null || isBoundedString(value))
40
+ return true;
41
+ if (typeof value !== "object" || Array.isArray(value))
42
+ return false;
43
+ const target = value;
44
+ return (isOptionalBoundedString(target.id) &&
45
+ isOptionalBoundedString(target.hfId) &&
46
+ isOptionalBoundedString(target.selector) &&
47
+ (target.selectorIndex == null || isFiniteNumber(target.selectorIndex)));
48
+ }
49
+ function dispatchColorGrading(target, value, apply) {
50
+ const resolvedTarget = target ?? null;
51
+ if (isGradingTarget(resolvedTarget))
52
+ apply(resolvedTarget, value ?? null);
53
+ }
17
54
  // Per-action dispatchers. Splitting the handler into a lookup table keeps the
18
55
  // top-level message listener trivial (one map lookup), and each action's logic
19
56
  // becomes individually testable / inheritable for fallow's CRAP analysis.
57
+ // Each dispatcher checks its payload fields for type and range and drops the
58
+ // message when a field is invalid.
20
59
  const CONTROL_HANDLERS = new Map(Object.entries({
21
60
  play: (_d, deps) => deps.onPlay(),
22
61
  pause: (_d, deps) => deps.onPause(),
23
62
  "stop-media": (_d, deps) => deps.onStopMedia(),
24
- seek: (data, deps) => deps.onSeek(resolveSeekTimeSeconds(data, deps), data.seekMode ?? "commit"),
63
+ seek: (data, deps) => {
64
+ const timeSeconds = resolveSeekTimeSeconds(data, deps);
65
+ if (timeSeconds !== null)
66
+ deps.onSeek(timeSeconds, data.seekMode === "drag" ? "drag" : "commit");
67
+ },
25
68
  tick: (_d, deps) => deps.onTick(),
26
- "set-muted": (data, deps) => deps.onSetMuted(Boolean(data.muted)),
27
- "set-volume": (data, deps) => deps.onSetVolume(Math.max(0, Math.min(1, Number(data.volume ?? 1)))),
28
- "set-media-output-muted": (data, deps) => deps.onSetMediaOutputMuted(Boolean(data.muted)),
29
- "set-native-media-sync-disabled": (data, deps) => deps.onSetNativeMediaSyncDisabled(Boolean(data.disabled)),
30
- "set-web-audio-media-disabled": (data, deps) => deps.onSetWebAudioMediaDisabled(Boolean(data.disabled)),
31
- "set-playback-rate": (data, deps) => deps.onSetPlaybackRate(Number(data.playbackRate ?? 1)),
32
- "set-idle-heartbeat": (data, deps) => deps.onSetIdleHeartbeat(Boolean(data.slow)),
33
- "set-display-scale": (data, deps) => deps.onSetDisplayScale?.(Number(data.scale)),
34
- "set-preview-quality": (data, deps) => deps.onSetPreviewQuality?.(Number(data.level)),
35
- "set-copies-ahead": (data, deps) => deps.onSetCopiesAhead?.(Boolean(data.on)),
69
+ "set-muted": (data, deps) => deps.onSetMuted(data.muted === true),
70
+ "set-volume": (data, deps) => {
71
+ const volume = readNumber(data.volume, 1);
72
+ if (volume !== null)
73
+ deps.onSetVolume(Math.max(0, Math.min(1, volume)));
74
+ },
75
+ "set-media-output-muted": (data, deps) => deps.onSetMediaOutputMuted(data.muted === true),
76
+ "set-native-media-sync-disabled": (data, deps) => deps.onSetNativeMediaSyncDisabled(data.disabled === true),
77
+ "set-web-audio-media-disabled": (data, deps) => deps.onSetWebAudioMediaDisabled(data.disabled === true),
78
+ "set-playback-rate": (data, deps) => {
79
+ const rate = readNumber(data.playbackRate, 1);
80
+ if (rate !== null)
81
+ deps.onSetPlaybackRate(rate);
82
+ },
83
+ "set-idle-heartbeat": (data, deps) => deps.onSetIdleHeartbeat(data.slow === true),
84
+ "set-display-scale": (data, deps) => {
85
+ if (isFiniteNumber(data.scale) && data.scale > 0)
86
+ deps.onSetDisplayScale?.(data.scale);
87
+ },
88
+ "set-preview-quality": (data, deps) => {
89
+ if (isFiniteNumber(data.level))
90
+ deps.onSetPreviewQuality?.(data.level);
91
+ },
92
+ "set-copies-ahead": (data, deps) => deps.onSetCopiesAhead?.(data.on === true),
36
93
  "retry-preview-copies": (_d, deps) => deps.onRetryPreviewCopies?.(),
37
94
  "request-preview-facts": (_d, deps) => deps.onRequestPreviewFacts?.(),
38
- "set-root-duration": (data, deps) => deps.onSetRootDuration(Number(data.durationSeconds ?? 0)),
39
- "set-play-range": (data, deps) => deps.onSetPlayRange(Number(data.startSeconds ?? 0), data.endSeconds == null ? null : Number(data.endSeconds)),
40
- "set-color-grading": (data, deps) => deps.onSetColorGrading(data.target ?? null, data.grading ?? null),
41
- "set-color-grading-compare": (data, deps) => deps.onSetColorGradingCompare(data.target ?? null, data.compare ?? null),
95
+ "set-root-duration": (data, deps) => {
96
+ const durationSeconds = readNumber(data.durationSeconds, 0);
97
+ if (durationSeconds !== null)
98
+ deps.onSetRootDuration(durationSeconds);
99
+ },
100
+ "set-play-range": (data, deps) => {
101
+ const startSeconds = readNumber(data.startSeconds, 0);
102
+ const endSeconds = data.endSeconds ?? null;
103
+ if (startSeconds === null || (endSeconds !== null && !isFiniteNumber(endSeconds)))
104
+ return;
105
+ deps.onSetPlayRange(startSeconds, endSeconds);
106
+ },
107
+ "set-color-grading": (data, deps) => dispatchColorGrading(data.target, data.grading, deps.onSetColorGrading),
108
+ "set-color-grading-compare": (data, deps) => dispatchColorGrading(data.target, data.compare, deps.onSetColorGradingCompare),
42
109
  "enable-pick-mode": (_d, deps) => deps.onEnablePickMode(),
43
110
  "disable-pick-mode": (_d, deps) => deps.onDisablePickMode(),
44
111
  "flash-elements": (data) => handleFlashElements(data),
@@ -52,12 +119,15 @@ const CONTROL_HANDLERS = new Map(Object.entries({
52
119
  },
53
120
  }));
54
121
  function resolveSeekTimeSeconds(data, deps) {
55
- const explicitSeconds = Number(data.timeSeconds);
56
- if (Number.isFinite(explicitSeconds))
57
- return Math.max(0, explicitSeconds);
122
+ if (data.timeSeconds != null) {
123
+ return isFiniteNumber(data.timeSeconds) ? Math.max(0, data.timeSeconds) : null;
124
+ }
125
+ const frame = readNumber(data.frame, 0);
126
+ if (frame === null)
127
+ return null;
58
128
  const messageFps = runtimeProtocolFpsToNumber(data.fps);
59
129
  const fps = messageFps ?? deps.getCanonicalFps();
60
- return Math.max(0, Number(data.frame ?? 0)) / fps;
130
+ return Math.max(0, frame) / fps;
61
131
  }
62
132
  function rejectUnsupportedProtocol(data) {
63
133
  const protocol = inspectRuntimeProtocol(data);
@@ -75,14 +145,20 @@ function rejectUnsupportedProtocol(data) {
75
145
  });
76
146
  return true;
77
147
  }
148
+ function readFlashSelectors(value) {
149
+ if (!Array.isArray(value) || value.length > MAX_FLASH_SELECTORS)
150
+ return null;
151
+ return value.every(isBoundedString) ? value : null;
152
+ }
78
153
  function handleFlashElements(data) {
79
154
  // Briefly highlight elements — used by the chat-canvas bridge
80
155
  // to show what changed after an agent edit
81
- const selectors = data.selectors;
82
- const duration = data.duration || 800;
83
- if (selectors) {
84
- flashElements(selectors, duration);
85
- }
156
+ const fields = data;
157
+ const selectors = readFlashSelectors(fields.selectors);
158
+ const duration = readNumber(fields.duration, FLASH_DEFAULT_DURATION_MS);
159
+ if (!selectors || duration === null || duration <= 0 || duration > FLASH_MAX_DURATION_MS)
160
+ return;
161
+ flashElements(selectors, duration);
86
162
  }
87
163
  export function installRuntimeControlBridge(deps) {
88
164
  const handler = (event) => {
@@ -109,6 +185,17 @@ export function installRuntimeControlBridge(deps) {
109
185
  postRuntimeMessage({ source: "hf-preview", type: "ready" });
110
186
  return handler;
111
187
  }
188
+ const FLASH_STYLE_RULES = `
189
+ .__hf-flash {
190
+ outline: 2px solid rgba(59, 130, 246, 0.6) !important;
191
+ outline-offset: 2px !important;
192
+ animation: __hf-flash-pulse var(--hf-flash-duration, 800ms) ease-out forwards !important;
193
+ }
194
+ @keyframes __hf-flash-pulse {
195
+ 0% { outline-color: rgba(59, 130, 246, 0.8); }
196
+ 100% { outline-color: transparent; }
197
+ }
198
+ `;
112
199
  /**
113
200
  * Flash elements — briefly highlight them with a blue outline.
114
201
  * Used by the chat-canvas bridge to show what changed after an agent edit.
@@ -117,23 +204,15 @@ function flashElements(selectors, duration) {
117
204
  if (!document.getElementById("__hf-flash-styles")) {
118
205
  const style = document.createElement("style");
119
206
  style.id = "__hf-flash-styles";
120
- style.textContent = `
121
- .__hf-flash {
122
- outline: 2px solid rgba(59, 130, 246, 0.6) !important;
123
- outline-offset: 2px !important;
124
- animation: __hf-flash-pulse ${duration}ms ease-out forwards !important;
125
- }
126
- @keyframes __hf-flash-pulse {
127
- 0% { outline-color: rgba(59, 130, 246, 0.8); }
128
- 100% { outline-color: transparent; }
129
- }
130
- `;
207
+ style.textContent = FLASH_STYLE_RULES;
131
208
  document.head.appendChild(style);
132
209
  }
133
210
  for (const selector of selectors) {
134
211
  try {
135
212
  const els = document.querySelectorAll(selector);
136
213
  els.forEach((el) => {
214
+ if (isStylableElement(el))
215
+ el.style.setProperty("--hf-flash-duration", `${duration}ms`);
137
216
  el.classList.add("__hf-flash");
138
217
  wallSetTimeout(() => el.classList.remove("__hf-flash"), duration);
139
218
  });
@@ -35,7 +35,10 @@ export declare function resolveWithinProject(base: string, relativePath: string)
35
35
  /** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
36
36
  export declare function projectPathSegments(relPath: string): string[];
37
37
  export declare function isVcsOrSecretPath(relPath: string): boolean;
38
- /** Files no composition loads, for a project-relative path in any spelling Windows opens: git, env, app records. */
38
+ /** Credential files and tool or agent state, for a project-relative path in any spelling Windows opens. */
39
+ export declare function isCredentialOrToolStatePath(relPath: string): boolean;
40
+ /** Files no composition loads, for a project-relative path in any spelling Windows opens: git, env, credentials, tool
41
+ * state, app records. */
39
42
  export declare function isStudioPrivatePath(relPath: string): boolean;
40
43
  /** Whether `isPrivate` holds for a file under `projectDir`, spelled as given or with its links resolved. */
41
44
  export declare function isPrivateFileUnder(projectDir: string, filePath: string, isPrivate: (relPath: string) => boolean): boolean;
package/dist/safePath.js CHANGED
@@ -126,9 +126,51 @@ const STUDIO_FILES = new Set([
126
126
  ".hyperframes/studio-manual-edits.json",
127
127
  ]);
128
128
  const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
129
- /** Files no composition loads, for a project-relative path in any spelling Windows opens: git, env, app records. */
129
+ // Credentials and coding-tool state that projects often sit next to: registry tokens, MCP and agent settings, cloud and
130
+ // SSH keys. No composition loads one, so no file server serves one and no upload ships one.
131
+ const CREDENTIAL_FILES = new Set([
132
+ ".npmrc",
133
+ ".yarnrc",
134
+ ".yarnrc.yml",
135
+ ".pypirc",
136
+ "pip.conf",
137
+ "pip.ini",
138
+ ".netrc",
139
+ "_netrc",
140
+ ".git-credentials",
141
+ ".gitconfig",
142
+ ".mcp.json",
143
+ ]);
144
+ const CREDENTIAL_FOLDERS = new Set([
145
+ ".ssh",
146
+ ".aws",
147
+ ".gnupg",
148
+ ".docker",
149
+ ".kube",
150
+ ".azure",
151
+ ".claude",
152
+ ".codex",
153
+ ".cursor",
154
+ ".agents",
155
+ ".gemini",
156
+ ".vscode",
157
+ ".idea",
158
+ ]);
159
+ const CREDENTIAL_CONFIG_FOLDERS = new Set(["gcloud", "gh"]);
160
+ const KEY_FILE = /^(?:id_(?:rsa|dsa|ecdsa|ed25519).*|.*\.(?:pem|key|p12|pfx))$/;
161
+ /** Credential files and tool or agent state, for a project-relative path in any spelling Windows opens. */
162
+ export function isCredentialOrToolStatePath(relPath) {
163
+ const segments = projectPathSegments(relPath);
164
+ const name = segments.at(-1) ?? "";
165
+ return (CREDENTIAL_FILES.has(name) ||
166
+ KEY_FILE.test(name) ||
167
+ segments.some((segment, at) => CREDENTIAL_FOLDERS.has(segment) ||
168
+ (segment === ".config" && CREDENTIAL_CONFIG_FOLDERS.has(segments[at + 1] ?? ""))));
169
+ }
170
+ /** Files no composition loads, for a project-relative path in any spelling Windows opens: git, env, credentials, tool
171
+ * state, app records. */
130
172
  export function isStudioPrivatePath(relPath) {
131
- if (isVcsOrSecretPath(relPath))
173
+ if (isVcsOrSecretPath(relPath) || isCredentialOrToolStatePath(relPath))
132
174
  return true;
133
175
  const path = projectPathSegments(relPath).join("/");
134
176
  return ((path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/core",
3
- "version": "0.9.55",
3
+ "version": "0.9.56",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -68,6 +68,10 @@
68
68
  "import": "./dist/atomicFile.js",
69
69
  "types": "./dist/atomicFile.d.ts"
70
70
  },
71
+ "./preview-proof": {
72
+ "import": "./dist/previewProof.js",
73
+ "types": "./dist/previewProof.d.ts"
74
+ },
71
75
  "./cache-dir": {
72
76
  "import": "./dist/cacheDir.js",
73
77
  "types": "./dist/cacheDir.d.ts"
@@ -457,9 +461,9 @@
457
461
  "linkedom": "^0.18.12",
458
462
  "postcss": "^8.5.8",
459
463
  "wawoff2": "^2.0.1",
460
- "@hyperframes/parsers": "0.9.55",
461
- "@hyperframes/studio-server": "0.9.55",
462
- "@hyperframes/lint": "0.9.55"
464
+ "@hyperframes/lint": "0.9.56",
465
+ "@hyperframes/parsers": "0.9.56",
466
+ "@hyperframes/studio-server": "0.9.56"
463
467
  },
464
468
  "devDependencies": {
465
469
  "@fontsource/archivo-black": "^5.2.8",