sentinelayer-cli 0.6.2 → 0.8.1
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 +1009 -996
- package/bin/create-sentinelayer.js +5 -5
- package/bin/sentinelayer-cli.js +4 -4
- package/bin/sl.js +5 -5
- package/package.json +64 -63
- package/src/agents/ai-governance/index.js +12 -0
- package/src/agents/ai-governance/tools/base.js +171 -0
- package/src/agents/ai-governance/tools/eval-regression.js +47 -0
- package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
- package/src/agents/ai-governance/tools/index.js +52 -0
- package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
- package/src/agents/ai-governance/tools/provenance-check.js +69 -0
- package/src/agents/backend/index.js +12 -0
- package/src/agents/backend/tools/base.js +189 -0
- package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
- package/src/agents/backend/tools/idempotency-audit.js +105 -0
- package/src/agents/backend/tools/index.js +87 -0
- package/src/agents/backend/tools/retry-audit.js +132 -0
- package/src/agents/backend/tools/timeout-audit.js +144 -0
- package/src/agents/code-quality/index.js +12 -0
- package/src/agents/code-quality/tools/base.js +159 -0
- package/src/agents/code-quality/tools/complexity-measure.js +197 -0
- package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
- package/src/agents/code-quality/tools/cycle-detect.js +49 -0
- package/src/agents/code-quality/tools/dep-graph.js +196 -0
- package/src/agents/code-quality/tools/index.js +89 -0
- package/src/agents/data-layer/index.js +12 -0
- package/src/agents/data-layer/tools/base.js +181 -0
- package/src/agents/data-layer/tools/index-audit.js +165 -0
- package/src/agents/data-layer/tools/index.js +83 -0
- package/src/agents/data-layer/tools/migration-scan.js +135 -0
- package/src/agents/data-layer/tools/query-explain.js +120 -0
- package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
- package/src/agents/documentation/index.js +12 -0
- package/src/agents/documentation/tools/api-diff.js +91 -0
- package/src/agents/documentation/tools/base.js +151 -0
- package/src/agents/documentation/tools/dead-link-check.js +58 -0
- package/src/agents/documentation/tools/docstring-coverage.js +78 -0
- package/src/agents/documentation/tools/index.js +52 -0
- package/src/agents/documentation/tools/readme-freshness.js +61 -0
- package/src/agents/envelope/fix-cycle.js +45 -0
- package/src/agents/envelope/index.js +31 -0
- package/src/agents/envelope/loop.js +150 -0
- package/src/agents/envelope/pulse.js +18 -0
- package/src/agents/envelope/stream.js +40 -0
- package/src/agents/infrastructure/index.js +12 -0
- package/src/agents/infrastructure/tools/base.js +171 -0
- package/src/agents/infrastructure/tools/checkov-run.js +32 -0
- package/src/agents/infrastructure/tools/drift-detect.js +59 -0
- package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
- package/src/agents/infrastructure/tools/index.js +52 -0
- package/src/agents/infrastructure/tools/tflint-run.js +31 -0
- package/src/agents/jules/config/definition.js +160 -160
- package/src/agents/jules/config/system-prompt.js +182 -182
- package/src/agents/jules/error-intake.js +51 -51
- package/src/agents/jules/fix-cycle.js +17 -17
- package/src/agents/jules/loop.js +460 -450
- package/src/agents/jules/pulse.js +10 -10
- package/src/agents/jules/stream.js +187 -186
- package/src/agents/jules/swarm/file-scanner.js +74 -74
- package/src/agents/jules/swarm/index.js +11 -11
- package/src/agents/jules/swarm/orchestrator.js +362 -362
- package/src/agents/jules/swarm/pattern-hunter.js +123 -123
- package/src/agents/jules/swarm/sub-agent.js +315 -309
- package/src/agents/jules/tools/aidenid-email.js +189 -189
- package/src/agents/jules/tools/auth-audit.js +1708 -1691
- package/src/agents/jules/tools/dispatch.js +340 -335
- package/src/agents/jules/tools/file-edit.js +2 -2
- package/src/agents/jules/tools/file-read.js +2 -2
- package/src/agents/jules/tools/frontend-analyze.js +570 -570
- package/src/agents/jules/tools/glob.js +2 -2
- package/src/agents/jules/tools/grep.js +2 -2
- package/src/agents/jules/tools/index.js +29 -29
- package/src/agents/jules/tools/path-guards.js +2 -2
- package/src/agents/jules/tools/runtime-audit.js +507 -507
- package/src/agents/jules/tools/shell.js +2 -2
- package/src/agents/jules/tools/url-policy.js +100 -100
- package/src/agents/mode.js +113 -0
- package/src/agents/observability/index.js +12 -0
- package/src/agents/observability/tools/alert-audit.js +39 -0
- package/src/agents/observability/tools/base.js +181 -0
- package/src/agents/observability/tools/dashboard-gap.js +42 -0
- package/src/agents/observability/tools/index.js +54 -0
- package/src/agents/observability/tools/log-schema-check.js +74 -0
- package/src/agents/observability/tools/span-coverage.js +74 -0
- package/src/agents/persona-visuals.js +102 -61
- package/src/agents/release/index.js +12 -0
- package/src/agents/release/tools/base.js +181 -0
- package/src/agents/release/tools/changelog-diff.js +86 -0
- package/src/agents/release/tools/feature-flag-audit.js +126 -0
- package/src/agents/release/tools/index.js +61 -0
- package/src/agents/release/tools/rollback-verify.js +129 -0
- package/src/agents/release/tools/semver-check.js +109 -0
- package/src/agents/reliability/index.js +12 -0
- package/src/agents/reliability/tools/backpressure-check.js +129 -0
- package/src/agents/reliability/tools/base.js +181 -0
- package/src/agents/reliability/tools/chaos-probe.js +109 -0
- package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
- package/src/agents/reliability/tools/health-check-audit.js +111 -0
- package/src/agents/reliability/tools/index.js +87 -0
- package/src/agents/run-persona.js +109 -0
- package/src/agents/security/index.js +12 -0
- package/src/agents/security/tools/authz-audit.js +134 -0
- package/src/agents/security/tools/base.js +190 -0
- package/src/agents/security/tools/crypto-review.js +175 -0
- package/src/agents/security/tools/index.js +97 -0
- package/src/agents/security/tools/sast-scan.js +175 -0
- package/src/agents/security/tools/secrets-scan.js +216 -0
- package/src/agents/shared-tools/dispatch-core.js +320 -315
- package/src/agents/shared-tools/file-edit.js +180 -180
- package/src/agents/shared-tools/file-read.js +100 -100
- package/src/agents/shared-tools/glob.js +168 -168
- package/src/agents/shared-tools/grep.js +228 -228
- package/src/agents/shared-tools/index.js +46 -46
- package/src/agents/shared-tools/path-guards.js +161 -161
- package/src/agents/shared-tools/shell.js +383 -383
- package/src/agents/supply-chain/index.js +12 -0
- package/src/agents/supply-chain/tools/attestation-check.js +42 -0
- package/src/agents/supply-chain/tools/base.js +151 -0
- package/src/agents/supply-chain/tools/index.js +52 -0
- package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
- package/src/agents/supply-chain/tools/package-verify.js +56 -0
- package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
- package/src/agents/testing/index.js +12 -0
- package/src/agents/testing/tools/base.js +202 -0
- package/src/agents/testing/tools/coverage-gap.js +144 -0
- package/src/agents/testing/tools/flake-detect.js +125 -0
- package/src/agents/testing/tools/index.js +85 -0
- package/src/agents/testing/tools/mutation-test.js +143 -0
- package/src/agents/testing/tools/snapshot-diff.js +103 -0
- package/src/ai/aidenid.js +1021 -1009
- package/src/ai/client.js +553 -553
- package/src/ai/domain-target-store.js +268 -268
- package/src/ai/identity-store.js +270 -270
- package/src/ai/proxy.js +137 -137
- package/src/ai/site-store.js +145 -145
- package/src/audit/agents/architecture.js +180 -180
- package/src/audit/agents/compliance.js +179 -179
- package/src/audit/agents/documentation.js +165 -165
- package/src/audit/agents/performance.js +145 -145
- package/src/audit/agents/security.js +215 -215
- package/src/audit/agents/testing.js +172 -172
- package/src/audit/orchestrator.js +557 -557
- package/src/audit/package.js +204 -204
- package/src/audit/registry.js +284 -284
- package/src/audit/replay.js +103 -103
- package/src/auth/gate.js +428 -371
- package/src/auth/http.js +681 -611
- package/src/auth/service.js +1106 -1106
- package/src/auth/session-store.js +813 -813
- package/src/cli.js +257 -252
- package/src/commands/ai/identity-lifecycle.js +1338 -1338
- package/src/commands/ai/provision-governance.js +1272 -1272
- package/src/commands/ai/shared.js +147 -147
- package/src/commands/ai.js +11 -11
- package/src/commands/apply.js +12 -12
- package/src/commands/audit.js +1171 -1166
- package/src/commands/auth.js +419 -419
- package/src/commands/chat.js +184 -191
- package/src/commands/config.js +184 -184
- package/src/commands/cost.js +311 -311
- package/src/commands/daemon/core.js +850 -850
- package/src/commands/daemon/extended.js +1048 -1048
- package/src/commands/daemon/shared.js +213 -213
- package/src/commands/daemon.js +11 -11
- package/src/commands/guide.js +174 -174
- package/src/commands/ingest.js +58 -58
- package/src/commands/init.js +55 -55
- package/src/commands/legacy-args.js +20 -10
- package/src/commands/mcp.js +461 -461
- package/src/commands/omargate.js +63 -29
- package/src/commands/persona.js +65 -20
- package/src/commands/plugin.js +260 -260
- package/src/commands/policy.js +132 -132
- package/src/commands/prompt.js +238 -238
- package/src/commands/review.js +704 -704
- package/src/commands/scan.js +865 -872
- package/src/commands/session.js +1238 -0
- package/src/commands/spec.js +771 -716
- package/src/commands/swarm.js +651 -651
- package/src/commands/telemetry.js +202 -202
- package/src/commands/watch.js +511 -511
- package/src/config/agent-dictionary.js +182 -182
- package/src/config/io.js +56 -56
- package/src/config/paths.js +18 -18
- package/src/config/schema.js +55 -55
- package/src/config/service.js +184 -184
- package/src/coord/events-log.js +141 -0
- package/src/coord/handshake.js +719 -0
- package/src/coord/index.js +35 -0
- package/src/coord/paths.js +84 -0
- package/src/coord/priority.js +62 -0
- package/src/coord/tarjan.js +157 -0
- package/src/cost/budget.js +235 -235
- package/src/cost/history.js +188 -188
- package/src/cost/tokenizer.js +160 -0
- package/src/cost/tracker.js +232 -171
- package/src/daemon/artifact-lineage.js +896 -534
- package/src/daemon/assignment-ledger.js +1083 -770
- package/src/daemon/ast-drift.js +496 -0
- package/src/daemon/ast-parser-layer.js +258 -258
- package/src/daemon/budget-governor.js +633 -633
- package/src/daemon/callgraph-overlay.js +646 -646
- package/src/daemon/error-worker.js +1209 -626
- package/src/daemon/fix-cycle.js +384 -377
- package/src/daemon/hybrid-mapper.js +929 -929
- package/src/daemon/ingest-refresh.js +79 -11
- package/src/daemon/jira-lifecycle.js +767 -632
- package/src/daemon/operator-control.js +657 -657
- package/src/daemon/pulse.js +327 -327
- package/src/daemon/reliability-lane.js +471 -471
- package/src/daemon/scope-engine.js +1068 -0
- package/src/daemon/watchdog.js +971 -971
- package/src/events/schema.js +190 -0
- package/src/guide/generator.js +316 -316
- package/src/ingest/engine.js +933 -918
- package/src/ingest/ownership.js +380 -0
- package/src/interactive/index.js +97 -97
- package/src/legacy-cli.js +3228 -2994
- package/src/mcp/registry.js +695 -695
- package/src/memory/blackboard.js +301 -301
- package/src/memory/retrieval.js +581 -581
- package/src/orchestrator/kai-chen.js +126 -0
- package/src/plugin/manifest.js +553 -553
- package/src/policy/packs.js +144 -144
- package/src/prompt/generator.js +136 -118
- package/src/review/ai-review.js +672 -679
- package/src/review/compliance-pack.js +389 -0
- package/src/review/investor-dd-config.js +54 -0
- package/src/review/investor-dd-file-loop.js +303 -0
- package/src/review/investor-dd-file-router.js +406 -0
- package/src/review/investor-dd-html-report.js +233 -0
- package/src/review/investor-dd-notification.js +120 -0
- package/src/review/investor-dd-orchestrator.js +405 -0
- package/src/review/investor-dd-persona-runner.js +275 -0
- package/src/review/live-validator.js +253 -0
- package/src/review/local-review.js +1351 -1305
- package/src/review/omargate-interactive.js +68 -68
- package/src/review/omargate-orchestrator.js +492 -300
- package/src/review/persona-prompts.js +484 -296
- package/src/review/reconciliation-rules.js +329 -0
- package/src/review/replay.js +235 -235
- package/src/review/report.js +664 -664
- package/src/review/reproducibility-chain.js +136 -0
- package/src/review/scan-modes.js +147 -42
- package/src/review/spec-binding.js +487 -487
- package/src/scaffold/generator.js +67 -67
- package/src/scaffold/templates.js +150 -150
- package/src/scan/generator.js +418 -418
- package/src/scan/gh-secrets.js +107 -107
- package/src/session/agent-registry.js +359 -0
- package/src/session/analytics.js +479 -0
- package/src/session/daemon.js +1396 -0
- package/src/session/file-locks.js +666 -0
- package/src/session/paths.js +37 -0
- package/src/session/recap.js +567 -0
- package/src/session/redact.js +82 -0
- package/src/session/runtime-bridge.js +762 -0
- package/src/session/scoring.js +406 -0
- package/src/session/setup-guides.js +304 -0
- package/src/session/store.js +704 -0
- package/src/session/stream.js +333 -0
- package/src/session/sync.js +753 -0
- package/src/session/tasks.js +1054 -0
- package/src/session/templates.js +188 -0
- package/src/spec/generator.js +619 -519
- package/src/spec/regenerate.js +237 -237
- package/src/spec/templates.js +91 -91
- package/src/swarm/dashboard.js +247 -247
- package/src/swarm/factory.js +363 -363
- package/src/swarm/pentest.js +934 -934
- package/src/swarm/registry.js +419 -419
- package/src/swarm/report.js +158 -158
- package/src/swarm/runtime.js +569 -576
- package/src/swarm/scenario-dsl.js +272 -272
- package/src/telemetry/ledger.js +302 -302
- package/src/telemetry/session-tracker.js +234 -234
- package/src/telemetry/sync.js +203 -203
- package/src/ui/command-hints.js +13 -13
- package/src/ui/markdown.js +220 -220
|
@@ -1,813 +1,813 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
|
-
import os from "node:os";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import fsp from "node:fs/promises";
|
|
5
|
-
import process from "node:process";
|
|
6
|
-
|
|
7
|
-
const CREDENTIALS_VERSION = 1;
|
|
8
|
-
const KEYRING_SERVICE = "sentinelayer-cli";
|
|
9
|
-
const SESSION_WARNING_PREFIX = "sentinelayer.auth.session";
|
|
10
|
-
const SESSION_WARNING_REDACT_KEYS = /token|secret|password|key|authorization/i;
|
|
11
|
-
const SESSION_WARNING_MAX_VALUE_LENGTH = 200;
|
|
12
|
-
const SESSION_WARNING_ALLOWED_FIELDS = new Set([
|
|
13
|
-
"reason",
|
|
14
|
-
"source",
|
|
15
|
-
"operation",
|
|
16
|
-
"storage",
|
|
17
|
-
"codeHint",
|
|
18
|
-
"requestIdHash",
|
|
19
|
-
]);
|
|
20
|
-
|
|
21
|
-
function nowIso() {
|
|
22
|
-
return new Date().toISOString();
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function createSessionWarningId() {
|
|
26
|
-
try {
|
|
27
|
-
return crypto.randomUUID();
|
|
28
|
-
} catch {
|
|
29
|
-
return `session-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function sanitizeSessionWarningValue(value, depth = 0) {
|
|
34
|
-
if (value === null || value === undefined) {
|
|
35
|
-
return value;
|
|
36
|
-
}
|
|
37
|
-
if (depth > 3) {
|
|
38
|
-
return "[TRUNCATED]";
|
|
39
|
-
}
|
|
40
|
-
if (Array.isArray(value)) {
|
|
41
|
-
return value.map((entry) => sanitizeSessionWarningValue(entry, depth + 1));
|
|
42
|
-
}
|
|
43
|
-
if (typeof value === "object") {
|
|
44
|
-
const sanitized = {};
|
|
45
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
46
|
-
if (SESSION_WARNING_REDACT_KEYS.test(key)) {
|
|
47
|
-
sanitized[key] = "[REDACTED]";
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
sanitized[key] = sanitizeSessionWarningValue(entry, depth + 1);
|
|
51
|
-
}
|
|
52
|
-
return sanitized;
|
|
53
|
-
}
|
|
54
|
-
if (typeof value === "string") {
|
|
55
|
-
if (value.length > SESSION_WARNING_MAX_VALUE_LENGTH) {
|
|
56
|
-
return `${value.slice(0, SESSION_WARNING_MAX_VALUE_LENGTH)}…`;
|
|
57
|
-
}
|
|
58
|
-
return value;
|
|
59
|
-
}
|
|
60
|
-
return value;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function sanitizeSessionWarningDetails(details) {
|
|
64
|
-
if (!details || typeof details !== "object") {
|
|
65
|
-
return {};
|
|
66
|
-
}
|
|
67
|
-
return sanitizeSessionWarningValue(details, 0);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function emitSessionWarning(code, details = {}) {
|
|
71
|
-
const sanitizedDetails = sanitizeSessionWarningDetails(details);
|
|
72
|
-
const payload = {
|
|
73
|
-
level: "warn",
|
|
74
|
-
code: String(code || "SESSION_WARNING").toUpperCase(),
|
|
75
|
-
warningId: createSessionWarningId(),
|
|
76
|
-
timestamp: nowIso(),
|
|
77
|
-
};
|
|
78
|
-
for (const [key, value] of Object.entries(sanitizedDetails)) {
|
|
79
|
-
if (SESSION_WARNING_ALLOWED_FIELDS.has(key)) {
|
|
80
|
-
payload[key] = value;
|
|
81
|
-
} else {
|
|
82
|
-
payload[key] = "[OMITTED]";
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
try {
|
|
86
|
-
console.warn(`${SESSION_WARNING_PREFIX} ${JSON.stringify(payload)}`);
|
|
87
|
-
} catch {
|
|
88
|
-
console.warn(`${SESSION_WARNING_PREFIX} ${payload.code}`);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function resolveHomeDir(homeDir) {
|
|
93
|
-
return path.resolve(String(homeDir || os.homedir()));
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Resolve the deterministic credentials metadata file path for the current user/home override.
|
|
98
|
-
*
|
|
99
|
-
* @param {{ homeDir?: string }} [options]
|
|
100
|
-
* @returns {string}
|
|
101
|
-
*/
|
|
102
|
-
export function resolveCredentialsFilePath({ homeDir } = {}) {
|
|
103
|
-
const resolvedHome = resolveHomeDir(homeDir);
|
|
104
|
-
return path.join(resolvedHome, ".sentinelayer", "credentials.json");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function resolveCredentialsKeyPath({ homeDir } = {}) {
|
|
108
|
-
const resolvedHome = resolveHomeDir(homeDir);
|
|
109
|
-
return path.join(resolvedHome, ".sentinelayer", "keys", "credentials.key");
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function resolveLegacyCredentialsKeyPath({ homeDir } = {}) {
|
|
113
|
-
const resolvedHome = resolveHomeDir(homeDir);
|
|
114
|
-
return path.join(resolvedHome, ".sentinelayer", "credentials.key");
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async function loadOrCreateFileKey({ homeDir } = {}) {
|
|
118
|
-
const keyPath = resolveCredentialsKeyPath({ homeDir });
|
|
119
|
-
const legacyKeyPath = resolveLegacyCredentialsKeyPath({ homeDir });
|
|
120
|
-
try {
|
|
121
|
-
const raw = await fsp.readFile(keyPath, "utf-8");
|
|
122
|
-
const key = Buffer.from(String(raw || "").trim(), "base64");
|
|
123
|
-
if (key.length === 32) {
|
|
124
|
-
return key;
|
|
125
|
-
}
|
|
126
|
-
} catch (error) {
|
|
127
|
-
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
128
|
-
throw error;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
try {
|
|
133
|
-
const legacyRaw = await fsp.readFile(legacyKeyPath, "utf-8");
|
|
134
|
-
const legacyKey = Buffer.from(String(legacyRaw || "").trim(), "base64");
|
|
135
|
-
if (legacyKey.length === 32) {
|
|
136
|
-
await fsp.mkdir(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
|
137
|
-
await fsp.writeFile(keyPath, legacyKey.toString("base64"), { encoding: "utf-8", mode: 0o600 });
|
|
138
|
-
try {
|
|
139
|
-
await fsp.chmod(keyPath, 0o600);
|
|
140
|
-
} catch {
|
|
141
|
-
// Windows does not reliably support POSIX chmod semantics.
|
|
142
|
-
}
|
|
143
|
-
let verified = false;
|
|
144
|
-
try {
|
|
145
|
-
const verifyRaw = await fsp.readFile(keyPath, "utf-8");
|
|
146
|
-
const verifyKey = Buffer.from(String(verifyRaw || "").trim(), "base64");
|
|
147
|
-
verified = verifyKey.length === 32 && verifyKey.equals(legacyKey);
|
|
148
|
-
} catch {
|
|
149
|
-
verified = false;
|
|
150
|
-
}
|
|
151
|
-
if (verified) {
|
|
152
|
-
await fsp.rm(legacyKeyPath, { force: true });
|
|
153
|
-
}
|
|
154
|
-
return legacyKey;
|
|
155
|
-
}
|
|
156
|
-
} catch (error) {
|
|
157
|
-
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
158
|
-
throw error;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const key = crypto.randomBytes(32);
|
|
163
|
-
await fsp.mkdir(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
|
164
|
-
await fsp.writeFile(keyPath, key.toString("base64"), { encoding: "utf-8", mode: 0o600 });
|
|
165
|
-
try {
|
|
166
|
-
await fsp.chmod(keyPath, 0o600);
|
|
167
|
-
} catch {
|
|
168
|
-
// Windows does not reliably support POSIX chmod semantics.
|
|
169
|
-
}
|
|
170
|
-
return key;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function encryptToken(token, key) {
|
|
174
|
-
const iv = crypto.randomBytes(12);
|
|
175
|
-
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
176
|
-
const ciphertext = Buffer.concat([cipher.update(token, "utf-8"), cipher.final()]);
|
|
177
|
-
const tag = cipher.getAuthTag();
|
|
178
|
-
return {
|
|
179
|
-
tokenEncrypted: ciphertext.toString("base64"),
|
|
180
|
-
tokenIv: iv.toString("base64"),
|
|
181
|
-
tokenTag: tag.toString("base64"),
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function decryptToken({ tokenEncrypted, tokenIv, tokenTag }, key) {
|
|
186
|
-
const iv = Buffer.from(tokenIv, "base64");
|
|
187
|
-
const tag = Buffer.from(tokenTag, "base64");
|
|
188
|
-
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
|
189
|
-
decipher.setAuthTag(tag);
|
|
190
|
-
const plaintext = Buffer.concat([
|
|
191
|
-
decipher.update(Buffer.from(tokenEncrypted, "base64")),
|
|
192
|
-
decipher.final(),
|
|
193
|
-
]);
|
|
194
|
-
return plaintext.toString("utf-8");
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function buildKeyringAccountName(apiUrl) {
|
|
198
|
-
const digest = crypto
|
|
199
|
-
.createHash("sha256")
|
|
200
|
-
.update(String(apiUrl || "").trim().toLowerCase())
|
|
201
|
-
.digest("hex")
|
|
202
|
-
.slice(0, 16);
|
|
203
|
-
return `default-${digest}`;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function normalizeUser(user = {}) {
|
|
207
|
-
return {
|
|
208
|
-
id: String(user.id || "").trim(),
|
|
209
|
-
githubUsername: String(user.githubUsername || user.github_username || "").trim(),
|
|
210
|
-
email: String(user.email || "").trim(),
|
|
211
|
-
avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
|
|
212
|
-
isAdmin: Boolean(user.isAdmin || user.is_admin),
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function normalizeAidenId(raw) {
|
|
217
|
-
if (!raw || typeof raw !== "object") return null;
|
|
218
|
-
const orgId = String(raw.orgId || "").trim();
|
|
219
|
-
const projectId = String(raw.projectId || "").trim();
|
|
220
|
-
if (!orgId && !projectId) return null;
|
|
221
|
-
return {
|
|
222
|
-
orgId: orgId || null,
|
|
223
|
-
projectId: projectId || null,
|
|
224
|
-
apiKeyPrefix: String(raw.apiKeyPrefix || "").trim() || null,
|
|
225
|
-
provisionedAt: String(raw.provisionedAt || "").trim() || null,
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function normalizeMetadata(raw = {}) {
|
|
230
|
-
return {
|
|
231
|
-
version: Number(raw.version || CREDENTIALS_VERSION),
|
|
232
|
-
apiUrl: String(raw.apiUrl || "").trim(),
|
|
233
|
-
storage: String(raw.storage || "file").trim(),
|
|
234
|
-
keyringService: String(raw.keyringService || KEYRING_SERVICE).trim(),
|
|
235
|
-
keyringAccount: String(raw.keyringAccount || "").trim(),
|
|
236
|
-
tokenId: String(raw.tokenId || "").trim() || null,
|
|
237
|
-
tokenPrefix: String(raw.tokenPrefix || "").trim() || null,
|
|
238
|
-
tokenExpiresAt: String(raw.tokenExpiresAt || "").trim() || null,
|
|
239
|
-
createdAt: String(raw.createdAt || "").trim() || nowIso(),
|
|
240
|
-
updatedAt: String(raw.updatedAt || "").trim() || nowIso(),
|
|
241
|
-
user: normalizeUser(raw.user),
|
|
242
|
-
token: String(raw.token || "").trim() || null,
|
|
243
|
-
tokenEncrypted: String(raw.tokenEncrypted || "").trim() || null,
|
|
244
|
-
tokenIv: String(raw.tokenIv || "").trim() || null,
|
|
245
|
-
tokenTag: String(raw.tokenTag || "").trim() || null,
|
|
246
|
-
aidenid: normalizeAidenId(raw.aidenid),
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
function isRetriableRenameError(error) {
|
|
251
|
-
if (!error || typeof error !== "object") {
|
|
252
|
-
return false;
|
|
253
|
-
}
|
|
254
|
-
return (
|
|
255
|
-
error.code === "EPERM" ||
|
|
256
|
-
error.code === "EACCES" ||
|
|
257
|
-
error.code === "EEXIST" ||
|
|
258
|
-
error.code === "EBUSY"
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
function delayMilliseconds(ms) {
|
|
263
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
async function renameWithRetry(sourcePath, destinationPath, { attempts = 3, baseDelayMs = 25 } = {}) {
|
|
267
|
-
let lastError = null;
|
|
268
|
-
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
269
|
-
try {
|
|
270
|
-
await fsp.rename(sourcePath, destinationPath);
|
|
271
|
-
return;
|
|
272
|
-
} catch (error) {
|
|
273
|
-
lastError = error;
|
|
274
|
-
if (!isRetriableRenameError(error) || attempt >= attempts) {
|
|
275
|
-
break;
|
|
276
|
-
}
|
|
277
|
-
await delayMilliseconds(baseDelayMs * attempt);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
throw lastError;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
async function syncFile(filePath) {
|
|
284
|
-
const normalizedPath = String(filePath || "").trim();
|
|
285
|
-
if (!normalizedPath) {
|
|
286
|
-
return;
|
|
287
|
-
}
|
|
288
|
-
let handle = null;
|
|
289
|
-
try {
|
|
290
|
-
handle = await fsp.open(normalizedPath, "r");
|
|
291
|
-
await handle.sync();
|
|
292
|
-
} catch {
|
|
293
|
-
// Best effort only. Some filesystems/runtimes do not support explicit fsync.
|
|
294
|
-
} finally {
|
|
295
|
-
if (handle) {
|
|
296
|
-
await handle.close().catch(() => {});
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
async function syncDirectory(directoryPath) {
|
|
302
|
-
const normalizedPath = String(directoryPath || "").trim();
|
|
303
|
-
if (!normalizedPath) {
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
let handle = null;
|
|
307
|
-
try {
|
|
308
|
-
handle = await fsp.open(normalizedPath, "r");
|
|
309
|
-
await handle.sync();
|
|
310
|
-
} catch {
|
|
311
|
-
// Directory fsync support is platform-dependent; ignore when unsupported.
|
|
312
|
-
} finally {
|
|
313
|
-
if (handle) {
|
|
314
|
-
await handle.close().catch(() => {});
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
async function replaceWithBackup(tmpPath, filePath) {
|
|
320
|
-
const directory = path.dirname(filePath);
|
|
321
|
-
const backupPath = path.join(
|
|
322
|
-
directory,
|
|
323
|
-
`.credentials.backup.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.bak`
|
|
324
|
-
);
|
|
325
|
-
let backupCreated = false;
|
|
326
|
-
try {
|
|
327
|
-
try {
|
|
328
|
-
await fsp.rename(filePath, backupPath);
|
|
329
|
-
backupCreated = true;
|
|
330
|
-
await syncDirectory(directory);
|
|
331
|
-
} catch (error) {
|
|
332
|
-
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
333
|
-
throw error;
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
await renameWithRetry(tmpPath, filePath, { attempts: 3, baseDelayMs: 40 });
|
|
338
|
-
await syncFile(filePath);
|
|
339
|
-
await syncDirectory(directory);
|
|
340
|
-
|
|
341
|
-
if (backupCreated) {
|
|
342
|
-
await fsp.rm(backupPath, { force: true }).catch(() => {});
|
|
343
|
-
await syncDirectory(directory);
|
|
344
|
-
}
|
|
345
|
-
} catch (error) {
|
|
346
|
-
if (backupCreated) {
|
|
347
|
-
try {
|
|
348
|
-
await fsp.rename(backupPath, filePath);
|
|
349
|
-
await syncFile(filePath);
|
|
350
|
-
await syncDirectory(directory);
|
|
351
|
-
} catch {
|
|
352
|
-
// Best-effort restore; keep original error as the primary failure.
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
throw error;
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
async function loadKeytarClient() {
|
|
360
|
-
const disableKeyring = String(process.env.SENTINELAYER_DISABLE_KEYRING || "")
|
|
361
|
-
.trim()
|
|
362
|
-
.toLowerCase();
|
|
363
|
-
if (disableKeyring === "1" || disableKeyring === "true" || disableKeyring === "yes" || disableKeyring === "on") {
|
|
364
|
-
return null;
|
|
365
|
-
}
|
|
366
|
-
const keyringMode = String(process.env.SENTINELAYER_KEYRING_MODE || "")
|
|
367
|
-
.trim()
|
|
368
|
-
.toLowerCase();
|
|
369
|
-
const enableKeyring =
|
|
370
|
-
keyringMode === "keyring" ||
|
|
371
|
-
keyringMode === "enabled" ||
|
|
372
|
-
keyringMode === "on" ||
|
|
373
|
-
keyringMode === "true" ||
|
|
374
|
-
keyringMode === "1";
|
|
375
|
-
if (!enableKeyring) {
|
|
376
|
-
return null;
|
|
377
|
-
}
|
|
378
|
-
try {
|
|
379
|
-
const mod = await import("keytar");
|
|
380
|
-
const client = mod && typeof mod === "object" ? mod.default || mod : null;
|
|
381
|
-
if (!client) {
|
|
382
|
-
return null;
|
|
383
|
-
}
|
|
384
|
-
if (
|
|
385
|
-
typeof client.getPassword !== "function" ||
|
|
386
|
-
typeof client.setPassword !== "function" ||
|
|
387
|
-
typeof client.deletePassword !== "function"
|
|
388
|
-
) {
|
|
389
|
-
return null;
|
|
390
|
-
}
|
|
391
|
-
return client;
|
|
392
|
-
} catch {
|
|
393
|
-
return null;
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
async function readMetadata({ homeDir } = {}) {
|
|
398
|
-
const filePath = resolveCredentialsFilePath({ homeDir });
|
|
399
|
-
try {
|
|
400
|
-
const raw = await fsp.readFile(filePath, "utf-8");
|
|
401
|
-
const parsed = JSON.parse(raw);
|
|
402
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
403
|
-
return { filePath, metadata: null };
|
|
404
|
-
}
|
|
405
|
-
return { filePath, metadata: normalizeMetadata(parsed) };
|
|
406
|
-
} catch (error) {
|
|
407
|
-
if (error && typeof error === "object" && error.code === "ENOENT") {
|
|
408
|
-
return { filePath, metadata: null };
|
|
409
|
-
}
|
|
410
|
-
throw error;
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
async function writeMetadata(filePath, metadata) {
|
|
415
|
-
const directory = path.dirname(filePath);
|
|
416
|
-
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
417
|
-
try {
|
|
418
|
-
await fsp.chmod(directory, 0o700);
|
|
419
|
-
} catch {
|
|
420
|
-
// Windows does not reliably support POSIX chmod semantics.
|
|
421
|
-
}
|
|
422
|
-
const tmpPath = path.join(
|
|
423
|
-
directory,
|
|
424
|
-
`.credentials.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`
|
|
425
|
-
);
|
|
426
|
-
const payload = `${JSON.stringify(metadata, null, 2)}\n`;
|
|
427
|
-
try {
|
|
428
|
-
let tmpHandle = null;
|
|
429
|
-
try {
|
|
430
|
-
tmpHandle = await fsp.open(tmpPath, "w", 0o600);
|
|
431
|
-
await tmpHandle.writeFile(payload, { encoding: "utf-8" });
|
|
432
|
-
await tmpHandle.sync();
|
|
433
|
-
} finally {
|
|
434
|
-
if (tmpHandle) {
|
|
435
|
-
await tmpHandle.close().catch(() => {});
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
try {
|
|
439
|
-
await fsp.chmod(tmpPath, 0o600);
|
|
440
|
-
} catch {
|
|
441
|
-
// Windows does not reliably support POSIX chmod semantics.
|
|
442
|
-
}
|
|
443
|
-
try {
|
|
444
|
-
await renameWithRetry(tmpPath, filePath, { attempts: 3, baseDelayMs: 25 });
|
|
445
|
-
} catch (error) {
|
|
446
|
-
if (isRetriableRenameError(error)) {
|
|
447
|
-
await replaceWithBackup(tmpPath, filePath);
|
|
448
|
-
} else {
|
|
449
|
-
throw error;
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
await syncFile(filePath);
|
|
453
|
-
await syncDirectory(directory);
|
|
454
|
-
} finally {
|
|
455
|
-
await fsp.rm(tmpPath, { force: true }).catch(() => {});
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
async function migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir } = {}) {
|
|
460
|
-
if (!metadata || !metadata.token) {
|
|
461
|
-
return { metadata, token: null, migrated: false };
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
const plaintextToken = String(metadata.token || "").trim();
|
|
465
|
-
if (!plaintextToken) {
|
|
466
|
-
return { metadata: { ...metadata, token: null }, token: null, migrated: false };
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
const updatedAt = nowIso();
|
|
470
|
-
const nextMetadata = normalizeMetadata({
|
|
471
|
-
...metadata,
|
|
472
|
-
token: null,
|
|
473
|
-
updatedAt,
|
|
474
|
-
});
|
|
475
|
-
|
|
476
|
-
const keytar = await loadKeytarClient();
|
|
477
|
-
if (keytar) {
|
|
478
|
-
const keyringAccount = metadata.keyringAccount || buildKeyringAccountName(metadata.apiUrl);
|
|
479
|
-
await keytar.setPassword(KEYRING_SERVICE, keyringAccount, plaintextToken);
|
|
480
|
-
nextMetadata.storage = "keyring";
|
|
481
|
-
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
482
|
-
nextMetadata.keyringAccount = keyringAccount;
|
|
483
|
-
const key = await loadOrCreateFileKey({ homeDir });
|
|
484
|
-
const encrypted = encryptToken(plaintextToken, key);
|
|
485
|
-
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
486
|
-
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
487
|
-
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
488
|
-
} else {
|
|
489
|
-
const key = await loadOrCreateFileKey({ homeDir });
|
|
490
|
-
const encrypted = encryptToken(plaintextToken, key);
|
|
491
|
-
nextMetadata.storage = "file";
|
|
492
|
-
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
493
|
-
nextMetadata.keyringAccount = "";
|
|
494
|
-
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
495
|
-
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
496
|
-
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
await writeMetadata(filePath, nextMetadata);
|
|
500
|
-
const { metadata: verify } = await readMetadata({ homeDir });
|
|
501
|
-
if (verify && verify.token) {
|
|
502
|
-
throw new Error("Plaintext token migration failed: token field persisted.");
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
return { metadata: nextMetadata, token: plaintextToken, migrated: true };
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
async function tryDecryptFileToken({ metadata, homeDir }) {
|
|
509
|
-
if (!metadata || !metadata.tokenEncrypted || !metadata.tokenIv || !metadata.tokenTag) {
|
|
510
|
-
return null;
|
|
511
|
-
}
|
|
512
|
-
try {
|
|
513
|
-
const key = await loadOrCreateFileKey({ homeDir });
|
|
514
|
-
const token = decryptToken(
|
|
515
|
-
{
|
|
516
|
-
tokenEncrypted: metadata.tokenEncrypted,
|
|
517
|
-
tokenIv: metadata.tokenIv,
|
|
518
|
-
tokenTag: metadata.tokenTag,
|
|
519
|
-
},
|
|
520
|
-
key
|
|
521
|
-
);
|
|
522
|
-
return token || null;
|
|
523
|
-
} catch {
|
|
524
|
-
return null;
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
/**
|
|
529
|
-
* Load the active stored session, resolving keyring-backed tokens when configured.
|
|
530
|
-
*
|
|
531
|
-
* @param {{ homeDir?: string }} [options]
|
|
532
|
-
* @returns {Promise<null | {
|
|
533
|
-
* version: number,
|
|
534
|
-
* apiUrl: string,
|
|
535
|
-
* storage: "file" | "keyring",
|
|
536
|
-
* keyringService: string,
|
|
537
|
-
* keyringAccount: string,
|
|
538
|
-
* tokenId: string | null,
|
|
539
|
-
* tokenPrefix: string | null,
|
|
540
|
-
* tokenExpiresAt: string | null,
|
|
541
|
-
* createdAt: string,
|
|
542
|
-
* updatedAt: string,
|
|
543
|
-
* user: {
|
|
544
|
-
* id: string,
|
|
545
|
-
* githubUsername: string,
|
|
546
|
-
* email: string,
|
|
547
|
-
* avatarUrl: string,
|
|
548
|
-
* isAdmin: boolean
|
|
549
|
-
* },
|
|
550
|
-
* token: string,
|
|
551
|
-
* filePath: string
|
|
552
|
-
* }>}
|
|
553
|
-
*/
|
|
554
|
-
export async function readStoredSession({ homeDir } = {}) {
|
|
555
|
-
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
556
|
-
if (!metadata) {
|
|
557
|
-
return null;
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
if (metadata.token) {
|
|
561
|
-
const migrated = await migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir });
|
|
562
|
-
if (migrated.migrated) {
|
|
563
|
-
return {
|
|
564
|
-
...migrated.metadata,
|
|
565
|
-
filePath,
|
|
566
|
-
token: migrated.token,
|
|
567
|
-
storage: migrated.metadata.storage || "file",
|
|
568
|
-
};
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
if (metadata.storage === "keyring") {
|
|
573
|
-
const keytar = await loadKeytarClient();
|
|
574
|
-
let keyringError = null;
|
|
575
|
-
if (keytar && metadata.keyringAccount) {
|
|
576
|
-
try {
|
|
577
|
-
const token = await keytar.getPassword(
|
|
578
|
-
metadata.keyringService || KEYRING_SERVICE,
|
|
579
|
-
metadata.keyringAccount
|
|
580
|
-
);
|
|
581
|
-
if (token) {
|
|
582
|
-
return {
|
|
583
|
-
...metadata,
|
|
584
|
-
filePath,
|
|
585
|
-
token,
|
|
586
|
-
storage: "keyring",
|
|
587
|
-
};
|
|
588
|
-
}
|
|
589
|
-
keyringError = new Error("Keyring token not found");
|
|
590
|
-
} catch (error) {
|
|
591
|
-
keyringError = error instanceof Error ? error : new Error("Keyring access failed");
|
|
592
|
-
}
|
|
593
|
-
} else {
|
|
594
|
-
keyringError = new Error("Keyring unavailable");
|
|
595
|
-
}
|
|
596
|
-
const fallbackToken = await tryDecryptFileToken({ metadata, homeDir });
|
|
597
|
-
if (fallbackToken) {
|
|
598
|
-
emitSessionWarning("KEYRING_FALLBACK_USED", {
|
|
599
|
-
reason: keyringError ? String(keyringError.message || keyringError) : "unknown",
|
|
600
|
-
source: "file-encrypted",
|
|
601
|
-
});
|
|
602
|
-
return {
|
|
603
|
-
...metadata,
|
|
604
|
-
filePath,
|
|
605
|
-
token: fallbackToken,
|
|
606
|
-
storage: "file",
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
emitSessionWarning("KEYRING_FALLBACK_UNAVAILABLE", {
|
|
610
|
-
reason: keyringError ? String(keyringError.message || keyringError) : "unknown",
|
|
611
|
-
source: "keyring",
|
|
612
|
-
});
|
|
613
|
-
return null;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
if (!metadata.token) {
|
|
617
|
-
if (metadata.tokenEncrypted && metadata.tokenIv && metadata.tokenTag) {
|
|
618
|
-
const token = await tryDecryptFileToken({ metadata, homeDir });
|
|
619
|
-
if (!token) {
|
|
620
|
-
return null;
|
|
621
|
-
}
|
|
622
|
-
return {
|
|
623
|
-
...metadata,
|
|
624
|
-
filePath,
|
|
625
|
-
token,
|
|
626
|
-
storage: "file",
|
|
627
|
-
};
|
|
628
|
-
}
|
|
629
|
-
return null;
|
|
630
|
-
}
|
|
631
|
-
return {
|
|
632
|
-
...metadata,
|
|
633
|
-
filePath,
|
|
634
|
-
token: metadata.token,
|
|
635
|
-
storage: "file",
|
|
636
|
-
};
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Read persisted session metadata without returning secret token material.
|
|
641
|
-
*
|
|
642
|
-
* @param {{ homeDir?: string }} [options]
|
|
643
|
-
* @returns {Promise<null | {
|
|
644
|
-
* version: number,
|
|
645
|
-
* apiUrl: string,
|
|
646
|
-
* storage: string,
|
|
647
|
-
* keyringService: string,
|
|
648
|
-
* keyringAccount: string,
|
|
649
|
-
* tokenId: string | null,
|
|
650
|
-
* tokenPrefix: string | null,
|
|
651
|
-
* tokenExpiresAt: string | null,
|
|
652
|
-
* createdAt: string,
|
|
653
|
-
* updatedAt: string,
|
|
654
|
-
* user: {
|
|
655
|
-
* id: string,
|
|
656
|
-
* githubUsername: string,
|
|
657
|
-
* email: string,
|
|
658
|
-
* avatarUrl: string,
|
|
659
|
-
* isAdmin: boolean
|
|
660
|
-
* },
|
|
661
|
-
* filePath: string,
|
|
662
|
-
* token: null
|
|
663
|
-
* }>}
|
|
664
|
-
*/
|
|
665
|
-
export async function readStoredSessionMetadata({ homeDir } = {}) {
|
|
666
|
-
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
667
|
-
if (!metadata) {
|
|
668
|
-
return null;
|
|
669
|
-
}
|
|
670
|
-
if (metadata.token) {
|
|
671
|
-
const migrated = await migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir });
|
|
672
|
-
return {
|
|
673
|
-
...migrated.metadata,
|
|
674
|
-
filePath,
|
|
675
|
-
token: null,
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
return {
|
|
679
|
-
...metadata,
|
|
680
|
-
filePath,
|
|
681
|
-
token: null,
|
|
682
|
-
};
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
/**
|
|
686
|
-
* Persist a new session token and metadata using keyring storage when available.
|
|
687
|
-
*
|
|
688
|
-
* @param {{
|
|
689
|
-
* apiUrl: string,
|
|
690
|
-
* token: string,
|
|
691
|
-
* tokenId?: string | null,
|
|
692
|
-
* tokenPrefix?: string | null,
|
|
693
|
-
* tokenExpiresAt?: string | null,
|
|
694
|
-
* user?: Record<string, unknown>
|
|
695
|
-
* }} [session]
|
|
696
|
-
* @param {{ homeDir?: string }} [options]
|
|
697
|
-
* @returns {Promise<{
|
|
698
|
-
* version: number,
|
|
699
|
-
* apiUrl: string,
|
|
700
|
-
* storage: "file" | "keyring",
|
|
701
|
-
* keyringService: string,
|
|
702
|
-
* keyringAccount: string,
|
|
703
|
-
* tokenId: string | null,
|
|
704
|
-
* tokenPrefix: string | null,
|
|
705
|
-
* tokenExpiresAt: string | null,
|
|
706
|
-
* createdAt: string,
|
|
707
|
-
* updatedAt: string,
|
|
708
|
-
* user: {
|
|
709
|
-
* id: string,
|
|
710
|
-
* githubUsername: string,
|
|
711
|
-
* email: string,
|
|
712
|
-
* avatarUrl: string,
|
|
713
|
-
* isAdmin: boolean
|
|
714
|
-
* },
|
|
715
|
-
* filePath: string,
|
|
716
|
-
* token: string
|
|
717
|
-
* }>}
|
|
718
|
-
*/
|
|
719
|
-
export async function writeStoredSession(
|
|
720
|
-
{
|
|
721
|
-
apiUrl,
|
|
722
|
-
token,
|
|
723
|
-
tokenId = null,
|
|
724
|
-
tokenPrefix = null,
|
|
725
|
-
tokenExpiresAt = null,
|
|
726
|
-
user = {},
|
|
727
|
-
} = {},
|
|
728
|
-
{ homeDir } = {}
|
|
729
|
-
) {
|
|
730
|
-
const normalizedApiUrl = String(apiUrl || "").trim();
|
|
731
|
-
const normalizedToken = String(token || "").trim();
|
|
732
|
-
if (!normalizedApiUrl) {
|
|
733
|
-
throw new Error("apiUrl is required to persist CLI auth session.");
|
|
734
|
-
}
|
|
735
|
-
if (!normalizedToken) {
|
|
736
|
-
throw new Error("token is required to persist CLI auth session.");
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
const { filePath, metadata: existingMetadata } = await readMetadata({ homeDir });
|
|
740
|
-
const keytar = await loadKeytarClient();
|
|
741
|
-
const keyringAccount = buildKeyringAccountName(normalizedApiUrl);
|
|
742
|
-
const updatedAt = nowIso();
|
|
743
|
-
|
|
744
|
-
const nextMetadata = normalizeMetadata({
|
|
745
|
-
version: CREDENTIALS_VERSION,
|
|
746
|
-
apiUrl: normalizedApiUrl,
|
|
747
|
-
tokenId,
|
|
748
|
-
tokenPrefix,
|
|
749
|
-
tokenExpiresAt,
|
|
750
|
-
user: normalizeUser(user),
|
|
751
|
-
createdAt: existingMetadata?.createdAt || updatedAt,
|
|
752
|
-
updatedAt,
|
|
753
|
-
});
|
|
754
|
-
|
|
755
|
-
if (keytar) {
|
|
756
|
-
const previousKeyringAccount = String(existingMetadata?.keyringAccount || "").trim();
|
|
757
|
-
const previousStorage = String(existingMetadata?.storage || "").trim();
|
|
758
|
-
if (previousStorage === "keyring" && previousKeyringAccount && previousKeyringAccount !== keyringAccount) {
|
|
759
|
-
await keytar.deletePassword(KEYRING_SERVICE, previousKeyringAccount);
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
await keytar.setPassword(KEYRING_SERVICE, keyringAccount, normalizedToken);
|
|
763
|
-
nextMetadata.storage = "keyring";
|
|
764
|
-
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
765
|
-
nextMetadata.keyringAccount = keyringAccount;
|
|
766
|
-
nextMetadata.token = null;
|
|
767
|
-
} else {
|
|
768
|
-
nextMetadata.storage = "file";
|
|
769
|
-
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
770
|
-
nextMetadata.keyringAccount = "";
|
|
771
|
-
const key = await loadOrCreateFileKey({ homeDir });
|
|
772
|
-
const encrypted = encryptToken(normalizedToken, key);
|
|
773
|
-
nextMetadata.token = null;
|
|
774
|
-
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
775
|
-
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
776
|
-
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
await writeMetadata(filePath, nextMetadata);
|
|
780
|
-
|
|
781
|
-
return {
|
|
782
|
-
...nextMetadata,
|
|
783
|
-
filePath,
|
|
784
|
-
token: normalizedToken,
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
/**
|
|
789
|
-
* Remove local session metadata and keyring credentials for the active account.
|
|
790
|
-
*
|
|
791
|
-
* @param {{ homeDir?: string }} [options]
|
|
792
|
-
* @returns {Promise<{ filePath: string, hadSession: boolean }>}
|
|
793
|
-
*/
|
|
794
|
-
export async function clearStoredSession({ homeDir } = {}) {
|
|
795
|
-
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
796
|
-
if (metadata && metadata.storage === "keyring") {
|
|
797
|
-
const keytar = await loadKeytarClient();
|
|
798
|
-
if (keytar && metadata.keyringAccount) {
|
|
799
|
-
await keytar.deletePassword(metadata.keyringService || KEYRING_SERVICE, metadata.keyringAccount);
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
try {
|
|
804
|
-
await fsp.rm(filePath, { force: true });
|
|
805
|
-
} catch {
|
|
806
|
-
// Ignore cleanup errors.
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
return {
|
|
810
|
-
filePath,
|
|
811
|
-
hadSession: Boolean(metadata),
|
|
812
|
-
};
|
|
813
|
-
}
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fsp from "node:fs/promises";
|
|
5
|
+
import process from "node:process";
|
|
6
|
+
|
|
7
|
+
const CREDENTIALS_VERSION = 1;
|
|
8
|
+
const KEYRING_SERVICE = "sentinelayer-cli";
|
|
9
|
+
const SESSION_WARNING_PREFIX = "sentinelayer.auth.session";
|
|
10
|
+
const SESSION_WARNING_REDACT_KEYS = /token|secret|password|key|authorization/i;
|
|
11
|
+
const SESSION_WARNING_MAX_VALUE_LENGTH = 200;
|
|
12
|
+
const SESSION_WARNING_ALLOWED_FIELDS = new Set([
|
|
13
|
+
"reason",
|
|
14
|
+
"source",
|
|
15
|
+
"operation",
|
|
16
|
+
"storage",
|
|
17
|
+
"codeHint",
|
|
18
|
+
"requestIdHash",
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
function nowIso() {
|
|
22
|
+
return new Date().toISOString();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function createSessionWarningId() {
|
|
26
|
+
try {
|
|
27
|
+
return crypto.randomUUID();
|
|
28
|
+
} catch {
|
|
29
|
+
return `session-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function sanitizeSessionWarningValue(value, depth = 0) {
|
|
34
|
+
if (value === null || value === undefined) {
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
if (depth > 3) {
|
|
38
|
+
return "[TRUNCATED]";
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(value)) {
|
|
41
|
+
return value.map((entry) => sanitizeSessionWarningValue(entry, depth + 1));
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === "object") {
|
|
44
|
+
const sanitized = {};
|
|
45
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
46
|
+
if (SESSION_WARNING_REDACT_KEYS.test(key)) {
|
|
47
|
+
sanitized[key] = "[REDACTED]";
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
sanitized[key] = sanitizeSessionWarningValue(entry, depth + 1);
|
|
51
|
+
}
|
|
52
|
+
return sanitized;
|
|
53
|
+
}
|
|
54
|
+
if (typeof value === "string") {
|
|
55
|
+
if (value.length > SESSION_WARNING_MAX_VALUE_LENGTH) {
|
|
56
|
+
return `${value.slice(0, SESSION_WARNING_MAX_VALUE_LENGTH)}…`;
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function sanitizeSessionWarningDetails(details) {
|
|
64
|
+
if (!details || typeof details !== "object") {
|
|
65
|
+
return {};
|
|
66
|
+
}
|
|
67
|
+
return sanitizeSessionWarningValue(details, 0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function emitSessionWarning(code, details = {}) {
|
|
71
|
+
const sanitizedDetails = sanitizeSessionWarningDetails(details);
|
|
72
|
+
const payload = {
|
|
73
|
+
level: "warn",
|
|
74
|
+
code: String(code || "SESSION_WARNING").toUpperCase(),
|
|
75
|
+
warningId: createSessionWarningId(),
|
|
76
|
+
timestamp: nowIso(),
|
|
77
|
+
};
|
|
78
|
+
for (const [key, value] of Object.entries(sanitizedDetails)) {
|
|
79
|
+
if (SESSION_WARNING_ALLOWED_FIELDS.has(key)) {
|
|
80
|
+
payload[key] = value;
|
|
81
|
+
} else {
|
|
82
|
+
payload[key] = "[OMITTED]";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
console.warn(`${SESSION_WARNING_PREFIX} ${JSON.stringify(payload)}`);
|
|
87
|
+
} catch {
|
|
88
|
+
console.warn(`${SESSION_WARNING_PREFIX} ${payload.code}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function resolveHomeDir(homeDir) {
|
|
93
|
+
return path.resolve(String(homeDir || os.homedir()));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Resolve the deterministic credentials metadata file path for the current user/home override.
|
|
98
|
+
*
|
|
99
|
+
* @param {{ homeDir?: string }} [options]
|
|
100
|
+
* @returns {string}
|
|
101
|
+
*/
|
|
102
|
+
export function resolveCredentialsFilePath({ homeDir } = {}) {
|
|
103
|
+
const resolvedHome = resolveHomeDir(homeDir);
|
|
104
|
+
return path.join(resolvedHome, ".sentinelayer", "credentials.json");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function resolveCredentialsKeyPath({ homeDir } = {}) {
|
|
108
|
+
const resolvedHome = resolveHomeDir(homeDir);
|
|
109
|
+
return path.join(resolvedHome, ".sentinelayer", "keys", "credentials.key");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function resolveLegacyCredentialsKeyPath({ homeDir } = {}) {
|
|
113
|
+
const resolvedHome = resolveHomeDir(homeDir);
|
|
114
|
+
return path.join(resolvedHome, ".sentinelayer", "credentials.key");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function loadOrCreateFileKey({ homeDir } = {}) {
|
|
118
|
+
const keyPath = resolveCredentialsKeyPath({ homeDir });
|
|
119
|
+
const legacyKeyPath = resolveLegacyCredentialsKeyPath({ homeDir });
|
|
120
|
+
try {
|
|
121
|
+
const raw = await fsp.readFile(keyPath, "utf-8");
|
|
122
|
+
const key = Buffer.from(String(raw || "").trim(), "base64");
|
|
123
|
+
if (key.length === 32) {
|
|
124
|
+
return key;
|
|
125
|
+
}
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
const legacyRaw = await fsp.readFile(legacyKeyPath, "utf-8");
|
|
134
|
+
const legacyKey = Buffer.from(String(legacyRaw || "").trim(), "base64");
|
|
135
|
+
if (legacyKey.length === 32) {
|
|
136
|
+
await fsp.mkdir(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
|
137
|
+
await fsp.writeFile(keyPath, legacyKey.toString("base64"), { encoding: "utf-8", mode: 0o600 });
|
|
138
|
+
try {
|
|
139
|
+
await fsp.chmod(keyPath, 0o600);
|
|
140
|
+
} catch {
|
|
141
|
+
// Windows does not reliably support POSIX chmod semantics.
|
|
142
|
+
}
|
|
143
|
+
let verified = false;
|
|
144
|
+
try {
|
|
145
|
+
const verifyRaw = await fsp.readFile(keyPath, "utf-8");
|
|
146
|
+
const verifyKey = Buffer.from(String(verifyRaw || "").trim(), "base64");
|
|
147
|
+
verified = verifyKey.length === 32 && verifyKey.equals(legacyKey);
|
|
148
|
+
} catch {
|
|
149
|
+
verified = false;
|
|
150
|
+
}
|
|
151
|
+
if (verified) {
|
|
152
|
+
await fsp.rm(legacyKeyPath, { force: true });
|
|
153
|
+
}
|
|
154
|
+
return legacyKey;
|
|
155
|
+
}
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const key = crypto.randomBytes(32);
|
|
163
|
+
await fsp.mkdir(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
|
164
|
+
await fsp.writeFile(keyPath, key.toString("base64"), { encoding: "utf-8", mode: 0o600 });
|
|
165
|
+
try {
|
|
166
|
+
await fsp.chmod(keyPath, 0o600);
|
|
167
|
+
} catch {
|
|
168
|
+
// Windows does not reliably support POSIX chmod semantics.
|
|
169
|
+
}
|
|
170
|
+
return key;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function encryptToken(token, key) {
|
|
174
|
+
const iv = crypto.randomBytes(12);
|
|
175
|
+
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
176
|
+
const ciphertext = Buffer.concat([cipher.update(token, "utf-8"), cipher.final()]);
|
|
177
|
+
const tag = cipher.getAuthTag();
|
|
178
|
+
return {
|
|
179
|
+
tokenEncrypted: ciphertext.toString("base64"),
|
|
180
|
+
tokenIv: iv.toString("base64"),
|
|
181
|
+
tokenTag: tag.toString("base64"),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function decryptToken({ tokenEncrypted, tokenIv, tokenTag }, key) {
|
|
186
|
+
const iv = Buffer.from(tokenIv, "base64");
|
|
187
|
+
const tag = Buffer.from(tokenTag, "base64");
|
|
188
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
|
189
|
+
decipher.setAuthTag(tag);
|
|
190
|
+
const plaintext = Buffer.concat([
|
|
191
|
+
decipher.update(Buffer.from(tokenEncrypted, "base64")),
|
|
192
|
+
decipher.final(),
|
|
193
|
+
]);
|
|
194
|
+
return plaintext.toString("utf-8");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function buildKeyringAccountName(apiUrl) {
|
|
198
|
+
const digest = crypto
|
|
199
|
+
.createHash("sha256")
|
|
200
|
+
.update(String(apiUrl || "").trim().toLowerCase())
|
|
201
|
+
.digest("hex")
|
|
202
|
+
.slice(0, 16);
|
|
203
|
+
return `default-${digest}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function normalizeUser(user = {}) {
|
|
207
|
+
return {
|
|
208
|
+
id: String(user.id || "").trim(),
|
|
209
|
+
githubUsername: String(user.githubUsername || user.github_username || "").trim(),
|
|
210
|
+
email: String(user.email || "").trim(),
|
|
211
|
+
avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
|
|
212
|
+
isAdmin: Boolean(user.isAdmin || user.is_admin),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function normalizeAidenId(raw) {
|
|
217
|
+
if (!raw || typeof raw !== "object") return null;
|
|
218
|
+
const orgId = String(raw.orgId || "").trim();
|
|
219
|
+
const projectId = String(raw.projectId || "").trim();
|
|
220
|
+
if (!orgId && !projectId) return null;
|
|
221
|
+
return {
|
|
222
|
+
orgId: orgId || null,
|
|
223
|
+
projectId: projectId || null,
|
|
224
|
+
apiKeyPrefix: String(raw.apiKeyPrefix || "").trim() || null,
|
|
225
|
+
provisionedAt: String(raw.provisionedAt || "").trim() || null,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function normalizeMetadata(raw = {}) {
|
|
230
|
+
return {
|
|
231
|
+
version: Number(raw.version || CREDENTIALS_VERSION),
|
|
232
|
+
apiUrl: String(raw.apiUrl || "").trim(),
|
|
233
|
+
storage: String(raw.storage || "file").trim(),
|
|
234
|
+
keyringService: String(raw.keyringService || KEYRING_SERVICE).trim(),
|
|
235
|
+
keyringAccount: String(raw.keyringAccount || "").trim(),
|
|
236
|
+
tokenId: String(raw.tokenId || "").trim() || null,
|
|
237
|
+
tokenPrefix: String(raw.tokenPrefix || "").trim() || null,
|
|
238
|
+
tokenExpiresAt: String(raw.tokenExpiresAt || "").trim() || null,
|
|
239
|
+
createdAt: String(raw.createdAt || "").trim() || nowIso(),
|
|
240
|
+
updatedAt: String(raw.updatedAt || "").trim() || nowIso(),
|
|
241
|
+
user: normalizeUser(raw.user),
|
|
242
|
+
token: String(raw.token || "").trim() || null,
|
|
243
|
+
tokenEncrypted: String(raw.tokenEncrypted || "").trim() || null,
|
|
244
|
+
tokenIv: String(raw.tokenIv || "").trim() || null,
|
|
245
|
+
tokenTag: String(raw.tokenTag || "").trim() || null,
|
|
246
|
+
aidenid: normalizeAidenId(raw.aidenid),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function isRetriableRenameError(error) {
|
|
251
|
+
if (!error || typeof error !== "object") {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
return (
|
|
255
|
+
error.code === "EPERM" ||
|
|
256
|
+
error.code === "EACCES" ||
|
|
257
|
+
error.code === "EEXIST" ||
|
|
258
|
+
error.code === "EBUSY"
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function delayMilliseconds(ms) {
|
|
263
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function renameWithRetry(sourcePath, destinationPath, { attempts = 3, baseDelayMs = 25 } = {}) {
|
|
267
|
+
let lastError = null;
|
|
268
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
269
|
+
try {
|
|
270
|
+
await fsp.rename(sourcePath, destinationPath);
|
|
271
|
+
return;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
lastError = error;
|
|
274
|
+
if (!isRetriableRenameError(error) || attempt >= attempts) {
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
await delayMilliseconds(baseDelayMs * attempt);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
throw lastError;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function syncFile(filePath) {
|
|
284
|
+
const normalizedPath = String(filePath || "").trim();
|
|
285
|
+
if (!normalizedPath) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
let handle = null;
|
|
289
|
+
try {
|
|
290
|
+
handle = await fsp.open(normalizedPath, "r");
|
|
291
|
+
await handle.sync();
|
|
292
|
+
} catch {
|
|
293
|
+
// Best effort only. Some filesystems/runtimes do not support explicit fsync.
|
|
294
|
+
} finally {
|
|
295
|
+
if (handle) {
|
|
296
|
+
await handle.close().catch(() => {});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function syncDirectory(directoryPath) {
|
|
302
|
+
const normalizedPath = String(directoryPath || "").trim();
|
|
303
|
+
if (!normalizedPath) {
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
let handle = null;
|
|
307
|
+
try {
|
|
308
|
+
handle = await fsp.open(normalizedPath, "r");
|
|
309
|
+
await handle.sync();
|
|
310
|
+
} catch {
|
|
311
|
+
// Directory fsync support is platform-dependent; ignore when unsupported.
|
|
312
|
+
} finally {
|
|
313
|
+
if (handle) {
|
|
314
|
+
await handle.close().catch(() => {});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function replaceWithBackup(tmpPath, filePath) {
|
|
320
|
+
const directory = path.dirname(filePath);
|
|
321
|
+
const backupPath = path.join(
|
|
322
|
+
directory,
|
|
323
|
+
`.credentials.backup.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.bak`
|
|
324
|
+
);
|
|
325
|
+
let backupCreated = false;
|
|
326
|
+
try {
|
|
327
|
+
try {
|
|
328
|
+
await fsp.rename(filePath, backupPath);
|
|
329
|
+
backupCreated = true;
|
|
330
|
+
await syncDirectory(directory);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) {
|
|
333
|
+
throw error;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
await renameWithRetry(tmpPath, filePath, { attempts: 3, baseDelayMs: 40 });
|
|
338
|
+
await syncFile(filePath);
|
|
339
|
+
await syncDirectory(directory);
|
|
340
|
+
|
|
341
|
+
if (backupCreated) {
|
|
342
|
+
await fsp.rm(backupPath, { force: true }).catch(() => {});
|
|
343
|
+
await syncDirectory(directory);
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (backupCreated) {
|
|
347
|
+
try {
|
|
348
|
+
await fsp.rename(backupPath, filePath);
|
|
349
|
+
await syncFile(filePath);
|
|
350
|
+
await syncDirectory(directory);
|
|
351
|
+
} catch {
|
|
352
|
+
// Best-effort restore; keep original error as the primary failure.
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function loadKeytarClient() {
|
|
360
|
+
const disableKeyring = String(process.env.SENTINELAYER_DISABLE_KEYRING || "")
|
|
361
|
+
.trim()
|
|
362
|
+
.toLowerCase();
|
|
363
|
+
if (disableKeyring === "1" || disableKeyring === "true" || disableKeyring === "yes" || disableKeyring === "on") {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
const keyringMode = String(process.env.SENTINELAYER_KEYRING_MODE || "")
|
|
367
|
+
.trim()
|
|
368
|
+
.toLowerCase();
|
|
369
|
+
const enableKeyring =
|
|
370
|
+
keyringMode === "keyring" ||
|
|
371
|
+
keyringMode === "enabled" ||
|
|
372
|
+
keyringMode === "on" ||
|
|
373
|
+
keyringMode === "true" ||
|
|
374
|
+
keyringMode === "1";
|
|
375
|
+
if (!enableKeyring) {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
const mod = await import("keytar");
|
|
380
|
+
const client = mod && typeof mod === "object" ? mod.default || mod : null;
|
|
381
|
+
if (!client) {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
if (
|
|
385
|
+
typeof client.getPassword !== "function" ||
|
|
386
|
+
typeof client.setPassword !== "function" ||
|
|
387
|
+
typeof client.deletePassword !== "function"
|
|
388
|
+
) {
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
return client;
|
|
392
|
+
} catch {
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function readMetadata({ homeDir } = {}) {
|
|
398
|
+
const filePath = resolveCredentialsFilePath({ homeDir });
|
|
399
|
+
try {
|
|
400
|
+
const raw = await fsp.readFile(filePath, "utf-8");
|
|
401
|
+
const parsed = JSON.parse(raw);
|
|
402
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
403
|
+
return { filePath, metadata: null };
|
|
404
|
+
}
|
|
405
|
+
return { filePath, metadata: normalizeMetadata(parsed) };
|
|
406
|
+
} catch (error) {
|
|
407
|
+
if (error && typeof error === "object" && error.code === "ENOENT") {
|
|
408
|
+
return { filePath, metadata: null };
|
|
409
|
+
}
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function writeMetadata(filePath, metadata) {
|
|
415
|
+
const directory = path.dirname(filePath);
|
|
416
|
+
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
417
|
+
try {
|
|
418
|
+
await fsp.chmod(directory, 0o700);
|
|
419
|
+
} catch {
|
|
420
|
+
// Windows does not reliably support POSIX chmod semantics.
|
|
421
|
+
}
|
|
422
|
+
const tmpPath = path.join(
|
|
423
|
+
directory,
|
|
424
|
+
`.credentials.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`
|
|
425
|
+
);
|
|
426
|
+
const payload = `${JSON.stringify(metadata, null, 2)}\n`;
|
|
427
|
+
try {
|
|
428
|
+
let tmpHandle = null;
|
|
429
|
+
try {
|
|
430
|
+
tmpHandle = await fsp.open(tmpPath, "w", 0o600);
|
|
431
|
+
await tmpHandle.writeFile(payload, { encoding: "utf-8" });
|
|
432
|
+
await tmpHandle.sync();
|
|
433
|
+
} finally {
|
|
434
|
+
if (tmpHandle) {
|
|
435
|
+
await tmpHandle.close().catch(() => {});
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
await fsp.chmod(tmpPath, 0o600);
|
|
440
|
+
} catch {
|
|
441
|
+
// Windows does not reliably support POSIX chmod semantics.
|
|
442
|
+
}
|
|
443
|
+
try {
|
|
444
|
+
await renameWithRetry(tmpPath, filePath, { attempts: 3, baseDelayMs: 25 });
|
|
445
|
+
} catch (error) {
|
|
446
|
+
if (isRetriableRenameError(error)) {
|
|
447
|
+
await replaceWithBackup(tmpPath, filePath);
|
|
448
|
+
} else {
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
await syncFile(filePath);
|
|
453
|
+
await syncDirectory(directory);
|
|
454
|
+
} finally {
|
|
455
|
+
await fsp.rm(tmpPath, { force: true }).catch(() => {});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
async function migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir } = {}) {
|
|
460
|
+
if (!metadata || !metadata.token) {
|
|
461
|
+
return { metadata, token: null, migrated: false };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const plaintextToken = String(metadata.token || "").trim();
|
|
465
|
+
if (!plaintextToken) {
|
|
466
|
+
return { metadata: { ...metadata, token: null }, token: null, migrated: false };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const updatedAt = nowIso();
|
|
470
|
+
const nextMetadata = normalizeMetadata({
|
|
471
|
+
...metadata,
|
|
472
|
+
token: null,
|
|
473
|
+
updatedAt,
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
const keytar = await loadKeytarClient();
|
|
477
|
+
if (keytar) {
|
|
478
|
+
const keyringAccount = metadata.keyringAccount || buildKeyringAccountName(metadata.apiUrl);
|
|
479
|
+
await keytar.setPassword(KEYRING_SERVICE, keyringAccount, plaintextToken);
|
|
480
|
+
nextMetadata.storage = "keyring";
|
|
481
|
+
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
482
|
+
nextMetadata.keyringAccount = keyringAccount;
|
|
483
|
+
const key = await loadOrCreateFileKey({ homeDir });
|
|
484
|
+
const encrypted = encryptToken(plaintextToken, key);
|
|
485
|
+
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
486
|
+
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
487
|
+
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
488
|
+
} else {
|
|
489
|
+
const key = await loadOrCreateFileKey({ homeDir });
|
|
490
|
+
const encrypted = encryptToken(plaintextToken, key);
|
|
491
|
+
nextMetadata.storage = "file";
|
|
492
|
+
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
493
|
+
nextMetadata.keyringAccount = "";
|
|
494
|
+
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
495
|
+
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
496
|
+
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
await writeMetadata(filePath, nextMetadata);
|
|
500
|
+
const { metadata: verify } = await readMetadata({ homeDir });
|
|
501
|
+
if (verify && verify.token) {
|
|
502
|
+
throw new Error("Plaintext token migration failed: token field persisted.");
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
return { metadata: nextMetadata, token: plaintextToken, migrated: true };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function tryDecryptFileToken({ metadata, homeDir }) {
|
|
509
|
+
if (!metadata || !metadata.tokenEncrypted || !metadata.tokenIv || !metadata.tokenTag) {
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
try {
|
|
513
|
+
const key = await loadOrCreateFileKey({ homeDir });
|
|
514
|
+
const token = decryptToken(
|
|
515
|
+
{
|
|
516
|
+
tokenEncrypted: metadata.tokenEncrypted,
|
|
517
|
+
tokenIv: metadata.tokenIv,
|
|
518
|
+
tokenTag: metadata.tokenTag,
|
|
519
|
+
},
|
|
520
|
+
key
|
|
521
|
+
);
|
|
522
|
+
return token || null;
|
|
523
|
+
} catch {
|
|
524
|
+
return null;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Load the active stored session, resolving keyring-backed tokens when configured.
|
|
530
|
+
*
|
|
531
|
+
* @param {{ homeDir?: string }} [options]
|
|
532
|
+
* @returns {Promise<null | {
|
|
533
|
+
* version: number,
|
|
534
|
+
* apiUrl: string,
|
|
535
|
+
* storage: "file" | "keyring",
|
|
536
|
+
* keyringService: string,
|
|
537
|
+
* keyringAccount: string,
|
|
538
|
+
* tokenId: string | null,
|
|
539
|
+
* tokenPrefix: string | null,
|
|
540
|
+
* tokenExpiresAt: string | null,
|
|
541
|
+
* createdAt: string,
|
|
542
|
+
* updatedAt: string,
|
|
543
|
+
* user: {
|
|
544
|
+
* id: string,
|
|
545
|
+
* githubUsername: string,
|
|
546
|
+
* email: string,
|
|
547
|
+
* avatarUrl: string,
|
|
548
|
+
* isAdmin: boolean
|
|
549
|
+
* },
|
|
550
|
+
* token: string,
|
|
551
|
+
* filePath: string
|
|
552
|
+
* }>}
|
|
553
|
+
*/
|
|
554
|
+
export async function readStoredSession({ homeDir } = {}) {
|
|
555
|
+
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
556
|
+
if (!metadata) {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (metadata.token) {
|
|
561
|
+
const migrated = await migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir });
|
|
562
|
+
if (migrated.migrated) {
|
|
563
|
+
return {
|
|
564
|
+
...migrated.metadata,
|
|
565
|
+
filePath,
|
|
566
|
+
token: migrated.token,
|
|
567
|
+
storage: migrated.metadata.storage || "file",
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (metadata.storage === "keyring") {
|
|
573
|
+
const keytar = await loadKeytarClient();
|
|
574
|
+
let keyringError = null;
|
|
575
|
+
if (keytar && metadata.keyringAccount) {
|
|
576
|
+
try {
|
|
577
|
+
const token = await keytar.getPassword(
|
|
578
|
+
metadata.keyringService || KEYRING_SERVICE,
|
|
579
|
+
metadata.keyringAccount
|
|
580
|
+
);
|
|
581
|
+
if (token) {
|
|
582
|
+
return {
|
|
583
|
+
...metadata,
|
|
584
|
+
filePath,
|
|
585
|
+
token,
|
|
586
|
+
storage: "keyring",
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
keyringError = new Error("Keyring token not found");
|
|
590
|
+
} catch (error) {
|
|
591
|
+
keyringError = error instanceof Error ? error : new Error("Keyring access failed");
|
|
592
|
+
}
|
|
593
|
+
} else {
|
|
594
|
+
keyringError = new Error("Keyring unavailable");
|
|
595
|
+
}
|
|
596
|
+
const fallbackToken = await tryDecryptFileToken({ metadata, homeDir });
|
|
597
|
+
if (fallbackToken) {
|
|
598
|
+
emitSessionWarning("KEYRING_FALLBACK_USED", {
|
|
599
|
+
reason: keyringError ? String(keyringError.message || keyringError) : "unknown",
|
|
600
|
+
source: "file-encrypted",
|
|
601
|
+
});
|
|
602
|
+
return {
|
|
603
|
+
...metadata,
|
|
604
|
+
filePath,
|
|
605
|
+
token: fallbackToken,
|
|
606
|
+
storage: "file",
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
emitSessionWarning("KEYRING_FALLBACK_UNAVAILABLE", {
|
|
610
|
+
reason: keyringError ? String(keyringError.message || keyringError) : "unknown",
|
|
611
|
+
source: "keyring",
|
|
612
|
+
});
|
|
613
|
+
return null;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
if (!metadata.token) {
|
|
617
|
+
if (metadata.tokenEncrypted && metadata.tokenIv && metadata.tokenTag) {
|
|
618
|
+
const token = await tryDecryptFileToken({ metadata, homeDir });
|
|
619
|
+
if (!token) {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
return {
|
|
623
|
+
...metadata,
|
|
624
|
+
filePath,
|
|
625
|
+
token,
|
|
626
|
+
storage: "file",
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
return {
|
|
632
|
+
...metadata,
|
|
633
|
+
filePath,
|
|
634
|
+
token: metadata.token,
|
|
635
|
+
storage: "file",
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Read persisted session metadata without returning secret token material.
|
|
641
|
+
*
|
|
642
|
+
* @param {{ homeDir?: string }} [options]
|
|
643
|
+
* @returns {Promise<null | {
|
|
644
|
+
* version: number,
|
|
645
|
+
* apiUrl: string,
|
|
646
|
+
* storage: string,
|
|
647
|
+
* keyringService: string,
|
|
648
|
+
* keyringAccount: string,
|
|
649
|
+
* tokenId: string | null,
|
|
650
|
+
* tokenPrefix: string | null,
|
|
651
|
+
* tokenExpiresAt: string | null,
|
|
652
|
+
* createdAt: string,
|
|
653
|
+
* updatedAt: string,
|
|
654
|
+
* user: {
|
|
655
|
+
* id: string,
|
|
656
|
+
* githubUsername: string,
|
|
657
|
+
* email: string,
|
|
658
|
+
* avatarUrl: string,
|
|
659
|
+
* isAdmin: boolean
|
|
660
|
+
* },
|
|
661
|
+
* filePath: string,
|
|
662
|
+
* token: null
|
|
663
|
+
* }>}
|
|
664
|
+
*/
|
|
665
|
+
export async function readStoredSessionMetadata({ homeDir } = {}) {
|
|
666
|
+
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
667
|
+
if (!metadata) {
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
if (metadata.token) {
|
|
671
|
+
const migrated = await migratePlaintextTokenIfNeeded({ metadata, filePath, homeDir });
|
|
672
|
+
return {
|
|
673
|
+
...migrated.metadata,
|
|
674
|
+
filePath,
|
|
675
|
+
token: null,
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
return {
|
|
679
|
+
...metadata,
|
|
680
|
+
filePath,
|
|
681
|
+
token: null,
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Persist a new session token and metadata using keyring storage when available.
|
|
687
|
+
*
|
|
688
|
+
* @param {{
|
|
689
|
+
* apiUrl: string,
|
|
690
|
+
* token: string,
|
|
691
|
+
* tokenId?: string | null,
|
|
692
|
+
* tokenPrefix?: string | null,
|
|
693
|
+
* tokenExpiresAt?: string | null,
|
|
694
|
+
* user?: Record<string, unknown>
|
|
695
|
+
* }} [session]
|
|
696
|
+
* @param {{ homeDir?: string }} [options]
|
|
697
|
+
* @returns {Promise<{
|
|
698
|
+
* version: number,
|
|
699
|
+
* apiUrl: string,
|
|
700
|
+
* storage: "file" | "keyring",
|
|
701
|
+
* keyringService: string,
|
|
702
|
+
* keyringAccount: string,
|
|
703
|
+
* tokenId: string | null,
|
|
704
|
+
* tokenPrefix: string | null,
|
|
705
|
+
* tokenExpiresAt: string | null,
|
|
706
|
+
* createdAt: string,
|
|
707
|
+
* updatedAt: string,
|
|
708
|
+
* user: {
|
|
709
|
+
* id: string,
|
|
710
|
+
* githubUsername: string,
|
|
711
|
+
* email: string,
|
|
712
|
+
* avatarUrl: string,
|
|
713
|
+
* isAdmin: boolean
|
|
714
|
+
* },
|
|
715
|
+
* filePath: string,
|
|
716
|
+
* token: string
|
|
717
|
+
* }>}
|
|
718
|
+
*/
|
|
719
|
+
export async function writeStoredSession(
|
|
720
|
+
{
|
|
721
|
+
apiUrl,
|
|
722
|
+
token,
|
|
723
|
+
tokenId = null,
|
|
724
|
+
tokenPrefix = null,
|
|
725
|
+
tokenExpiresAt = null,
|
|
726
|
+
user = {},
|
|
727
|
+
} = {},
|
|
728
|
+
{ homeDir } = {}
|
|
729
|
+
) {
|
|
730
|
+
const normalizedApiUrl = String(apiUrl || "").trim();
|
|
731
|
+
const normalizedToken = String(token || "").trim();
|
|
732
|
+
if (!normalizedApiUrl) {
|
|
733
|
+
throw new Error("apiUrl is required to persist CLI auth session.");
|
|
734
|
+
}
|
|
735
|
+
if (!normalizedToken) {
|
|
736
|
+
throw new Error("token is required to persist CLI auth session.");
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const { filePath, metadata: existingMetadata } = await readMetadata({ homeDir });
|
|
740
|
+
const keytar = await loadKeytarClient();
|
|
741
|
+
const keyringAccount = buildKeyringAccountName(normalizedApiUrl);
|
|
742
|
+
const updatedAt = nowIso();
|
|
743
|
+
|
|
744
|
+
const nextMetadata = normalizeMetadata({
|
|
745
|
+
version: CREDENTIALS_VERSION,
|
|
746
|
+
apiUrl: normalizedApiUrl,
|
|
747
|
+
tokenId,
|
|
748
|
+
tokenPrefix,
|
|
749
|
+
tokenExpiresAt,
|
|
750
|
+
user: normalizeUser(user),
|
|
751
|
+
createdAt: existingMetadata?.createdAt || updatedAt,
|
|
752
|
+
updatedAt,
|
|
753
|
+
});
|
|
754
|
+
|
|
755
|
+
if (keytar) {
|
|
756
|
+
const previousKeyringAccount = String(existingMetadata?.keyringAccount || "").trim();
|
|
757
|
+
const previousStorage = String(existingMetadata?.storage || "").trim();
|
|
758
|
+
if (previousStorage === "keyring" && previousKeyringAccount && previousKeyringAccount !== keyringAccount) {
|
|
759
|
+
await keytar.deletePassword(KEYRING_SERVICE, previousKeyringAccount);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
await keytar.setPassword(KEYRING_SERVICE, keyringAccount, normalizedToken);
|
|
763
|
+
nextMetadata.storage = "keyring";
|
|
764
|
+
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
765
|
+
nextMetadata.keyringAccount = keyringAccount;
|
|
766
|
+
nextMetadata.token = null;
|
|
767
|
+
} else {
|
|
768
|
+
nextMetadata.storage = "file";
|
|
769
|
+
nextMetadata.keyringService = KEYRING_SERVICE;
|
|
770
|
+
nextMetadata.keyringAccount = "";
|
|
771
|
+
const key = await loadOrCreateFileKey({ homeDir });
|
|
772
|
+
const encrypted = encryptToken(normalizedToken, key);
|
|
773
|
+
nextMetadata.token = null;
|
|
774
|
+
nextMetadata.tokenEncrypted = encrypted.tokenEncrypted;
|
|
775
|
+
nextMetadata.tokenIv = encrypted.tokenIv;
|
|
776
|
+
nextMetadata.tokenTag = encrypted.tokenTag;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
await writeMetadata(filePath, nextMetadata);
|
|
780
|
+
|
|
781
|
+
return {
|
|
782
|
+
...nextMetadata,
|
|
783
|
+
filePath,
|
|
784
|
+
token: normalizedToken,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Remove local session metadata and keyring credentials for the active account.
|
|
790
|
+
*
|
|
791
|
+
* @param {{ homeDir?: string }} [options]
|
|
792
|
+
* @returns {Promise<{ filePath: string, hadSession: boolean }>}
|
|
793
|
+
*/
|
|
794
|
+
export async function clearStoredSession({ homeDir } = {}) {
|
|
795
|
+
const { filePath, metadata } = await readMetadata({ homeDir });
|
|
796
|
+
if (metadata && metadata.storage === "keyring") {
|
|
797
|
+
const keytar = await loadKeytarClient();
|
|
798
|
+
if (keytar && metadata.keyringAccount) {
|
|
799
|
+
await keytar.deletePassword(metadata.keyringService || KEYRING_SERVICE, metadata.keyringAccount);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
try {
|
|
804
|
+
await fsp.rm(filePath, { force: true });
|
|
805
|
+
} catch {
|
|
806
|
+
// Ignore cleanup errors.
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
return {
|
|
810
|
+
filePath,
|
|
811
|
+
hadSession: Boolean(metadata),
|
|
812
|
+
};
|
|
813
|
+
}
|