@popmelt.com/core 0.40.0 → 0.41.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 (205) hide show
  1. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  2. package/codex-plugin/.codex-plugin/plugin.json +1 -1
  3. package/dist/ExploreAttachment-ALV7FL3Y.mjs +1 -0
  4. package/dist/PagePreviewLayer-UPCGG4EV.mjs +1 -0
  5. package/dist/ParticipantRuntime-CBUA7BL5.mjs +1 -0
  6. package/dist/PhoneHostGate-TVNOJYL5.mjs +1 -0
  7. package/dist/PopmeltProvider-5g-1VH5a.d.mts +15 -0
  8. package/dist/PopmeltTasteConnectedPane-PD64Q6LF.mjs +1 -0
  9. package/dist/QueuedReplies-ESF5UL3J.mjs +1 -0
  10. package/dist/SamplePlacementOverlay-V533Y4XN.mjs +1 -0
  11. package/dist/ShareProjectPane-PMODH6QQ.mjs +1 -0
  12. package/dist/SuppliedContext-ADMN2D2I.mjs +1 -0
  13. package/dist/{ThreadErrorCard-KPP7YUFC.mjs → ThreadErrorCard-KS2XWRT3.mjs} +1 -1
  14. package/dist/ThreadPanel-5TDPZBAU.mjs +1 -0
  15. package/dist/adapter-react-three-fiber.d.mts +1 -1
  16. package/dist/adapter-react-three-fiber.mjs +1 -1
  17. package/dist/adapter-three.d.mts +1 -1
  18. package/dist/adapter-three.mjs +1 -1
  19. package/dist/bridge-entry.mjs +1 -1
  20. package/dist/browser-runtime-FUXWVGQ7.mjs +1 -0
  21. package/dist/browser.d.mts +4 -4
  22. package/dist/browser.mjs +1 -1
  23. package/dist/canvas-text.d.mts +1 -1
  24. package/dist/{checkFixture-VDRYDCUX.mjs → checkFixture-42NYMFAK.mjs} +1 -1
  25. package/dist/chunk-2TA7N3CI.mjs +1 -0
  26. package/dist/chunk-32BKJ5JN.mjs +1 -0
  27. package/dist/chunk-3HVPVKWV.mjs +1 -0
  28. package/dist/{chunk-RDB75FUD.mjs → chunk-44NLL6X3.mjs} +1 -1
  29. package/dist/chunk-4RQ5XD3I.mjs +1 -0
  30. package/dist/chunk-5J4BZL6N.mjs +1 -0
  31. package/dist/chunk-6OPX4CUT.mjs +1 -0
  32. package/dist/{chunk-27WBFE5X.mjs → chunk-776SEJZO.mjs} +1 -1
  33. package/dist/chunk-7OATJ6BO.mjs +1 -0
  34. package/dist/chunk-7VIC4MGC.mjs +1 -0
  35. package/dist/{chunk-6RMM7JB6.mjs → chunk-ADRWR5GI.mjs} +1 -1
  36. package/dist/chunk-AET77LFV.mjs +1 -0
  37. package/dist/chunk-ALWPAFIW.mjs +1 -0
  38. package/dist/chunk-AOFKEBLN.mjs +1 -0
  39. package/dist/{chunk-6EO73WJN.mjs → chunk-BSVZXOOS.mjs} +1 -1
  40. package/dist/chunk-D2ONGS5P.mjs +1 -0
  41. package/dist/chunk-DDUXU6LA.mjs +1 -0
  42. package/dist/chunk-DMKBAI2Z.mjs +1 -0
  43. package/dist/chunk-DUWONLQE.mjs +1 -0
  44. package/dist/chunk-EG6UHPJV.mjs +1 -0
  45. package/dist/{chunk-DJFZGYX6.mjs → chunk-FZUHHJWW.mjs} +1 -1
  46. package/dist/{chunk-CR6TRUUV.mjs → chunk-GE5BE6PI.mjs} +1 -1
  47. package/dist/{chunk-K22VZV3V.mjs → chunk-GLF7Z5IR.mjs} +1 -1
  48. package/dist/chunk-GLIGPLM4.mjs +1 -0
  49. package/dist/chunk-H3T2O3HA.mjs +1 -0
  50. package/dist/chunk-HFKGW34E.mjs +1 -0
  51. package/dist/{chunk-V5FCWXMN.mjs → chunk-HFWGYXPG.mjs} +1 -1
  52. package/dist/{chunk-53QOGFAT.mjs → chunk-ITLRSHNZ.mjs} +1 -1
  53. package/dist/chunk-JWWWU4GY.mjs +1 -0
  54. package/dist/chunk-KD2AOPYP.mjs +1 -0
  55. package/dist/chunk-KE4MQBRY.mjs +1 -0
  56. package/dist/{chunk-TVIKC33M.mjs → chunk-KF35YUNZ.mjs} +1 -1
  57. package/dist/chunk-KF73S7MG.mjs +1 -0
  58. package/dist/{chunk-UBPJIVWE.mjs → chunk-LDDDSIAQ.mjs} +1 -1
  59. package/dist/chunk-LWPNOBGS.mjs +1 -0
  60. package/dist/{chunk-MPEVFQ43.mjs → chunk-PCUUOIFD.mjs} +1 -1
  61. package/dist/chunk-PRZ6C5X3.mjs +1 -0
  62. package/dist/chunk-PTMHSMZH.mjs +1 -0
  63. package/dist/chunk-RFTQCRGC.mjs +1 -0
  64. package/dist/{chunk-FFBBRCPC.mjs → chunk-S2U2IGUO.mjs} +1 -1
  65. package/dist/{chunk-Y2BJZLYU.mjs → chunk-S7IWZSWH.mjs} +1 -1
  66. package/dist/chunk-SOFNYBJD.mjs +1 -0
  67. package/dist/chunk-SZQTGYPS.mjs +1 -0
  68. package/dist/chunk-TA2BMDSC.mjs +30 -0
  69. package/dist/{chunk-T4WUQPBS.mjs → chunk-ULR4IDEX.mjs} +1 -1
  70. package/dist/{chunk-OECEYJNK.mjs → chunk-VJKC2RJB.mjs} +1 -1
  71. package/dist/{chunk-NFO2CREV.mjs → chunk-VLTK7KWK.mjs} +1 -1
  72. package/dist/chunk-VOL4KS67.mjs +1 -0
  73. package/dist/chunk-VSWRWS2H.mjs +1 -0
  74. package/dist/chunk-W5TNOJOR.mjs +1 -0
  75. package/dist/{chunk-LUTP7QBD.mjs → chunk-WSI2SQWU.mjs} +1 -1
  76. package/dist/chunk-WWNI7JCA.mjs +1 -0
  77. package/dist/chunk-XDZUDDYB.mjs +1 -0
  78. package/dist/chunk-XGSOAF5E.mjs +1 -0
  79. package/dist/chunk-XHTSKQMB.mjs +1 -0
  80. package/dist/chunk-YG3RSK5J.mjs +1 -0
  81. package/dist/chunk-YHCZYT4T.mjs +1 -0
  82. package/dist/{chunk-3LZQLRZ2.mjs → chunk-YTIDSDPP.mjs} +1 -1
  83. package/dist/chunk-Z4NMA34Y.mjs +1 -0
  84. package/dist/chunk-ZXCAONMC.mjs +1 -0
  85. package/dist/cli.mjs +1 -1
  86. package/dist/codex-note-context-WX33QFE7.mjs +1 -0
  87. package/dist/codex-project-77GHT2I3.mjs +1 -0
  88. package/dist/{codex-session-registry-YNU6LEVH.mjs → codex-session-registry-A3NQRRZ3.mjs} +1 -1
  89. package/dist/codex-store-mount-KFJYT6AS.mjs +1 -0
  90. package/dist/dev-app-port-LHUBCOBE.mjs +1 -0
  91. package/dist/{dev-server-BRrhkH5t.d.mts → dev-server-D8Qxrp1A.d.mts} +2 -1
  92. package/dist/dev-server-FZJ6HDKP.mjs +1 -0
  93. package/dist/{focus-inspection-BMDJJC5K.mjs → focus-inspection-FVQ6TVGA.mjs} +1 -1
  94. package/dist/guest-admission.mjs +1 -1
  95. package/dist/guest-live-canvas.mjs +1 -1
  96. package/dist/index.d.mts +9 -25
  97. package/dist/index.mjs +1 -1
  98. package/dist/media.d.mts +3 -3
  99. package/dist/memory-store.d.mts +7 -2
  100. package/dist/memory.mjs +1 -1
  101. package/dist/orientation-markup.mjs +1 -0
  102. package/dist/outline-trace.mjs +1 -0
  103. package/dist/{page-interaction-YXHXEYOT.mjs → page-interaction-74JGNCZ5.mjs} +1 -1
  104. package/dist/{page-planes-Jz2yR_Wk.d.mts → page-planes-BeFZ3Wso.d.mts} +15 -472
  105. package/dist/{participantBootstrap-DDOxY-Cy.d.mts → participantBootstrap-BcfNTEe9.d.mts} +3 -3
  106. package/dist/peer-client-B2KMU667.mjs +1 -0
  107. package/dist/phone-app-HNBDX7UX.mjs +1 -0
  108. package/dist/plain-html-H35WPIRO.mjs +1 -0
  109. package/dist/plane-history.mjs +1 -0
  110. package/dist/plugin-astro.d.mts +8 -3
  111. package/dist/plugin-astro.mjs +1 -1
  112. package/dist/plugin-nuxt.d.mts +6 -2
  113. package/dist/plugin-nuxt.mjs +1 -1
  114. package/dist/plugin-vite.d.mts +10 -5
  115. package/dist/plugin-vite.mjs +1 -1
  116. package/dist/protocol-BIUE4rB6.d.mts +9 -0
  117. package/dist/server.d.mts +14 -3
  118. package/dist/server.mjs +1 -1
  119. package/dist/shared-page-6AUYAPJ3.mjs +1 -0
  120. package/dist/steerStyles-C4YBV4TZ.mjs +1 -0
  121. package/dist/sticker-colors.mjs +1 -0
  122. package/dist/sticker-mode.mjs +1 -0
  123. package/dist/{subjects-cLtt9-iK.d.mts → subjects-qHIrZrlt.d.mts} +57 -1
  124. package/dist/taste-constraints.mjs +1 -0
  125. package/dist/taste-contract.mjs +1 -0
  126. package/dist/taste-fragment.mjs +1 -0
  127. package/dist/taste-graph-inspection.mjs +1 -0
  128. package/dist/taste-layout.mjs +1 -0
  129. package/dist/taste-page-composition.mjs +1 -0
  130. package/dist/taste-proposal-session-PSI4TX6H.mjs +1 -0
  131. package/dist/taste-proposal.mjs +1 -0
  132. package/dist/taste-token-math.mjs +1 -0
  133. package/dist/thread-request.mjs +1 -0
  134. package/dist/thread-view-client.d.mts +2 -0
  135. package/dist/thread-view-client.mjs +1 -0
  136. package/dist/thread-view.html +136 -0
  137. package/dist/{video-adapter-xL95wukX.d.mts → video-adapter-B5eap10v.d.mts} +1 -1
  138. package/infra/phone-pairing/app-listener.cjs +107 -0
  139. package/infra/phone-pairing/binding.mjs +369 -20
  140. package/infra/phone-pairing/machine-config.mjs +43 -26
  141. package/infra/phone-pairing/machine-service.mjs +94 -6
  142. package/infra/phone-pairing/machine.mjs +5 -1
  143. package/infra/phone-pairing/reservations.mjs +103 -0
  144. package/infra/phone-pairing/writer-lock.mjs +107 -0
  145. package/package.json +8 -3
  146. package/dist/ExploreAttachment-DBMYVYWK.mjs +0 -1
  147. package/dist/PagePreviewLayer-CVUA6CTQ.mjs +0 -1
  148. package/dist/ParticipantRuntime-PCBEG3Q2.mjs +0 -1
  149. package/dist/PhoneHostGate-FZLK4R6M.mjs +0 -1
  150. package/dist/PopmeltTasteConnectedPane-62LUNNWZ.mjs +0 -1
  151. package/dist/QueuedReplies-5YG2DN3W.mjs +0 -1
  152. package/dist/SamplePlacementOverlay-LR7GZVYP.mjs +0 -1
  153. package/dist/ShareProjectPane-U47UTAOP.mjs +0 -1
  154. package/dist/SuppliedContext-F7WKJ5XO.mjs +0 -1
  155. package/dist/ThreadPanel-GOYQEF3I.mjs +0 -1
  156. package/dist/browser-runtime-BBQQQLF7.mjs +0 -1
  157. package/dist/chunk-3EYAVOPH.mjs +0 -1
  158. package/dist/chunk-4EDMISUV.mjs +0 -1
  159. package/dist/chunk-52OTX7DP.mjs +0 -1
  160. package/dist/chunk-5IZHN3A7.mjs +0 -1
  161. package/dist/chunk-6GS4BQVU.mjs +0 -30
  162. package/dist/chunk-6U5JWZ4X.mjs +0 -1
  163. package/dist/chunk-7DXJSJCI.mjs +0 -1
  164. package/dist/chunk-A4GARXVQ.mjs +0 -1
  165. package/dist/chunk-AKUIREET.mjs +0 -1
  166. package/dist/chunk-AWWUJO3N.mjs +0 -1
  167. package/dist/chunk-BDUWFDBP.mjs +0 -1
  168. package/dist/chunk-C4AMAM3W.mjs +0 -1
  169. package/dist/chunk-CRZEJJI6.mjs +0 -1
  170. package/dist/chunk-ERPJ6LXX.mjs +0 -1
  171. package/dist/chunk-EWTZVC7E.mjs +0 -1
  172. package/dist/chunk-FR6VIGJ2.mjs +0 -1
  173. package/dist/chunk-FSSHNWMO.mjs +0 -1
  174. package/dist/chunk-HC2SF7KE.mjs +0 -1
  175. package/dist/chunk-HTQEMKFA.mjs +0 -1
  176. package/dist/chunk-LLVF422C.mjs +0 -1
  177. package/dist/chunk-MHTX52KW.mjs +0 -1
  178. package/dist/chunk-OA63PYHZ.mjs +0 -1
  179. package/dist/chunk-P2LMCRUN.mjs +0 -1
  180. package/dist/chunk-PQITT2QK.mjs +0 -1
  181. package/dist/chunk-PQKSXNIZ.mjs +0 -1
  182. package/dist/chunk-PYGRFSUU.mjs +0 -1
  183. package/dist/chunk-RCY5N5KQ.mjs +0 -1
  184. package/dist/chunk-TMSGNHXH.mjs +0 -1
  185. package/dist/chunk-TTOCYOEH.mjs +0 -1
  186. package/dist/chunk-U5NROUVA.mjs +0 -24
  187. package/dist/chunk-UIADZXVT.mjs +0 -1
  188. package/dist/chunk-UPEEIAVJ.mjs +0 -1
  189. package/dist/chunk-VQ76TWRR.mjs +0 -1
  190. package/dist/chunk-WYQZ7DAK.mjs +0 -1
  191. package/dist/chunk-X6I6KQDG.mjs +0 -1
  192. package/dist/chunk-YMWXWXPV.mjs +0 -1
  193. package/dist/chunk-ZC2I35WD.mjs +0 -1
  194. package/dist/codex-note-context-2CHDGTG3.mjs +0 -1
  195. package/dist/codex-project-TIMWOCE5.mjs +0 -1
  196. package/dist/codex-store-mount-MAQK6VEG.mjs +0 -1
  197. package/dist/dev-server-ESGE6QNP.mjs +0 -1
  198. package/dist/participantBootstrap-BuTrTQbo.d.mts +0 -22
  199. package/dist/peer-client-LPDWWFT4.mjs +0 -1
  200. package/dist/plain-html-EF7MUNRZ.mjs +0 -1
  201. package/dist/shared-page-QN2XRXUE.mjs +0 -1
  202. package/dist/steerStyles-E76E44PI.mjs +0 -1
  203. package/dist/taste-proposal-session-AAXK4CFL.mjs +0 -1
  204. /package/dist/{toolbarFonts-JAGSN3DN.mjs → toolbarFonts-33BI56VQ.mjs} +0 -0
  205. /package/dist/{webpEncoder-QJRHTWUU.mjs → webpEncoder-JVMGDKHV.mjs} +0 -0
@@ -1,16 +1,24 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
3
  import {
4
+ closeSync,
5
+ constants,
6
+ existsSync,
7
+ fstatSync,
8
+ openSync,
9
+ readdirSync,
3
10
  linkSync,
4
11
  lstatSync,
5
12
  mkdirSync,
6
13
  readFileSync,
14
+ readSync,
7
15
  realpathSync,
8
16
  renameSync,
9
17
  unlinkSync,
10
18
  writeFileSync,
11
19
  } from 'node:fs';
12
20
  import { homedir } from 'node:os';
13
- import { join } from 'node:path';
21
+ import { dirname, join } from 'node:path';
14
22
 
15
23
  export const base = join(homedir(), '.popmelt-pair');
16
24
  export function privateDir(path) {
@@ -43,7 +51,7 @@ export function writePrivate(path, data, createOnly = false) {
43
51
  }
44
52
  }
45
53
  }
46
- function checkOrigin(origin) {
54
+ export function checkOrigin(origin) {
47
55
  if (
48
56
  typeof origin !== 'string' ||
49
57
  !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(origin) ||
@@ -51,48 +59,389 @@ function checkOrigin(origin) {
51
59
  )
52
60
  throw Error('Expected a loopback app origin with an explicit port.');
53
61
  }
54
- export function readBinding(projectKey) {
62
+ export function readPorts(records) {
63
+ const file = join(records, 'app-ports.json');
64
+ return existsSync(file) ? JSON.parse(readPrivate(file)) : {};
65
+ }
66
+
67
+ function bindingRecord(projectKey, records) {
55
68
  if (!/^[0-9a-f]{64}$/.test(projectKey)) throw Error('Invalid project key.');
56
- const record = JSON.parse(readPrivate(join(base, projectKey + '.json')));
69
+ const record = JSON.parse(readPrivate(join(records, projectKey + '.json')));
57
70
  if (record.projectKey !== projectKey || !/^[0-9a-f]{32}$/.test(record.id))
58
71
  throw Error('Invalid project binding.');
59
72
  checkOrigin(record.appOrigin);
73
+ const port = readPorts(records)[projectKey];
74
+ if (port !== undefined) {
75
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
76
+ throw Error('Invalid phone reservation.');
77
+ const origin = new URL(record.appOrigin);
78
+ origin.port = String(port);
79
+ checkOrigin(origin.origin);
80
+ record.appOrigin = origin.origin;
81
+ }
82
+ return record;
83
+ }
84
+ export function readBinding(projectKey) {
85
+ const record = bindingRecord(projectKey, base);
60
86
  privateDir(join(base, record.id));
61
87
  return record;
62
88
  }
63
- export function projectKeyFor(directory) {
64
- const stat = lstatSync(realpathSync(directory));
65
- if (!stat.isDirectory()) throw Error('Expected a project directory.');
89
+ function macVolumeId(directory) {
90
+ if (process.platform !== 'darwin') return;
91
+ const options = {
92
+ encoding: 'utf8',
93
+ timeout: 2000,
94
+ stdio: ['ignore', 'pipe', 'ignore'],
95
+ };
96
+ try {
97
+ const df = execFileSync('/bin/df', ['-P', directory], options);
98
+ const disk = /^([/]dev[/]disk[0-9]+(?:s[0-9]+)*)\s/m.exec(df)?.[1];
99
+ if (!disk) return;
100
+ const info = execFileSync(
101
+ '/usr/sbin/diskutil',
102
+ ['info', '-plist', disk],
103
+ options,
104
+ );
105
+ const uuid =
106
+ /<key>VolumeUUID<[/]key>\s*<string>([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})<[/]string>/i.exec(
107
+ info,
108
+ )?.[1];
109
+ return uuid?.toLowerCase();
110
+ } catch {
111
+ return;
112
+ }
113
+ }
114
+ function fingerprint(volume, file) {
66
115
  return createHash('sha256')
67
- .update([stat.dev, stat.ino, stat.birthtimeMs].join(':'))
116
+ .update([volume, file.ino, file.birthtimeMs].join(':'))
68
117
  .digest('hex');
69
118
  }
70
- export function bind(directory, appOrigin, assignedId) {
119
+ // The marker is local continuity metadata. Only the Mac's independently stored
120
+ // directory fingerprint and passkey grants may authorize a phone.
121
+ const markerName = 'checkout-id';
122
+ function markerPath(root, create) {
123
+ const state = join(root, '.popmelt'),
124
+ local = join(state, 'local-pairing');
125
+ for (const dir of [state, local]) {
126
+ if (create) {
127
+ try {
128
+ mkdirSync(dir, { mode: 0o700 });
129
+ } catch (error) {
130
+ if (error.code !== 'EEXIST') throw error;
131
+ }
132
+ }
133
+ const info = lstatSync(dir, { throwIfNoEntry: false });
134
+ if (!info) return;
135
+ if (!create && !info.isDirectory()) return;
136
+ if (!create && dir === state && !existsSync(local)) return;
137
+ if (
138
+ !info.isDirectory() ||
139
+ info.uid !== process.getuid?.() ||
140
+ info.mode & 0o022
141
+ )
142
+ throw Error('The local pairing directory must be owned by this user.');
143
+ }
144
+ return join(local, markerName);
145
+ }
146
+
147
+ function checkoutId(root, create = false) {
148
+ const path = markerPath(root, create);
149
+ if (!path) return;
150
+ if (create) {
151
+ // Git should ignore the ID even when an app has custom .popmelt ignore rules.
152
+ for (const [file, value] of [
153
+ [join(dirname(path), '.gitignore'), '*\n'],
154
+ [path, randomBytes(16).toString('hex')],
155
+ ]) {
156
+ try {
157
+ writePrivate(file, value, true);
158
+ } catch (error) {
159
+ if (error.code !== 'EEXIST') throw error;
160
+ }
161
+ }
162
+ }
163
+ let fd;
164
+ try {
165
+ fd = openSync(
166
+ path,
167
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
168
+ );
169
+ const file = fstatSync(fd);
170
+ if (
171
+ file.isFile() &&
172
+ file.uid === process.getuid() &&
173
+ !(file.mode & 0o077) &&
174
+ file.size === 32
175
+ ) {
176
+ const bytes = Buffer.alloc(32);
177
+ if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length)
178
+ throw Error('Incomplete local pairing ID.');
179
+ const id = bytes.toString('utf8');
180
+ if (/^[a-f0-9]{32}$/.test(id)) return id;
181
+ }
182
+ throw Error('The local pairing ID is invalid.');
183
+ } catch (error) {
184
+ if (error.code !== 'ENOENT') throw error;
185
+ } finally {
186
+ if (fd !== undefined) closeSync(fd);
187
+ }
188
+ }
189
+
190
+ // Running gateways also guard already-unlocked sessions if a project is
191
+ // replaced in place. Do not invoke diskutil on the app request path.
192
+ export function checkoutGuard(root, expected) {
193
+ if (expected === undefined) return () => true;
194
+ const initial = lstatSync(realpathSync(root));
195
+ return () => {
196
+ try {
197
+ const current = realpathSync(root);
198
+ const now = lstatSync(current);
199
+ return (
200
+ now.isDirectory() &&
201
+ now.dev === initial.dev &&
202
+ now.ino === initial.ino &&
203
+ now.birthtimeMs === initial.birthtimeMs &&
204
+ checkoutId(current) === expected
205
+ );
206
+ } catch {
207
+ return false;
208
+ }
209
+ };
210
+ }
211
+
212
+ function identity(directory) {
213
+ const path = realpathSync(directory);
214
+ const file = lstatSync(path);
215
+ if (!file.isDirectory()) throw Error('Expected a project directory.');
216
+ const uuid = macVolumeId(path);
217
+ let marker;
218
+ try {
219
+ marker = checkoutId(path);
220
+ } catch {
221
+ // A malformed marker cannot match a binding or block another project's
222
+ // port allocation. Explicit enrollment still reports the filesystem error.
223
+ marker = 'invalid';
224
+ }
225
+ const scope = (volume) =>
226
+ marker ? 'checkout:' + marker + ':' + volume : volume;
227
+ return {
228
+ file,
229
+ marker,
230
+ legacy: fingerprint(scope(file.dev), file),
231
+ stable: uuid && fingerprint(scope(uuid), file),
232
+ };
233
+ }
234
+
235
+ // The extra record is write-once. Keep canonical keys used by the provisioner
236
+ // and existing bookmarks, even if the OS renumbers a mounted volume.
237
+ function rememberVolume(records, key, stable) {
238
+ const path = join(records, key + '.volume');
239
+ try {
240
+ writePrivate(path, stable, true);
241
+ } catch (error) {
242
+ if (error.code !== 'EEXIST') throw error;
243
+ if (readPrivate(path) !== stable)
244
+ throw Error('Pairing belongs to a different volume.');
245
+ }
246
+ }
247
+ function matchingAnchors(records, stable) {
248
+ if (!stable) return [];
249
+ return readdirSync(records)
250
+ .filter((name) => {
251
+ if (!/^[0-9a-f]{64}\.volume$/.test(name)) return false;
252
+ try {
253
+ return readPrivate(join(records, name)) === stable;
254
+ } catch {
255
+ return false;
256
+ }
257
+ })
258
+ .map((name) => name.slice(0, -7));
259
+ }
260
+ function resolveProjectKey(records, legacy, stable) {
261
+ if (!existsSync(records)) return legacy;
262
+ privateDir(records);
263
+ const exact = join(records, legacy + '.json');
264
+ const anchor = join(records, legacy + '.volume');
265
+ const matches = matchingAnchors(records, stable);
266
+ if (matches.length > 1)
267
+ throw Error('More than one pairing record matches this directory.');
268
+ if (existsSync(exact)) {
269
+ const record = JSON.parse(readPrivate(exact));
270
+ if (record.projectKey !== legacy || !/^[0-9a-f]{32}$/.test(record.id))
271
+ throw Error('Invalid project binding.');
272
+ if (!existsSync(anchor)) {
273
+ if (matches.length)
274
+ throw Error('Another pairing already matches this directory.');
275
+ if (stable) rememberVolume(records, legacy, stable);
276
+ return legacy;
277
+ }
278
+ if (!stable) throw Error('Could not verify the paired project volume.');
279
+ if (readPrivate(anchor) === stable) return legacy;
280
+ }
281
+ if (matches.length) {
282
+ const key = matches[0];
283
+ if (!existsSync(join(records, key + '.json')))
284
+ throw Error('Missing project binding.');
285
+ return key;
286
+ }
287
+ // The old device number can also be reused by a different volume.
288
+ return existsSync(exact) ? stable : legacy;
289
+ }
290
+
291
+ // The allocator's private list supplies paths, never authority. Look only at
292
+ // existing registrations that still match the exact legacy device and directory.
293
+ export function migrateKnownVolumes(records, registered) {
294
+ const pending = new Set(
295
+ registered.filter(
296
+ (key) =>
297
+ /^[a-f0-9]{64}$/.test(key) &&
298
+ !existsSync(join(records, key + '.volume')),
299
+ ),
300
+ );
301
+ const ledger = join(records, 'dev-ports.json');
302
+ if (!pending.size || !existsSync(ledger)) return;
303
+ const choices = JSON.parse(readPrivate(ledger));
304
+ if (!Array.isArray(choices)) return;
305
+ const candidates = new Map();
306
+ for (const entry of choices) {
307
+ try {
308
+ const root = entry[0];
309
+ if (
310
+ typeof root !== 'string' ||
311
+ !root.startsWith('/') ||
312
+ realpathSync(root) !== root
313
+ )
314
+ continue;
315
+ const stat = lstatSync(root),
316
+ key = fingerprint(stat.dev, stat);
317
+ if (
318
+ !stat.isDirectory() ||
319
+ !pending.has(key) ||
320
+ checkoutId(root) !== undefined ||
321
+ bindingRecord(key, records).checkoutId !== undefined
322
+ )
323
+ continue;
324
+ if (
325
+ pending.size > 1 &&
326
+ Array.from(previousDeviceKeys(stat)).some((other) => pending.has(other))
327
+ )
328
+ continue;
329
+ const uuid = macVolumeId(root);
330
+ const verified = lstatSync(root);
331
+ if (!uuid || fingerprint(verified.dev, verified) !== key) continue;
332
+ const stable = fingerprint(uuid, stat);
333
+ const previous = candidates.get(stable);
334
+ candidates.set(
335
+ stable,
336
+ previous === undefined || previous.root === root
337
+ ? { root, key }
338
+ : false,
339
+ );
340
+ } catch {
341
+ /* Skip unavailable directories. */
342
+ }
343
+ }
344
+ for (const [stable, candidate] of candidates) {
345
+ if (!candidate) continue;
346
+ const { root, key } = candidate;
347
+ try {
348
+ const current = lstatSync(root);
349
+ if (
350
+ fingerprint(current.dev, current) !== key ||
351
+ matchingAnchors(records, stable).some((other) => other !== key)
352
+ )
353
+ continue;
354
+ rememberVolume(records, key, stable);
355
+ } catch {
356
+ /* A concurrent write or an unplugged drive affects only this checkout. */
357
+ }
358
+ }
359
+ }
360
+
361
+ // Older bindings contain only a hash. Offer explicit desktop recovery only
362
+ // when the inode and birth time reproduce that exact hash on an earlier disk
363
+ // number. Outside this bounded range the ordinary conflict guidance applies.
364
+ export function legacyVolumeMatch(directory, key) {
365
+ return previousVolumeMatch(identity(directory), key, base);
366
+ }
367
+ function previousVolumeMatch({ file, stable, marker }, key, records) {
368
+ if (marker) return;
369
+ if (existsSync(join(records, key + '.volume'))) return;
370
+ if (!stable) return;
371
+ for (const previous of previousDeviceKeys(file))
372
+ if (previous === key) return stable;
373
+ }
374
+ function* previousDeviceKeys(file) {
375
+ const first = Math.floor(file.dev / 0x1000000) * 0x1000000;
376
+ for (let device = first; device < first + 1024; device++)
377
+ if (device !== file.dev) yield fingerprint(device, file);
378
+ }
379
+ export function confirmLegacyVolume(key, stable) {
380
+ rememberVolume(base, key, stable);
381
+ }
382
+ export function projectKeyFor(directory, records = base) {
383
+ const { legacy, stable } = identity(directory);
384
+ return resolveProjectKey(records, legacy, stable);
385
+ }
386
+
387
+ // Port selection may recognize a legacy reservation. Only the explicit
388
+ // reconnect flow above can transfer the binding to a new disk identity.
389
+ export function pairedAppOrigins(directory, records = base) {
390
+ const keys = existsSync(records)
391
+ ? readdirSync(records).filter((name) => /^[0-9a-f]{64}\.json$/.test(name))
392
+ : [];
393
+ const reserved = new Set();
394
+ let own;
395
+ if (keys.length) {
396
+ const id = identity(directory);
397
+ const key = resolveProjectKey(records, id.legacy, id.stable);
398
+ for (const name of keys) {
399
+ const other = name.slice(0, -5);
400
+ const { appOrigin } = bindingRecord(other, records);
401
+ reserved.add(Number(new URL(appOrigin).port));
402
+ if (other === key || previousVolumeMatch(id, other, records))
403
+ own = new URL(appOrigin);
404
+ }
405
+ }
406
+ return { own, reserved };
407
+ }
408
+
409
+ export function bind(directory, appOrigin, idForKey) {
71
410
  checkOrigin(appOrigin);
72
- const projectKey = projectKeyFor(directory);
73
411
  privateDir(base);
74
- let record;
75
- try {
76
- record = readBinding(projectKey);
77
- } catch (e) {
78
- if (e.code !== 'ENOENT') throw e;
79
- const id = assignedId ?? randomBytes(16).toString('hex');
412
+ let projectKey = projectKeyFor(directory);
413
+ if (!existsSync(join(base, projectKey + '.json'))) {
414
+ const marker = checkoutId(realpathSync(directory), true);
415
+ const checkout = identity(directory);
416
+ if (!marker || marker !== checkout.marker)
417
+ throw Error('The checkout changed during pairing.');
418
+ projectKey = resolveProjectKey(base, checkout.legacy, checkout.stable);
419
+ const id = idForKey?.(projectKey) ?? randomBytes(16).toString('hex');
80
420
  try {
81
421
  writePrivate(
82
422
  join(base, projectKey + '.json'),
83
- JSON.stringify({ projectKey, id, appOrigin }),
423
+ JSON.stringify({ projectKey, id, appOrigin, checkoutId: marker }),
84
424
  true,
85
425
  );
86
- } catch (e) {
87
- if (e.code !== 'EEXIST') throw e;
426
+ } catch (error) {
427
+ if (error.code !== 'EEXIST') throw error;
88
428
  }
89
- record = readBinding(projectKey);
90
429
  }
430
+ const record = readBinding(projectKey);
91
431
  // localhost aliases for the same listener preserve the original binding.
92
432
  const stored = new URL(record.appOrigin),
93
433
  requested = new URL(appOrigin);
94
434
  if (stored.protocol !== requested.protocol || stored.port !== requested.port)
95
435
  throw Error('Review the existing binding before changing its app origin.');
436
+ const verified = identity(directory);
437
+ if (
438
+ verified.marker !== record.checkoutId ||
439
+ resolveProjectKey(base, verified.legacy, verified.stable) !== projectKey
440
+ )
441
+ throw Error(
442
+ 'The project changed during registration. Retry from its desktop host.',
443
+ );
444
+ if (verified.stable) rememberVolume(base, projectKey, verified.stable);
96
445
  return record;
97
446
  }
98
447
  export function route(id) {
@@ -1,10 +1,14 @@
1
+ import { withReservations } from './reservations.mjs';
1
2
  // The CLI and the running provisioner share one registry and one writer lock.
2
- import { existsSync, mkdirSync, rmdirSync } from 'node:fs';
3
+ import { existsSync } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
5
  import { join } from 'node:path';
5
6
  import {
6
7
  base,
7
8
  bind,
9
+ confirmLegacyVolume,
10
+ legacyVolumeMatch,
11
+ checkOrigin,
8
12
  privateDir,
9
13
  projectKeyFor,
10
14
  readBinding,
@@ -45,17 +49,7 @@ export function routingTable(state) {
45
49
  export async function configure(command, args = [], provisionDns, idForKey) {
46
50
  privateDir(base);
47
51
  privateDir(machine);
48
- const lock = join(machine, 'provision.lock');
49
- try {
50
- mkdirSync(lock, { mode: 0o700 });
51
- } catch (e) {
52
- if (e.code === 'EEXIST')
53
- throw Error(
54
- 'Another project is being configured. Try again in a moment.',
55
- );
56
- throw e;
57
- }
58
- try {
52
+ return withReservations(base, async () => {
59
53
  let state;
60
54
  try {
61
55
  state = readState();
@@ -69,17 +63,42 @@ export async function configure(command, args = [], provisionDns, idForKey) {
69
63
  const table = routingTable(state);
70
64
  let project;
71
65
  if (command === 'add') {
72
- const key = projectKeyFor(args[0]);
73
- const port = new URL(args[1]).port;
74
- if (
75
- state.projects.some(
76
- (k) => k !== key && new URL(readBinding(k).appOrigin).port === port,
77
- )
78
- )
79
- throw Error(
80
- 'That loopback app port is already assigned to another project.',
81
- );
82
- project = bind(...args, idForKey?.(key));
66
+ checkOrigin(args[1]);
67
+ let key = projectKeyFor(args[0]);
68
+ const origin = new URL(args[1]);
69
+ const other = state.projects.find(
70
+ (k) =>
71
+ k !== key && new URL(readBinding(k).appOrigin).port === origin.port,
72
+ );
73
+ const confirmation = args[2];
74
+ if (other) {
75
+ const previous = readBinding(other);
76
+ const stable =
77
+ !existsSync(join(base, key + '.json')) &&
78
+ origin.protocol === new URL(previous.appOrigin).protocol &&
79
+ legacyVolumeMatch(args[0], other);
80
+ if (!stable)
81
+ throw Error(
82
+ 'That loopback app port is already assigned to another project.',
83
+ );
84
+ if (confirmation !== previous.id) {
85
+ throw Object.assign(
86
+ Error(
87
+ 'This directory matches a project paired before the disk identifier changed. Reconnecting lets its previously paired phones open this project.',
88
+ ),
89
+ { reconnectId: previous.id },
90
+ );
91
+ }
92
+ confirmLegacyVolume(other, stable);
93
+ key = other;
94
+ } else if (
95
+ confirmation &&
96
+ (!state.projects.includes(key) || readBinding(key).id !== confirmation)
97
+ ) {
98
+ throw Error('The pairing changed. Retry from the desktop host.');
99
+ }
100
+ project = bind(args[0], args[1], idForKey);
101
+ key = project.projectKey;
83
102
  const { hostname, socket } = route(project.id);
84
103
  if (!state.projects.includes(key)) {
85
104
  if (table.has(hostname))
@@ -128,7 +147,5 @@ export async function configure(command, args = [], provisionDns, idForKey) {
128
147
  projects: table.size,
129
148
  ...(project && route(project.id)),
130
149
  };
131
- } finally {
132
- rmdirSync(lock);
133
- }
150
+ });
134
151
  }
@@ -3,7 +3,10 @@ import { createConnection } from 'node:net';
3
3
  import { chmod, lstat, unlink } from 'node:fs/promises';
4
4
  import { execFile } from 'node:child_process';
5
5
  import { promisify } from 'node:util';
6
- import { isAbsolute } from 'node:path';
6
+ import { Worker, workerData, isMainThread } from 'node:worker_threads';
7
+ import { existsSync } from 'node:fs';
8
+ import { base, migrateKnownVolumes } from './binding.mjs';
9
+ import { join, isAbsolute } from 'node:path';
7
10
  import {
8
11
  configure,
9
12
  controlSocket,
@@ -13,6 +16,49 @@ import {
13
16
  routingTable,
14
17
  } from './machine-config.mjs';
15
18
 
19
+ // Volume discovery can stall on removable media. Keep it off the router's
20
+ // event loop, including on the first pass during service startup.
21
+ if (!isMainThread && workerData === 'migrate-volumes')
22
+ migrateKnownVolumes(base, readState().projects);
23
+
24
+ function watchVolumes() {
25
+ if (process.platform !== 'darwin') return;
26
+ let worker;
27
+ const check = () => {
28
+ if (worker || !existsSync(join(base, 'dev-ports.json'))) return;
29
+ try {
30
+ if (
31
+ !readState().projects.some(
32
+ (key) =>
33
+ /^[0-9a-f]{64}$/.test(key) &&
34
+ !existsSync(join(base, key + '.volume')),
35
+ )
36
+ )
37
+ return;
38
+ worker = new Worker(new URL(import.meta.url), {
39
+ workerData: 'migrate-volumes',
40
+ execArgv: [],
41
+ });
42
+ worker.on('error', () => {
43
+ /* Retry on the next pass. */
44
+ });
45
+ worker.once('exit', () => {
46
+ worker = undefined;
47
+ });
48
+ worker.unref();
49
+ } catch {
50
+ /* An unavailable registry can be checked later. */
51
+ }
52
+ };
53
+ const timer = setInterval(check, 300000);
54
+ timer.unref();
55
+ check();
56
+ return () => {
57
+ clearInterval(timer);
58
+ void worker?.terminate();
59
+ };
60
+ }
61
+
16
62
  const exec = promisify(execFile);
17
63
  export async function provisionDns(tunnel, hostname) {
18
64
  try {
@@ -81,8 +127,37 @@ export async function serve(registerDns = provisionDns, idForKey) {
81
127
  },
82
128
  );
83
129
  upstream.once('error', () => {
84
- if (!res.headersSent) res.writeHead(503, { 'Cache-Control': 'no-store' });
85
- res.end();
130
+ if (res.headersSent) return res.destroy();
131
+ res.setHeader('Cache-Control', 'private, no-store');
132
+ if (
133
+ req.headers.origin === 'https://pair.popmelt.com' &&
134
+ ['/__pair/options', '/__pair/finish'].includes(req.url)
135
+ ) {
136
+ res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
137
+ res.setHeader('Vary', 'Origin');
138
+ if (req.method === 'OPTIONS') {
139
+ res.setHeader('Access-Control-Allow-Methods', 'POST');
140
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
141
+ return res.writeHead(204).end();
142
+ }
143
+ if (req.method === 'POST')
144
+ return res
145
+ .writeHead(503, { 'Content-Type': 'application/json' })
146
+ .end('{"state":"reconnecting"}');
147
+ }
148
+ if (
149
+ req.method === 'GET' &&
150
+ req.headers['sec-fetch-mode'] === 'navigate'
151
+ ) {
152
+ const id = /^p-([a-f0-9]{32})\.popmelt\.com$/.exec(
153
+ req.headers.host,
154
+ )?.[1];
155
+ if (id)
156
+ return res
157
+ .writeHead(303, { Location: 'https://pair.popmelt.com/p/' + id })
158
+ .end();
159
+ }
160
+ res.writeHead(503).end();
86
161
  });
87
162
  res.once('close', () => upstream.destroy());
88
163
  req.once('error', () => upstream.destroy());
@@ -108,19 +183,22 @@ export async function serve(registerDns = provisionDns, idForKey) {
108
183
  if (size > 8192) throw Error('Invalid project registration.');
109
184
  chunks.push(chunk);
110
185
  }
111
- const { root, origin } = JSON.parse(
186
+ const { root, origin, reconnectId } = JSON.parse(
112
187
  Buffer.concat(chunks).toString('utf8'),
113
188
  );
114
189
  if (
115
190
  typeof root !== 'string' ||
116
191
  !isAbsolute(root) ||
117
- typeof origin !== 'string'
192
+ typeof origin !== 'string' ||
193
+ (reconnectId !== undefined &&
194
+ (typeof reconnectId !== 'string' ||
195
+ !/^[0-9a-f]{32}$/.test(reconnectId)))
118
196
  )
119
197
  throw Error('Invalid project registration.');
120
198
  const added = tail.then(async () => {
121
199
  const result = await configure(
122
200
  'add',
123
- [root, origin],
201
+ [root, origin, reconnectId],
124
202
  registerDns,
125
203
  idForKey,
126
204
  );
@@ -133,6 +211,14 @@ export async function serve(registerDns = provisionDns, idForKey) {
133
211
  .writeHead(200, { 'Content-Type': 'application/json' })
134
212
  .end(JSON.stringify(result));
135
213
  } catch (e) {
214
+ if (e.reconnectId) {
215
+ res
216
+ .writeHead(409, { 'Content-Type': 'application/json' })
217
+ .end(
218
+ JSON.stringify({ error: e.message, reconnectId: e.reconnectId }),
219
+ );
220
+ return;
221
+ }
136
222
  const message = e.message?.includes('loopback app port')
137
223
  ? 'This app port is assigned to another paired project.'
138
224
  : 'Could not register this project with the Mac’s tunnel. Retry, or pair over Wi-Fi.';
@@ -150,7 +236,9 @@ export async function serve(registerDns = provisionDns, idForKey) {
150
236
  control.close();
151
237
  throw e;
152
238
  }
239
+ const stopWatching = watchVolumes();
153
240
  return () => {
241
+ stopWatching?.();
154
242
  for (const server of [control, router]) {
155
243
  server.close();
156
244
  server.closeAllConnections();