passport-bridge 0.7.0 → 0.8.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,293 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, closeSync, constants, fchmodSync, fsyncSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ const LOCK_STALE_MS = 30_000;
6
+ const LOCK_PATIENCE_MS = LOCK_STALE_MS + 5_000;
7
+ const LOCK_HEARTBEAT_MS = 5_000;
8
+ export function credentialDir() {
9
+ return process.env.PASSPORT_HOME || join(homedir(), ".passport");
10
+ }
11
+ export function isMissing(error) {
12
+ return error.code === "ENOENT";
13
+ }
14
+ export function enforceOwner(stat, label) {
15
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
16
+ throw new Error(`Passport ${label} is owned by another account.`);
17
+ }
18
+ }
19
+ /** Create or repair the owner-only credential directory without following a
20
+ * symlink at the security boundary. */
21
+ export function ensurePrivateDirectory(create) {
22
+ try {
23
+ const stat = lstatSync(credentialDir());
24
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
25
+ throw new Error("Passport credential directory must be a regular directory, not a symlink.");
26
+ }
27
+ enforceOwner(stat, "credential directory");
28
+ if (process.platform !== "win32")
29
+ chmodSync(credentialDir(), 0o700);
30
+ return true;
31
+ }
32
+ catch (error) {
33
+ if (!isMissing(error))
34
+ throw error;
35
+ if (!create)
36
+ return false;
37
+ mkdirSync(credentialDir(), { recursive: true, mode: 0o700 });
38
+ const stat = lstatSync(credentialDir());
39
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
40
+ throw new Error("Passport credential directory must be a regular directory, not a symlink.");
41
+ }
42
+ enforceOwner(stat, "credential directory");
43
+ if (process.platform !== "win32")
44
+ chmodSync(credentialDir(), 0o700);
45
+ return true;
46
+ }
47
+ }
48
+ function lockContents(path) {
49
+ try {
50
+ const stat = lstatSync(path);
51
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 256)
52
+ return undefined;
53
+ return readFileSync(path, "utf8");
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ function lockOwnerIsDead(path) {
60
+ const owner = lockContents(path)?.match(/^(\d+):[a-f0-9]{32}$/i);
61
+ if (!owner)
62
+ return false;
63
+ const pid = Number(owner[1]);
64
+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid)
65
+ return false;
66
+ try {
67
+ process.kill(pid, 0);
68
+ return false;
69
+ }
70
+ catch (error) {
71
+ return error.code === "ESRCH";
72
+ }
73
+ }
74
+ function tryAcquireLease(path) {
75
+ const token = `${process.pid}:${randomBytes(16).toString("hex")}`;
76
+ let descriptor;
77
+ try {
78
+ descriptor = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
79
+ if (process.platform !== "win32")
80
+ fchmodSync(descriptor, 0o600);
81
+ writeFileSync(descriptor, token, "utf8");
82
+ fsyncSync(descriptor);
83
+ return { path, token };
84
+ }
85
+ catch (error) {
86
+ if (error.code === "EEXIST")
87
+ return undefined;
88
+ throw error;
89
+ }
90
+ finally {
91
+ if (descriptor !== undefined)
92
+ closeSync(descriptor);
93
+ }
94
+ }
95
+ /** Move a stale or dead-owner inode out of the lock pathname before deleting
96
+ * it. An old owner can therefore never unlink a successor's lease. */
97
+ function stealRecoverableLease(path) {
98
+ let stat;
99
+ try {
100
+ stat = lstatSync(path);
101
+ }
102
+ catch (error) {
103
+ return isMissing(error);
104
+ }
105
+ if (stat.isSymbolicLink() || !stat.isFile())
106
+ return false;
107
+ if (Date.now() - stat.mtimeMs <= LOCK_STALE_MS && !lockOwnerIsDead(path))
108
+ return false;
109
+ const expected = lockContents(path);
110
+ const quarantine = `${path}.stale.${process.pid}.${randomBytes(6).toString("hex")}`;
111
+ try {
112
+ renameSync(path, quarantine);
113
+ }
114
+ catch (error) {
115
+ if (isMissing(error))
116
+ return true;
117
+ return false;
118
+ }
119
+ // A second contender may have won the race and installed a fresh lease.
120
+ // Never delete a quarantined inode unless it is the one we inspected.
121
+ let quarantined;
122
+ try {
123
+ quarantined = lstatSync(quarantine);
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ if (quarantined.dev !== stat.dev ||
129
+ quarantined.ino !== stat.ino ||
130
+ (expected !== undefined && lockContents(quarantine) !== expected)) {
131
+ try {
132
+ linkSync(quarantine, path);
133
+ unlinkSync(quarantine);
134
+ }
135
+ catch {
136
+ /* Preserve the unexpected inode for manual inspection. */
137
+ }
138
+ return false;
139
+ }
140
+ unlinkSync(quarantine);
141
+ return true;
142
+ }
143
+ function acquireLease(path, timeoutMessage) {
144
+ ensurePrivateDirectory(true);
145
+ const started = Date.now();
146
+ for (;;) {
147
+ const lease = tryAcquireLease(path);
148
+ if (lease)
149
+ return lease;
150
+ if (stealRecoverableLease(path))
151
+ continue;
152
+ if (Date.now() - started > LOCK_PATIENCE_MS)
153
+ throw new Error(timeoutMessage);
154
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 + Math.floor(Math.random() * 25));
155
+ }
156
+ }
157
+ async function acquireLeaseAsync(path, timeoutMessage) {
158
+ ensurePrivateDirectory(true);
159
+ const started = Date.now();
160
+ for (;;) {
161
+ const lease = tryAcquireLease(path);
162
+ if (lease)
163
+ return lease;
164
+ if (stealRecoverableLease(path))
165
+ continue;
166
+ if (Date.now() - started > LOCK_PATIENCE_MS)
167
+ throw new Error(timeoutMessage);
168
+ await new Promise((resolve) => setTimeout(resolve, 50 + Math.floor(Math.random() * 50)));
169
+ }
170
+ }
171
+ function leaseOwned(lease) {
172
+ return lockContents(lease.path) === lease.token;
173
+ }
174
+ function renewLease(lease) {
175
+ if (!leaseOwned(lease))
176
+ return;
177
+ const now = new Date();
178
+ try {
179
+ utimesSync(lease.path, now, now);
180
+ }
181
+ catch {
182
+ /* A stolen or released lease cannot be renewed. */
183
+ }
184
+ }
185
+ function releaseLease(lease) {
186
+ if (!leaseOwned(lease))
187
+ return;
188
+ try {
189
+ unlinkSync(lease.path);
190
+ }
191
+ catch (error) {
192
+ if (!isMissing(error))
193
+ throw error;
194
+ }
195
+ }
196
+ /** The JSON document and the active-profile pointer share this lock. */
197
+ export function withCredentialStoreWriteLock(fn) {
198
+ const lease = acquireLease(join(credentialDir(), ".credentials-write.lock"), "Timed out waiting to update Passport credentials.");
199
+ try {
200
+ return fn();
201
+ }
202
+ finally {
203
+ releaseLease(lease);
204
+ }
205
+ }
206
+ export function syncDirectory() {
207
+ if (process.platform === "win32")
208
+ return;
209
+ const descriptor = openSync(credentialDir(), constants.O_RDONLY);
210
+ try {
211
+ fsyncSync(descriptor);
212
+ }
213
+ finally {
214
+ closeSync(descriptor);
215
+ }
216
+ }
217
+ function assertSafePrivateTarget(path, label) {
218
+ try {
219
+ const stat = lstatSync(path);
220
+ if (stat.isSymbolicLink() || !stat.isFile()) {
221
+ throw new Error(`Passport ${label} must be a regular file, not a symlink.`);
222
+ }
223
+ enforceOwner(stat, label);
224
+ }
225
+ catch (error) {
226
+ if (!isMissing(error))
227
+ throw error;
228
+ }
229
+ }
230
+ export function writePrivateAtomic(target, temporaryPrefix, contents, label) {
231
+ ensurePrivateDirectory(true);
232
+ assertSafePrivateTarget(target, label);
233
+ const tmp = join(credentialDir(), `${temporaryPrefix}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
234
+ let descriptor;
235
+ let failed = false;
236
+ let failure;
237
+ try {
238
+ descriptor = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
239
+ if (process.platform !== "win32")
240
+ fchmodSync(descriptor, 0o600);
241
+ writeFileSync(descriptor, contents, "utf8");
242
+ fsyncSync(descriptor);
243
+ closeSync(descriptor);
244
+ descriptor = undefined;
245
+ // Recheck after the strict mutation read so a swapped symlink or directory
246
+ // is rejected rather than silently replaced.
247
+ assertSafePrivateTarget(target, label);
248
+ renameSync(tmp, target);
249
+ if (process.platform !== "win32")
250
+ chmodSync(target, 0o600);
251
+ syncDirectory();
252
+ }
253
+ catch (error) {
254
+ failed = true;
255
+ failure = error;
256
+ }
257
+ finally {
258
+ if (descriptor !== undefined) {
259
+ try {
260
+ closeSync(descriptor);
261
+ }
262
+ catch (error) {
263
+ if (!failed) {
264
+ failed = true;
265
+ failure = error;
266
+ }
267
+ }
268
+ }
269
+ try {
270
+ unlinkSync(tmp);
271
+ }
272
+ catch (error) {
273
+ if (!isMissing(error) && !failed) {
274
+ failed = true;
275
+ failure = error;
276
+ }
277
+ }
278
+ }
279
+ if (failed)
280
+ throw failure;
281
+ }
282
+ export async function withProfileLock(name, fn) {
283
+ const lease = await acquireLeaseAsync(join(credentialDir(), `${name}.lock`), `Timed out waiting for Passport profile "${name}".`);
284
+ const heartbeat = setInterval(() => renewLease(lease), LOCK_HEARTBEAT_MS);
285
+ heartbeat.unref?.();
286
+ try {
287
+ return await fn();
288
+ }
289
+ finally {
290
+ clearInterval(heartbeat);
291
+ releaseLease(lease);
292
+ }
293
+ }