passport-bridge 0.7.1 → 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.
- package/README.md +37 -8
- package/dist/activeProfile.js +122 -0
- package/dist/bridge.js +2 -9
- package/dist/cli.js +3 -1
- package/dist/cliArgs.js +6 -1
- package/dist/cliConnect.js +161 -0
- package/dist/cliLogin.js +96 -24
- package/dist/cliOffline.js +70 -4
- package/dist/cliOutput.js +12 -2
- package/dist/cliResult.js +29 -5
- package/dist/cliSupport.js +46 -5
- package/dist/completion.js +3 -1
- package/dist/credentialStorage.js +293 -0
- package/dist/credentials.js +46 -291
- package/dist/doctor.js +73 -6
- package/dist/passport.js +91 -124
- package/dist/tokenWorkspace.js +5 -0
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/cliOffline.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { value } from "./cliArgs.js";
|
|
2
2
|
import { completionScript } from "./completion.js";
|
|
3
|
-
import { readCreds } from "./credentials.js";
|
|
3
|
+
import { readActiveProfile, readCreds, setActiveProfile } from "./credentials.js";
|
|
4
4
|
import { endpoint, failure, profileName } from "./cliSupport.js";
|
|
5
5
|
import { VERSION } from "./version.js";
|
|
6
6
|
export function completionResult(args) {
|
|
@@ -11,6 +11,71 @@ export function completionResult(args) {
|
|
|
11
11
|
const script = completionScript(shell);
|
|
12
12
|
return { json: { shell, script }, human: script, essential: true, raw: true };
|
|
13
13
|
}
|
|
14
|
+
export function profilesResult(_args) {
|
|
15
|
+
const creds = readCreds();
|
|
16
|
+
const names = Object.keys(creds).sort();
|
|
17
|
+
const selected = readActiveProfile();
|
|
18
|
+
const active = selected && creds[selected] ? selected : undefined;
|
|
19
|
+
const profiles = names.map((name) => ({
|
|
20
|
+
name,
|
|
21
|
+
active: name === active,
|
|
22
|
+
...(creds[name].client ? { client: creds[name].client } : {})
|
|
23
|
+
}));
|
|
24
|
+
if (!profiles.length) {
|
|
25
|
+
return {
|
|
26
|
+
json: { profiles: [] },
|
|
27
|
+
human: "No Passport profiles saved.\nRun: passport login --workspace <workspace-id>.",
|
|
28
|
+
essential: true
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const lines = [
|
|
32
|
+
"Passport profiles:",
|
|
33
|
+
...profiles.map((profile) => ` ${profile.active ? "*" : " "} ${profile.name}${profile.active ? " (active)" : ""}`),
|
|
34
|
+
"",
|
|
35
|
+
"Use `passport use <name>` to select a profile."
|
|
36
|
+
];
|
|
37
|
+
return {
|
|
38
|
+
json: { profiles, ...(active ? { active } : {}) },
|
|
39
|
+
human: lines.join("\n"),
|
|
40
|
+
essential: true
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function useProfileResult(args, env) {
|
|
44
|
+
const profile = profileName(args.positionals[0]);
|
|
45
|
+
const creds = readCreds();
|
|
46
|
+
const names = Object.keys(creds).sort();
|
|
47
|
+
if (!creds[profile]) {
|
|
48
|
+
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
49
|
+
return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", {
|
|
50
|
+
hint: names.length
|
|
51
|
+
? `Choose one with: passport use <name> (available: ${names.join(", ")}).`
|
|
52
|
+
: "Run: passport login --workspace <workspace-id>.",
|
|
53
|
+
...(names.length
|
|
54
|
+
? {
|
|
55
|
+
profiles: names,
|
|
56
|
+
next: names.map((name) => ({
|
|
57
|
+
argv: ["passport", "use", name],
|
|
58
|
+
description: `Select the saved profile "${name}".`
|
|
59
|
+
}))
|
|
60
|
+
}
|
|
61
|
+
: { requiredInput: ["workspace-id"] })
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
setActiveProfile(profile);
|
|
65
|
+
const environmentProfile = env.PASSPORT_PROFILE ? profileName(env.PASSPORT_PROFILE) : undefined;
|
|
66
|
+
const overridden = environmentProfile && environmentProfile !== profile;
|
|
67
|
+
return {
|
|
68
|
+
json: {
|
|
69
|
+
profile,
|
|
70
|
+
active: true,
|
|
71
|
+
effectiveProfile: overridden ? environmentProfile : profile,
|
|
72
|
+
...(overridden ? { overriddenBy: "PASSPORT_PROFILE" } : {})
|
|
73
|
+
},
|
|
74
|
+
human: overridden
|
|
75
|
+
? `Saved active profile: "${profile}".\nPASSPORT_PROFILE still overrides it with "${environmentProfile}" for authenticated commands.`
|
|
76
|
+
: `Active profile: "${profile}".\nNext: passport status`
|
|
77
|
+
};
|
|
78
|
+
}
|
|
14
79
|
export function versionResult(args, env) {
|
|
15
80
|
let profile;
|
|
16
81
|
let resolvedEndpoint;
|
|
@@ -28,9 +93,10 @@ export function versionResult(args, env) {
|
|
|
28
93
|
? profileName(explicitProfile)
|
|
29
94
|
: env.PASSPORT_PROFILE
|
|
30
95
|
? profileName(env.PASSPORT_PROFILE)
|
|
31
|
-
:
|
|
32
|
-
|
|
33
|
-
: "";
|
|
96
|
+
: (() => {
|
|
97
|
+
const active = readActiveProfile();
|
|
98
|
+
return active && creds[active] ? profileName(active) : names.length === 1 ? profileName(names[0]) : "";
|
|
99
|
+
})();
|
|
34
100
|
if (candidate && creds[candidate]) {
|
|
35
101
|
profile = candidate;
|
|
36
102
|
resolvedEndpoint = endpoint(creds[candidate].endpoint);
|
package/dist/cliOutput.js
CHANGED
|
@@ -4,8 +4,10 @@ import { CliFailure, sanitize } from "./cliSupport.js";
|
|
|
4
4
|
import { VERSION } from "./version.js";
|
|
5
5
|
function helpText(verb) {
|
|
6
6
|
const details = {
|
|
7
|
-
login: "passport login --
|
|
7
|
+
login: "passport login [--workspace <id>] [--cloud <origin>] [--client <id>] [--profile <name>] [--no-open]\nStarts device sign-in, stores a cli-surface rotating credential, and makes that profile active. Passport Cloud is used when --workspace is provided without --cloud.",
|
|
8
8
|
logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
|
|
9
|
+
profiles: "passport profiles\nLists saved profiles and marks the active profile. Works offline.",
|
|
10
|
+
use: "passport use <name>\nSelects a saved profile as the default for subsequent commands. Works offline.",
|
|
9
11
|
status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
|
|
10
12
|
doctor: "passport doctor [--profile <name>]\nChecks Node, credential-store safety, endpoint security, server health, authentication, serverInfo, and the exact CLI protocol. JSON includes {ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
|
|
11
13
|
search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
|
|
@@ -28,6 +30,8 @@ Usage: passport <command> [options]
|
|
|
28
30
|
|
|
29
31
|
login Sign in with the device flow
|
|
30
32
|
logout Revoke and remove a profile
|
|
33
|
+
profiles List saved profiles and the active selection
|
|
34
|
+
use Select a saved profile for subsequent commands
|
|
31
35
|
status Show identity and visible MCP connection state
|
|
32
36
|
doctor Diagnose local setup and server compatibility
|
|
33
37
|
search Find permitted tools or list the catalog
|
|
@@ -101,6 +105,12 @@ export function failurePayload(error) {
|
|
|
101
105
|
exitCode: error.exitCode,
|
|
102
106
|
...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
|
|
103
107
|
...(error.details.app ? { app: error.details.app } : {}),
|
|
104
|
-
...(error.details.connectUrl ? { connectUrl: error.details.connectUrl } : {})
|
|
108
|
+
...(error.details.connectUrl ? { connectUrl: error.details.connectUrl } : {}),
|
|
109
|
+
...(error.details.hint ? { hint: error.details.hint } : {}),
|
|
110
|
+
...(error.details.profiles ? { profiles: error.details.profiles } : {}),
|
|
111
|
+
...(error.details.next ? { next: error.details.next } : {}),
|
|
112
|
+
...(error.details.remediation ? { remediation: error.details.remediation } : {}),
|
|
113
|
+
...(error.details.retry ? { retry: error.details.retry } : {}),
|
|
114
|
+
...(error.details.requiredInput ? { requiredInput: error.details.requiredInput } : {})
|
|
105
115
|
};
|
|
106
116
|
}
|
package/dist/cliResult.js
CHANGED
|
@@ -60,20 +60,44 @@ export function refusalOf(result) {
|
|
|
60
60
|
app,
|
|
61
61
|
connectUrl,
|
|
62
62
|
hint: connectUrl
|
|
63
|
-
?
|
|
64
|
-
:
|
|
63
|
+
? `Open: ${connectUrl}\nFinish the browser sign-in, then retry the command.`
|
|
64
|
+
: app
|
|
65
|
+
? "Run the connect action below, then retry the command."
|
|
66
|
+
: "Run passport status to identify the app that needs connecting.",
|
|
67
|
+
next: app
|
|
68
|
+
? [
|
|
69
|
+
{
|
|
70
|
+
argv: ["passport", "connect", app, "--wait", "120"],
|
|
71
|
+
description: "Connect the required app, then retry the tool call."
|
|
72
|
+
}
|
|
73
|
+
]
|
|
74
|
+
: [{ argv: ["passport", "status"], description: "Identify the app that needs connecting." }]
|
|
65
75
|
});
|
|
66
76
|
}
|
|
67
77
|
if (cause === "approval_pending") {
|
|
68
78
|
if (approvalId && !message.includes(approvalId))
|
|
69
79
|
message = `${message}\nApproval ID: ${approvalId}`;
|
|
70
|
-
return new CliFailure(message, 4, cause, {
|
|
80
|
+
return new CliFailure(message, 4, cause, {
|
|
81
|
+
app,
|
|
82
|
+
approvalId,
|
|
83
|
+
hint: "Approve the request in Passport, then retry it. For future calls, add --wait <seconds>."
|
|
84
|
+
});
|
|
71
85
|
}
|
|
72
86
|
if (cause === "approval_denied" || cause === "blocked") {
|
|
73
87
|
return new CliFailure(message, 5, cause, { app, approvalId });
|
|
74
88
|
}
|
|
75
|
-
if (cause === "unknown_tool")
|
|
76
|
-
return new CliFailure(message, 6, cause, {
|
|
89
|
+
if (cause === "unknown_tool") {
|
|
90
|
+
return new CliFailure(message, 6, cause, {
|
|
91
|
+
app,
|
|
92
|
+
hint: `Run: passport search${app ? ` --app ${app}` : ""}`,
|
|
93
|
+
next: [
|
|
94
|
+
{
|
|
95
|
+
argv: app ? ["passport", "search", "", "--app", app] : ["passport", "search", ""],
|
|
96
|
+
description: "List permitted tool names."
|
|
97
|
+
}
|
|
98
|
+
]
|
|
99
|
+
});
|
|
100
|
+
}
|
|
77
101
|
return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", {
|
|
78
102
|
app,
|
|
79
103
|
approvalId
|
package/dist/cliSupport.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { value } from "./cliArgs.js";
|
|
3
|
-
import { assertProfileName, readCreds } from "./credentials.js";
|
|
3
|
+
import { assertProfileName, readActiveProfile, readCreds } from "./credentials.js";
|
|
4
4
|
import { readBoundedJson } from "./boundedResponse.js";
|
|
5
5
|
export { readBoundedJson } from "./boundedResponse.js";
|
|
6
6
|
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
@@ -73,7 +73,7 @@ export function resolveCliAuth(args, env) {
|
|
|
73
73
|
if (agentKey || agentEndpoint) {
|
|
74
74
|
if (!agentKey || !agentEndpoint) {
|
|
75
75
|
return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", {
|
|
76
|
-
hint: "Set both variables, or
|
|
76
|
+
hint: "Set both variables, or unset both before running passport login."
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
79
|
if (explicitProfile !== undefined) {
|
|
@@ -83,17 +83,58 @@ export function resolveCliAuth(args, env) {
|
|
|
83
83
|
}
|
|
84
84
|
const creds = readCreds();
|
|
85
85
|
const names = Object.keys(creds).sort();
|
|
86
|
-
const
|
|
86
|
+
const active = readActiveProfile();
|
|
87
|
+
// Explicit CLI and environment selection always win. A locally selected
|
|
88
|
+
// profile is next, followed by the historical single-profile fallback. We
|
|
89
|
+
// only honor the active pointer when it still names a stored profile; a
|
|
90
|
+
// stale pointer must never make us guess a different workspace.
|
|
91
|
+
const fallbackProfile = env.PASSPORT_PROFILE || (active && creds[active] ? active : names.length === 1 ? names[0] : "");
|
|
87
92
|
const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
|
|
88
93
|
if (!profile) {
|
|
89
94
|
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
90
|
-
|
|
95
|
+
const hint = names.length
|
|
96
|
+
? `Choose one with: passport use <name> (available: ${names.join(", ")}), or pass --profile <name>.`
|
|
97
|
+
: "Run: passport login --workspace <workspace-id>.";
|
|
98
|
+
return failure(`No Passport profile selected.${suffix}`, 2, "auth", {
|
|
99
|
+
hint,
|
|
100
|
+
...(names.length
|
|
101
|
+
? {
|
|
102
|
+
profiles: names,
|
|
103
|
+
next: [
|
|
104
|
+
{ argv: ["passport", "profiles"], description: "List saved profiles." },
|
|
105
|
+
...names.map((name) => ({
|
|
106
|
+
argv: ["passport", "use", name],
|
|
107
|
+
description: `Select the saved profile "${name}".`
|
|
108
|
+
}))
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
: {
|
|
112
|
+
requiredInput: ["workspace-id"]
|
|
113
|
+
})
|
|
114
|
+
});
|
|
91
115
|
}
|
|
92
116
|
const saved = creds[profile];
|
|
93
117
|
if (!saved) {
|
|
94
118
|
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
119
|
+
const hint = names.length
|
|
120
|
+
? `Choose one with: passport use <name> (available: ${names.join(", ")}), or pass --profile <name>.`
|
|
121
|
+
: "Run: passport login --workspace <workspace-id>.";
|
|
95
122
|
return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", {
|
|
96
|
-
hint
|
|
123
|
+
hint,
|
|
124
|
+
...(names.length
|
|
125
|
+
? {
|
|
126
|
+
profiles: names,
|
|
127
|
+
next: [
|
|
128
|
+
{ argv: ["passport", "profiles"], description: "List saved profiles." },
|
|
129
|
+
...names.map((name) => ({
|
|
130
|
+
argv: ["passport", "use", name],
|
|
131
|
+
description: `Select the saved profile "${name}".`
|
|
132
|
+
}))
|
|
133
|
+
]
|
|
134
|
+
}
|
|
135
|
+
: {
|
|
136
|
+
requiredInput: ["workspace-id"]
|
|
137
|
+
})
|
|
97
138
|
});
|
|
98
139
|
}
|
|
99
140
|
return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
|
package/dist/completion.js
CHANGED
|
@@ -2,6 +2,8 @@ import { COMMANDS } from "./cliArgs.js";
|
|
|
2
2
|
const DESCRIPTIONS = {
|
|
3
3
|
login: "Sign in with the device flow",
|
|
4
4
|
logout: "Revoke and remove a profile",
|
|
5
|
+
profiles: "List saved profiles and the active selection",
|
|
6
|
+
use: "Select a saved profile for subsequent commands",
|
|
5
7
|
status: "Show identity and MCP connection state",
|
|
6
8
|
doctor: "Diagnose local configuration and server compatibility",
|
|
7
9
|
search: "Find permitted tools",
|
|
@@ -18,7 +20,7 @@ const DESCRIPTIONS = {
|
|
|
18
20
|
};
|
|
19
21
|
const GLOBAL = ["--profile", "--json", "--timeout", "--quiet", "--caller", "--help"];
|
|
20
22
|
const COMMAND_FLAGS = {
|
|
21
|
-
login: ["--cloud", "--workspace", "--client"],
|
|
23
|
+
login: ["--cloud", "--workspace", "--client", "--no-open"],
|
|
22
24
|
search: ["--app"],
|
|
23
25
|
run: ["--args", "--set", "--set-json", "--wait"],
|
|
24
26
|
connect: ["--alias", "--open", "--wait"],
|
|
@@ -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
|
+
}
|