Repository navigation
Expand file tree
/
Copy pathdbus.ts
More file actions
209 lines (187 loc) · 7.55 KB
/
Copy pathdbus.ts
File metadata and controls
209 lines (187 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// The Secret Service over D-Bus (busctl, or gdbus without systemd), and
// secret-tool to read a secret when the user asks for it.
import { exec } from "@backslash/api";
import {
attributeArgs,
type Collection,
explain,
IFACE,
lookupIsUnique,
parseBusctl,
parseGdbus,
parseSearch,
type SecretItem,
SERVICE,
SERVICE_PATH,
toCollection,
toItem,
unwrapVariants,
} from "./lib.ts";
type Arg = { s: string } | { ao: string[] };
let tool: "busctl" | "gdbus" | undefined;
const notFound = (e: unknown) => e instanceof Deno.errors.NotFound;
function busctlArgs(path: string, iface: string, method: string, args: Arg[]): string[] {
const sig = args.map((a) => ("s" in a ? "s" : "ao")).join("");
const values = args.flatMap((a) => ("s" in a ? [a.s] : [String(a.ao.length), ...a.ao]));
return ["--user", "--json=short", "call", SERVICE, path, iface, method, ...(sig ? [sig, ...values] : [])];
}
const gvString = (s: string) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
function gdbusArgs(path: string, iface: string, method: string, args: Arg[]): string[] {
const values = args.map((a) => ("s" in a ? gvString(a.s) : `@ao [${a.ao.map(gvString).join(", ")}]`));
return ["call", "--session", "--dest", SERVICE, "--object-path", path, "--method", `${iface}.${method}`, ...values];
}
/** Calls a Secret Service method; returns its out values as plain data. */
export async function call(
path: string,
iface: string,
method: string,
args: Arg[] = [],
signal?: AbortSignal,
): Promise<unknown[]> {
try {
if (tool !== "gdbus") {
try {
const out = parseBusctl(await exec("busctl", busctlArgs(path, iface, method, args), { signal }));
tool = "busctl";
return out;
} catch (e) {
if (!notFound(e)) throw e;
tool = "gdbus";
}
}
return parseGdbus(await exec("gdbus", gdbusArgs(path, iface, method, args), { signal }));
} catch (e) {
if (notFound(e)) throw new Error("Neither busctl (systemd) nor gdbus (GLib) is installed to reach the keyring");
if (signal?.aborted) throw e;
throw new Error(explain(e instanceof Error ? e.message : String(e)));
}
}
const getAll = async (path: string, iface: string, signal?: AbortSignal) =>
unwrapVariants((await call(path, IFACE.properties, "GetAll", [{ s: iface }], signal))[0]);
export async function collections(signal?: AbortSignal): Promise<Collection[]> {
const [paths] = await call(
SERVICE_PATH,
IFACE.properties,
"Get",
[{ s: IFACE.service }, { s: "Collections" }],
signal,
);
const defaultPath = await call(SERVICE_PATH, IFACE.service, "ReadAlias", [{ s: "default" }], signal)
.then(([p]) => (typeof p === "string" && p !== "/" ? p : undefined))
.catch(() => undefined);
const list = Array.isArray(paths) ? paths.map(String) : [];
// The session collection lives in memory and is usually empty: keep it only when it isn't.
const found = await Promise.all(
list.map(async (p) => toCollection(p, await getAll(p, IFACE.collection, signal), defaultPath)),
);
return found.filter((c) => !(c.path.endsWith("/session") && !c.items.length));
}
/** Every item's properties, a few calls at a time, yielding as they arrive. */
export async function* items(paths: string[], signal?: AbortSignal): AsyncGenerator<SecretItem[]> {
const queue = [...paths];
const batch: SecretItem[] = [];
let last = Date.now();
const worker = async () => {
for (let p = queue.shift(); p; p = queue.shift()) {
if (signal?.aborted) return;
try {
batch.push(toItem(p, await getAll(p, IFACE.item, signal)));
} catch {
// Deleted meanwhile, or not readable: leave it out.
}
}
};
const all = Promise.all(Array.from({ length: 8 }, worker));
let done = false;
all.finally(() => done = true);
while (!done) {
await Promise.race([all, new Promise((r) => setTimeout(r, 250))]);
if (batch.length && (done || Date.now() - last > 400)) {
yield batch.splice(0);
last = Date.now();
}
}
await all;
if (batch.length) yield batch.splice(0);
}
// ---------------------------------------------------------------------------
// Changes
async function prompt(path: unknown): Promise<boolean> {
if (typeof path !== "string" || path === "/" || !path) return false;
await call(path, IFACE.prompt, "Prompt", [{ s: "" }]);
return true;
}
/** Asks the service to unlock; true when it shows a password prompt. */
export async function unlock(collection: string): Promise<boolean> {
const [, p] = await call(SERVICE_PATH, IFACE.service, "Unlock", [{ ao: [collection] }]);
return prompt(p);
}
export async function lock(collection: string): Promise<void> {
const [, p] = await call(SERVICE_PATH, IFACE.service, "Lock", [{ ao: [collection] }]);
await prompt(p);
}
export async function isLocked(collection: string): Promise<boolean> {
return (await getAll(collection, IFACE.collection)).Locked === true;
}
/** Deletes the item; true when the service asks the user to confirm in a prompt. */
export async function remove(item: SecretItem): Promise<boolean> {
const [p] = await call(item.path, IFACE.item, "Delete");
return prompt(p);
}
// ---------------------------------------------------------------------------
// Secrets
async function secretTool(args: string[]): Promise<string> {
try {
const out = await new Deno.Command("secret-tool", { args, stdin: "null", stdout: "piped", stderr: "piped" })
.output();
const text = new TextDecoder().decode(out.stdout);
if (!out.success) {
throw new Error(explain(new TextDecoder().decode(out.stderr).trim() || "secret-tool couldn't read the secret"));
}
return text;
} catch (e) {
if (notFound(e)) {
throw new Error("secret-tool is needed to read secrets: install libsecret-tools (Debian, Ubuntu) or libsecret");
}
throw e;
}
}
/**
* The item's secret, exactly. `secret-tool lookup` when its attributes find
* only this item; otherwise `search --all`, picking it by object path. Both
* unlock the keyring first if needed (the keyring shows its prompt).
*/
export async function readSecret(item: SecretItem, all: SecretItem[]): Promise<string> {
const attrs = attributeArgs(item.attributes);
if (!attrs.length) {
throw new Error("This item has no attributes, so secret-tool can't find it: open it in Seahorse or KWalletManager");
}
if (lookupIsUnique(item, all)) {
const secret = await secretTool(["lookup", ...attrs]);
if (secret) return secret;
}
const found = parseSearch(await secretTool(["search", "--all", "--unlock", ...attrs]));
const mine = found.find((r) => r.path === item.path);
if (mine?.secret === undefined) {
throw new Error(found.length ? "The keyring didn't give this secret: is it still locked?" : "Item not found");
}
return mine.secret;
}
// ---------------------------------------------------------------------------
// Keyring managers
/** Opens Seahorse (GNOME) or KWalletManager (KDE), whichever suits the keyring and is installed. */
export function openManager(collectionPath: string): string {
const kde = /kdewallet|kwallet/i.test(collectionPath);
const programs = kde
? ["kwalletmanager5", "kwalletmanager", "seahorse"]
: ["seahorse", "kwalletmanager5", "kwalletmanager"];
for (const program of programs) {
try {
new Deno.Command(program, { stdin: "null", stdout: "null", stderr: "null" }).spawn().unref();
return program === "seahorse" ? "Passwords and Keys" : "KWalletManager";
} catch (e) {
if (!notFound(e)) throw e;
}
}
throw new Error("Neither Seahorse (Passwords and Keys) nor KWalletManager is installed");
}