@asecret/cli 0.0.0-stage → 0.1.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/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/bin/asecret-mcp.js +4 -0
- package/bin/asecret.js +12 -0
- package/core/spec/0.2/messages.schema.json +751 -0
- package/core/src/agent-crypto.js +191 -0
- package/core/src/agent.js +237 -0
- package/core/src/assistant-instructions.js +64 -0
- package/core/src/authorization.js +266 -0
- package/core/src/credentials.js +149 -0
- package/core/src/host-login.js +110 -0
- package/core/src/mcp-tools.js +130 -0
- package/core/src/wire.js +76 -0
- package/package.json +68 -4
- package/skill/SKILL.md +66 -0
- package/src/agents.js +140 -0
- package/src/api.js +188 -0
- package/src/commands.js +864 -0
- package/src/config.js +76 -0
- package/src/core.d.ts +55 -0
- package/src/core.js +19 -0
- package/src/errors.js +11 -0
- package/src/main.js +520 -0
- package/src/mcp.js +107 -0
- package/src/output.js +93 -0
- package/src/server.js +242 -0
- package/src/storage.js +137 -0
package/src/output.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// How secrets and asks read in a terminal.
|
|
2
|
+
|
|
3
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Names, notes and server replies can come from strangers. Drop every control character
|
|
7
|
+
* but newline and tab, and the invisible direction marks, so a name from a server cannot
|
|
8
|
+
* move the cursor, recolour the screen or reorder what a reader sees.
|
|
9
|
+
*/
|
|
10
|
+
export function clean(/** @type {unknown} */ text) {
|
|
11
|
+
return String(text ?? "")
|
|
12
|
+
.replace(/\r\n?/g, "\n")
|
|
13
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g, "");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @param {boolean} enabled */
|
|
17
|
+
export function palette(enabled) {
|
|
18
|
+
const wrap = (/** @type {number} */ open, /** @type {number} */ close) =>
|
|
19
|
+
enabled ? (/** @type {unknown} */ s) => `\x1b[${open}m${s}\x1b[${close}m` : (/** @type {unknown} */ s) => String(s);
|
|
20
|
+
return {
|
|
21
|
+
bold: wrap(1, 22),
|
|
22
|
+
dim: wrap(2, 22),
|
|
23
|
+
red: wrap(31, 39),
|
|
24
|
+
green: wrap(32, 39),
|
|
25
|
+
yellow: wrap(33, 39),
|
|
26
|
+
blue: wrap(34, 39),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @typedef {ReturnType<typeof palette>} Palette */
|
|
31
|
+
|
|
32
|
+
/** `4 Oct 2026` */
|
|
33
|
+
export function day(/** @type {string | null | undefined} */ iso) {
|
|
34
|
+
if (!iso) return "";
|
|
35
|
+
const date = new Date(iso);
|
|
36
|
+
if (Number.isNaN(date.getTime())) return clean(iso);
|
|
37
|
+
return `${date.getDate()} ${MONTHS[date.getMonth()]} ${date.getFullYear()}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `4 Oct 14:05` */
|
|
41
|
+
export function moment(/** @type {string | null | undefined} */ iso) {
|
|
42
|
+
if (!iso) return "";
|
|
43
|
+
const date = new Date(iso);
|
|
44
|
+
if (Number.isNaN(date.getTime())) return clean(iso);
|
|
45
|
+
const time = `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
|
46
|
+
return `${date.getDate()} ${MONTHS[date.getMonth()]} ${time}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `8 seconds ago`, `1 minute ago`, `3 hours ago`, `2 days ago`: how old a location is. @param {string} iso @param {Date} [now] */
|
|
50
|
+
export function ago(iso, now = new Date()) {
|
|
51
|
+
const at = new Date(iso);
|
|
52
|
+
if (Number.isNaN(at.getTime())) return clean(iso);
|
|
53
|
+
const count = (/** @type {number} */ n, /** @type {string} */ unit) => `${n} ${unit}${n === 1 ? "" : "s"} ago`;
|
|
54
|
+
const seconds = Math.max(1, Math.floor((now.getTime() - at.getTime()) / 1000));
|
|
55
|
+
if (seconds < 60) return count(seconds, "second");
|
|
56
|
+
const minutes = Math.floor(seconds / 60);
|
|
57
|
+
if (minutes < 60) return count(minutes, "minute");
|
|
58
|
+
const hours = Math.floor(minutes / 60);
|
|
59
|
+
if (hours < 24) return count(hours, "hour");
|
|
60
|
+
return count(Math.floor(hours / 24), "day");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A text block set off with a rule, wrapped to `width`, so it reads as quoted. @param {string} text @param {Palette} c @param {number} width */
|
|
64
|
+
export function quoted(text, c, width) {
|
|
65
|
+
return clean(text)
|
|
66
|
+
.split("\n")
|
|
67
|
+
.flatMap((line) => (line ? wrap(line, width - 2) : [""]))
|
|
68
|
+
.map((line) => `${c.dim("│")} ${line}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Wrap words to `width`, breaking a word only when it is longer than a line. @param {string} text @param {number} width */
|
|
72
|
+
export function wrap(text, width) {
|
|
73
|
+
const words = text.split(" ").flatMap((word) => {
|
|
74
|
+
const chars = Array.from(word);
|
|
75
|
+
if (chars.length <= width) return [word];
|
|
76
|
+
const pieces = [];
|
|
77
|
+
for (let i = 0; i < chars.length; i += width) pieces.push(chars.slice(i, i + width).join(""));
|
|
78
|
+
return pieces;
|
|
79
|
+
});
|
|
80
|
+
/** @type {string[]} */
|
|
81
|
+
const lines = [];
|
|
82
|
+
let line = "";
|
|
83
|
+
for (const word of words) {
|
|
84
|
+
if (line && Array.from(`${line} ${word}`).length > width) {
|
|
85
|
+
lines.push(line);
|
|
86
|
+
line = word;
|
|
87
|
+
} else {
|
|
88
|
+
line = line ? `${line} ${word}` : word;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (line) lines.push(line);
|
|
92
|
+
return lines;
|
|
93
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Your person's aSecret server: the owner-approved link to it, and the asks your person decides in their
|
|
2
|
+
// own app. This agent never reads the person's details; it reads receipts.
|
|
3
|
+
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import * as core from "./core.js";
|
|
8
|
+
import { NotLinked, UsageError } from "./errors.js";
|
|
9
|
+
|
|
10
|
+
/** Where the link to one server is kept: its own file, so renewals can lock it. @param {string} dir @param {string} origin */
|
|
11
|
+
export function linkFile(dir, origin) {
|
|
12
|
+
const url = new URL(origin);
|
|
13
|
+
const name = `${url.hostname.replace(/[^A-Za-z0-9.-]/g, "_")}${url.port ? `_${url.port}` : ""}.json`;
|
|
14
|
+
return join(dir, "servers", name);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The origin of a server, refusing anything that is not one. @param {string} value */
|
|
18
|
+
export function serverOrigin(value) {
|
|
19
|
+
let url;
|
|
20
|
+
try {
|
|
21
|
+
url = new URL(value);
|
|
22
|
+
} catch {
|
|
23
|
+
throw new UsageError(`"${value}" is not a server address. Give its https:// origin, such as https://server.example.`);
|
|
24
|
+
}
|
|
25
|
+
if (url.protocol !== "https:" || url.pathname !== "/" || url.search || url.hash || url.username)
|
|
26
|
+
throw new UsageError(`Give the server's https:// origin with no path, such as ${url.protocol === "https:" ? url.origin : "https://server.example"}.`);
|
|
27
|
+
return url.origin;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Pair with the person's aSecret server: they review this agent there and choose how long it may ask.
|
|
32
|
+
* @param {{ origin: string, file: string, name?: string, client?: string, callback?: string, show: (url: string) => void, fetch: typeof fetch }} options
|
|
33
|
+
*/
|
|
34
|
+
export async function pair({ origin, file, name, client, callback, show, fetch: send }) {
|
|
35
|
+
const previous = await core.readCredential(file, origin);
|
|
36
|
+
if (previous && (previous.expiresAt === undefined || previous.expiresAt > Date.now())) return { grant: previous, already: true };
|
|
37
|
+
await mkdir(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
38
|
+
const grant = await core.login(origin, {
|
|
39
|
+
name,
|
|
40
|
+
file,
|
|
41
|
+
clientId: client,
|
|
42
|
+
redirectUri: callback,
|
|
43
|
+
showURL: show,
|
|
44
|
+
fetcher: send,
|
|
45
|
+
});
|
|
46
|
+
await core.saveCredential(file, grant, previous);
|
|
47
|
+
return { grant, already: false };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The live link, renewed when due, and a client for asks. @param {string} origin @param {string} file @param {typeof fetch} send */
|
|
51
|
+
export async function session(origin, file, send) {
|
|
52
|
+
const stored = await core.usableCredential(file, origin);
|
|
53
|
+
if (!stored) throw new NotLinked();
|
|
54
|
+
if (stored.expiresAt !== undefined && stored.expiresAt <= Date.now())
|
|
55
|
+
throw new NotLinked("The link to your person's aSecret server has expired. Link again with: asecret link");
|
|
56
|
+
return { stored, server: await core.connectServer(origin, { accessToken: stored.accessToken, fetcher: send }) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** End the link at the server, then forget it here. @param {string} origin @param {string} file @param {typeof fetch} send */
|
|
60
|
+
export async function unpair(origin, file, send) {
|
|
61
|
+
const stored = await core.usableCredential(file, origin);
|
|
62
|
+
if (!stored) return { state: "not_linked" };
|
|
63
|
+
const server = await core.connectServer(origin, { accessToken: stored.accessToken, fetcher: send });
|
|
64
|
+
try {
|
|
65
|
+
await server.disconnect(stored.connectionId);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (!(error instanceof core.ServerError) || error.status !== 401 || error.code !== "invalid_token") throw error;
|
|
68
|
+
const cleared = await core.clearDisconnectedCredential(file, stored, { requireSameToken: true });
|
|
69
|
+
if (!cleared) throw new Error("The link changed while ending it. Check it with asecret me before trying again.");
|
|
70
|
+
return { state: "credential_removed", provider_status: "unconfirmed" };
|
|
71
|
+
}
|
|
72
|
+
await core.clearDisconnectedCredential(file, stored);
|
|
73
|
+
return { state: "disconnected" };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Asks this agent started, so `asks` can list them: the API reads one ask at a time.
|
|
77
|
+
|
|
78
|
+
/** @typedef {{ id: string, what: string, operation: string, recipient?: string, order_id?: string, review_url?: string, created_at: string, expires_at?: string, state?: string }} Ask */
|
|
79
|
+
|
|
80
|
+
/** @param {string} file @returns {Promise<Record<string, Ask[]>>} */
|
|
81
|
+
async function readAsks(file) {
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return {};
|
|
86
|
+
throw new Error(`Could not read ${file}. Fix or delete it, then try again.`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** @param {string} file @param {string} origin */
|
|
91
|
+
export async function asksAt(file, origin) {
|
|
92
|
+
return (await readAsks(file))[origin] ?? [];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Remember an ask, newest first, keeping the 200 most recent. @param {string} file @param {string} origin @param {Ask} ask */
|
|
96
|
+
export async function rememberAsk(file, origin, ask) {
|
|
97
|
+
const all = await readAsks(file);
|
|
98
|
+
all[origin] = [ask, ...(all[origin] ?? []).filter((known) => known.id !== ask.id)].slice(0, 200);
|
|
99
|
+
await mkdir(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
100
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
101
|
+
await writeFile(temporary, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
|
|
102
|
+
await rename(temporary, file);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** What the receipt check needs to know about an ask. @param {Ask | undefined} ask */
|
|
106
|
+
export function expected(ask) {
|
|
107
|
+
if (!ask) return undefined;
|
|
108
|
+
return { operation: ask.operation, ...(ask.order_id ? { orderId: ask.order_id } : {}) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const DONE = new Set(["confirmed", "declined", "canceled", "expired", "failed", "outcome_unknown"]);
|
|
112
|
+
export const finished = (/** @type {string} */ state) => DONE.has(state);
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Check an ask until it is decided or expires.
|
|
116
|
+
* @param {() => Promise<any>} check @param {{ every?: number, until?: number, sleep?: (ms: number) => Promise<void> }} [options]
|
|
117
|
+
*/
|
|
118
|
+
export async function waitFor(check, { every = 3000, until = Date.now() + 15 * 60e3, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
119
|
+
for (;;) {
|
|
120
|
+
const state = await check();
|
|
121
|
+
if (finished(state.state) || Date.now() >= until) return state;
|
|
122
|
+
await sleep(every);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** What an ask's state means, in a sentence. @param {any} view @param {Ask | undefined} ask */
|
|
127
|
+
export function describe(view, ask) {
|
|
128
|
+
const result = view.result ?? {};
|
|
129
|
+
switch (view.state) {
|
|
130
|
+
case "awaiting_owner":
|
|
131
|
+
return "Waiting for your person.";
|
|
132
|
+
case "authorized":
|
|
133
|
+
case "dispatch_committed":
|
|
134
|
+
return "Approved. Waiting for the recipient.";
|
|
135
|
+
case "confirmed":
|
|
136
|
+
if (result.delivery_address_status === "accepted") return `${ask?.recipient ?? "The recipient"} accepted the address for order ${result.order_id}.`;
|
|
137
|
+
if (result.order_status) return `Order ${result.order_id}: ${String(result.order_status).replaceAll("_", " ")}.`;
|
|
138
|
+
if (result.owner_status === "ready") return "Your person finished setting up their details.";
|
|
139
|
+
if (result.detail_status === "saved") return "Your person saved it in aSecret.";
|
|
140
|
+
return "Done.";
|
|
141
|
+
case "declined":
|
|
142
|
+
return "Your person declined.";
|
|
143
|
+
case "canceled":
|
|
144
|
+
return "Canceled.";
|
|
145
|
+
case "expired":
|
|
146
|
+
return "It expired before your person decided.";
|
|
147
|
+
case "failed":
|
|
148
|
+
return "It did not go through.";
|
|
149
|
+
case "outcome_unknown":
|
|
150
|
+
return "The recipient's answer is unknown. Your person can check it in their app.";
|
|
151
|
+
default:
|
|
152
|
+
return String(view.state);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The kinds of detail an ask can be about, beyond the saved detail types. */
|
|
157
|
+
export const ASK_FORMS = ["address", "order-status", "setup", "form", "payment_method"];
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Start an ask at the server, tracked by id.
|
|
161
|
+
* @param {any} server @param {string} what @param {{ to?: string, order?: string, reference?: string, key?: string }} opts
|
|
162
|
+
*/
|
|
163
|
+
export async function startAsk(server, what, opts) {
|
|
164
|
+
const idempotencyKey = opts.key ?? randomUUID();
|
|
165
|
+
if (what === "address") {
|
|
166
|
+
if (!opts.to || !opts.order) throw new UsageError("Say where and which order: asecret ask address --to <recipient> --order <id>");
|
|
167
|
+
return {
|
|
168
|
+
view: await server.requestAddress({ recipient: opts.to, orderId: opts.order, reference: opts.reference, idempotencyKey }),
|
|
169
|
+
ask: { what, operation: "orders.set_delivery_address", recipient: opts.to, order_id: opts.order },
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (what === "order-status") {
|
|
173
|
+
if (!opts.to || !opts.order) throw new UsageError("Say where and which order: asecret ask order-status --to <recipient> --order <id>");
|
|
174
|
+
return {
|
|
175
|
+
view: await server.requestOrderStatus({ recipient: opts.to, orderId: opts.order, idempotencyKey }),
|
|
176
|
+
ask: { what, operation: "orders.get_status", recipient: opts.to, order_id: opts.order },
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (opts.to || opts.order || opts.reference) throw new UsageError("--to, --order and --reference go with ask address or ask order-status.");
|
|
180
|
+
if (what === "setup") return { view: await server.requestSetup({ idempotencyKey }), ask: { what, operation: "details.request_setup" } };
|
|
181
|
+
return {
|
|
182
|
+
view: await server.requestSave({ detailType: what, idempotencyKey }),
|
|
183
|
+
ask: { what, operation: what === "payment_method" ? "payments.save_method" : "details.save" },
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Asks through the agent's own storage API (api.asecret.sh), for an agent linked to its person with
|
|
189
|
+
* a code: its storage token stands for the connection, and the person answers signed in at
|
|
190
|
+
* asecret.sh. The same calls as a self-hosted server's connection, for what the hosted API takes.
|
|
191
|
+
* @param {import("./api.js").Client} client
|
|
192
|
+
*/
|
|
193
|
+
export function hostedServer(client) {
|
|
194
|
+
const elsewhere = (/** @type {string} */ what) =>
|
|
195
|
+
new UsageError(`asecret.sh doesn't take ${what} yet. Your person's own aSecret server does: --server <origin>.`);
|
|
196
|
+
return {
|
|
197
|
+
/** @param {{ idempotencyKey: string }} options */
|
|
198
|
+
requestSetup: async ({ idempotencyKey }) => client.ask({ operation: "details.request_setup" }, idempotencyKey),
|
|
199
|
+
/** @param {{ detailType: string, idempotencyKey: string }} options */
|
|
200
|
+
requestSave: async ({ detailType, idempotencyKey }) => {
|
|
201
|
+
if (detailType === "payment_method") throw elsewhere("payment methods");
|
|
202
|
+
return client.ask({ operation: "details.save", detail_type: detailType }, idempotencyKey);
|
|
203
|
+
},
|
|
204
|
+
requestAddress: async () => {
|
|
205
|
+
throw elsewhere("deliveries to merchants");
|
|
206
|
+
},
|
|
207
|
+
requestOrderStatus: async () => {
|
|
208
|
+
throw elsewhere("order status checks");
|
|
209
|
+
},
|
|
210
|
+
/** @param {string} id */
|
|
211
|
+
status: (id) => client.askStatus(id),
|
|
212
|
+
/** @param {string} id */
|
|
213
|
+
cancel: (id) => client.cancelAsk(id),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The page a person opens without an ask, at asecret.sh (from the API's link_url): a save page for a
|
|
219
|
+
* kind of detail, or My details for setup. Not tracked.
|
|
220
|
+
* @param {any} info the API's discovery @param {string} what
|
|
221
|
+
*/
|
|
222
|
+
export function hostedLink(info, what) {
|
|
223
|
+
const site = new URL(info.link_url).origin;
|
|
224
|
+
if (what === "setup") return `${site}/details`;
|
|
225
|
+
if (what === "payment_method") throw new UsageError("asecret.sh doesn't take payment methods yet. Your person's own aSecret server does: --server <origin>.");
|
|
226
|
+
if (what === "address" || what === "order-status" || what === "form")
|
|
227
|
+
throw new UsageError(`ask ${what} needs your person's own aSecret server: --server <origin>.`);
|
|
228
|
+
return `${site}/details/save/${what}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** A public link for the person, which needs no link and is not tracked. @param {string} origin @param {string} what @param {typeof fetch} send */
|
|
232
|
+
export async function publicLink(origin, what, send) {
|
|
233
|
+
const options = { fetcher: send };
|
|
234
|
+
if (what === "form") return (await core.privateWebsiteFormLink(origin, options)).private_form_url;
|
|
235
|
+
if (what === "setup") {
|
|
236
|
+
const { owner_setup_url } = await core.privateOwnerSetupLink(origin, options);
|
|
237
|
+
if (!owner_setup_url) throw new Error("This server has no public setup link. Ask your person how they want to connect.");
|
|
238
|
+
return owner_setup_url;
|
|
239
|
+
}
|
|
240
|
+
if (what === "address" || what === "order-status") throw new UsageError(`ask ${what} needs a linked server, so your person can approve it. Link first: asecret link`);
|
|
241
|
+
return core.privateSaveLink(origin, what, options);
|
|
242
|
+
}
|
package/src/storage.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// What this agent keeps: its secrets, encrypted on the way in and decrypted on the way out. The API
|
|
2
|
+
// only ever sees ciphertext; every name and value is sealed here first.
|
|
3
|
+
|
|
4
|
+
import * as core from "./core.js";
|
|
5
|
+
import { UsageError } from "./errors.js";
|
|
6
|
+
|
|
7
|
+
/** The largest secret a server keeps. */
|
|
8
|
+
export const MAX_SECRET = 64 * 1024;
|
|
9
|
+
const SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ agentKey: string }} Keys
|
|
13
|
+
* @typedef {{ name: string, kind: "secret", type: string, size: number, sha256: string, tags: string[], note: string }} Meta
|
|
14
|
+
* @typedef {{ item: any, meta: Meta | null, itemKey: Uint8Array | null }} Opened
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The key saved with this agent's credentials. @param {any} saved @returns {Keys} */
|
|
18
|
+
export function keysOf(saved) {
|
|
19
|
+
const keys = saved?.keys;
|
|
20
|
+
if (!keys?.agent) throw new Error("This machine has the agent's token but not its key. Restore it with: asecret connect --restore <file>");
|
|
21
|
+
return { agentKey: keys.agent };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The key for a new agent. */
|
|
25
|
+
export function newKeys() {
|
|
26
|
+
return { agent: core.newKey() };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* This agent's key, sealed to its person's recovery key and sent to aSecret, when the person turned
|
|
31
|
+
* agent recovery on and has no copy from this agent yet. Only their browser opens it. Returns the
|
|
32
|
+
* new me view, or null when there was nothing to send.
|
|
33
|
+
* @param {import("./api.js").Client} client @param {any} saved @param {any} me
|
|
34
|
+
*/
|
|
35
|
+
export async function shareKeys(client, saved, me) {
|
|
36
|
+
if (!me?.linked?.person_key || me.linked.escrow || !saved?.keys?.agent) return null;
|
|
37
|
+
return client.setEscrow(await core.sealToReceiveKey(me.linked.person_key, new TextEncoder().encode(JSON.stringify(saved.keys))));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A short, stable way to tell two keys apart. @param {string} key */
|
|
41
|
+
export async function keyFingerprint(key) {
|
|
42
|
+
return (await core.sha256Hex(core.fromBase64url(key))).slice(0, 16).match(/.{4}/g)?.join("-") ?? "";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One item with its metadata decrypted, or null metadata when it does not decrypt. @param {any} item @param {Keys} keys @returns {Promise<Opened>} */
|
|
46
|
+
export async function opened(item, keys) {
|
|
47
|
+
try {
|
|
48
|
+
const itemKey = await core.itemKeyOf(item, keys);
|
|
49
|
+
return { item, meta: await core.openMeta(itemKey, item.meta), itemKey };
|
|
50
|
+
} catch {
|
|
51
|
+
return { item, meta: null, itemKey: null };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Every secret this agent has, decrypted, newest change first. @param {import("./api.js").Client} client @param {Keys} keys */
|
|
56
|
+
export async function secrets(client, keys) {
|
|
57
|
+
/** @type {Opened[]} */
|
|
58
|
+
const all = [];
|
|
59
|
+
let cursor;
|
|
60
|
+
do {
|
|
61
|
+
const page = await client.items(cursor, 200);
|
|
62
|
+
all.push(...(await Promise.all(page.data.map((/** @type {any} */ item) => opened(item, keys)))));
|
|
63
|
+
cursor = page.next_cursor;
|
|
64
|
+
} while (cursor);
|
|
65
|
+
return all.filter((entry) => entry.meta?.kind === "secret");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The secret with this name, or null. @param {import("./api.js").Client} client @param {Keys} keys @param {string} name */
|
|
69
|
+
export async function find(client, keys, name) {
|
|
70
|
+
return (await secrets(client, keys)).find((entry) => entry.meta?.name === name) ?? null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The secret with this name, or a usage error that says how to save it. @param {import("./api.js").Client} client @param {Keys} keys @param {string} name */
|
|
74
|
+
export async function named(client, keys, name) {
|
|
75
|
+
const found = await find(client, keys, name);
|
|
76
|
+
if (!found) throw new UsageError(`No secret named ${name}. See them with: asecret list`);
|
|
77
|
+
return found;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A secret's name: the way an environment variable is named. @param {string | undefined} name */
|
|
81
|
+
export function checkSecretName(name) {
|
|
82
|
+
if (!SECRET_NAME.test(name ?? ""))
|
|
83
|
+
throw new UsageError(`Name the secret the way an environment variable is named, such as OPENAI_API_KEY.`);
|
|
84
|
+
return /** @type {string} */ (name);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `512 B`, `1.2 KiB`, `3.4 MiB`. @param {number} bytes */
|
|
88
|
+
export function size(bytes) {
|
|
89
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
90
|
+
const units = ["KiB", "MiB", "GiB", "TiB"];
|
|
91
|
+
let value = bytes / 1024;
|
|
92
|
+
let unit = 0;
|
|
93
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
94
|
+
value /= 1024;
|
|
95
|
+
unit++;
|
|
96
|
+
}
|
|
97
|
+
return `${value >= 10 ? Math.round(value) : value.toFixed(1).replace(/\.0$/, "")} ${units[unit]}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Seal and store a new secret.
|
|
102
|
+
* @param {import("./api.js").Client} client @param {Keys} keys
|
|
103
|
+
* @param {{ name: string, bytes: Uint8Array, key?: string }} input
|
|
104
|
+
*/
|
|
105
|
+
export async function saveSecret(client, keys, { name, bytes, key }) {
|
|
106
|
+
/** @type {Meta} */
|
|
107
|
+
const meta = { name, kind: "secret", type: "text/plain", size: bytes.length, sha256: await core.sha256Hex(bytes), tags: [], note: "" };
|
|
108
|
+
const sealed = await core.sealItem(keys.agentKey, meta, bytes);
|
|
109
|
+
const item = await client.createItem({ wrap: sealed.wrap, wrapped_key: sealed.wrapped_key, meta: sealed.meta }, sealed.content, key);
|
|
110
|
+
return { item, meta };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The decrypted value of a secret, checked against the fingerprint saved with it. @param {import("./api.js").Client} client @param {Opened} entry @param {number} [version] */
|
|
114
|
+
export async function readSecret(client, entry, version) {
|
|
115
|
+
if (!entry.itemKey || !entry.meta) throw new Error("This secret does not decrypt with this agent's key.");
|
|
116
|
+
let meta = entry.meta;
|
|
117
|
+
if (version !== undefined && version !== entry.item.version) {
|
|
118
|
+
const old = (await client.versions(entry.item.id)).data.find((/** @type {any} */ v) => v.version === version);
|
|
119
|
+
if (!old) throw new UsageError(`Version ${version} is gone. Earlier versions are kept for 30 days.`);
|
|
120
|
+
meta = await core.openMeta(entry.itemKey, old.meta);
|
|
121
|
+
}
|
|
122
|
+
const bytes = await core.openContent(entry.itemKey, await client.content(entry.item.id, version));
|
|
123
|
+
if ((await core.sha256Hex(bytes)) !== meta.sha256) throw new Error("The value does not match its saved fingerprint.");
|
|
124
|
+
return { bytes, meta };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Save a new value for a secret. It keeps its key; the value before is kept for 30 days.
|
|
129
|
+
* @param {import("./api.js").Client} client @param {Opened} entry @param {{ bytes: Uint8Array, etag: string }} change
|
|
130
|
+
*/
|
|
131
|
+
export async function updateSecret(client, entry, { bytes, etag }) {
|
|
132
|
+
if (!entry.itemKey || !entry.meta) throw new Error("This secret does not decrypt with this agent's key.");
|
|
133
|
+
/** @type {Meta} */
|
|
134
|
+
const meta = { ...entry.meta, size: bytes.length, sha256: await core.sha256Hex(bytes) };
|
|
135
|
+
const input = { wrap: entry.item.wrap, wrapped_key: entry.item.wrapped_key, meta: await core.sealMeta(entry.itemKey, meta) };
|
|
136
|
+
return { item: await client.updateItem(entry.item.id, input, await core.sealContent(entry.itemKey, bytes), etag), meta };
|
|
137
|
+
}
|