gestalt-mobile 0.65.7 → 0.66.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 (55) hide show
  1. package/README.md +22 -0
  2. package/dist/client/assets/index-BDsGojoG.js +128 -0
  3. package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +2 -1
  6. package/dist/server/server/composition.contracts.js +179 -84
  7. package/dist/server/server/composition.js +65 -5
  8. package/dist/server/server/features/autopilot/application/service.js +19 -2
  9. package/dist/server/server/features/autopilot/domain/supervision-protocol.js +3 -0
  10. package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
  11. package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
  12. package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
  13. package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
  14. package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
  15. package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
  16. package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
  17. package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
  18. package/dist/server/server/features/sessions/register-routes.js +29 -2
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
  21. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
  22. package/dist/server/server/platform/codex/codex-playwright.js +41 -3
  23. package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
  24. package/dist/server/server/platform/codex/codex-serena.js +2 -1
  25. package/dist/server/server/platform/codex/managed-playwright.js +48 -36
  26. package/dist/server/server/platform/codex/session-runtime.js +134 -4
  27. package/dist/server/server/platform/git/command.js +7 -1
  28. package/dist/server/server/platform/host-tests/runner.js +47 -6
  29. package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
  30. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
  31. package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
  32. package/dist/server/server/platform/persistence/migrate.js +24 -0
  33. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
  34. package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
  35. package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
  36. package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
  37. package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
  38. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  39. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
  40. package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +72 -2
  41. package/dist/server/server/platform/retrieval/xerj-indexer.js +104 -48
  42. package/dist/server/server/platform/scratch/child-environment.js +21 -0
  43. package/dist/server/server/platform/scratch/containment-fence.js +262 -0
  44. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +245 -0
  45. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
  46. package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
  47. package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
  48. package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
  49. package/dist/server/server/platform/scratch/owner-fence.js +27 -0
  50. package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
  51. package/dist/server/server/platform/self-debug/workspace.js +3 -0
  52. package/dist/server/shared/contracts/session-forget.js +6 -0
  53. package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
  54. package/package.json +1 -1
  55. package/dist/client/assets/index-CKJWzSwH.js +0 -128
@@ -0,0 +1,262 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { constants } from 'node:fs';
7
+ import { lstat, mkdir, open, realpath, rmdir } from 'node:fs/promises';
8
+ import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
9
+ import { canonicalScratchWorkspace, readManagedScratchAttribution, readManagedScratchLeases, } from './managed-scratch-owner.js';
10
+ import { privateDirectory } from './scratch-filesystem.js';
11
+ export const containmentFenceName = '.containment-lock';
12
+ const same = (left, right) => left.dev === right.dev && left.ino === right.ino && left.birth === right.birth;
13
+ async function directoryIdentity(path) {
14
+ const info = await lstat(path, { bigint: true });
15
+ if (!info.isDirectory() || info.isSymbolicLink())
16
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
17
+ return { dev: info.dev, ino: info.ino, birth: info.birthtimeNs };
18
+ }
19
+ async function ancestorIdentity(directory, allowRetired) {
20
+ let owner;
21
+ try {
22
+ owner = await readManagedScratchAttribution(directory, allowRetired);
23
+ await readManagedScratchLeases(directory, owner.marker);
24
+ }
25
+ catch (error) {
26
+ if (error instanceof Error &&
27
+ (error.message.startsWith('SESSION_SCRATCH_') || error.message.startsWith('SCRATCH_CLEANUP_')))
28
+ throw error;
29
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID', { cause: error });
30
+ }
31
+ const marker = owner.marker;
32
+ return {
33
+ directory,
34
+ ownerId: owner.ownerId,
35
+ identity: await directoryIdentity(directory),
36
+ provenance: JSON.stringify([
37
+ marker.schemaVersion,
38
+ marker.ownerKind,
39
+ marker.ownerId,
40
+ marker.workspacePath,
41
+ marker.sessionId,
42
+ marker.createdAt,
43
+ marker.authority.kind,
44
+ marker.authority.sessionId ?? null,
45
+ marker.authority.leaseId ?? null,
46
+ ]),
47
+ };
48
+ }
49
+ async function assertClaimIdentity(claim) {
50
+ if (claim.handle) {
51
+ const held = await claim.handle.stat({ bigint: true });
52
+ if (!same(claim.identity, { dev: held.dev, ino: held.ino, birth: held.birthtimeNs }))
53
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_FENCE_CHANGED');
54
+ }
55
+ if (!same(claim.identity, await directoryIdentity(claim.path)))
56
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_FENCE_CHANGED');
57
+ }
58
+ async function releaseClaim(claim, retire) {
59
+ if (claim.attempted)
60
+ return;
61
+ claim.attempted = true;
62
+ try {
63
+ await assertClaimIdentity(claim);
64
+ await rmdir(claim.path);
65
+ // Cleanup has already retired the marker. Keep the acquired directory FD
66
+ // open through removal of the now-empty registered removal namespace.
67
+ await retire?.();
68
+ }
69
+ finally {
70
+ await claim.handle?.close();
71
+ }
72
+ }
73
+ async function releaseClaims(claims) {
74
+ let failure;
75
+ for (const claim of [...claims].reverse()) {
76
+ try {
77
+ await releaseClaim(claim);
78
+ }
79
+ catch (error) {
80
+ failure ??= error;
81
+ }
82
+ }
83
+ if (failure)
84
+ throw failure;
85
+ }
86
+ /** Interoperates with Launcher scratchWithContainment; no PID/age recovery. */
87
+ export async function claimScratchContainment(workspace, cleanupOwnerId) {
88
+ let selected = await canonicalScratchWorkspace(workspace);
89
+ const selectedIdentity = await directoryIdentity(selected);
90
+ 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);
104
+ }
105
+ }
106
+ const claims = [];
107
+ const revalidate = async () => {
108
+ await canonicalScratchWorkspace(selected);
109
+ if (!same(selectedIdentity, await directoryIdentity(selected)))
110
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
111
+ for (const ancestor of ancestors) {
112
+ const current = await ancestorIdentity(ancestor.directory, ancestor.directory === selected && cleanupOwnerId !== undefined);
113
+ if (!same(ancestor.identity, current.identity) || ancestor.provenance !== current.provenance)
114
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
115
+ }
116
+ for (const claim of claims)
117
+ if (!claim.attempted)
118
+ await assertClaimIdentity(claim);
119
+ };
120
+ try {
121
+ // Ancestors are discovered in path order. Containment always precedes the
122
+ // owner's controller/association operation, and never spans a service lifetime.
123
+ for (const ancestor of ancestors) {
124
+ const path = join(ancestor.directory, containmentFenceName);
125
+ try {
126
+ await mkdir(path, { mode: 0o700 });
127
+ }
128
+ catch (error) {
129
+ if (error.code === 'EEXIST')
130
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_BUSY');
131
+ throw error;
132
+ }
133
+ const claim = {
134
+ directory: ancestor.directory,
135
+ path,
136
+ identity: await directoryIdentity(path),
137
+ attempted: false,
138
+ };
139
+ claims.push(claim);
140
+ await privateDirectory(path, false);
141
+ claim.handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
142
+ const held = await claim.handle.stat({ bigint: true });
143
+ if (!same(claim.identity, { dev: held.dev, ino: held.ino, birth: held.birthtimeNs }))
144
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_FENCE_CHANGED');
145
+ const current = await ancestorIdentity(ancestor.directory, ancestor.directory === selected && cleanupOwnerId !== undefined);
146
+ if (!same(ancestor.identity, current.identity) || ancestor.provenance !== current.provenance)
147
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
148
+ }
149
+ await revalidate();
150
+ }
151
+ catch (error) {
152
+ await releaseClaims(claims);
153
+ throw error;
154
+ }
155
+ return {
156
+ revalidate,
157
+ async relocate(from, to) {
158
+ const ancestor = ancestors.find((value) => value.directory === from);
159
+ const claim = claims.find((value) => value.directory === from);
160
+ if (selected !== from || !cleanupOwnerId || !ancestor || !claim)
161
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
162
+ await privateDirectory(to, false);
163
+ if (!same(ancestor.identity, await directoryIdentity(to)))
164
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
165
+ selected = to;
166
+ ancestor.directory = to;
167
+ claim.directory = to;
168
+ claim.path = join(to, containmentFenceName);
169
+ },
170
+ async retireCurrent(at, remove) {
171
+ const claim = claims.at(-1);
172
+ const ancestor = ancestors.at(-1);
173
+ if (!cleanupOwnerId ||
174
+ !claim ||
175
+ !ancestor ||
176
+ claim.directory !== at ||
177
+ !same(ancestor.identity, await directoryIdentity(at)))
178
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
179
+ await releaseClaim(claim, remove);
180
+ },
181
+ release: () => releaseClaims(claims),
182
+ };
183
+ }
184
+ export async function withScratchContainment(workspace, publish) {
185
+ const guard = await claimScratchContainment(workspace);
186
+ try {
187
+ return await publish();
188
+ }
189
+ finally {
190
+ await guard.release();
191
+ }
192
+ }
193
+ /** Detached history may outlive its cwd; publishing it never allocates scratch. */
194
+ export async function withHistoryScratchContainment(workspace, publish) {
195
+ if (!isAbsolute(workspace))
196
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
197
+ try {
198
+ await directoryIdentity(workspace);
199
+ return withScratchContainment(workspace, publish);
200
+ }
201
+ catch (error) {
202
+ if (error.code !== 'ENOENT')
203
+ throw error;
204
+ }
205
+ if (workspace !== resolve(workspace))
206
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
207
+ let existing = workspace;
208
+ let missing = workspace;
209
+ let identity;
210
+ for (;;) {
211
+ try {
212
+ identity = await directoryIdentity(existing);
213
+ break;
214
+ }
215
+ catch (error) {
216
+ if (error.code !== 'ENOENT')
217
+ throw error;
218
+ missing = existing;
219
+ const parent = dirname(existing);
220
+ if (parent === existing)
221
+ throw error;
222
+ existing = parent;
223
+ }
224
+ }
225
+ // This prefix is only observed: system-owned ordinary ancestors (including /)
226
+ // do not acquire session ownership or become allocation/deletion targets.
227
+ const revalidate = async () => {
228
+ if ((await realpath(existing)) !== existing ||
229
+ !same(identity, await directoryIdentity(existing)))
230
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
231
+ const absent = await lstat(missing).then(() => false, (error) => {
232
+ if (error.code !== 'ENOENT')
233
+ throw error;
234
+ return true;
235
+ });
236
+ if (!absent)
237
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_CHANGED');
238
+ };
239
+ await revalidate();
240
+ let deepestOwner;
241
+ let ownerCount = 0;
242
+ const parts = workspace.slice(parse(workspace).root.length).split(sep).filter(Boolean);
243
+ let directory = parse(workspace).root;
244
+ for (let index = 0; index < parts.length; index++) {
245
+ directory = join(directory, parts[index]);
246
+ if (index >= 2 && parts[index - 1] === 'sessions' && parts[index - 2] === 'tmp') {
247
+ if (++ownerCount > 64)
248
+ throw new Error('SESSION_SCRATCH_CONTAINMENT_INVALID');
249
+ deepestOwner = directory;
250
+ }
251
+ }
252
+ // Scan the full lexical target, even beyond the missing frontier. Claiming the
253
+ // deepest owner validates every reserved ancestor; absent/unknown owners fail.
254
+ const guard = deepestOwner ? await claimScratchContainment(deepestOwner) : undefined;
255
+ try {
256
+ await revalidate();
257
+ return await publish();
258
+ }
259
+ finally {
260
+ await guard?.release();
261
+ }
262
+ }
@@ -0,0 +1,245 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { lstat, mkdir, opendir, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
8
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
+ import { emptyScratchCounts, } from '../../features/sessions/clean-tmp/use-case.js';
10
+ import { mobileScratchOwnerId, privateDirectory, scratchMarkerName } from './scratch-filesystem.js';
11
+ import { claimOwnerFence } from './owner-fence.js';
12
+ import { isAmbiguousLegacyScratch } from './legacy-scratch-layouts.js';
13
+ import { canonicalScratchWorkspace, managedScratchOwnerId, readManagedScratchOwner, readManagedScratchLeases, } from './managed-scratch-owner.js';
14
+ import { claimScratchContainment, containmentFenceName } from './containment-fence.js';
15
+ function reject(reason) {
16
+ throw new Error(`SCRATCH_CLEANUP_${reason}`);
17
+ }
18
+ /** Only the managed namespace is traversed. There are no prefix/age/PID legacy recognizers. */
19
+ export class FilesystemScratchCleanup {
20
+ async cleanSession(session, authorized, protectedSessions) {
21
+ const counts = await this.cleanWorkspace(session.workspacePath, protectedSessions, mobileScratchOwnerId(session.id), authorized);
22
+ if (counts.skipped || counts.failed)
23
+ throw new Error('SESSION_CLEANUP_FAILED');
24
+ }
25
+ async canonicalWorkspace(path) {
26
+ return canonicalScratchWorkspace(path);
27
+ }
28
+ async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized) {
29
+ await this.canonicalWorkspace(workspacePath);
30
+ const counts = emptyScratchCounts();
31
+ const temporary = join(workspacePath, 'tmp');
32
+ try {
33
+ const info = await lstat(temporary);
34
+ if (!info.isDirectory() ||
35
+ info.isSymbolicLink() ||
36
+ (await realpath(temporary)) !== temporary ||
37
+ (process.getuid && info.uid !== process.getuid()))
38
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
39
+ }
40
+ catch (error) {
41
+ if (error.code === 'ENOENT')
42
+ return counts;
43
+ throw error;
44
+ }
45
+ if (!onlyOwnerId) {
46
+ for (const entry of await readdir(temporary, { withFileTypes: true })) {
47
+ if (!isAmbiguousLegacyScratch(entry.name) ||
48
+ (!entry.isDirectory() && !entry.isSymbolicLink()))
49
+ continue;
50
+ counts.skipped++;
51
+ counts.reasons[entry.isSymbolicLink() ? 'unsafe' : 'unrecognized']++;
52
+ }
53
+ }
54
+ const container = join(temporary, 'sessions');
55
+ try {
56
+ await privateDirectory(container, false);
57
+ }
58
+ catch (error) {
59
+ if (error.code === 'ENOENT')
60
+ return counts;
61
+ throw error;
62
+ }
63
+ for (const name of await readdir(container)) {
64
+ if (name === '.gitignore')
65
+ continue;
66
+ if (onlyOwnerId && managedScratchOwnerId(name) !== onlyOwnerId)
67
+ continue;
68
+ let release;
69
+ let containment;
70
+ let directory = join(container, name);
71
+ let outcome;
72
+ try {
73
+ const ownerId = managedScratchOwnerId(name);
74
+ if (!ownerId)
75
+ reject('unrecognized');
76
+ await privateDirectory(directory, false);
77
+ // A removal reservation/partial allocation is not an owner yet. Inspect
78
+ // its locator before claiming a fence; authority is rechecked below.
79
+ await readManagedScratchOwner(directory, workspacePath, ownerId);
80
+ containment = await claimScratchContainment(directory, ownerId);
81
+ release = await claimOwnerFence(directory);
82
+ const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
83
+ await this.releasedLeases(directory, marker);
84
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
85
+ await this.noLinks(directory);
86
+ await privateDirectory(directory, false);
87
+ await containment.revalidate();
88
+ if (name === ownerId) {
89
+ const retired = join(container, `.cleanup-${ownerId}-${randomUUID()}`);
90
+ // Reserve the random destination exclusively; never replace a collision.
91
+ await mkdir(retired, { mode: 0o700 });
92
+ try {
93
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
94
+ }
95
+ catch (error) {
96
+ await rmdir(retired);
97
+ throw error;
98
+ }
99
+ await rename(directory, retired);
100
+ directory = retired;
101
+ // The fence moved with the owner. Never release a replacement at its old path.
102
+ const claimed = release;
103
+ release = () => claimed(retired);
104
+ await containment.relocate(join(container, name), retired);
105
+ }
106
+ await privateDirectory(directory, false);
107
+ await containment.revalidate();
108
+ await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized);
109
+ // Keep authority metadata until disposable payload has been removed. A failed
110
+ // payload deletion is retryable; an interrupted metadata retirement is unknown.
111
+ for (const child of await readdir(directory)) {
112
+ if ([scratchMarkerName, 'leases', '.controller-lock', containmentFenceName].includes(child))
113
+ continue;
114
+ await rm(join(directory, child), { recursive: true });
115
+ }
116
+ if ((await readdir(directory)).includes('leases'))
117
+ await rm(join(directory, 'leases'), { recursive: true });
118
+ await rm(join(directory, scratchMarkerName));
119
+ // With marker/payload retired, no publisher can validate this namespace.
120
+ // Remove only our own fence instances, then the still-empty owner directory.
121
+ await release();
122
+ release = undefined;
123
+ await containment.retireCurrent(directory, () => rmdir(directory));
124
+ counts.removed++;
125
+ outcome = 'removed';
126
+ }
127
+ catch (error) {
128
+ const code = error.code;
129
+ const message = error instanceof Error ? error.message : '';
130
+ const reason = message.startsWith('SCRATCH_CLEANUP_')
131
+ ? message.slice('SCRATCH_CLEANUP_'.length)
132
+ : error instanceof SyntaxError
133
+ ? 'unrecognized'
134
+ : message === 'SESSION_SCRATCH_LEASE_INVALID'
135
+ ? 'lease'
136
+ : ['SESSION_SCRATCH_BUSY', 'SESSION_SCRATCH_CONTAINMENT_BUSY'].includes(message)
137
+ ? 'busy'
138
+ : message.startsWith('SESSION_SCRATCH_') ||
139
+ ['ELOOP', 'ENOTDIR'].includes(code ?? '')
140
+ ? 'unsafe'
141
+ : code === 'ENOENT'
142
+ ? 'busy'
143
+ : 'io';
144
+ counts.reasons[reason]++;
145
+ outcome = reason === 'io' ? 'failed' : 'skipped';
146
+ counts[outcome]++;
147
+ }
148
+ finally {
149
+ if (release) {
150
+ try {
151
+ await release();
152
+ }
153
+ catch {
154
+ if (outcome !== 'failed') {
155
+ if (outcome)
156
+ counts[outcome]--;
157
+ counts.failed++;
158
+ outcome = 'failed';
159
+ }
160
+ counts.reasons.io++;
161
+ }
162
+ }
163
+ if (containment) {
164
+ try {
165
+ await containment.release();
166
+ }
167
+ catch {
168
+ if (outcome !== 'failed') {
169
+ if (outcome)
170
+ counts[outcome]--;
171
+ counts.failed++;
172
+ outcome = 'failed';
173
+ }
174
+ counts.reasons.io++;
175
+ }
176
+ }
177
+ }
178
+ }
179
+ return counts;
180
+ }
181
+ async releasedLeases(directory, marker) {
182
+ if ((await readdir(directory)).includes('.association-lock'))
183
+ reject('busy');
184
+ const leases = await readManagedScratchLeases(directory, marker);
185
+ if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0))
186
+ reject('lease');
187
+ }
188
+ async assertProtection(directory, logicalDirectory, marker, protectedSessions, authorized) {
189
+ if (authorized && !authorized())
190
+ reject('protected');
191
+ const within = (root, path) => {
192
+ const suffix = relative(root, path);
193
+ return (suffix === '' || (!isAbsolute(suffix) && suffix !== '..' && !suffix.startsWith(`..${sep}`)));
194
+ };
195
+ for (const session of protectedSessions()) {
196
+ // Only this exact targeted owner's authorized Forget may exclude itself.
197
+ if (authorized && marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
198
+ continue;
199
+ if (marker.ownerKind === 'mobile-session' && session.id === marker.sessionId)
200
+ reject('protected');
201
+ if (!isAbsolute(session.workspacePath))
202
+ reject('unrecognized');
203
+ const paths = new Set([resolve(session.workspacePath)]);
204
+ try {
205
+ paths.add(await realpath(session.workspacePath));
206
+ }
207
+ catch {
208
+ // Durable canonical locators remain protective even after a retirement.
209
+ // Missing unrelated workspaces are reported by their own scan.
210
+ }
211
+ for (const workspace of paths) {
212
+ const scratch = join(workspace, 'tmp', 'sessions', mobileScratchOwnerId(session.id));
213
+ if ([directory, logicalDirectory].some((owner) => within(owner, workspace) || within(owner, scratch)))
214
+ reject('protected');
215
+ }
216
+ }
217
+ }
218
+ async noLinks(directory, root = directory, depth = 0, budget = { entries: 0 }) {
219
+ if (depth > 128)
220
+ reject('unrecognized');
221
+ // Even an empty nested namespace is not authority to retire a workspace's
222
+ // contents recursively as another owner's payload.
223
+ if (directory !== root &&
224
+ basename(directory) === 'sessions' &&
225
+ basename(dirname(directory)) === 'tmp')
226
+ reject('unrecognized');
227
+ for await (const entry of await opendir(directory)) {
228
+ const child = entry.name;
229
+ if (++budget.entries > 100_000)
230
+ reject('unrecognized');
231
+ if (directory !== root &&
232
+ [scratchMarkerName, '.controller-lock', '.association-lock', containmentFenceName].includes(child))
233
+ reject('unrecognized');
234
+ const path = join(directory, child);
235
+ const info = await lstat(path);
236
+ if (info.isSymbolicLink() ||
237
+ (process.getuid && info.uid !== process.getuid()) ||
238
+ (!info.isDirectory() && !info.isFile()) ||
239
+ (info.isFile() && info.nlink !== 1))
240
+ reject('unsafe');
241
+ if (info.isDirectory())
242
+ await this.noLinks(path, root, depth + 1, budget);
243
+ }
244
+ }
245
+ }