gestalt-mobile 0.72.0 → 0.72.2

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.
@@ -6,8 +6,10 @@
6
6
  import { constants } from 'node:fs';
7
7
  import { lstat, mkdir, open, realpath, rmdir } from 'node:fs/promises';
8
8
  import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
9
- import { canonicalScratchWorkspace, readManagedScratchAttribution, readManagedScratchLeases, } from './managed-scratch-owner.js';
9
+ import { canonicalScratchWorkspace, readManagedScratchAttribution, readManagedScratchLeases, readRuntimeScratchAttribution, } from './managed-scratch-owner.js';
10
10
  import { privateDirectory } from './scratch-filesystem.js';
11
+ import { runtimeContainer } from './runtime-root.js';
12
+ import { assertParentPublications, claimWorkspacePublication } from './workspace-publication.js';
11
13
  export const containmentFenceName = '.containment-lock';
12
14
  const same = (left, right) => left.dev === right.dev && left.ino === right.ino && left.birth === right.birth;
13
15
  async function directoryIdentity(path) {
@@ -32,6 +34,7 @@ async function ancestorIdentity(directory, allowRetired) {
32
34
  return {
33
35
  directory,
34
36
  ownerId: owner.ownerId,
37
+ workspacePath: owner.workspacePath,
35
38
  identity: await directoryIdentity(directory),
36
39
  provenance: JSON.stringify([
37
40
  marker.schemaVersion,
@@ -43,6 +46,9 @@ async function ancestorIdentity(directory, allowRetired) {
43
46
  marker.authority.kind,
44
47
  marker.authority.sessionId ?? null,
45
48
  marker.authority.leaseId ?? null,
49
+ marker.runtime
50
+ ? [marker.runtime.directory, marker.runtime.token, marker.runtime.identity]
51
+ : null,
46
52
  ]),
47
53
  };
48
54
  }
@@ -84,27 +90,43 @@ async function releaseClaims(claims) {
84
90
  throw failure;
85
91
  }
86
92
  /** Interoperates with Launcher scratchWithContainment; no PID/age recovery. */
87
- export async function claimScratchContainment(workspace, cleanupOwnerId) {
93
+ export async function claimScratchContainment(workspace, cleanupOwnerId, inherited) {
88
94
  let selected = await canonicalScratchWorkspace(workspace);
89
95
  const selectedIdentity = await directoryIdentity(selected);
90
96
  const ancestors = [];
91
- const parts = selected.slice(parse(selected).root.length).split(sep).filter(Boolean);
92
- let directory = parse(selected).root;
93
- for (let index = 0; index < parts.length; index++) {
94
- directory = join(directory, parts[index]);
95
- if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
96
- if (ancestors.length >= 64)
97
- throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
98
- const ancestor = await ancestorIdentity(directory, directory === selected && cleanupOwnerId !== undefined);
99
- if (directory === selected &&
100
- cleanupOwnerId !== undefined &&
101
- ancestor.ownerId !== cleanupOwnerId)
102
- throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
103
- ancestors.push(ancestor);
97
+ const visiting = new Set();
98
+ const runtimeBase = process.getuid ? await runtimeContainer() : undefined;
99
+ const discover = async (path) => {
100
+ if (visiting.has(path) || visiting.size >= 64)
101
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
102
+ visiting.add(path);
103
+ const parts = path.slice(parse(path).root.length).split(sep).filter(Boolean);
104
+ let directory = parse(path).root;
105
+ for (let index = 0; index < parts.length; index++) {
106
+ directory = join(directory, parts[index]);
107
+ if (dirname(directory) === runtimeBase) {
108
+ const owner = await readRuntimeScratchAttribution(directory);
109
+ await discover(owner.directory);
110
+ }
111
+ if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
112
+ if (ancestors.some((ancestor) => ancestor.directory === directory))
113
+ continue;
114
+ if (ancestors.length >= 64)
115
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
116
+ const ancestor = await ancestorIdentity(directory, directory === selected && cleanupOwnerId !== undefined);
117
+ if (directory === selected &&
118
+ cleanupOwnerId !== undefined &&
119
+ ancestor.ownerId !== cleanupOwnerId)
120
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
121
+ ancestors.push(ancestor);
122
+ }
104
123
  }
105
- }
124
+ visiting.delete(path);
125
+ };
126
+ await discover(selected);
106
127
  const claims = [];
107
128
  const revalidate = async () => {
129
+ await inherited?.revalidate();
108
130
  await canonicalScratchWorkspace(selected);
109
131
  if (!same(selectedIdentity, await directoryIdentity(selected)))
110
132
  throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
@@ -121,6 +143,10 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
121
143
  // Ancestors are discovered in path order. Containment always precedes the
122
144
  // owner's controller/association operation, and never spans a service lifetime.
123
145
  for (const ancestor of ancestors) {
146
+ if (inherited?.owns(ancestor.directory)) {
147
+ await inherited.revalidate();
148
+ continue;
149
+ }
124
150
  const path = join(ancestor.directory, containmentFenceName);
125
151
  try {
126
152
  await mkdir(path, { mode: 0o700 });
@@ -153,6 +179,9 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
153
179
  throw error;
154
180
  }
155
181
  return {
182
+ publicationParents: ancestors.map((ancestor) => ancestor.workspacePath),
183
+ owns: (directory) => claims.some((claim) => !claim.attempted && claim.directory === directory) ||
184
+ !!inherited?.owns(directory),
156
185
  revalidate,
157
186
  async relocate(from, to) {
158
187
  const ancestor = ancestors.find((value) => value.directory === from);
@@ -182,12 +211,31 @@ export async function claimScratchContainment(workspace, cleanupOwnerId) {
182
211
  };
183
212
  }
184
213
  export async function withScratchContainment(workspace, publish) {
185
- const guard = await claimScratchContainment(workspace);
214
+ const releaseWorkspace = await claimWorkspacePublication(workspace);
215
+ let guard;
216
+ let failed = false;
186
217
  try {
187
- return await publish();
218
+ guard = await claimScratchContainment(workspace);
219
+ await assertParentPublications(workspace, guard.publicationParents);
220
+ const result = await publish();
221
+ await assertParentPublications(workspace, guard.publicationParents);
222
+ return result;
223
+ }
224
+ catch (error) {
225
+ failed = true;
226
+ throw error;
188
227
  }
189
228
  finally {
190
- await guard.release();
229
+ try {
230
+ await guard?.release();
231
+ }
232
+ finally {
233
+ // Preserve the first failed boundary when the selected workspace changed.
234
+ if (failed)
235
+ await releaseWorkspace().catch(() => { });
236
+ else
237
+ await releaseWorkspace();
238
+ }
191
239
  }
192
240
  }
193
241
  /** Detached history may outlive its cwd; publishing it never allocates scratch. */
@@ -241,8 +289,13 @@ export async function withHistoryScratchContainment(workspace, publish) {
241
289
  let ownerCount = 0;
242
290
  const parts = workspace.slice(parse(workspace).root.length).split(sep).filter(Boolean);
243
291
  let directory = parse(workspace).root;
292
+ const runtimeBase = process.getuid ? await runtimeContainer() : undefined;
244
293
  for (let index = 0; index < parts.length; index++) {
245
294
  directory = join(directory, parts[index]);
295
+ if (dirname(directory) === runtimeBase) {
296
+ await readRuntimeScratchAttribution(directory);
297
+ deepestOwner = directory;
298
+ }
246
299
  if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
247
300
  if (++ownerCount > 64)
248
301
  throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
@@ -254,7 +307,10 @@ export async function withHistoryScratchContainment(workspace, publish) {
254
307
  const guard = deepestOwner ? await claimScratchContainment(deepestOwner) : undefined;
255
308
  try {
256
309
  await revalidate();
257
- return await publish();
310
+ await assertParentPublications(workspace, guard?.publicationParents);
311
+ const result = await publish();
312
+ await assertParentPublications(workspace, guard?.publicationParents);
313
+ return result;
258
314
  }
259
315
  finally {
260
316
  await guard?.release();
@@ -4,14 +4,16 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
- import { lstat, mkdir, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
7
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
8
8
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { emptyScratchCounts, } from '../../features/sessions/clean-tmp/use-case.js';
10
10
  import { mobileScratchOwnerId, privateDirectory, scratchMarkerName } from './scratch-filesystem.js';
11
11
  import { claimOwnerFence } from './owner-fence.js';
12
12
  import { isAmbiguousLegacyScratch } from './legacy-scratch-layouts.js';
13
13
  import { canonicalScratchWorkspace, managedScratchOwnerId, readManagedScratchOwner, readManagedScratchLeases, } from './managed-scratch-owner.js';
14
- import { claimScratchContainment, containmentFenceName } from './containment-fence.js';
14
+ import { claimScratchContainment, containmentFenceName, } from './containment-fence.js';
15
+ import { workspacePublicationName } from './workspace-publication.js';
16
+ import { hasRuntimeOwner, runtimeIdentity, runtimeMarkerName, validateRuntime, } from './runtime-root.js';
15
17
  function reject(reason) {
16
18
  throw new Error(`SCRATCH_CLEANUP_${reason}`);
17
19
  }
@@ -30,8 +32,15 @@ export class FilesystemScratchCleanup {
30
32
  await lstat(session.workspacePath);
31
33
  }
32
34
  catch (error) {
33
- if (error.code === 'ENOENT')
35
+ if (error.code === 'ENOENT') {
36
+ if (process.getuid &&
37
+ (await hasRuntimeOwner({
38
+ workspacePath: session.workspacePath,
39
+ ownerId: mobileScratchOwnerId(session.id),
40
+ })))
41
+ throw new Error('SESSION_CLEANUP_FAILED');
34
42
  return;
43
+ }
35
44
  throw error;
36
45
  }
37
46
  }
@@ -42,7 +51,7 @@ export class FilesystemScratchCleanup {
42
51
  async canonicalWorkspace(path) {
43
52
  return canonicalScratchWorkspace(path);
44
53
  }
45
- async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized) {
54
+ async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized, authorizedSessionId, inherited) {
46
55
  await this.canonicalWorkspace(workspacePath);
47
56
  const counts = emptyScratchCounts();
48
57
  const temporary = join(workspacePath, 'tmp');
@@ -94,12 +103,26 @@ export class FilesystemScratchCleanup {
94
103
  // A removal reservation/partial allocation is not an owner yet. Inspect
95
104
  // its locator before claiming a fence; authority is rechecked below.
96
105
  await readManagedScratchOwner(directory, workspacePath, ownerId);
97
- containment = await claimScratchContainment(directory, ownerId);
106
+ containment = await claimScratchContainment(directory, ownerId, inherited);
98
107
  release = await claimOwnerFence(directory);
99
108
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
100
109
  await this.releasedLeases(directory, marker);
101
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
110
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
111
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
112
+ if (authorized) {
113
+ await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
114
+ if (marker.runtime && (await validateRuntime(marker, marker.runtime, true)))
115
+ await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
116
+ }
102
117
  await this.validatePayload(directory);
118
+ if (marker.runtime) {
119
+ const present = await validateRuntime(marker, marker.runtime, true);
120
+ if (present) {
121
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
122
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
123
+ await this.validatePayload(marker.runtime.directory);
124
+ }
125
+ }
103
126
  await privateDirectory(directory, false);
104
127
  await containment.revalidate();
105
128
  if (name === ownerId) {
@@ -107,7 +130,8 @@ export class FilesystemScratchCleanup {
107
130
  // Reserve the random destination exclusively; never replace a collision.
108
131
  await mkdir(retired, { mode: 0o700 });
109
132
  try {
110
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
133
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
134
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
111
135
  }
112
136
  catch (error) {
113
137
  await rmdir(retired);
@@ -122,7 +146,8 @@ export class FilesystemScratchCleanup {
122
146
  }
123
147
  await privateDirectory(directory, false);
124
148
  await containment.revalidate();
125
- await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
149
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
150
+ (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
126
151
  // Keep authority metadata until disposable payload has been removed. A failed
127
152
  // payload deletion is retryable; an interrupted metadata retirement is unknown.
128
153
  for (const child of await readdir(directory, { encoding: 'buffer' })) {
@@ -130,6 +155,7 @@ export class FilesystemScratchCleanup {
130
155
  continue;
131
156
  await rm(payloadPath(directory, child), { recursive: true });
132
157
  }
158
+ await this.retireRuntime(directory, marker);
133
159
  if ((await readdir(directory)).includes('leases'))
134
160
  await rm(join(directory, 'leases'), { recursive: true });
135
161
  await rm(join(directory, scratchMarkerName));
@@ -202,7 +228,96 @@ export class FilesystemScratchCleanup {
202
228
  if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0))
203
229
  reject('lease');
204
230
  }
205
- async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized) {
231
+ /** Final workspace authority can retire positively attributed nested namespaces,
232
+ * but every nested roster, lease, inode and fence still has to pass its gate. */
233
+ async retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, inherited, skipContainer = false, depth = 0, budget = { entries: 0 }) {
234
+ if (depth > 128 || !authorized())
235
+ reject('protected');
236
+ let entries;
237
+ try {
238
+ entries = await readdir(directory, { encoding: 'buffer', withFileTypes: true });
239
+ }
240
+ catch (error) {
241
+ if (error.code === 'ENOENT')
242
+ return;
243
+ throw error;
244
+ }
245
+ for (const entry of entries) {
246
+ if (++budget.entries > 100000)
247
+ reject('unrecognized');
248
+ const name = entry.name.toString();
249
+ if (skipContainer && name === 'sessions')
250
+ continue;
251
+ const path = payloadPath(directory, entry.name), info = await lstat(path);
252
+ if (process.getuid && info.uid !== process.getuid())
253
+ reject('unsafe');
254
+ if (!info.isDirectory() || info.isSymbolicLink())
255
+ continue;
256
+ if (name === 'tmp') {
257
+ const workspace = directory.toString();
258
+ if (Buffer.isBuffer(directory) && !Buffer.from(workspace).equals(directory))
259
+ reject('unrecognized');
260
+ const counts = await this.cleanWorkspace(workspace, protectedSessions, undefined, authorized, authorizedSessionId, inherited);
261
+ if (counts.skipped || counts.failed)
262
+ reject('unrecognized');
263
+ const container = join(workspace, 'tmp', 'sessions');
264
+ try {
265
+ await privateDirectory(container, false);
266
+ const remaining = await readdir(container);
267
+ if (remaining.some((child) => child !== '.gitignore'))
268
+ reject('unrecognized');
269
+ if (remaining.includes('.gitignore'))
270
+ await rm(join(container, '.gitignore'));
271
+ await rmdir(container);
272
+ }
273
+ catch (error) {
274
+ if (error.code !== 'ENOENT')
275
+ throw error;
276
+ }
277
+ }
278
+ await this.retireNestedNamespaces(path, protectedSessions, authorized, authorizedSessionId, inherited, name === 'tmp', depth + 1, budget);
279
+ }
280
+ }
281
+ async retireRuntime(directory, marker) {
282
+ if (!marker.runtime)
283
+ return;
284
+ const runtime = marker.runtime;
285
+ if (!(await validateRuntime(marker, runtime, true)))
286
+ return;
287
+ // Persist retirement intent before either authority record is removed.
288
+ // After a crash an absent runtime is acceptable only with this exact record;
289
+ // a replacement inode or a nonempty directory without its marker is retained.
290
+ if (!runtime.retiring) {
291
+ marker.runtime = { ...runtime, retiring: true };
292
+ const staging = join(directory, `.owner-${randomUUID()}.json`);
293
+ const handle = await open(staging, 'wx', 0o600);
294
+ try {
295
+ await handle.writeFile(`${JSON.stringify(marker)}\n`);
296
+ await handle.sync();
297
+ }
298
+ finally {
299
+ await handle.close();
300
+ }
301
+ await rename(staging, join(directory, scratchMarkerName));
302
+ }
303
+ const children = await readdir(runtime.directory, { encoding: 'buffer' });
304
+ const attributed = children.some((child) => child.toString() === runtimeMarkerName);
305
+ if (!attributed && children.length)
306
+ reject('unrecognized');
307
+ if (attributed) {
308
+ await validateRuntime(marker, marker.runtime, true);
309
+ for (const child of children) {
310
+ if (child.toString() !== runtimeMarkerName)
311
+ await rm(payloadPath(runtime.directory, child), { recursive: true });
312
+ }
313
+ await validateRuntime(marker, marker.runtime, true);
314
+ await rm(join(runtime.directory, runtimeMarkerName));
315
+ }
316
+ if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
317
+ reject('unsafe');
318
+ await rmdir(runtime.directory);
319
+ }
320
+ async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized, authorizedOwnerId) {
206
321
  if (authorized && !authorized())
207
322
  reject('protected');
208
323
  const within = (root, path) => {
@@ -211,7 +326,10 @@ export class FilesystemScratchCleanup {
211
326
  };
212
327
  for (const session of protectedSessions()) {
213
328
  // Only this exact targeted owner's authorized Forget may exclude itself.
214
- if (authorized && marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
329
+ if (authorized &&
330
+ marker.ownerId === authorizedOwnerId &&
331
+ marker.ownerKind === 'mobile-session' &&
332
+ session.id === marker.sessionId)
215
333
  continue;
216
334
  if (marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
217
335
  reject('protected');
@@ -227,7 +345,7 @@ export class FilesystemScratchCleanup {
227
345
  }
228
346
  for (const workspace of paths) {
229
347
  const scratch = join(workspace, 'tmp', 'sessions', mobileScratchOwnerId(session.id));
230
- if ([directory, logicalDirectory].some((owner) => within(owner, workspace) || within(owner, scratch)))
348
+ if ([directory, logicalDirectory, ...(marker.runtime ? [marker.runtime.directory] : [])].some((owner) => within(owner, workspace) || within(owner, scratch)))
231
349
  reject('protected');
232
350
  }
233
351
  }
@@ -243,15 +361,23 @@ export class FilesystemScratchCleanup {
243
361
  reject('unrecognized');
244
362
  for (const entry of await readdir(directory, { encoding: 'buffer', withFileTypes: true })) {
245
363
  const child = entry.name;
364
+ if (child.toString() === workspacePublicationName)
365
+ reject('busy');
246
366
  if (++budget.entries > 100_000)
247
367
  reject('unrecognized');
248
368
  if (directory !== root &&
249
- [scratchMarkerName, '.controller-lock', '.association-lock', containmentFenceName].includes(child.toString()))
369
+ [
370
+ scratchMarkerName,
371
+ runtimeMarkerName,
372
+ '.controller-lock',
373
+ '.association-lock',
374
+ containmentFenceName,
375
+ ].includes(child.toString()))
250
376
  reject('unrecognized');
251
377
  const path = payloadPath(directory, child);
252
378
  const info = await lstat(path);
253
379
  if ((process.getuid && info.uid !== process.getuid()) ||
254
- (!info.isDirectory() && !info.isFile() && !info.isSymbolicLink()) ||
380
+ (!info.isDirectory() && !info.isFile() && !info.isSymbolicLink() && !info.isSocket()) ||
255
381
  (info.isFile() && info.nlink !== 1))
256
382
  reject('unsafe');
257
383
  // Payload symlinks (for example npm's .bin entries) are disposable links.
@@ -11,6 +11,7 @@ import { claimOwnerFence } from './owner-fence.js';
11
11
  import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
12
12
  export { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, scratchContextVariable, } from './scratch-filesystem.js';
13
13
  import { withScratchContainment } from './containment-fence.js';
14
+ import { allocateRuntime, validateRuntime } from './runtime-root.js';
14
15
  function validId(value) {
15
16
  if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(value))
16
17
  throw new Error('SESSION_SCRATCH_INVALID_ID');
@@ -18,7 +19,9 @@ function validId(value) {
18
19
  function validateMarker(value, expected) {
19
20
  const marker = value;
20
21
  if (!marker ||
21
- marker.schemaVersion !== 1 ||
22
+ ![1, 2].includes(marker.schemaVersion) ||
23
+ (marker.schemaVersion === 1 && marker.runtime !== undefined) ||
24
+ (marker.schemaVersion === 2 && !marker.runtime) ||
22
25
  marker.ownerKind !== expected.ownerKind ||
23
26
  marker.ownerId !== expected.ownerId ||
24
27
  marker.workspacePath !== expected.workspacePath ||
@@ -46,7 +49,7 @@ export class FilesystemSessionScratch {
46
49
  async borrow(session) {
47
50
  validId(session.id);
48
51
  this.assertAvailable(session.id);
49
- return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
52
+ return this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
50
53
  this.assertAvailable(session.id);
51
54
  const { context, releaseFence } = await this.prepare(session);
52
55
  try {
@@ -120,7 +123,7 @@ export class FilesystemSessionScratch {
120
123
  /** One lease per owned service process, independent of its first caller. */
121
124
  async allocateService(workspacePath, consumer) {
122
125
  validId(consumer);
123
- return withScratchContainment(workspacePath, async () => {
126
+ return this.serialized(workspacePath, () => withScratchContainment(workspacePath, async () => {
124
127
  const leaseId = randomUUID();
125
128
  const ownerId = `service-${randomUUID()}`;
126
129
  const { context, releaseFence } = await this.prepare({ id: ownerId, workspacePath }, leaseId);
@@ -191,7 +194,7 @@ export class FilesystemSessionScratch {
191
194
  released = true;
192
195
  },
193
196
  };
194
- });
197
+ }));
195
198
  }
196
199
  async serialized(key, operation) {
197
200
  const previous = this.pending.get(key);
@@ -208,7 +211,7 @@ export class FilesystemSessionScratch {
208
211
  async allocate(session) {
209
212
  validId(session.id);
210
213
  this.assertAvailable(session.id);
211
- return this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
214
+ return this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
212
215
  this.assertAvailable(session.id);
213
216
  const { context, releaseFence } = await this.prepare(session);
214
217
  try {
@@ -226,7 +229,7 @@ export class FilesystemSessionScratch {
226
229
  validId(threadId);
227
230
  if (!['codex', 'kimi'].includes(provider))
228
231
  throw new Error('SESSION_SCRATCH_INVALID_PROVIDER');
229
- await this.serialized(`${session.workspacePath}\0${session.id}`, () => withScratchContainment(session.workspacePath, async () => {
232
+ await this.serialized(session.workspacePath, () => withScratchContainment(session.workspacePath, async () => {
230
233
  this.assertAvailable(session.id);
231
234
  const { context, marker, releaseFence } = await this.prepare(session);
232
235
  try {
@@ -301,7 +304,7 @@ export class FilesystemSessionScratch {
301
304
  try {
302
305
  const markerPath = join(directory, scratchMarkerName);
303
306
  const expected = {
304
- schemaVersion: 1,
307
+ schemaVersion: process.platform === 'win32' ? 1 : 2,
305
308
  ownerKind: leaseId ? 'workspace-service' : 'mobile-session',
306
309
  ownerId,
307
310
  workspacePath,
@@ -315,6 +318,8 @@ export class FilesystemSessionScratch {
315
318
  let marker;
316
319
  if (created) {
317
320
  try {
321
+ if (expected.schemaVersion === 2)
322
+ expected.runtime = await allocateRuntime(expected);
318
323
  const handle = await open(markerPath, 'wx', 0o600);
319
324
  try {
320
325
  await handle.writeFile(`${JSON.stringify(expected)}\n`);
@@ -334,21 +339,25 @@ export class FilesystemSessionScratch {
334
339
  else {
335
340
  marker = validateMarker(await readMarker(markerPath), expected);
336
341
  }
342
+ if (marker.schemaVersion === 2)
343
+ await validateRuntime(marker, marker.runtime);
337
344
  await privateDirectory(directory, false);
345
+ const runtimeDirectory = marker.runtime?.directory ?? directory;
338
346
  const context = {
339
347
  workspacePath,
340
348
  ownerId,
341
349
  directory,
342
350
  environment: {
343
- TMPDIR: directory,
344
- TMP: directory,
345
- TEMP: directory,
351
+ TMPDIR: runtimeDirectory,
352
+ TMP: runtimeDirectory,
353
+ TEMP: runtimeDirectory,
346
354
  [scratchContextVariable]: JSON.stringify({
347
- schemaVersion: 1,
355
+ schemaVersion: marker.schemaVersion,
348
356
  workspacePath,
349
357
  ownerId,
350
358
  directory,
351
359
  markerPath,
360
+ ...(marker.runtime ? { runtime: marker.runtime } : {}),
352
361
  }),
353
362
  },
354
363
  };
@@ -4,10 +4,13 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { lstatSync, mkdirSync, realpathSync, renameSync } from 'node:fs';
7
- import { lstat, rm } from 'node:fs/promises';
7
+ import { lstat, readdir, rm } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
9
9
  import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
10
10
  import { canonicalSessionWorkspace, workspaceContains, } from '../persistence/sqlite-workspace-lifecycle.js';
11
+ import { FilesystemScratchCleanup } from './filesystem-scratch-cleanup.js';
12
+ import { claimWorkspacePublication } from './workspace-publication.js';
13
+ import { hasRuntimeOwner } from './runtime-root.js';
11
14
  /** Final Forget owns the entire selected workspace's explicitly disposable tmp directory. */
12
15
  export class FilesystemWorkspaceForget {
13
16
  db;
@@ -24,20 +27,73 @@ export class FilesystemWorkspaceForget {
24
27
  if (workspaceContains(temporary, canonicalSessionWorkspace(other.workspacePath)))
25
28
  throw new WorkspaceSessionConflict('SESSION_NESTED_WORKSPACE', other.id);
26
29
  }
27
- const retired = this.retire(session, operationId, workspace, temporary, authorized);
28
- if (retired)
29
- await rm(retired, { recursive: true, force: true, maxRetries: 3 });
30
- // A non-cooperating external publisher must not turn retained files into a
31
- // successful final Forget. New Mobile starts remain durably fenced.
32
30
  try {
33
- await lstat(temporary);
31
+ await lstat(workspace);
32
+ }
33
+ catch (error) {
34
+ if (error.code !== 'ENOENT')
35
+ throw error;
36
+ await new FilesystemScratchCleanup().cleanSession(session, authorized, knownSessions);
37
+ return;
38
+ }
39
+ // Keep the physical publication fence through durable finalization. It is
40
+ // outside tmp, so a retiring namespace cannot hide it from new publishers.
41
+ const release = await claimWorkspacePublication(workspace);
42
+ try {
43
+ const cleanup = new FilesystemScratchCleanup();
44
+ await cleanup.retireNestedNamespaces(temporary, knownSessions, authorized, session.id, undefined, true);
45
+ const counts = await cleanup.cleanWorkspace(workspace, knownSessions, undefined, authorized, session.id);
46
+ if (counts.skipped || counts.failed)
47
+ throw new Error('SESSION_CLEANUP_FAILED');
48
+ if (process.getuid && (await hasRuntimeOwner({ workspacePath: workspace })))
49
+ throw new Error('SESSION_CLEANUP_FAILED');
50
+ const retired = this.retire(session, operationId, workspace, temporary, authorized);
51
+ if (retired) {
52
+ await this.assertRetired(retired);
53
+ await rm(retired, { recursive: true, force: true, maxRetries: 3 });
54
+ }
55
+ // A non-cooperating external publisher must not turn retained files into a
56
+ // successful final Forget. New Mobile starts remain durably fenced.
57
+ try {
58
+ await lstat(temporary);
59
+ }
60
+ catch (error) {
61
+ if (error.code === 'ENOENT')
62
+ return { release };
63
+ throw error;
64
+ }
65
+ throw new Error('SESSION_CLEANUP_FAILED');
66
+ }
67
+ catch (error) {
68
+ await release();
69
+ throw error;
70
+ }
71
+ }
72
+ async assertRetired(directory, depth = 0, budget = { entries: 0 }) {
73
+ if (depth > 128)
74
+ throw new Error('SESSION_CLEANUP_FAILED');
75
+ let entries;
76
+ try {
77
+ entries = await readdir(directory, { encoding: 'buffer', withFileTypes: true });
34
78
  }
35
79
  catch (error) {
36
80
  if (error.code === 'ENOENT')
37
81
  return;
38
82
  throw error;
39
83
  }
40
- throw new Error('SESSION_CLEANUP_FAILED');
84
+ for (const entry of entries) {
85
+ if (++budget.entries > 100000 ||
86
+ [
87
+ '.gestalt-owner.json',
88
+ '.gestalt-runtime.json',
89
+ '.controller-lock',
90
+ '.containment-lock',
91
+ '.gestalt-scratch-lock',
92
+ ].includes(entry.name.toString()))
93
+ throw new Error('SESSION_CLEANUP_FAILED');
94
+ if (entry.isDirectory() && !entry.isSymbolicLink())
95
+ await this.assertRetired(Buffer.concat([Buffer.from(directory), Buffer.from('/'), entry.name]), depth + 1, budget);
96
+ }
41
97
  }
42
98
  retire(session, operationId, workspace, temporary, authorized) {
43
99
  // The short synchronous transaction atomically checks authority and moves
@@ -6,6 +6,7 @@
6
6
  import { lstat, readdir, realpath } from 'node:fs/promises';
7
7
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
8
8
  import { mobileScratchOwnerId, privateDirectory, readMarker, scratchMarkerName, } from './scratch-filesystem.js';
9
+ import { runtimeMarkerName, validateRuntime } from './runtime-root.js';
9
10
  export const scratchUuidPattern = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
10
11
  const ownerPattern = `(?:mobile-[0-9a-f]{64}|(?:cli|service)-${scratchUuidPattern})`;
11
12
  const ownerName = new RegExp(`^${ownerPattern}$`);
@@ -44,7 +45,9 @@ export async function readManagedScratchOwner(directory, workspacePath, ownerId)
44
45
  throw error;
45
46
  }
46
47
  if (!marker ||
47
- marker.schemaVersion !== 1 ||
48
+ ![1, 2].includes(marker.schemaVersion) ||
49
+ (marker.schemaVersion === 1 && marker.runtime !== undefined) ||
50
+ (marker.schemaVersion === 2 && !marker.runtime) ||
48
51
  marker.ownerId !== ownerId ||
49
52
  marker.workspacePath !== workspacePath ||
50
53
  !validTime(marker.createdAt) ||
@@ -96,8 +99,21 @@ export async function readManagedScratchAttribution(directory, allowRetired = fa
96
99
  await privateDirectory(container, false);
97
100
  await privateDirectory(directory, false);
98
101
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
102
+ if (marker.runtime)
103
+ await validateRuntime(marker, marker.runtime, allowRetired);
99
104
  return { directory, workspacePath, ownerId, marker };
100
105
  }
106
+ /** A runtime locator is not authority until the durable owner binds it back. */
107
+ export async function readRuntimeScratchAttribution(runtimeDirectory) {
108
+ await privateDirectory(runtimeDirectory, false);
109
+ const locator = (await readMarker(join(runtimeDirectory, runtimeMarkerName)));
110
+ if (!locator || !isAbsolute(locator.workspacePath) || !ownerName.test(locator.ownerId))
111
+ rejectOwner();
112
+ const owner = await readManagedScratchAttribution(join(locator.workspacePath, 'tmp', 'sessions', locator.ownerId));
113
+ if (owner.marker.runtime?.directory !== runtimeDirectory)
114
+ rejectOwner();
115
+ return owner;
116
+ }
101
117
  function rejectLease() {
102
118
  throw new Error('SESSION_SCRATCH_LEASE_INVALID');
103
119
  }