@cotal-ai/workspace 0.170.0 → 0.171.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.
@@ -0,0 +1,166 @@
1
+ import { type Stats } from "node:fs";
2
+ import { type Identity } from "@cotal-ai/core";
3
+ /** The persisted MANAGER INSTANCE identity (P2 item 3, SPEC 13.6 item 7): the LOGICAL instanceId
4
+ * (stable across restart, so a restart re-registers the SAME id with an ADVANCED epoch and the
5
+ * (i) fence bites) + the serve nkey identity (so re-registration reuses the SAME gate principal —
6
+ * provisionEndpointGateOpen stays idempotent, no core barrier change, and eviction targets a
7
+ * stable principal). Holds a private seed, so it lands in a HARDENED secret file in the space's
8
+ * segment of this root (see {@link rootIdentityFile}). */
9
+ export interface ManagerInstanceIdentity {
10
+ instanceId: string;
11
+ serveIdentity: {
12
+ id: string;
13
+ seed: string;
14
+ };
15
+ }
16
+ /** The nkey identity a persisted record holds at `v`, or undefined when `v` is not one: the check
17
+ * every identity record's `parse` applies to each nkey it holds. */
18
+ export declare function identityOf(v: unknown): Identity | undefined;
19
+ /** Load this workspace root's persisted manager instance identity for `space`, or undefined if a
20
+ * manager has never registered here. A present-but-MALFORMED file fails LOUD: minting a fresh id
21
+ * over it would orphan the prior registration and break the restart-fence guarantee, so a restart
22
+ * never silently becomes a fresh instance (no-fallbacks). */
23
+ export declare function loadManagerInstanceIdentity(root: string, space: string): ManagerInstanceIdentity | undefined;
24
+ /** First-start identity mint through {@link claimIdentityRecord}: of N concurrent creators on a
25
+ * fresh root, exactly one creates the file and the others adopt the winner. `mint` runs only when
26
+ * no record exists, so a restart does not mint a lifecycle uid and a serve nkey it then discards. */
27
+ export declare function createManagerInstanceIdentity(root: string, space: string, mint: () => ManagerInstanceIdentity): ManagerInstanceIdentity;
28
+ /** The manager's goal-writer and session-ledger nkeys for `space`. Both are siblings of the serve
29
+ * identity in its §13.1 credential family and persist for the same reason: the family never drops
30
+ * a row and every re-registration verify-evicts each holder it ever staged, so a fresh pair per
31
+ * boot made each restart sweep two more holders than the one before. */
32
+ export interface ManagerSiblingIdentities {
33
+ goalWriter: {
34
+ id: string;
35
+ seed: string;
36
+ };
37
+ sessionLedger: {
38
+ id: string;
39
+ seed: string;
40
+ };
41
+ }
42
+ /** This root's manager sibling identities for `space`, minted on the first start and read back on
43
+ * every later one through {@link claimIdentityRecord}, so concurrent first starts adopt one pair. */
44
+ export declare function claimManagerSiblingIdentities(root: string, space: string): ManagerSiblingIdentities;
45
+ /** The AUTH PLANE's persisted instance identity (#399 M2): a stable `instanceId` + serve nkey so
46
+ * a restart re-registers the SAME `svc.auth.<instanceId>` instance (`registerServiceInstance`
47
+ * advances the process epoch on a re-registration and fences the predecessor rather than minting
48
+ * a fresh, un-fenced one). Mirrors {@link ManagerInstanceIdentity} exactly; kept as its own type
49
+ * (not a reuse) because it is a distinct persisted principal for a distinct served endpoint. */
50
+ export interface AuthInstanceIdentity {
51
+ instanceId: string;
52
+ serveIdentity: {
53
+ id: string;
54
+ seed: string;
55
+ };
56
+ }
57
+ /** Load this workspace root's persisted auth-plane instance identity for `space`, or undefined if
58
+ * the auth plane has never registered here. A present-but-MALFORMED file fails LOUD: minting a
59
+ * fresh id over it would orphan the prior registration and break the restart-fence guarantee. */
60
+ export declare function loadAuthInstanceIdentity(root: string, space: string): AuthInstanceIdentity | undefined;
61
+ /** First-start identity mint for the auth plane, as {@link createManagerInstanceIdentity}. */
62
+ export declare function createAuthInstanceIdentity(root: string, space: string, mint: () => AuthInstanceIdentity): AuthInstanceIdentity;
63
+ /** Remove this root's auth-plane instance record for `space`. A hosted context calls it once its
64
+ * injected store holds the record, so the serve seed no longer sits in its state dir. */
65
+ export declare function removeAuthInstanceIdentity(root: string, space: string): void;
66
+ /** The outcome of {@link retireManagerInstanceIdentity}. `removed` means this call deleted the
67
+ * record that matched `expected`. `absent` means no record exists for the space: a retry after an
68
+ * earlier `removed`, or a record that was never created. It never reports that this call deleted
69
+ * anything, so a caller that cannot prove it created the record must not count it as retired. */
70
+ export type ManagerInstanceIdentityRetirement = {
71
+ outcome: "removed";
72
+ } | {
73
+ outcome: "absent";
74
+ };
75
+ /** Deterministic instrumentation hooks for testing concurrent retirement races. Hooks do not
76
+ * replace filesystem operations: each callback returns before the real rename or link runs. */
77
+ export interface RetireManagerInstanceIdentityOpts {
78
+ /** Invoked after the initial pre-check passes and immediately before `renameSync`. */
79
+ readonly onBeforeRename?: () => void;
80
+ /** Invoked if the captured record differs from expected, immediately before attempting `linkSync`. */
81
+ readonly onBeforeLinkBack?: () => void;
82
+ }
83
+ /**
84
+ * Delete this root's persisted manager instance identity for `space`, only when the stored record
85
+ * is the complete `expected` identity (instanceId, serve nkey id and serve seed).
86
+ *
87
+ * It refuses, throwing an error that starts with `manager-instance-identity-retire-refused`, when
88
+ * the entry is not regular, does not parse, is malformed, or holds another identity. A missing
89
+ * record returns `absent` and never establishes ownership. The record is renamed to a private name
90
+ * in its own directory and checked again there before deletion. A changed captured record is
91
+ * linked back only if the canonical path is still free; on a collision both records are preserved.
92
+ *
93
+ * This establishes only which record was deleted. It is not proof that a manager stopped: the
94
+ * caller must hold its own stop and ownership evidence before retiring. A normal restart keeps the
95
+ * identity, and retirement is for failed-new-space compensation or terminal retirement.
96
+ */
97
+ export declare function retireManagerInstanceIdentity(root: string, space: string, expected: ManagerInstanceIdentity, opts?: RetireManagerInstanceIdentityOpts): ManagerInstanceIdentityRetirement;
98
+ /**
99
+ * The per-seat WRITER GENERATION: which custody of one seat's identity is current.
100
+ *
101
+ * It is not a second identity. The seat's identity stays its `lifecycleUid`, unchanged across a
102
+ * move, because the durables are keyed by it and a resume must recover it. The generation says
103
+ * which host may write as that identity now, and it is monotonic, so it survives a clock that is
104
+ * wrong in a way a time-based lease does not.
105
+ *
106
+ * It follows the three rules {@link ManagerInstanceIdentity}'s file established:
107
+ * space-scoped by a hex key (an auth dir is a shared namespace and a raw space token can collide or
108
+ * case-fold), published by exclusive create, and loud on a malformed record rather than minted over,
109
+ * because minting over it is how a stale host would become authoritative again.
110
+ */
111
+ export interface SeatWriterGeneration {
112
+ readonly space: string;
113
+ readonly name: string;
114
+ readonly lifecycleUid: string;
115
+ readonly generation: number;
116
+ }
117
+ /**
118
+ * Claim a whole set of seat writer generations, or none of them.
119
+ *
120
+ * Each claim is its own exclusive create, so a later one can lose even when every earlier one
121
+ * succeeded. A claim is a create that can never be made again, so a partial set would let one
122
+ * refusal consume the retry over the very same input. This creates them in order and, on any
123
+ * failure, removes the files IT created in this call before rethrowing.
124
+ *
125
+ * The compensation is deliberately narrow. It unlinks by the exact path it wrote and nothing else,
126
+ * so it can never remove a generation another destination holds. An unlink that finds the file
127
+ * already gone is fine; any other unlink error is reported alongside the original failure rather
128
+ * than replacing it, because the original is why the operation is failing and the unlink error is
129
+ * why the tree is not clean.
130
+ *
131
+ * No lock, no retry, no fallback: a lost create still refuses the whole set.
132
+ */
133
+ export declare function claimSeatWriterGenerations(root: string, claims: readonly SeatWriterGeneration[]): readonly SeatWriterGeneration[];
134
+ /** The highest generation this host has claimed for a seat, or undefined when it never has.
135
+ * A present-but-malformed record fails LOUD, for the reason {@link loadManagerInstanceIdentity}
136
+ * gives: replacing it is how custody silently returns to a host that lost it. */
137
+ export declare function loadSeatWriterGeneration(root: string, space: string, name: string): SeatWriterGeneration | undefined;
138
+ /**
139
+ * Take custody of a seat at `claim.generation` by exclusive create, before anything launches.
140
+ *
141
+ * The publication primitive is {@link createManagerInstanceIdentity}'s, and the resolution of a
142
+ * lost create is deliberately NOT: that helper adopts the winner on EEXIST, because two managers
143
+ * sharing one logical instanceId is the intended outcome there. Here a lost create means two hosts
144
+ * are claiming one seat, which is the condition this fence exists to stop, so it refuses. Same
145
+ * primitive, opposite disposition.
146
+ */
147
+ export declare function advanceSeatWriterGeneration(root: string, claim: SeatWriterGeneration): SeatWriterGeneration;
148
+ /** The lstat of a trust path that holds an auth-material record, or undefined when it is absent:
149
+ * - a non-regular entry (symlink, directory, fifo) is REFUSED, never followed — nothing in this
150
+ * module writes one, so following it would trust material this module cannot vouch for (and
151
+ * enumeration counts the same entry as corrupt: one answer everywhere);
152
+ * - only ENOENT means absent; any other errno is uncertainty about trust material and throws. */
153
+ export declare function authRecordStat(f: string, what: string): Stats | undefined;
154
+ /** Read one auth-material record: the file's raw text, or undefined when absent. Shared by every
155
+ * load/save below so the readers cannot disagree: the entry is checked by {@link authRecordStat},
156
+ * and the JSON parse is wrapped so a truncated/hand-edited record surfaces as one legible sentence
157
+ * naming the file, never a raw SyntaxError deep in a caller. */
158
+ export declare function readAuthRecord<T>(f: string, what: string): T | undefined;
159
+ /**
160
+ * A persisted identity record of this root: the stored one, or on a fresh root `mint()`'s,
161
+ * published by exclusive create. Of N concurrent first mints exactly one creates the file and the
162
+ * others adopt it, so a loser never keeps the identity it minted in memory; an atomic rename would
163
+ * let it. A loser that cannot read the winner refuses with `identity-record-create-lost`.
164
+ */
165
+ export declare function claimIdentityRecord<T>(path: string, what: string, parse: (raw: unknown) => T | undefined, mint: () => T): T;
166
+ //# sourceMappingURL=auth-identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-identity.d.ts","sourceRoot":"","sources":["../src/auth-identity.ts"],"names":[],"mappings":"AAKA,OAAO,EAA8F,KAAK,KAAK,EAAE,MAAM,SAAS,CAAC;AAGjI,OAAO,EAAuD,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAGpG;;;;;2DAK2D;AAC3D,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC7C;AAED;qEACqE;AACrE,wBAAgB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,CAI3D;AAwCD;;;8DAG8D;AAC9D,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,uBAA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,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAe3H"}
@@ -0,0 +1,362 @@
1
+ /** A root's persisted identity records: the manager's instance and sibling identities, the auth
2
+ * plane's instance identity and the manager's retirement of its own, the per-seat writer
3
+ * generations, and the auth-record reader they and the trust records in `auth-paths.ts` share.
4
+ * `auth-paths.ts` re-exports every public name here, so importers keep their path. */
5
+ import { CommandFailure } from "./output.js";
6
+ import { existsSync, linkSync, lstatSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync } from "node:fs";
7
+ import { randomUUID } from "node:crypto";
8
+ import { join, dirname } from "node:path";
9
+ import { mkSecretDir, newIdentity, writeSecretFileCreateOnly } from "@cotal-ai/core";
10
+ import { authDir, spaceKey, spaceSegment, userAuthStateDir } from "./auth-paths.js";
11
+ const MANAGER_INSTANCE = "the manager instance identity";
12
+ /** The nkey identity a persisted record holds at `v`, or undefined when `v` is not one: the check
13
+ * every identity record's `parse` applies to each nkey it holds. */
14
+ export function identityOf(v) {
15
+ const k = v;
16
+ if (typeof k?.id !== "string" || k.id.length === 0 || typeof k.seed !== "string" || k.seed.length === 0)
17
+ return undefined;
18
+ return { id: k.id, seed: k.seed };
19
+ }
20
+ /** The shape both the manager and the auth plane persist as their instance identity. */
21
+ function instanceIdentityOf(raw) {
22
+ const r = raw;
23
+ const serveIdentity = identityOf(r?.serveIdentity);
24
+ if (typeof r?.instanceId !== "string" || r.instanceId.length === 0 || serveIdentity === undefined)
25
+ return undefined;
26
+ return { instanceId: r.instanceId, serveIdentity };
27
+ }
28
+ /** An identity record of this root, `<root>/.cotal/space.<hex>/<name>`. It is state of this root,
29
+ * so it stays out of `.cotal/auth`: that folder is what an operator copies to give another root a
30
+ * mesh's trust, and an identity copied with it made the other root's manager this root's logical
31
+ * instance. An older build kept the record at a `legacy` path; the first touch moves it here, so an
32
+ * upgraded root restarts as the same instance (SPEC 13.6). A `legacy` entry that is not a regular
33
+ * file is refused like the record itself, so a dangling link cannot pass for a fresh root and mint
34
+ * a new identity. */
35
+ function rootIdentityFile(root, space, name, ...legacy) {
36
+ const path = join(root, ".cotal", spaceSegment(space), name);
37
+ for (const from of legacy) {
38
+ if (!authRecordStat(from, "an identity record"))
39
+ continue;
40
+ mkSecretDir(dirname(path));
41
+ // A link, not a rename: it never replaces a record already at `path`, and a concurrent first
42
+ // touch that linked first is the same inode, which tells it apart from a second record.
43
+ try {
44
+ linkSync(from, path);
45
+ }
46
+ catch (e) {
47
+ const code = e.code;
48
+ if (code === "ENOENT")
49
+ continue;
50
+ if (code !== "EEXIST")
51
+ throw e;
52
+ // lstat, as the readers do: stat would follow a link on either side to the other's inode,
53
+ // pass the two entries as one record and remove the only regular copy.
54
+ const old = authRecordStat(from, "an identity record");
55
+ const current = authRecordStat(path, "an identity record");
56
+ if (old && (!current || old.ino !== current.ino || old.dev !== current.dev))
57
+ throw new Error(`both ${path} and the older ${from} hold an identity record for space "${space}" - refusing to guess which belongs to this root. Remove the one that did not come from this root, then retry.`);
58
+ }
59
+ rmSync(from, { force: true });
60
+ }
61
+ return path;
62
+ }
63
+ function managerInstanceFile(root, space) {
64
+ return rootIdentityFile(root, space, "manager-instance.json", join(authDir(root), `manager-instance.${spaceKey(space)}.json`));
65
+ }
66
+ /** Load this workspace root's persisted manager instance identity for `space`, or undefined if a
67
+ * manager has never registered here. A present-but-MALFORMED file fails LOUD: minting a fresh id
68
+ * over it would orphan the prior registration and break the restart-fence guarantee, so a restart
69
+ * never silently becomes a fresh instance (no-fallbacks). */
70
+ export function loadManagerInstanceIdentity(root, space) {
71
+ return readManagerInstanceRecord(managerInstanceFile(root, space));
72
+ }
73
+ /** First-start identity mint through {@link claimIdentityRecord}: of N concurrent creators on a
74
+ * fresh root, exactly one creates the file and the others adopt the winner. `mint` runs only when
75
+ * no record exists, so a restart does not mint a lifecycle uid and a serve nkey it then discards. */
76
+ export function createManagerInstanceIdentity(root, space, mint) {
77
+ return claimIdentityRecord(managerInstanceFile(root, space), MANAGER_INSTANCE, instanceIdentityOf, mint);
78
+ }
79
+ function managerSiblingFile(root, space) {
80
+ return rootIdentityFile(root, space, "manager-siblings.json", join(authDir(root), `manager-siblings.${spaceKey(space)}.json`));
81
+ }
82
+ function siblingIdentitiesOf(raw) {
83
+ const r = raw;
84
+ const goalWriter = identityOf(r?.goalWriter);
85
+ const sessionLedger = identityOf(r?.sessionLedger);
86
+ return goalWriter && sessionLedger ? { goalWriter, sessionLedger } : undefined;
87
+ }
88
+ /** This root's manager sibling identities for `space`, minted on the first start and read back on
89
+ * every later one through {@link claimIdentityRecord}, so concurrent first starts adopt one pair. */
90
+ export function claimManagerSiblingIdentities(root, space) {
91
+ return claimIdentityRecord(managerSiblingFile(root, space), "the manager sibling identities", siblingIdentitiesOf, () => ({ goalWriter: newIdentity(), sessionLedger: newIdentity() }));
92
+ }
93
+ const AUTH_INSTANCE = "the auth instance identity";
94
+ /** The auth plane's record sits beside the manager's. An older build kept it in `.cotal/auth` under
95
+ * the plane's state dir. For a CLI root that dir is the root's user-auth state dir, inside the folder
96
+ * an operator copies; a hosted context passes its state dir as the root, so its record sat in the
97
+ * root's own `.cotal/auth`. */
98
+ function authInstanceFile(root, space) {
99
+ const legacyName = `auth-instance.${spaceKey(space)}.json`;
100
+ return rootIdentityFile(root, space, "auth-instance.json", join(authDir(userAuthStateDir(root, space)), legacyName), join(authDir(root), legacyName));
101
+ }
102
+ /** Load this workspace root's persisted auth-plane instance identity for `space`, or undefined if
103
+ * the auth plane has never registered here. A present-but-MALFORMED file fails LOUD: minting a
104
+ * fresh id over it would orphan the prior registration and break the restart-fence guarantee. */
105
+ export function loadAuthInstanceIdentity(root, space) {
106
+ return readIdentityRecord(authInstanceFile(root, space), AUTH_INSTANCE, instanceIdentityOf);
107
+ }
108
+ /** First-start identity mint for the auth plane, as {@link createManagerInstanceIdentity}. */
109
+ export function createAuthInstanceIdentity(root, space, mint) {
110
+ return claimIdentityRecord(authInstanceFile(root, space), AUTH_INSTANCE, instanceIdentityOf, mint);
111
+ }
112
+ /** Remove this root's auth-plane instance record for `space`. A hosted context calls it once its
113
+ * injected store holds the record, so the serve seed no longer sits in its state dir. */
114
+ export function removeAuthInstanceIdentity(root, space) {
115
+ rmSync(authInstanceFile(root, space), { force: true });
116
+ }
117
+ function sameManagerInstanceIdentity(a, b) {
118
+ return a.instanceId === b.instanceId && a.serveIdentity.id === b.serveIdentity.id && a.serveIdentity.seed === b.serveIdentity.seed;
119
+ }
120
+ function readManagerInstanceRecord(f) {
121
+ return readIdentityRecord(f, MANAGER_INSTANCE, instanceIdentityOf);
122
+ }
123
+ /**
124
+ * Delete this root's persisted manager instance identity for `space`, only when the stored record
125
+ * is the complete `expected` identity (instanceId, serve nkey id and serve seed).
126
+ *
127
+ * It refuses, throwing an error that starts with `manager-instance-identity-retire-refused`, when
128
+ * the entry is not regular, does not parse, is malformed, or holds another identity. A missing
129
+ * record returns `absent` and never establishes ownership. The record is renamed to a private name
130
+ * in its own directory and checked again there before deletion. A changed captured record is
131
+ * linked back only if the canonical path is still free; on a collision both records are preserved.
132
+ *
133
+ * This establishes only which record was deleted. It is not proof that a manager stopped: the
134
+ * caller must hold its own stop and ownership evidence before retiring. A normal restart keeps the
135
+ * identity, and retirement is for failed-new-space compensation or terminal retirement.
136
+ */
137
+ export function retireManagerInstanceIdentity(root, space, expected, opts) {
138
+ const path = managerInstanceFile(root, space);
139
+ const refuse = (why) => {
140
+ throw new Error(`manager-instance-identity-retire-refused: space "${space}" at ${path}: ${why}`);
141
+ };
142
+ let current;
143
+ try {
144
+ current = readManagerInstanceRecord(path);
145
+ }
146
+ catch (e) {
147
+ return refuse(e.message);
148
+ }
149
+ if (current === undefined)
150
+ return { outcome: "absent" };
151
+ if (!sameManagerInstanceIdentity(current, expected))
152
+ return refuse("the stored identity is not the expected generation");
153
+ opts?.onBeforeRename?.();
154
+ const captured = `${path}.retiring.${randomUUID()}`;
155
+ try {
156
+ renameSync(path, captured);
157
+ }
158
+ catch (e) {
159
+ if (e.code === "ENOENT")
160
+ return { outcome: "absent" };
161
+ throw new Error(`manager-instance-identity-retire-refused: space "${space}" at ${path}: capture failed`, { cause: e });
162
+ }
163
+ let held;
164
+ try {
165
+ held = readManagerInstanceRecord(captured);
166
+ }
167
+ catch {
168
+ held = undefined;
169
+ }
170
+ if (held === undefined || !sameManagerInstanceIdentity(held, expected)) {
171
+ opts?.onBeforeLinkBack?.();
172
+ try {
173
+ linkSync(captured, path);
174
+ unlinkSync(captured);
175
+ }
176
+ catch {
177
+ return refuse(`the record changed before deletion and could not be put back; it is kept at ${captured}`);
178
+ }
179
+ return refuse("the record changed before deletion and was put back");
180
+ }
181
+ unlinkSync(captured);
182
+ return { outcome: "removed" };
183
+ }
184
+ /** One file per CLAIMED GENERATION, not one per seat. The exclusive create has to be on the
185
+ * successor VALUE, or a host that legitimately takes custody twice would collide with its own
186
+ * earlier claim and a fresh host would win a create that proves nothing. `<seat>.<generation>`
187
+ * makes "claim generation N" the atomic act. */
188
+ function seatGenerationFile(root, space, name, generation) {
189
+ return join(authDir(root), `${seatGenerationPrefix(space, name)}${generation}.json`);
190
+ }
191
+ /** Both parts are {@link spaceKey}, so the seat key inherits every rule the space key has. They are
192
+ * joined by a NUL byte, so a NUL inside either part would let two different (space, seat) pairs
193
+ * spell one key and one seat's claim refuse the other's. */
194
+ function seatGenerationPrefix(space, name) {
195
+ if (space.includes("\u0000") || name.includes("\u0000"))
196
+ throw new Error(`seat ${JSON.stringify(name)} in space ${JSON.stringify(space)} cannot hold a writer generation: NUL separates the space from the seat in its key`);
197
+ return `seat-generation.${spaceKey(space)}00${spaceKey(name)}.`;
198
+ }
199
+ /**
200
+ * Claim a whole set of seat writer generations, or none of them.
201
+ *
202
+ * Each claim is its own exclusive create, so a later one can lose even when every earlier one
203
+ * succeeded. A claim is a create that can never be made again, so a partial set would let one
204
+ * refusal consume the retry over the very same input. This creates them in order and, on any
205
+ * failure, removes the files IT created in this call before rethrowing.
206
+ *
207
+ * The compensation is deliberately narrow. It unlinks by the exact path it wrote and nothing else,
208
+ * so it can never remove a generation another destination holds. An unlink that finds the file
209
+ * already gone is fine; any other unlink error is reported alongside the original failure rather
210
+ * than replacing it, because the original is why the operation is failing and the unlink error is
211
+ * why the tree is not clean.
212
+ *
213
+ * No lock, no retry, no fallback: a lost create still refuses the whole set.
214
+ */
215
+ export function claimSeatWriterGenerations(root, claims) {
216
+ const written = [];
217
+ for (const claim of claims) {
218
+ try {
219
+ advanceSeatWriterGeneration(root, claim);
220
+ }
221
+ catch (error) {
222
+ const undoFailures = [];
223
+ for (const path of written) {
224
+ try {
225
+ rmSync(path);
226
+ }
227
+ catch (e) {
228
+ if (e.code !== "ENOENT")
229
+ undoFailures.push(`${path}: ${e.message}`);
230
+ }
231
+ }
232
+ if (undoFailures.length)
233
+ throw new Error(`${error.message}; additionally, these generations claimed by this attempt could not be released and must be removed by hand: ${undoFailures.join("; ")}`);
234
+ throw error;
235
+ }
236
+ written.push(seatGenerationFile(root, claim.space, claim.name, claim.generation));
237
+ }
238
+ return claims;
239
+ }
240
+ /** The highest generation this host has claimed for a seat, or undefined when it never has.
241
+ * A present-but-malformed record fails LOUD, for the reason {@link loadManagerInstanceIdentity}
242
+ * gives: replacing it is how custody silently returns to a host that lost it. */
243
+ export function loadSeatWriterGeneration(root, space, name) {
244
+ const prefix = seatGenerationPrefix(space, name);
245
+ const dir = authDir(root);
246
+ if (!existsSync(dir))
247
+ return undefined;
248
+ let held;
249
+ for (const entry of readdirSync(dir)) {
250
+ if (!entry.startsWith(prefix) || !entry.endsWith(".json"))
251
+ continue;
252
+ const f = join(dir, entry);
253
+ const parsed = readAuthRecord(f, "a seat writer generation");
254
+ if (parsed === undefined)
255
+ continue;
256
+ if (parsed === null || typeof parsed !== "object"
257
+ || parsed.space !== space || parsed.name !== name
258
+ || typeof parsed.lifecycleUid !== "string" || parsed.lifecycleUid.length === 0
259
+ || !Number.isInteger(parsed.generation) || parsed.generation < 0
260
+ || entry !== `${prefix}${parsed.generation}.json`)
261
+ throw new Error(`the persisted seat writer generation at ${f} is malformed; refusing to mint a fresh generation over it - that is how a stale host becomes authoritative again`);
262
+ if (!held || parsed.generation > held.generation)
263
+ held = { space, name, lifecycleUid: parsed.lifecycleUid, generation: parsed.generation };
264
+ }
265
+ return held;
266
+ }
267
+ /**
268
+ * Take custody of a seat at `claim.generation` by exclusive create, before anything launches.
269
+ *
270
+ * The publication primitive is {@link createManagerInstanceIdentity}'s, and the resolution of a
271
+ * lost create is deliberately NOT: that helper adopts the winner on EEXIST, because two managers
272
+ * sharing one logical instanceId is the intended outcome there. Here a lost create means two hosts
273
+ * are claiming one seat, which is the condition this fence exists to stop, so it refuses. Same
274
+ * primitive, opposite disposition.
275
+ */
276
+ export function advanceSeatWriterGeneration(root, claim) {
277
+ if (!Number.isInteger(claim.generation) || claim.generation < 0)
278
+ throw new Error(`a seat writer generation must be a non-negative integer; got ${JSON.stringify(claim.generation)}`);
279
+ const path = seatGenerationFile(root, claim.space, claim.name, claim.generation);
280
+ const dir = authDir(root);
281
+ mkSecretDir(dir);
282
+ try {
283
+ writeSecretFileCreateOnly(path, JSON.stringify(claim, null, 2));
284
+ return claim;
285
+ }
286
+ catch (e) {
287
+ if (e.code !== "EEXIST")
288
+ throw e;
289
+ throw new Error(`seat-writer-generation-create-lost: generation ${claim.generation} of seat ${JSON.stringify(claim.name)} in space ${JSON.stringify(claim.space)} is already claimed; refusing to resume as a second writer`);
290
+ }
291
+ }
292
+ /** The lstat of a trust path that holds an auth-material record, or undefined when it is absent:
293
+ * - a non-regular entry (symlink, directory, fifo) is REFUSED, never followed — nothing in this
294
+ * module writes one, so following it would trust material this module cannot vouch for (and
295
+ * enumeration counts the same entry as corrupt: one answer everywhere);
296
+ * - only ENOENT means absent; any other errno is uncertainty about trust material and throws. */
297
+ export function authRecordStat(f, what) {
298
+ let st;
299
+ try {
300
+ st = lstatSync(f);
301
+ }
302
+ catch (e) {
303
+ if (e.code === "ENOENT")
304
+ return undefined;
305
+ throw e;
306
+ }
307
+ if (!st.isFile())
308
+ throw new Error(`${f} is not a regular file - refusing to read ${what} through it; remove or restore the real record`);
309
+ return st;
310
+ }
311
+ /** Read one auth-material record: the file's raw text, or undefined when absent. Shared by every
312
+ * load/save below so the readers cannot disagree: the entry is checked by {@link authRecordStat},
313
+ * and the JSON parse is wrapped so a truncated/hand-edited record surfaces as one legible sentence
314
+ * naming the file, never a raw SyntaxError deep in a caller. */
315
+ export function readAuthRecord(f, what) {
316
+ if (!authRecordStat(f, what))
317
+ return undefined;
318
+ try {
319
+ return JSON.parse(readFileSync(f, "utf8"));
320
+ }
321
+ catch (e) {
322
+ throw new CommandFailure("refused", "SCHEMA_INVALID", `${f} does not parse as ${what}`, { target: { path: f }, remedy: `restore ${f} from backup; do not remove other account records, then re-run \`cotal up\`` });
323
+ }
324
+ }
325
+ /** A persisted identity record, or undefined when absent. Every identity reads through
326
+ * {@link readAuthRecord}, so they refuse the same entries, and a record `parse` rejects fails LOUD:
327
+ * minting over it would orphan the identity it held. */
328
+ function readIdentityRecord(f, what, parse) {
329
+ const raw = readAuthRecord(f, what);
330
+ if (raw === undefined)
331
+ return undefined;
332
+ const record = parse(raw);
333
+ if (record === undefined)
334
+ throw new Error(`${f} is not a well-formed record of ${what} - restore it from backup or remove it deliberately`);
335
+ return record;
336
+ }
337
+ /**
338
+ * A persisted identity record of this root: the stored one, or on a fresh root `mint()`'s,
339
+ * published by exclusive create. Of N concurrent first mints exactly one creates the file and the
340
+ * others adopt it, so a loser never keeps the identity it minted in memory; an atomic rename would
341
+ * let it. A loser that cannot read the winner refuses with `identity-record-create-lost`.
342
+ */
343
+ export function claimIdentityRecord(path, what, parse, mint) {
344
+ const stored = readIdentityRecord(path, what, parse);
345
+ if (stored !== undefined)
346
+ return stored;
347
+ mkSecretDir(dirname(path));
348
+ const candidate = mint();
349
+ try {
350
+ writeSecretFileCreateOnly(path, JSON.stringify(candidate, null, 2));
351
+ return candidate;
352
+ }
353
+ catch (e) {
354
+ if (e.code !== "EEXIST")
355
+ throw e;
356
+ const winner = readIdentityRecord(path, what, parse);
357
+ if (winner === undefined)
358
+ throw new Error(`identity-record-create-lost: exclusive create of ${what} at ${path} lost and the existing record could not be adopted`);
359
+ return winner;
360
+ }
361
+ }
362
+ //# sourceMappingURL=auth-identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-identity.js","sourceRoot":"","sources":["../src/auth-identity.ts"],"names":[],"mappings":"AAAA;;;uFAGuF;AACvF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAc,MAAM,SAAS,CAAC;AACjI,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,yBAAyB,EAAiB,MAAM,gBAAgB,CAAC;AACpG,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAYpF,MAAM,gBAAgB,GAAG,+BAA+B,CAAC;AACzD;qEACqE;AACrE,MAAM,UAAU,UAAU,CAAC,CAAU;IACnC,MAAM,CAAC,GAAG,CAAwD,CAAC;IACnE,IAAI,OAAO,CAAC,EAAE,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC1H,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE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