claude-code-session-manager 0.141.0 → 0.143.0

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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,218 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackBoxKeys — machine-local store mapping each feedback widget box to its project and
4
+ * private key.
5
+ *
6
+ * Only this desktop can decrypt its boxes' sealed reports, so every box's private JWK lives in ONE
7
+ * 0600 file outside every project tree: <schedulerHome>/feedback-boxes.json. Writes go through
8
+ * util/atomicFs.cjs inside a serialized read-modify-write queue; a missing or corrupt file reads as
9
+ * empty. listBoxes() never returns a private key — only getPrivateKey(boxId) does.
10
+ *
11
+ * Each box may also hold an identitySecret (32 random bytes, base64url): the HMAC key the site's
12
+ * backend signs the reporter with (site-feedback.md#verified-reporter). It is minted on the first
13
+ * getIdentitySecret(boxId), replaced by rotateIdentitySecret(boxId), and — like the private key —
14
+ * never returned by listBoxes() and never sent to the relay or the widget.
15
+ */
16
+ 'use strict';
17
+
18
+ const path = require('node:path');
19
+ const fsp = require('node:fs/promises');
20
+ const crypto = require('node:crypto');
21
+ const atomicFs = require('../util/atomicFs.cjs');
22
+ const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
23
+
24
+ const SCHEMA_VERSION = 1;
25
+ const FILE_MODE = 0o600;
26
+
27
+ /**
28
+ * @typedef {Record<string, unknown>} PrivateKeyJwk
29
+ * @typedef {{ boxId: string, projectCwd: string, label: string, publicKey: string,
30
+ * fingerprint: string, createdAt: number }} BoxRecord
31
+ * @typedef {BoxRecord & { privateKeyJwk: PrivateKeyJwk, identitySecret?: string }} StoredBox
32
+ * @typedef {{ boxId: string, projectCwd: string, label?: string, publicKey: string,
33
+ * fingerprint: string, privateKeyJwk: PrivateKeyJwk, createdAt?: number }} AddBoxInput
34
+ */
35
+
36
+ function storeFile() {
37
+ return path.join(schedulerPaths.schedulerHome(), 'feedback-boxes.json');
38
+ }
39
+
40
+ /** @param {unknown} v @returns {v is string} */
41
+ function nonEmptyString(v) {
42
+ return typeof v === 'string' && v.length > 0;
43
+ }
44
+
45
+ /** @param {unknown} raw @returns {raw is StoredBox} */
46
+ function isStoredBox(raw) {
47
+ if (!raw || typeof raw !== 'object') return false;
48
+ const r = /** @type {Record<string, unknown>} */ (raw);
49
+ return nonEmptyString(r.boxId) && nonEmptyString(r.projectCwd) && nonEmptyString(r.publicKey)
50
+ && nonEmptyString(r.fingerprint) && !!r.privateKeyJwk && typeof r.privateKeyJwk === 'object';
51
+ }
52
+
53
+ /** @param {string} file @returns {Promise<StoredBox[]>} */
54
+ async function readBoxes(file) {
55
+ try {
56
+ const data = JSON.parse(await fsp.readFile(file, 'utf8'));
57
+ if (data && Array.isArray(data.boxes)) return data.boxes.filter(isStoredBox);
58
+ } catch { /* missing or corrupt reads as empty */ }
59
+ return [];
60
+ }
61
+
62
+ /** @param {StoredBox} b @returns {BoxRecord} */
63
+ function publicRecord(b) {
64
+ return {
65
+ boxId: b.boxId,
66
+ projectCwd: b.projectCwd,
67
+ label: typeof b.label === 'string' ? b.label : '',
68
+ publicKey: b.publicKey,
69
+ fingerprint: b.fingerprint,
70
+ createdAt: typeof b.createdAt === 'number' ? b.createdAt : 0,
71
+ };
72
+ }
73
+
74
+ /** @type {Promise<unknown>} */
75
+ let writeQueue = Promise.resolve();
76
+ /**
77
+ * Serialized read-modify-write: each mutation reads the freshest on-disk boxes.
78
+ * @template T
79
+ * @param {(boxes: StoredBox[]) => { boxes: StoredBox[], result: T }} mutate
80
+ * @returns {Promise<T>}
81
+ */
82
+ function mutateStore(mutate) {
83
+ const file = storeFile();
84
+ const run = async () => {
85
+ const { boxes, result } = mutate(await readBoxes(file));
86
+ await atomicFs.writeJsonAtomic(file, { schemaVersion: SCHEMA_VERSION, boxes }, { mode: FILE_MODE });
87
+ return result;
88
+ };
89
+ const tail = writeQueue.then(run, run);
90
+ writeQueue = tail.then(() => {}, () => {});
91
+ return tail;
92
+ }
93
+
94
+ /**
95
+ * Records a new box. Throws on malformed input or an existing boxId (a key is never overwritten).
96
+ * @param {AddBoxInput} input
97
+ * @returns {Promise<BoxRecord>}
98
+ */
99
+ function addBox(input) {
100
+ const src = input || /** @type {AddBoxInput} */ ({});
101
+ if (!nonEmptyString(src.boxId)) return Promise.reject(new Error('boxId is required'));
102
+ if (!nonEmptyString(src.projectCwd)) return Promise.reject(new Error('projectCwd is required'));
103
+ if (!nonEmptyString(src.publicKey)) return Promise.reject(new Error('publicKey is required'));
104
+ if (!nonEmptyString(src.fingerprint)) return Promise.reject(new Error('fingerprint is required'));
105
+ if (!src.privateKeyJwk || typeof src.privateKeyJwk !== 'object') {
106
+ return Promise.reject(new Error('privateKeyJwk is required'));
107
+ }
108
+ /** @type {StoredBox} */
109
+ const box = {
110
+ boxId: src.boxId,
111
+ projectCwd: src.projectCwd,
112
+ label: typeof src.label === 'string' ? src.label : '',
113
+ publicKey: src.publicKey,
114
+ fingerprint: src.fingerprint,
115
+ privateKeyJwk: src.privateKeyJwk,
116
+ createdAt: typeof src.createdAt === 'number' ? src.createdAt : Date.now(),
117
+ };
118
+ return mutateStore((boxes) => {
119
+ if (boxes.some((b) => b.boxId === box.boxId)) throw new Error(`box ${box.boxId} already exists`);
120
+ return { boxes: [...boxes, box], result: publicRecord(box) };
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Lists boxes (optionally one project's), WITHOUT private keys.
126
+ * @param {{ projectCwd?: string }} [opts]
127
+ * @returns {Promise<BoxRecord[]>}
128
+ */
129
+ async function listBoxes(opts) {
130
+ const cwd = opts && opts.projectCwd;
131
+ const boxes = await readBoxes(storeFile());
132
+ return boxes.filter((b) => !cwd || b.projectCwd === cwd).map(publicRecord);
133
+ }
134
+
135
+ /**
136
+ * @param {string} boxId
137
+ * @returns {Promise<PrivateKeyJwk|null>}
138
+ */
139
+ async function getPrivateKey(boxId) {
140
+ if (!nonEmptyString(boxId)) return null;
141
+ const hit = (await readBoxes(storeFile())).find((b) => b.boxId === boxId);
142
+ return hit ? hit.privateKeyJwk : null;
143
+ }
144
+
145
+ /** @returns {string} 32 random bytes, base64url (43 chars, no padding) */
146
+ function newIdentitySecret() {
147
+ return crypto.randomBytes(32).toString('base64url');
148
+ }
149
+
150
+ /**
151
+ * Serialized write of one box's identity secret. `replace` false keeps an existing secret.
152
+ * @param {string} boxId
153
+ * @param {boolean} replace
154
+ * @returns {Promise<string|null>} the box's secret, or null when no such box exists
155
+ */
156
+ function writeIdentitySecret(boxId, replace) {
157
+ if (!nonEmptyString(boxId)) return Promise.resolve(null);
158
+ return mutateStore((boxes) => {
159
+ const hit = boxes.find((b) => b.boxId === boxId);
160
+ if (!hit) return { boxes, result: /** @type {string|null} */ (null) };
161
+ if (!replace && nonEmptyString(hit.identitySecret)) return { boxes, result: hit.identitySecret };
162
+ const identitySecret = newIdentitySecret();
163
+ return {
164
+ boxes: boxes.map((b) => (b === hit ? { ...b, identitySecret } : b)),
165
+ result: identitySecret,
166
+ };
167
+ });
168
+ }
169
+
170
+ /**
171
+ * The box's identity signing secret, minted on first request.
172
+ * @param {string} boxId
173
+ * @returns {Promise<string|null>} null when no such box exists
174
+ */
175
+ async function getIdentitySecret(boxId) {
176
+ if (!nonEmptyString(boxId)) return null;
177
+ const hit = (await readBoxes(storeFile())).find((b) => b.boxId === boxId);
178
+ if (!hit) return null;
179
+ if (nonEmptyString(hit.identitySecret)) return hit.identitySecret;
180
+ return writeIdentitySecret(boxId, false);
181
+ }
182
+
183
+ /**
184
+ * The box's identity signing secret if one was already minted. Read-only: never mints or writes,
185
+ * so verifying a signed report can never change the keystore.
186
+ * @param {string} boxId
187
+ * @returns {Promise<string|null>} null when no such box exists or it has no secret yet
188
+ */
189
+ async function peekIdentitySecret(boxId) {
190
+ if (!nonEmptyString(boxId)) return null;
191
+ const hit = (await readBoxes(storeFile())).find((b) => b.boxId === boxId);
192
+ return hit && nonEmptyString(hit.identitySecret) ? hit.identitySecret : null;
193
+ }
194
+
195
+ /**
196
+ * Replaces the box's identity signing secret; signatures made with the old one stop verifying.
197
+ * @param {string} boxId
198
+ * @returns {Promise<string|null>} the new secret, or null when no such box exists
199
+ */
200
+ function rotateIdentitySecret(boxId) {
201
+ return writeIdentitySecret(boxId, true);
202
+ }
203
+
204
+ /**
205
+ * @param {string} boxId
206
+ * @returns {Promise<boolean>} true when a box was removed
207
+ */
208
+ function removeBox(boxId) {
209
+ return mutateStore((boxes) => {
210
+ const next = boxes.filter((b) => b.boxId !== boxId);
211
+ return { boxes: next, result: next.length !== boxes.length };
212
+ });
213
+ }
214
+
215
+ module.exports = {
216
+ storeFile, addBox, listBoxes, getPrivateKey, getIdentitySecret, peekIdentitySecret,
217
+ rotateIdentitySecret, removeBox,
218
+ };
@@ -0,0 +1,163 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackEnvelope — the one function the desktop drain calls per downloaded envelope.
4
+ *
5
+ * openReportEnvelope(buf, { privateKeyJwk, boxId, maxBytes }) enforces the size cap, opens the
6
+ * sealed envelope (feedbackSeal.cjs), parses the handoff's multipart/form-data body, then
7
+ * validates the Report v1 (feedbackReport.cjs) and both PNG images.
8
+ *
9
+ * Everything inside the envelope is attacker-controlled. The function never throws and every
10
+ * failure is `{ ok: false, code }` with a fixed code — never report text, image bytes or key
11
+ * material.
12
+ */
13
+ 'use strict';
14
+
15
+ const { openEnvelope } = require('./feedbackSeal.cjs');
16
+ const { parseReport } = require('./feedbackReport.cjs');
17
+ const { sniffImageMime } = require('../epic/epicAttachments.cjs');
18
+
19
+ const MAX_ENVELOPE_BYTES = 12 * 1024 * 1024;
20
+ const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
21
+ const MAX_IMAGE_EDGE = 8192;
22
+ const DIMENSION_SLACK = 1;
23
+ const FIELD_NAMES = Object.freeze(['report', 'screenshot', 'annotated']);
24
+ const ERROR_CODES = Object.freeze([
25
+ 'too_large', 'bad_envelope', 'decrypt_failed', 'bad_multipart', 'bad_report', 'bad_image',
26
+ ]);
27
+
28
+ /**
29
+ * @typedef {'too_large' | 'bad_envelope' | 'decrypt_failed' | 'bad_multipart' | 'bad_report' | 'bad_image'} EnvelopeErrorCode
30
+ * @typedef {import('./feedbackReport.cjs').Report} Report
31
+ * @typedef {{ ok: true, report: Report, screenshot: Buffer, annotated: Buffer }
32
+ * | { ok: false, code: EnvelopeErrorCode }} OpenResult
33
+ */
34
+
35
+ /**
36
+ * @param {EnvelopeErrorCode} code
37
+ * @returns {{ ok: false, code: EnvelopeErrorCode }}
38
+ */
39
+ function failed(code) {
40
+ return { ok: false, code };
41
+ }
42
+
43
+ /**
44
+ * multipart/form-data with a non-empty boundary parameter.
45
+ * @param {string} contentType
46
+ */
47
+ function isMultipartWithBoundary(contentType) {
48
+ const parts = contentType.split(';').map((s) => s.trim());
49
+ if ((parts[0] || '').toLowerCase() !== 'multipart/form-data') return false;
50
+ return parts.slice(1).some((p) => {
51
+ const eq = p.indexOf('=');
52
+ if (eq < 0) return false;
53
+ const name = p.slice(0, eq).trim().toLowerCase();
54
+ const value = p.slice(eq + 1).trim().replace(/^"(.*)"$/, '$1');
55
+ return name === 'boundary' && value.length > 0;
56
+ });
57
+ }
58
+
59
+ /**
60
+ * PNG IHDR width/height (bytes 16-23, big-endian), or null when the chunk is not where it must be.
61
+ * @param {Buffer} buf
62
+ * @returns {{ width: number, height: number } | null}
63
+ */
64
+ function pngSize(buf) {
65
+ if (buf.length < 24) return null;
66
+ if (buf.subarray(12, 16).toString('latin1') !== 'IHDR') return null;
67
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
68
+ }
69
+
70
+ /**
71
+ * @param {Buffer} buf
72
+ * @param {{ width: number, height: number }} expected
73
+ */
74
+ function imageOk(buf, expected) {
75
+ if (buf.length === 0 || buf.length > MAX_IMAGE_BYTES) return false;
76
+ if (sniffImageMime(buf) !== 'image/png') return false;
77
+ const size = pngSize(buf);
78
+ if (!size) return false;
79
+ if (size.width < 1 || size.height < 1) return false;
80
+ if (size.width > MAX_IMAGE_EDGE || size.height > MAX_IMAGE_EDGE) return false;
81
+ return Math.abs(size.width - expected.width) <= DIMENSION_SLACK
82
+ && Math.abs(size.height - expected.height) <= DIMENSION_SLACK;
83
+ }
84
+
85
+ /**
86
+ * Open, parse and validate one downloaded feedback envelope. Never throws.
87
+ * @param {Buffer|Uint8Array} buf
88
+ * @param {{ privateKeyJwk: import('node:crypto').JsonWebKey, boxId: string, maxBytes?: number }} opts
89
+ * @returns {Promise<OpenResult>}
90
+ */
91
+ async function openReportEnvelope(buf, opts) {
92
+ if (!opts || typeof opts !== 'object') return failed('decrypt_failed');
93
+ const { privateKeyJwk, boxId, maxBytes = MAX_ENVELOPE_BYTES } = opts;
94
+ if (!buf || typeof buf.length !== 'number') return failed('bad_envelope');
95
+ if (buf.length > maxBytes) return failed('too_large');
96
+
97
+ /** @type {{ contentType: string, body: Buffer }} */
98
+ let opened;
99
+ try {
100
+ opened = openEnvelope(buf, privateKeyJwk, boxId);
101
+ } catch (e) {
102
+ const msg = e instanceof Error ? e.message : '';
103
+ return failed(msg === 'bad_envelope' ? 'bad_envelope' : 'decrypt_failed');
104
+ }
105
+
106
+ if (!isMultipartWithBoundary(opened.contentType)) return failed('bad_multipart');
107
+
108
+ /** @type {FormData} */
109
+ let form;
110
+ try {
111
+ form = await new Response(opened.body, { headers: { 'content-type': opened.contentType } }).formData();
112
+ } catch {
113
+ return failed('bad_multipart');
114
+ }
115
+
116
+ /** @type {Map<string, string | File>} */
117
+ const fields = new Map();
118
+ for (const [name, value] of form.entries()) {
119
+ if (!FIELD_NAMES.includes(name) || fields.has(name)) return failed('bad_multipart');
120
+ fields.set(name, value);
121
+ }
122
+ if (fields.size !== FIELD_NAMES.length) return failed('bad_multipart');
123
+ const reportEntry = /** @type {string | File} */ (fields.get('report'));
124
+ const shotEntry = /** @type {string | File} */ (fields.get('screenshot'));
125
+ const annotatedEntry = /** @type {string | File} */ (fields.get('annotated'));
126
+ if (typeof shotEntry === 'string' || typeof annotatedEntry === 'string') return failed('bad_multipart');
127
+
128
+ /** @type {unknown} */
129
+ let reportJson;
130
+ try {
131
+ const text = typeof reportEntry === 'string' ? reportEntry : await reportEntry.text();
132
+ reportJson = JSON.parse(text);
133
+ } catch {
134
+ return failed('bad_report');
135
+ }
136
+ const parsed = parseReport(reportJson);
137
+ if (!parsed.ok) return failed('bad_report');
138
+ const report = parsed.report;
139
+
140
+ /** @type {Buffer} */
141
+ let screenshot;
142
+ /** @type {Buffer} */
143
+ let annotated;
144
+ try {
145
+ if (shotEntry.size > MAX_IMAGE_BYTES || annotatedEntry.size > MAX_IMAGE_BYTES) return failed('bad_image');
146
+ screenshot = Buffer.from(await shotEntry.arrayBuffer());
147
+ annotated = Buffer.from(await annotatedEntry.arrayBuffer());
148
+ } catch {
149
+ return failed('bad_multipart');
150
+ }
151
+ const expected = { width: report.screenshot.width, height: report.screenshot.height };
152
+ if (!imageOk(screenshot, expected) || !imageOk(annotated, expected)) return failed('bad_image');
153
+
154
+ return { ok: true, report, screenshot, annotated };
155
+ }
156
+
157
+ module.exports = {
158
+ openReportEnvelope,
159
+ ERROR_CODES,
160
+ MAX_ENVELOPE_BYTES,
161
+ MAX_IMAGE_BYTES,
162
+ MAX_IMAGE_EDGE,
163
+ };
@@ -0,0 +1,164 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackRelayClient — the desktop's REST client for the bilko.run relay's sealed drop-box routes
4
+ * ("Host contract v1" in session-manager-operations/architecture/site-feedback.md).
5
+ *
6
+ * Authenticates with the device token the bilko.run pairing stored (webRemote.getLinkedDeviceToken),
7
+ * independent of `remoteEnabled`: website feedback is a separate capability from remote control.
8
+ *
9
+ * Every method resolves to `{ ok: true, ... }` or `{ ok: false, status, error, retryAfterSec? }` and
10
+ * never throws. `error` is the host's `{ error }` code verbatim; transport failures use
11
+ * `network_error` / `timeout` (status 0); no token at all is `not_linked` (status 0, no request).
12
+ * The device token never appears in a returned value.
13
+ */
14
+ 'use strict';
15
+
16
+ const DEFAULT_BASE_URL = 'https://bilko.run';
17
+ const API_PREFIX = '/api/sm-relay';
18
+ const TIMEOUT_MS = 15000;
19
+
20
+ /**
21
+ * @typedef {{ ok: false, status: number, error: string, retryAfterSec?: number }} RelayFailure
22
+ * @typedef {{ label: string, publicKey: string, allowedOrigins: string[] }} CreateBoxInput
23
+ * @typedef {{ label?: string, allowedOrigins?: string[], state?: 'open'|'paused' }} PatchBoxInput
24
+ * @typedef {{ baseUrl?: string, getDeviceToken: () => (string|null|undefined|Promise<string|null|undefined>),
25
+ * fetchImpl?: typeof fetch, timeoutMs?: number }} RelayClientOptions
26
+ */
27
+
28
+ /** @param {string|null} header @returns {number|undefined} */
29
+ function parseRetryAfter(header) {
30
+ if (!header) return undefined;
31
+ const s = header.trim();
32
+ if (/^\d+$/.test(s)) return Number(s);
33
+ const at = Date.parse(s);
34
+ if (Number.isNaN(at)) return undefined;
35
+ return Math.max(0, Math.ceil((at - Date.now()) / 1000));
36
+ }
37
+
38
+ /** @param {unknown} code */
39
+ function safeCode(code) {
40
+ return typeof code === 'string' && /^[a-z0-9_]{1,64}$/i.test(code) ? code : null;
41
+ }
42
+
43
+ /** @param {RelayClientOptions} opts */
44
+ function createRelayClient(opts) {
45
+ const { baseUrl = DEFAULT_BASE_URL, getDeviceToken, fetchImpl, timeoutMs = TIMEOUT_MS } = opts || /** @type {any} */ ({});
46
+ const apiBase = String(baseUrl).replace(/\/+$/, '') + API_PREFIX;
47
+
48
+ /** @returns {Promise<string|null>} */
49
+ async function token() {
50
+ try {
51
+ const t = typeof getDeviceToken === 'function' ? await getDeviceToken() : null;
52
+ return typeof t === 'string' && t.length > 0 ? t : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {string} method
60
+ * @param {string} path already URL-encoded, starting with '/'
61
+ * @param {{ json?: unknown, binary?: boolean }} [o]
62
+ * @returns {Promise<{ ok: true, status: number, data: any } | RelayFailure>}
63
+ */
64
+ async function request(method, path, o = {}) {
65
+ const tok = await token();
66
+ if (!tok) return { ok: false, status: 0, error: 'not_linked' };
67
+ /** @type {Record<string, string>} */
68
+ const headers = { Authorization: `Bearer ${tok}`, Accept: o.binary ? 'application/octet-stream' : 'application/json' };
69
+ /** @type {RequestInit} */
70
+ const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
71
+ if (o.json !== undefined) {
72
+ headers['Content-Type'] = 'application/json';
73
+ init.body = JSON.stringify(o.json);
74
+ }
75
+ let res;
76
+ try {
77
+ res = await (fetchImpl || fetch)(apiBase + path, init);
78
+ } catch (e) {
79
+ const name = e && typeof e === 'object' ? /** @type {{ name?: string }} */ (e).name : '';
80
+ return { ok: false, status: 0, error: name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network_error' };
81
+ }
82
+ try {
83
+ if (!res.ok) {
84
+ let code = null;
85
+ try {
86
+ const body = await res.json();
87
+ code = safeCode(body && typeof body === 'object' ? /** @type {{ error?: unknown }} */ (body).error : null);
88
+ } catch {
89
+ /* non-JSON error body */
90
+ }
91
+ /** @type {RelayFailure} */
92
+ const fail = { ok: false, status: res.status, error: code || `http_${res.status}` };
93
+ if (res.status === 429) {
94
+ const ra = parseRetryAfter(res.headers.get('retry-after'));
95
+ if (ra !== undefined) fail.retryAfterSec = ra;
96
+ }
97
+ return fail;
98
+ }
99
+ if (o.binary) return { ok: true, status: res.status, data: Buffer.from(await res.arrayBuffer()) };
100
+ const text = await res.text();
101
+ let data = {};
102
+ if (text) {
103
+ try {
104
+ data = JSON.parse(text);
105
+ } catch {
106
+ return { ok: false, status: res.status, error: 'invalid_response' };
107
+ }
108
+ }
109
+ return { ok: true, status: res.status, data };
110
+ } catch (e) {
111
+ const name = e && typeof e === 'object' ? /** @type {{ name?: string }} */ (e).name : '';
112
+ return { ok: false, status: 0, error: name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network_error' };
113
+ }
114
+ }
115
+
116
+ const seg = (/** @type {unknown} */ s) => encodeURIComponent(String(s));
117
+
118
+ return {
119
+ /** @param {CreateBoxInput} input */
120
+ async createBox(input) {
121
+ const r = await request('POST', '/boxes', { json: input });
122
+ if (!r.ok) return r;
123
+ return { ok: /** @type {const} */ (true), boxId: r.data.boxId, state: r.data.state, createdAt: r.data.createdAt };
124
+ },
125
+ async listBoxes() {
126
+ const r = await request('GET', '/boxes');
127
+ if (!r.ok) return r;
128
+ return { ok: /** @type {const} */ (true), boxes: Array.isArray(r.data.boxes) ? r.data.boxes : [] };
129
+ },
130
+ /** @param {string} boxId @param {PatchBoxInput} patch */
131
+ async patchBox(boxId, patch) {
132
+ const r = await request('PATCH', `/boxes/${seg(boxId)}`, { json: patch || {} });
133
+ if (!r.ok) return r;
134
+ return { ok: /** @type {const} */ (true), box: r.data };
135
+ },
136
+ /** @param {string} boxId */
137
+ async deleteBox(boxId) {
138
+ const r = await request('DELETE', `/boxes/${seg(boxId)}`);
139
+ if (!r.ok) return r;
140
+ return { ok: /** @type {const} */ (true) };
141
+ },
142
+ /** @param {string} boxId @param {number} [limit] */
143
+ async listEnvelopes(boxId, limit) {
144
+ const q = limit === undefined || limit === null ? '' : `?limit=${seg(limit)}`;
145
+ const r = await request('GET', `/boxes/${seg(boxId)}/envelopes${q}`);
146
+ if (!r.ok) return r;
147
+ return { ok: /** @type {const} */ (true), envelopes: Array.isArray(r.data.envelopes) ? r.data.envelopes : [] };
148
+ },
149
+ /** @param {string} boxId @param {string} envelopeId */
150
+ async getEnvelope(boxId, envelopeId) {
151
+ const r = await request('GET', `/boxes/${seg(boxId)}/envelopes/${seg(envelopeId)}`, { binary: true });
152
+ if (!r.ok) return r;
153
+ return { ok: /** @type {const} */ (true), body: /** @type {Buffer} */ (r.data) };
154
+ },
155
+ /** @param {string} boxId @param {string} envelopeId */
156
+ async ackEnvelope(boxId, envelopeId) {
157
+ const r = await request('DELETE', `/boxes/${seg(boxId)}/envelopes/${seg(envelopeId)}`);
158
+ if (!r.ok) return r;
159
+ return { ok: /** @type {const} */ (true) };
160
+ },
161
+ };
162
+ }
163
+
164
+ module.exports = { createRelayClient, DEFAULT_BASE_URL, API_PREFIX, TIMEOUT_MS };