@ant0/cli 0.0.0-stage → 0.3.22-beta.8
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/LICENSE +28 -0
- package/README.md +97 -2
- package/dist/api/generated/schema.d.ts +11615 -0
- package/dist/api/generated/schema.js +6 -0
- package/dist/api/index.d.ts +219 -0
- package/dist/api/index.js +342 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.js +12 -0
- package/dist/bulk.d.ts +38 -0
- package/dist/bulk.js +66 -0
- package/dist/commands/account.d.ts +48 -0
- package/dist/commands/account.js +337 -0
- package/dist/commands/api-keys.d.ts +5 -0
- package/dist/commands/api-keys.js +310 -0
- package/dist/commands/browsers.d.ts +4 -0
- package/dist/commands/browsers.js +165 -0
- package/dist/commands/daemon.d.ts +15 -0
- package/dist/commands/daemon.js +202 -0
- package/dist/commands/events.d.ts +8 -0
- package/dist/commands/events.js +81 -0
- package/dist/commands/extensions.d.ts +4 -0
- package/dist/commands/extensions.js +74 -0
- package/dist/commands/profiles.d.ts +36 -0
- package/dist/commands/profiles.js +552 -0
- package/dist/commands/proxies.d.ts +23 -0
- package/dist/commands/proxies.js +170 -0
- package/dist/commands/sync.d.ts +4 -0
- package/dist/commands/sync.js +435 -0
- package/dist/commands/team.d.ts +7 -0
- package/dist/commands/team.js +403 -0
- package/dist/commands/trash.d.ts +10 -0
- package/dist/commands/trash.js +54 -0
- package/dist/commands/workspace.d.ts +10 -0
- package/dist/commands/workspace.js +56 -0
- package/dist/context.d.ts +111 -0
- package/dist/context.js +300 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +96 -0
- package/dist/format.d.ts +23 -0
- package/dist/format.js +85 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +35 -0
- package/dist/inventory.d.ts +50 -0
- package/dist/inventory.js +202 -0
- package/dist/management-transport.d.ts +3 -0
- package/dist/management-transport.js +90 -0
- package/dist/native-terminal.d.ts +50 -0
- package/dist/native-terminal.js +228 -0
- package/dist/program.d.ts +10 -0
- package/dist/program.js +217 -0
- package/dist/runtime-types.d.ts +20 -0
- package/dist/runtime-types.js +2 -0
- package/dist/set.d.ts +15 -0
- package/dist/set.js +87 -0
- package/dist/shared/parse-error.d.ts +6 -0
- package/dist/shared/parse-error.js +8 -0
- package/dist/shared/proxy-parse.d.ts +72 -0
- package/dist/shared/proxy-parse.js +294 -0
- package/dist/shared/proxy-types.d.ts +21 -0
- package/dist/shared/proxy-types.js +2 -0
- package/dist/shared/recovery-code.d.ts +7 -0
- package/dist/shared/recovery-code.js +53 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.js +18 -0
- package/licenses/README.md +5 -0
- package/licenses/THIRD_PARTY_NOTICES +96 -0
- package/package.json +63 -4
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { type Client, type Middleware } from "openapi-fetch";
|
|
2
|
+
import type { components, paths } from "./generated/schema.js";
|
|
3
|
+
export type { components, operations, paths, webhooks } from "./generated/schema.js";
|
|
4
|
+
type Schemas = components["schemas"];
|
|
5
|
+
export type ApiError = Schemas["ApiError"];
|
|
6
|
+
export type Session = Schemas["Session"];
|
|
7
|
+
export type Proxy = Schemas["Proxy"];
|
|
8
|
+
export type ProxyCheck = Schemas["ProxyCheck"];
|
|
9
|
+
export type ProxyCreate = Schemas["ProxyCreate"];
|
|
10
|
+
export type Cookie = Schemas["Cookie"];
|
|
11
|
+
export type Ant0Event = Schemas["Ant0Event"];
|
|
12
|
+
export type ProfileManifest = Schemas["ProfileManifest"];
|
|
13
|
+
export type ProfileDetail = Schemas["ProfileDetail"];
|
|
14
|
+
export type ProfileSummary = Schemas["ProfileSummary"];
|
|
15
|
+
export type ProfileCreate = Schemas["ProfileCreate"];
|
|
16
|
+
export type ProfileInput = Schemas["ProfileInput"];
|
|
17
|
+
export type InstalledBrowser = Schemas["InstalledBrowser"];
|
|
18
|
+
export type InstallJob = Schemas["InstallJob"];
|
|
19
|
+
/** `GET /v1/workspaces` response and one workspace in it. */
|
|
20
|
+
export type WorkspaceList = paths["/v1/workspaces"]["get"]["responses"][200]["content"]["application/json"];
|
|
21
|
+
export type WorkspaceSummary = WorkspaceList["workspaces"][number];
|
|
22
|
+
/** Public sync state. Recovery material is intentionally absent from these aliases. */
|
|
23
|
+
export type SyncStatus = paths["/v1/sync/status"]["get"]["responses"][200]["content"]["application/json"];
|
|
24
|
+
export type SyncMapping = Schemas["LocalSyncMapping"];
|
|
25
|
+
export type SyncKeyState = Schemas["LocalSyncKeyState"];
|
|
26
|
+
export type RemoteProfileList = paths["/v1/sync/profiles/remote"]["get"]["responses"][200]["content"]["application/json"];
|
|
27
|
+
export type RemoteProfile = RemoteProfileList["items"][number];
|
|
28
|
+
export type RemoteTrashList = paths["/v1/sync/trash/remote"]["get"]["responses"][200]["content"]["application/json"];
|
|
29
|
+
export type RemoteTrashItem = RemoteTrashList["items"][number];
|
|
30
|
+
export type RemoteTrashKeyUsage = paths["/v1/sync/trash/remote/key-usage"]["get"]["responses"][200]["content"]["application/json"];
|
|
31
|
+
export type SyncConflictList = paths["/v1/sync/conflicts"]["get"]["responses"][200]["content"]["application/json"];
|
|
32
|
+
export type SyncConflict = SyncConflictList["items"][number];
|
|
33
|
+
export type SyncRecipientList = paths["/v1/sync/keys/recipients"]["get"]["responses"][200]["content"]["application/json"];
|
|
34
|
+
export type SyncRecipient = SyncRecipientList["items"][number];
|
|
35
|
+
export type SyncTransferList = paths["/v1/sync/transfers"]["get"]["responses"][200]["content"]["application/json"];
|
|
36
|
+
export type SyncTransfer = SyncTransferList["items"][number];
|
|
37
|
+
/** Team list responses and their item summaries. */
|
|
38
|
+
export type TeamFolderList = paths["/v1/team/folders"]["get"]["responses"][200]["content"]["application/json"];
|
|
39
|
+
export type TeamFolder = TeamFolderList["items"][number];
|
|
40
|
+
export type TeamMemberList = paths["/v1/team/members"]["get"]["responses"][200]["content"]["application/json"];
|
|
41
|
+
export type TeamMember = TeamMemberList["items"][number];
|
|
42
|
+
export type TeamInviteList = paths["/v1/team/invites"]["get"]["responses"][200]["content"]["application/json"];
|
|
43
|
+
export type TeamInvite = TeamInviteList["items"][number];
|
|
44
|
+
export type TeamOwnershipList = paths["/v1/team/ownership-transfers/outgoing"]["get"]["responses"][200]["content"]["application/json"];
|
|
45
|
+
export type TeamOwnershipSummary = TeamOwnershipList["items"][number];
|
|
46
|
+
/** `GET /v1/health` response. */
|
|
47
|
+
export type Health = paths["/v1/health"]["get"]["responses"][200]["content"]["application/json"];
|
|
48
|
+
export declare const DEFAULT_HOST = "127.0.0.1";
|
|
49
|
+
/** `127.x.x.x`, `localhost`, or `::1` (with or without brackets). */
|
|
50
|
+
export declare function isLoopbackHost(host: string): boolean;
|
|
51
|
+
export declare const DEFAULT_PORT = 27100;
|
|
52
|
+
export interface DiscoveredPidFile {
|
|
53
|
+
pid: number;
|
|
54
|
+
port: number;
|
|
55
|
+
host: string;
|
|
56
|
+
}
|
|
57
|
+
export interface DiscoverOptions {
|
|
58
|
+
/** Data directory; default `$ANT0_HOME`, else the platform data folder (see `resolveHome`). */
|
|
59
|
+
home?: string;
|
|
60
|
+
/** Environment to consult; default `process.env`. */
|
|
61
|
+
env?: Record<string, string | undefined>;
|
|
62
|
+
/** Port override (e.g. a `--port` flag); wins over the pid file and the environment. */
|
|
63
|
+
port?: number;
|
|
64
|
+
}
|
|
65
|
+
export interface DiscoveredDaemon {
|
|
66
|
+
/** `http://<host>:<port>` without a trailing slash. */
|
|
67
|
+
baseUrl: string;
|
|
68
|
+
/** Contents of `ant0d.token`, or undefined when the file is missing or empty. */
|
|
69
|
+
token: string | undefined;
|
|
70
|
+
/** Resolved data directory. */
|
|
71
|
+
home: string;
|
|
72
|
+
/** Parsed `ant0d.pid` when present and well-formed. Liveness is not checked here. */
|
|
73
|
+
pidFile?: DiscoveredPidFile;
|
|
74
|
+
}
|
|
75
|
+
export interface ResolveHomeOptions {
|
|
76
|
+
/** Explicit data directory (a `--home` flag); wins over everything. */
|
|
77
|
+
home?: string;
|
|
78
|
+
env?: Record<string, string | undefined>;
|
|
79
|
+
/** `process.platform`; `win32`, `darwin`, anything else counts as Linux/Unix. */
|
|
80
|
+
platform?: string;
|
|
81
|
+
/** `os.homedir()`. */
|
|
82
|
+
homedir?: () => string;
|
|
83
|
+
/** Whether a candidate data folder counts as existing; default `homeExists`. */
|
|
84
|
+
exists?: (path: string) => boolean;
|
|
85
|
+
/** `process.execPath`; the folder holding it is refused as a data folder. */
|
|
86
|
+
execPath?: string;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A data folder exists for the legacy rule only when a daemon has run on it (`ant0.db` or
|
|
90
|
+
* `profiles/` present); an empty directory does not shadow a populated `~/.ant0`. The daemon and
|
|
91
|
+
* the desktop app use the same rule.
|
|
92
|
+
*/
|
|
93
|
+
export declare function homeExists(dir: string): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Refuse a data folder that is the directory holding the running executable (an installer that
|
|
96
|
+
* unpacks into the data folder would put the database next to the binary). Mirrors
|
|
97
|
+
* `assertNotExecutableDir` in `ant0d`; resolved paths, case-insensitive on Windows.
|
|
98
|
+
*/
|
|
99
|
+
export declare function assertNotExecutableDir(home: string, execPath: string, platform: string): void;
|
|
100
|
+
/**
|
|
101
|
+
* The platform data folder: Windows `%LOCALAPPDATA%\Ant0`; macOS
|
|
102
|
+
* `~/Library/Application Support/Ant0`; Linux `$XDG_DATA_HOME/ant0` or `~/.local/share/ant0`.
|
|
103
|
+
*/
|
|
104
|
+
export declare function platformDefaultHome(platform: string, env: Record<string, string | undefined>, userHome: string): string;
|
|
105
|
+
/**
|
|
106
|
+
* Resolve the data directory with the same rule as the daemon and the desktop app: the explicit `home`, then `ANT0_HOME`, then the
|
|
107
|
+
* platform default; an existing legacy `~/.ant0` is kept while the platform default does not
|
|
108
|
+
* exist, so the CLI keeps finding a daemon that still runs there.
|
|
109
|
+
*/
|
|
110
|
+
export declare function resolveHome(opts?: ResolveHomeOptions): string;
|
|
111
|
+
/**
|
|
112
|
+
* Locate the daemon from the files in the data directory. Does not throw for a missing file: an
|
|
113
|
+
* unreadable pid file falls back to `ANT0D_HOST`/`ANT0D_PORT` or `127.0.0.1:27100`, and a
|
|
114
|
+
* missing token yields `token: undefined` (callers treat that as "daemon not running"). The one
|
|
115
|
+
* exception is a token file that exists but is not private: that throws `TokenFileNotPrivateError`.
|
|
116
|
+
*/
|
|
117
|
+
export declare function discoverDaemon(opts?: DiscoverOptions): DiscoveredDaemon;
|
|
118
|
+
/** `ant0d.token` exists but other users could read it, or it is not a plain file of this user. */
|
|
119
|
+
export declare class TokenFileNotPrivateError extends Error {
|
|
120
|
+
readonly name = "TokenFileNotPrivateError";
|
|
121
|
+
readonly path: string;
|
|
122
|
+
readonly reason: string;
|
|
123
|
+
/**
|
|
124
|
+
* Whether `ANT0_ALLOW_SHARED_TOKEN_FILE=1` may waive this refusal: only a wide mode or a foreign
|
|
125
|
+
* owner. A symbolic link or a file that is not a regular file is always refused.
|
|
126
|
+
*/
|
|
127
|
+
readonly waivable: boolean;
|
|
128
|
+
constructor(path: string, reason: string, opts?: {
|
|
129
|
+
optOutHint?: boolean;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** Set to `1` to turn the token privacy refusal into a stderr warning. */
|
|
133
|
+
export declare const SHARED_TOKEN_FILE_ENV = "ANT0_ALLOW_SHARED_TOKEN_FILE";
|
|
134
|
+
/** The parts of `fs.Stats` that decide whether a token file is private. */
|
|
135
|
+
export interface TokenFileStat {
|
|
136
|
+
isFile(): boolean;
|
|
137
|
+
isSymbolicLink(): boolean;
|
|
138
|
+
uid: number;
|
|
139
|
+
mode: number;
|
|
140
|
+
}
|
|
141
|
+
export interface PrivateTokenOptions {
|
|
142
|
+
/** Default: `process.platform`. */
|
|
143
|
+
platform?: NodeJS.Platform;
|
|
144
|
+
/** Default: `process.geteuid()`. Root (0) may read a token owned by any user, as with OpenSSH. */
|
|
145
|
+
uid?: number | undefined;
|
|
146
|
+
/** Default: `process.env`. */
|
|
147
|
+
env?: Record<string, string | undefined>;
|
|
148
|
+
/** Default: writes to stderr. Called instead of throwing when the opt-out is set. */
|
|
149
|
+
warn?: (message: string) => void;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Why a token file's `lstat` result is not private, or `undefined` when it is. Not Windows: a
|
|
153
|
+
* regular file (not a link), owned by the current user, with no group or other permission bits.
|
|
154
|
+
* On Windows this returns `undefined`: there is no portable way to ask here, so the file goes
|
|
155
|
+
* unverified.
|
|
156
|
+
*/
|
|
157
|
+
export declare function privateTokenProblem(stat: TokenFileStat, opts?: PrivateTokenOptions): string | undefined;
|
|
158
|
+
/**
|
|
159
|
+
* Refuse a token file that is not private. A missing file, or one that cannot be inspected, passes
|
|
160
|
+
* (the caller then sees "no token" as before); a file that is there but fails
|
|
161
|
+
* {@link privateTokenProblem} throws {@link TokenFileNotPrivateError}. Never reads the contents.
|
|
162
|
+
*/
|
|
163
|
+
export declare function checkPrivateTokenFile(file: string, opts?: PrivateTokenOptions): void;
|
|
164
|
+
/**
|
|
165
|
+
* Where the daemon's token is about to be sent: refuse (or, with the opt-out, warn about) a token
|
|
166
|
+
* file that is not private. Does nothing when discovery found no token. Never reads the contents.
|
|
167
|
+
*/
|
|
168
|
+
export declare function checkDiscoveredToken(discovered: Pick<DiscoveredDaemon, "home" | "token">, opts?: PrivateTokenOptions): void;
|
|
169
|
+
export interface ClientOptions {
|
|
170
|
+
/** Default: discovered from the pid file / environment. */
|
|
171
|
+
baseUrl?: string;
|
|
172
|
+
/** Default: `~/.ant0/ant0d.token`. When neither is available, requests go out unauthenticated. */
|
|
173
|
+
token?: string;
|
|
174
|
+
/**
|
|
175
|
+
* No authentication: the token is never discovered, checked or sent (a given `token` is
|
|
176
|
+
* ignored). For health checks and other routes that need none. `baseUrl` is still discovered
|
|
177
|
+
* when omitted.
|
|
178
|
+
*/
|
|
179
|
+
anonymous?: boolean;
|
|
180
|
+
/** `ANT0_HOME` used for discovery when `baseUrl` or `token` are omitted. */
|
|
181
|
+
home?: string;
|
|
182
|
+
/** Injected fetch (tests, custom dispatchers). Default: `globalThis.fetch`. */
|
|
183
|
+
fetch?: typeof fetch;
|
|
184
|
+
}
|
|
185
|
+
export type Ant0Client = Client<paths>;
|
|
186
|
+
/** Middleware that adds `Authorization: Bearer <token>` to every request. */
|
|
187
|
+
export declare function bearerMiddleware(token: string): Middleware;
|
|
188
|
+
/**
|
|
189
|
+
* An `openapi-fetch` client for the daemon. Missing `baseUrl`/`token` are discovered from
|
|
190
|
+
* `opts.home` (see `discoverDaemon`). Connection failures surface as the `fetch` rejection
|
|
191
|
+
* (`TypeError: fetch failed` with `cause.code === "ECONNREFUSED"` when nothing listens).
|
|
192
|
+
*/
|
|
193
|
+
export declare function createAnt0Client(opts?: ClientOptions): Ant0Client;
|
|
194
|
+
/** A non-2xx answer from the daemon, decoded from the `{ error, message, details? }` envelope. */
|
|
195
|
+
export declare class Ant0ApiError extends Error {
|
|
196
|
+
readonly name = "Ant0ApiError";
|
|
197
|
+
readonly status: number;
|
|
198
|
+
/** Namespaced code such as `profile.not_found`; `http_<status>` when the body was not JSON. */
|
|
199
|
+
readonly code: string;
|
|
200
|
+
readonly details?: unknown;
|
|
201
|
+
constructor(status: number, code: string, message: string, details?: unknown);
|
|
202
|
+
static fromEnvelope(status: number, body: unknown, statusText?: string): Ant0ApiError;
|
|
203
|
+
}
|
|
204
|
+
export declare function isAnt0ApiError(value: unknown): value is Ant0ApiError;
|
|
205
|
+
/**
|
|
206
|
+
* Turn an `openapi-fetch` result into its data or throw `Ant0ApiError`. `openapi-fetch` yields
|
|
207
|
+
* `data: {}` for 204 responses, so `unwrap` on a DELETE resolves to an empty object.
|
|
208
|
+
*/
|
|
209
|
+
export declare function unwrap<T>(result: {
|
|
210
|
+
data?: T;
|
|
211
|
+
error?: unknown;
|
|
212
|
+
response: Response;
|
|
213
|
+
}): T;
|
|
214
|
+
/**
|
|
215
|
+
* WebSocket URL of the event stream: `ws://host:port/v1/events?token=...`. Browsers cannot set
|
|
216
|
+
* headers on `new WebSocket()`, so the route accepts the bearer token as a query parameter.
|
|
217
|
+
*/
|
|
218
|
+
export declare function eventsUrl(baseUrl: string, token: string): string;
|
|
219
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed client for the ant0d local API.
|
|
3
|
+
*
|
|
4
|
+
* `generated/schema.ts` is produced from the daemon's OpenAPI document and never edited by hand.
|
|
5
|
+
* This module adds the thin runtime layer every
|
|
6
|
+
* client needs: daemon discovery (`<ANT0_HOME>/ant0d.pid` + `ant0d.token`), a bearer-token middleware,
|
|
7
|
+
* an error type for the `{ error, message, details? }` envelope, and the WebSocket URL of the
|
|
8
|
+
* event stream.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, lstatSync, readFileSync } from "node:fs";
|
|
11
|
+
import { homedir, platform as osPlatform } from "node:os";
|
|
12
|
+
import { dirname, join, posix, resolve, win32 } from "node:path";
|
|
13
|
+
import createClient, {} from "openapi-fetch";
|
|
14
|
+
// ---------------------------------------------------------------------------------------------
|
|
15
|
+
// Discovery
|
|
16
|
+
// ---------------------------------------------------------------------------------------------
|
|
17
|
+
export const DEFAULT_HOST = "127.0.0.1";
|
|
18
|
+
/** `127.x.x.x`, `localhost`, or `::1` (with or without brackets). */
|
|
19
|
+
export function isLoopbackHost(host) {
|
|
20
|
+
const h = host
|
|
21
|
+
.trim()
|
|
22
|
+
.toLowerCase()
|
|
23
|
+
.replace(/^\[|\]$/g, "");
|
|
24
|
+
return h === "localhost" || h === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
|
|
25
|
+
}
|
|
26
|
+
export const DEFAULT_PORT = 27100;
|
|
27
|
+
/**
|
|
28
|
+
* A data folder exists for the legacy rule only when a daemon has run on it (`ant0.db` or
|
|
29
|
+
* `profiles/` present); an empty directory does not shadow a populated `~/.ant0`. The daemon and
|
|
30
|
+
* the desktop app use the same rule.
|
|
31
|
+
*/
|
|
32
|
+
export function homeExists(dir) {
|
|
33
|
+
return existsSync(join(dir, "ant0.db")) || existsSync(join(dir, "profiles"));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Refuse a data folder that is the directory holding the running executable (an installer that
|
|
37
|
+
* unpacks into the data folder would put the database next to the binary). Mirrors
|
|
38
|
+
* `assertNotExecutableDir` in `ant0d`; resolved paths, case-insensitive on Windows.
|
|
39
|
+
*/
|
|
40
|
+
export function assertNotExecutableDir(home, execPath, platform) {
|
|
41
|
+
const exeDir = resolve(dirname(execPath));
|
|
42
|
+
const target = resolve(home);
|
|
43
|
+
const same = platform === "win32" ? exeDir.toLowerCase() === target.toLowerCase() : exeDir === target;
|
|
44
|
+
if (same) {
|
|
45
|
+
throw new Error(`refusing to use ${target} as the data folder: it contains the running executable ` +
|
|
46
|
+
`(${execPath}); set ANT0_HOME or --home to a separate folder`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The platform data folder: Windows `%LOCALAPPDATA%\Ant0`; macOS
|
|
51
|
+
* `~/Library/Application Support/Ant0`; Linux `$XDG_DATA_HOME/ant0` or `~/.local/share/ant0`.
|
|
52
|
+
*/
|
|
53
|
+
export function platformDefaultHome(platform, env, userHome) {
|
|
54
|
+
if (platform === "win32") {
|
|
55
|
+
const local = env.LOCALAPPDATA && env.LOCALAPPDATA.length > 0 ? env.LOCALAPPDATA : undefined;
|
|
56
|
+
return local ? win32.join(local, "Ant0") : win32.join(userHome, "AppData", "Local", "Ant0");
|
|
57
|
+
}
|
|
58
|
+
if (platform === "darwin")
|
|
59
|
+
return posix.join(userHome, "Library", "Application Support", "Ant0");
|
|
60
|
+
const xdg = env.XDG_DATA_HOME && env.XDG_DATA_HOME.length > 0 ? env.XDG_DATA_HOME : undefined;
|
|
61
|
+
return xdg ? posix.join(xdg, "ant0") : posix.join(userHome, ".local", "share", "ant0");
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Resolve the data directory with the same rule as the daemon and the desktop app: the explicit `home`, then `ANT0_HOME`, then the
|
|
65
|
+
* platform default; an existing legacy `~/.ant0` is kept while the platform default does not
|
|
66
|
+
* exist, so the CLI keeps finding a daemon that still runs there.
|
|
67
|
+
*/
|
|
68
|
+
export function resolveHome(opts = {}) {
|
|
69
|
+
const env = opts.env ?? process.env;
|
|
70
|
+
const platform = opts.platform ?? osPlatform();
|
|
71
|
+
const execPath = opts.execPath ?? process.execPath;
|
|
72
|
+
const explicit = opts.home ?? env.ANT0_HOME?.trim();
|
|
73
|
+
if (explicit && explicit.length > 0) {
|
|
74
|
+
assertNotExecutableDir(explicit, execPath, platform);
|
|
75
|
+
return explicit;
|
|
76
|
+
}
|
|
77
|
+
const exists = opts.exists ?? homeExists;
|
|
78
|
+
const userHome = (opts.homedir ?? homedir)();
|
|
79
|
+
const def = platformDefaultHome(platform, env, userHome);
|
|
80
|
+
const legacy = (platform === "win32" ? win32 : posix).join(userHome, ".ant0");
|
|
81
|
+
const home = !exists(def) && exists(legacy) ? legacy : def;
|
|
82
|
+
assertNotExecutableDir(home, execPath, platform);
|
|
83
|
+
return home;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Locate the daemon from the files in the data directory. Does not throw for a missing file: an
|
|
87
|
+
* unreadable pid file falls back to `ANT0D_HOST`/`ANT0D_PORT` or `127.0.0.1:27100`, and a
|
|
88
|
+
* missing token yields `token: undefined` (callers treat that as "daemon not running"). The one
|
|
89
|
+
* exception is a token file that exists but is not private: that throws `TokenFileNotPrivateError`.
|
|
90
|
+
*/
|
|
91
|
+
export function discoverDaemon(opts = {}) {
|
|
92
|
+
const env = opts.env ?? process.env;
|
|
93
|
+
const home = resolveHome({ ...(opts.home !== undefined ? { home: opts.home } : {}), env });
|
|
94
|
+
const pidFile = readPidFile(join(home, "ant0d.pid"));
|
|
95
|
+
const envPort = parsePort(env.ANT0D_PORT);
|
|
96
|
+
// The daemon only ever listens on loopback; a pid file naming another host is tampered or
|
|
97
|
+
// stale and must not redirect the bearer token anywhere (mirrors the desktop shell's rule).
|
|
98
|
+
const pidHost = pidFile && isLoopbackHost(pidFile.host) ? pidFile.host : undefined;
|
|
99
|
+
const host = pidHost ?? (env.ANT0D_HOST && env.ANT0D_HOST.length > 0 ? env.ANT0D_HOST : DEFAULT_HOST);
|
|
100
|
+
const port = opts.port ?? pidFile?.port ?? envPort ?? DEFAULT_PORT;
|
|
101
|
+
const token = readToken(join(home, "ant0d.token"));
|
|
102
|
+
const result = { baseUrl: baseUrlFor(host, port), token, home };
|
|
103
|
+
if (pidFile)
|
|
104
|
+
result.pidFile = pidFile;
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
function baseUrlFor(host, port) {
|
|
108
|
+
const h = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
109
|
+
return `http://${h}:${port}`;
|
|
110
|
+
}
|
|
111
|
+
function parsePort(value) {
|
|
112
|
+
if (value === undefined || value.trim() === "")
|
|
113
|
+
return undefined;
|
|
114
|
+
const n = Number(value);
|
|
115
|
+
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : undefined;
|
|
116
|
+
}
|
|
117
|
+
function readPidFile(file) {
|
|
118
|
+
try {
|
|
119
|
+
if (!existsSync(file))
|
|
120
|
+
return undefined;
|
|
121
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
122
|
+
if (typeof parsed.pid !== "number" || typeof parsed.port !== "number")
|
|
123
|
+
return undefined;
|
|
124
|
+
return {
|
|
125
|
+
pid: parsed.pid,
|
|
126
|
+
port: parsed.port,
|
|
127
|
+
host: typeof parsed.host === "string" && parsed.host.length > 0 ? parsed.host : DEFAULT_HOST,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function readToken(file) {
|
|
135
|
+
// Discovery only reads: daemon start/stop/status and health checks never send the token. The
|
|
136
|
+
// privacy check runs where the token is sent (`checkDiscoveredToken`).
|
|
137
|
+
try {
|
|
138
|
+
if (!existsSync(file))
|
|
139
|
+
return undefined;
|
|
140
|
+
const token = readFileSync(file, "utf8").trim();
|
|
141
|
+
return token.length > 0 ? token : undefined;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** `ant0d.token` exists but other users could read it, or it is not a plain file of this user. */
|
|
148
|
+
export class TokenFileNotPrivateError extends Error {
|
|
149
|
+
name = "TokenFileNotPrivateError";
|
|
150
|
+
path;
|
|
151
|
+
reason;
|
|
152
|
+
/**
|
|
153
|
+
* Whether `ANT0_ALLOW_SHARED_TOKEN_FILE=1` may waive this refusal: only a wide mode or a foreign
|
|
154
|
+
* owner. A symbolic link or a file that is not a regular file is always refused.
|
|
155
|
+
*/
|
|
156
|
+
waivable;
|
|
157
|
+
constructor(path, reason, opts = {}) {
|
|
158
|
+
const waivable = reason.startsWith("mode") || reason.startsWith("owned by another user");
|
|
159
|
+
super(`token file ${path} is not private (${reason}). ${tokenFileFix(path, reason, waivable && opts.optOutHint !== false)}`);
|
|
160
|
+
this.waivable = waivable;
|
|
161
|
+
this.path = path;
|
|
162
|
+
this.reason = reason;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** How to put a token file right; mentions the path, never the token. */
|
|
166
|
+
function tokenFileFix(path, reason, optOutHint) {
|
|
167
|
+
const q = shellQuote(path);
|
|
168
|
+
const optOut = optOutHint
|
|
169
|
+
? ` Or set ${SHARED_TOKEN_FILE_ENV}=1 to warn instead of refusing (for file systems without Unix modes).`
|
|
170
|
+
: "";
|
|
171
|
+
if (reason.startsWith("mode"))
|
|
172
|
+
return `Fix: chmod 600 ${q}.${optOut}`;
|
|
173
|
+
if (reason.startsWith("owned by another user"))
|
|
174
|
+
return `Run ant0 as the file's owner, or chown it to your user (chown "$(id -un)" ${q}) and chmod 600 it.${optOut}`;
|
|
175
|
+
return `Fix: remove it and run \`ant0 daemon start\` to recreate it as a private file.${optOut}`;
|
|
176
|
+
}
|
|
177
|
+
/** POSIX single quotes: safe for spaces, `$`, backticks and double quotes in the path. */
|
|
178
|
+
function shellQuote(path) {
|
|
179
|
+
return `'${path.replaceAll("'", `'\\''`)}'`;
|
|
180
|
+
}
|
|
181
|
+
/** Set to `1` to turn the token privacy refusal into a stderr warning. */
|
|
182
|
+
export const SHARED_TOKEN_FILE_ENV = "ANT0_ALLOW_SHARED_TOKEN_FILE";
|
|
183
|
+
/**
|
|
184
|
+
* Why a token file's `lstat` result is not private, or `undefined` when it is. Not Windows: a
|
|
185
|
+
* regular file (not a link), owned by the current user, with no group or other permission bits.
|
|
186
|
+
* On Windows this returns `undefined`: there is no portable way to ask here, so the file goes
|
|
187
|
+
* unverified.
|
|
188
|
+
*/
|
|
189
|
+
export function privateTokenProblem(stat, opts = {}) {
|
|
190
|
+
if ((opts.platform ?? process.platform) === "win32")
|
|
191
|
+
return undefined;
|
|
192
|
+
if (stat.isSymbolicLink())
|
|
193
|
+
return "a symbolic link";
|
|
194
|
+
if (!stat.isFile())
|
|
195
|
+
return "not a regular file";
|
|
196
|
+
const uid = "uid" in opts ? opts.uid : process.geteuid?.();
|
|
197
|
+
if (uid !== undefined && uid !== 0 && stat.uid !== uid)
|
|
198
|
+
return "owned by another user";
|
|
199
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
200
|
+
return `mode ${(stat.mode & 0o777).toString(8).padStart(3, "0")} gives group or others access`;
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Refuse a token file that is not private. A missing file, or one that cannot be inspected, passes
|
|
206
|
+
* (the caller then sees "no token" as before); a file that is there but fails
|
|
207
|
+
* {@link privateTokenProblem} throws {@link TokenFileNotPrivateError}. Never reads the contents.
|
|
208
|
+
*/
|
|
209
|
+
export function checkPrivateTokenFile(file, opts = {}) {
|
|
210
|
+
let stat;
|
|
211
|
+
try {
|
|
212
|
+
stat = lstatSync(file);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const problem = privateTokenProblem(stat, opts);
|
|
218
|
+
if (problem === undefined)
|
|
219
|
+
return;
|
|
220
|
+
const optedOut = (opts.env ?? process.env)[SHARED_TOKEN_FILE_ENV] === "1";
|
|
221
|
+
const error = new TokenFileNotPrivateError(file, problem, { optOutHint: !optedOut });
|
|
222
|
+
if (optedOut && error.waivable) {
|
|
223
|
+
const text = `ant0: warning: ${error.message} (continuing: ${SHARED_TOKEN_FILE_ENV}=1)\n`;
|
|
224
|
+
if (opts.warn)
|
|
225
|
+
opts.warn(text);
|
|
226
|
+
else
|
|
227
|
+
process.stderr.write(text);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Where the daemon's token is about to be sent: refuse (or, with the opt-out, warn about) a token
|
|
234
|
+
* file that is not private. Does nothing when discovery found no token. Never reads the contents.
|
|
235
|
+
*/
|
|
236
|
+
export function checkDiscoveredToken(discovered, opts = {}) {
|
|
237
|
+
if (discovered.token === undefined)
|
|
238
|
+
return;
|
|
239
|
+
checkPrivateTokenFile(join(discovered.home, "ant0d.token"), opts);
|
|
240
|
+
}
|
|
241
|
+
/** Middleware that adds `Authorization: Bearer <token>` to every request. */
|
|
242
|
+
export function bearerMiddleware(token) {
|
|
243
|
+
return {
|
|
244
|
+
onRequest({ request }) {
|
|
245
|
+
request.headers.set("authorization", `Bearer ${token}`);
|
|
246
|
+
return request;
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* An `openapi-fetch` client for the daemon. Missing `baseUrl`/`token` are discovered from
|
|
252
|
+
* `opts.home` (see `discoverDaemon`). Connection failures surface as the `fetch` rejection
|
|
253
|
+
* (`TypeError: fetch failed` with `cause.code === "ECONNREFUSED"` when nothing listens).
|
|
254
|
+
*/
|
|
255
|
+
export function createAnt0Client(opts = {}) {
|
|
256
|
+
let baseUrl = opts.baseUrl;
|
|
257
|
+
let token = opts.token;
|
|
258
|
+
if (opts.anonymous === true)
|
|
259
|
+
token = undefined;
|
|
260
|
+
if (baseUrl === undefined || (token === undefined && opts.anonymous !== true)) {
|
|
261
|
+
const discovered = discoverDaemon(opts.home !== undefined ? { home: opts.home } : {});
|
|
262
|
+
baseUrl ??= discovered.baseUrl;
|
|
263
|
+
if (token === undefined && opts.anonymous !== true) {
|
|
264
|
+
// The token is about to be sent: refuse a token file that is not private.
|
|
265
|
+
checkDiscoveredToken(discovered);
|
|
266
|
+
token = discovered.token;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const fetchFn = opts.fetch;
|
|
270
|
+
const client = createClient({
|
|
271
|
+
baseUrl,
|
|
272
|
+
...(fetchFn ? { fetch: (request) => fetchFn(request) } : {}),
|
|
273
|
+
});
|
|
274
|
+
if (token !== undefined)
|
|
275
|
+
client.use(bearerMiddleware(token));
|
|
276
|
+
return client;
|
|
277
|
+
}
|
|
278
|
+
// ---------------------------------------------------------------------------------------------
|
|
279
|
+
// Errors
|
|
280
|
+
// ---------------------------------------------------------------------------------------------
|
|
281
|
+
/** A non-2xx answer from the daemon, decoded from the `{ error, message, details? }` envelope. */
|
|
282
|
+
export class Ant0ApiError extends Error {
|
|
283
|
+
name = "Ant0ApiError";
|
|
284
|
+
status;
|
|
285
|
+
/** Namespaced code such as `profile.not_found`; `http_<status>` when the body was not JSON. */
|
|
286
|
+
code;
|
|
287
|
+
details;
|
|
288
|
+
constructor(status, code, message, details) {
|
|
289
|
+
super(message);
|
|
290
|
+
this.status = status;
|
|
291
|
+
this.code = code;
|
|
292
|
+
if (details !== undefined)
|
|
293
|
+
this.details = details;
|
|
294
|
+
}
|
|
295
|
+
static fromEnvelope(status, body, statusText = "") {
|
|
296
|
+
if (body !== null && typeof body === "object") {
|
|
297
|
+
const env = body;
|
|
298
|
+
const code = typeof env.error === "string" ? env.error : `http_${status}`;
|
|
299
|
+
const message = typeof env.message === "string"
|
|
300
|
+
? env.message
|
|
301
|
+
: typeof env.error === "string"
|
|
302
|
+
? env.error
|
|
303
|
+
: statusText || `HTTP ${status}`;
|
|
304
|
+
return new Ant0ApiError(status, code, message, env.details);
|
|
305
|
+
}
|
|
306
|
+
const text = typeof body === "string" && body.trim().length > 0 ? body.trim() : "";
|
|
307
|
+
return new Ant0ApiError(status, `http_${status}`, text || statusText || `HTTP ${status}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
export function isAnt0ApiError(value) {
|
|
311
|
+
return value instanceof Ant0ApiError;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Turn an `openapi-fetch` result into its data or throw `Ant0ApiError`. `openapi-fetch` yields
|
|
315
|
+
* `data: {}` for 204 responses, so `unwrap` on a DELETE resolves to an empty object.
|
|
316
|
+
*/
|
|
317
|
+
export function unwrap(result) {
|
|
318
|
+
if (result.error !== undefined) {
|
|
319
|
+
throw Ant0ApiError.fromEnvelope(result.response.status, result.error, result.response.statusText);
|
|
320
|
+
}
|
|
321
|
+
if (result.data === undefined && !result.response.ok) {
|
|
322
|
+
throw new Ant0ApiError(result.response.status, `http_${result.response.status}`, result.response.statusText || `HTTP ${result.response.status}`);
|
|
323
|
+
}
|
|
324
|
+
return result.data;
|
|
325
|
+
}
|
|
326
|
+
// ---------------------------------------------------------------------------------------------
|
|
327
|
+
// Events
|
|
328
|
+
// ---------------------------------------------------------------------------------------------
|
|
329
|
+
/**
|
|
330
|
+
* WebSocket URL of the event stream: `ws://host:port/v1/events?token=...`. Browsers cannot set
|
|
331
|
+
* headers on `new WebSocket()`, so the route accepts the bearer token as a query parameter.
|
|
332
|
+
*/
|
|
333
|
+
export function eventsUrl(baseUrl, token) {
|
|
334
|
+
const url = new URL(baseUrl);
|
|
335
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
336
|
+
url.pathname = `${url.pathname.replace(/\/+$/, "")}/v1/events`;
|
|
337
|
+
url.search = "";
|
|
338
|
+
url.hash = "";
|
|
339
|
+
url.searchParams.set("token", token);
|
|
340
|
+
return url.toString();
|
|
341
|
+
}
|
|
342
|
+
//# sourceMappingURL=index.js.map
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
async function main() {
|
|
3
|
+
const { run } = await import("./index.js");
|
|
4
|
+
process.exitCode = await run(process.argv.slice(2), {
|
|
5
|
+
stdout: process.stdout,
|
|
6
|
+
stderr: process.stderr,
|
|
7
|
+
env: process.env,
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
void main().catch(() => process.exit(1));
|
|
11
|
+
export {};
|
|
12
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bulk.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Context } from "./context.js";
|
|
2
|
+
export interface BulkError {
|
|
3
|
+
id: string;
|
|
4
|
+
error: string;
|
|
5
|
+
message: string;
|
|
6
|
+
}
|
|
7
|
+
export interface BulkResult {
|
|
8
|
+
updated: number;
|
|
9
|
+
errors: BulkError[];
|
|
10
|
+
}
|
|
11
|
+
/** The endpoint-free bulk-run route deliberately calls its failure field `code`. */
|
|
12
|
+
export interface CodedBulkResult {
|
|
13
|
+
updated: number;
|
|
14
|
+
errors: {
|
|
15
|
+
id: string;
|
|
16
|
+
code: string;
|
|
17
|
+
message: string;
|
|
18
|
+
}[];
|
|
19
|
+
}
|
|
20
|
+
export declare const BULK_MAX_IDS = 50;
|
|
21
|
+
/** Drop repeated refs while keeping the order of first appearance. */
|
|
22
|
+
export declare function uniqueRefs(refs: readonly string[]): string[];
|
|
23
|
+
/** Turn a thrown value into the per-id error shape (API errors keep their code). */
|
|
24
|
+
export declare function toBulkError(id: string, err: unknown): BulkError;
|
|
25
|
+
/**
|
|
26
|
+
* Run `fn` once per ref, sequentially (the daemon serializes launches anyway), and collect the
|
|
27
|
+
* outcome. Used for routes that have no bulk twin (delete, restore).
|
|
28
|
+
*/
|
|
29
|
+
export declare function forEachRef<T>(refs: readonly string[], fn: (ref: string) => Promise<T>): Promise<BulkResult & {
|
|
30
|
+
results: T[];
|
|
31
|
+
}>;
|
|
32
|
+
/** Human rendering: `<verb> N profile(s)` then one indented line per failure. */
|
|
33
|
+
export declare function bulkText(verb: string, result: BulkResult, extra?: string[]): string;
|
|
34
|
+
/** Emit the result (verbatim with `--json`) and exit 1 when any id failed. */
|
|
35
|
+
export declare function finishBulk(ctx: Context, verb: string, result: BulkResult, extra?: string[]): void;
|
|
36
|
+
/** Keep the new bulk-run wire envelope intact while retaining old `{ error }` bulk envelopes. */
|
|
37
|
+
export declare function finishCodedBulk(ctx: Context, verb: string, result: CodedBulkResult): void;
|
|
38
|
+
//# sourceMappingURL=bulk.d.ts.map
|