barndog 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -10
- package/dist/cli.js +11 -7
- package/dist/commands/add.js +33 -21
- package/dist/commands/arguments.js +12 -0
- package/dist/commands/asset-install.js +160 -0
- package/dist/commands/asset-list.js +121 -0
- package/dist/commands/asset-share.js +94 -0
- package/dist/commands/auth.js +4 -0
- package/dist/commands/availability.js +54 -26
- package/dist/commands/capabilities.js +71 -415
- package/dist/commands/collaboration.js +194 -110
- package/dist/commands/environment.js +18 -411
- package/dist/commands/github.js +200 -0
- package/dist/commands/helpers.js +39 -0
- package/dist/commands/hooks.js +87 -0
- package/dist/commands/init.js +4 -2
- package/dist/commands/knowledge.js +73 -0
- package/dist/commands/mcp.js +62 -0
- package/dist/commands/origin.js +21 -23
- package/dist/commands/people.js +51 -0
- package/dist/commands/sets.js +141 -0
- package/dist/commands/status.js +34 -24
- package/dist/commands/sync.js +11 -4
- package/dist/commands/workspace.js +33 -19
- package/dist/config/environment.js +13 -27
- package/dist/config/paths.js +62 -0
- package/dist/config/selection.js +30 -0
- package/dist/config/settings.js +97 -108
- package/dist/config/state.js +57 -57
- package/dist/entry/knowledge-startup.js +32 -0
- package/dist/entry/mcp-launch.js +71 -0
- package/dist/entry/opencode-plugin.js +62 -0
- package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
- package/dist/errors.js +198 -55
- package/dist/features/asset-kinds/index.js +120 -0
- package/dist/features/asset-selection/index.js +51 -19
- package/dist/features/auth/credentials.js +80 -47
- package/dist/features/auth/session.js +80 -45
- package/dist/features/auth/transport.js +66 -15
- package/dist/features/catalog/index.js +32 -61
- package/dist/features/collaboration/api.js +160 -0
- package/dist/features/collaboration/index.js +321 -233
- package/dist/features/collaboration/remote.js +35 -115
- package/dist/features/collaboration/results.js +2 -0
- package/dist/features/collaboration/workspace-git.js +233 -149
- package/dist/features/collaboration/workspace-github.js +117 -54
- package/dist/features/collaboration/workspace-store.js +140 -100
- package/dist/features/collaboration/workspace.js +257 -172
- package/dist/features/discovery/index.js +68 -57
- package/dist/features/doctor/index.js +32 -24
- package/dist/features/environment/auto-sync.js +28 -27
- package/dist/features/environment/names.js +67 -47
- package/dist/features/environment/operations.js +321 -228
- package/dist/features/environment/own-entries.js +89 -0
- package/dist/features/environment/settle-names.js +91 -0
- package/dist/features/environment/stage.js +178 -0
- package/dist/features/environment/sync.js +113 -484
- package/dist/features/environment/transaction.js +179 -147
- package/dist/features/environment/writes.js +196 -0
- package/dist/features/github/account.js +25 -0
- package/dist/features/github/connections.js +119 -0
- package/dist/features/github/pulls.js +118 -0
- package/dist/features/hooks/adapt.js +32 -25
- package/dist/features/hooks/catalog.js +28 -0
- package/dist/features/hooks/compatibility.js +49 -0
- package/dist/features/hooks/divergence.js +9 -6
- package/dist/features/hooks/test.js +74 -49
- package/dist/features/hooks/types.js +1 -0
- package/dist/features/imports/discover.js +134 -61
- package/dist/features/imports/folder.js +48 -14
- package/dist/features/imports/local.js +113 -134
- package/dist/features/imports/remote.js +44 -25
- package/dist/features/inspection/index.js +17 -17
- package/dist/features/inventory/index.js +99 -110
- package/dist/features/knowledge/index.js +69 -49
- package/dist/features/mcps/catalog.js +31 -0
- package/dist/features/mcps/import.js +316 -0
- package/dist/features/mcps/index.js +98 -49
- package/dist/features/migration/migrate.js +263 -0
- package/dist/features/{git-workspace → migration}/move.js +165 -109
- package/dist/features/migration/promote.js +24 -0
- package/dist/features/native/adapters.js +53 -94
- package/dist/features/native/configuration.js +128 -82
- package/dist/features/native/hook-shell.js +55 -0
- package/dist/features/native/plugin-module.js +56 -0
- package/dist/features/onboarding/environment.js +67 -34
- package/dist/features/onboarding/setup.js +43 -40
- package/dist/features/repositories/context.js +30 -13
- package/dist/features/server/catalog.js +58 -0
- package/dist/features/server/client.js +13 -0
- package/dist/features/server/connection.js +37 -0
- package/dist/features/server/origin.js +74 -0
- package/dist/features/server/pages.js +24 -0
- package/dist/features/skills/catalog.js +42 -0
- package/dist/features/workspace/assets.js +57 -0
- package/dist/features/workspace/cloud-source.js +34 -0
- package/dist/features/workspace/directory.js +38 -0
- package/dist/features/{git-workspace → workspace}/format.js +114 -51
- package/dist/features/workspace/git.js +214 -0
- package/dist/features/workspace/installed.js +92 -0
- package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
- package/dist/features/workspace/packages.js +160 -0
- package/dist/features/{git-workspace → workspace}/publish.js +120 -64
- package/dist/features/workspace/repo-source.js +192 -0
- package/dist/features/{git-workspace → workspace}/setup.js +60 -42
- package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
- package/dist/features/workspace/source.js +1 -0
- package/dist/features/workspace/tree.js +52 -0
- package/dist/features/workspace/workspace-source.js +27 -0
- package/dist/harnesses/claude.js +23 -1
- package/dist/harnesses/codex.js +57 -1
- package/dist/harnesses/cursor.js +22 -1
- package/dist/harnesses/detect.js +6 -50
- package/dist/harnesses/formats.js +45 -0
- package/dist/harnesses/opencode.js +111 -0
- package/dist/harnesses/registry.js +35 -2
- package/dist/platform.js +375 -0
- package/dist/program.js +225 -54
- package/dist/runtime.js +1 -0
- package/dist/shared/cli-error.js +22 -0
- package/dist/shared/constants.js +32 -0
- package/dist/shared/files.js +72 -0
- package/dist/shared/lock.js +49 -0
- package/dist/shared/lookup.js +11 -0
- package/dist/shared/patterns.js +94 -0
- package/dist/shared/shell.js +22 -0
- package/dist/shared/values.js +26 -0
- package/dist/ui/add-asset.js +41 -400
- package/dist/ui/add-hook.js +213 -0
- package/dist/ui/add-mcp.js +107 -0
- package/dist/ui/add-prompts.js +47 -0
- package/dist/ui/add-skills.js +115 -0
- package/dist/ui/asset-list.js +31 -13
- package/dist/ui/assets.js +33 -44
- package/dist/ui/auth.js +43 -33
- package/dist/ui/clash.js +11 -6
- package/dist/ui/collaboration.js +116 -44
- package/dist/ui/connection.js +10 -4
- package/dist/ui/decision-error.js +24 -0
- package/dist/ui/environment-onboarding.js +35 -13
- package/dist/ui/format.js +66 -18
- package/dist/ui/hook-compatibility.js +14 -6
- package/dist/ui/mcp.js +28 -3
- package/dist/ui/move.js +10 -5
- package/dist/ui/onboarding.js +113 -73
- package/dist/ui/options.js +9 -0
- package/dist/ui/output.js +106 -43
- package/dist/ui/pick.js +45 -33
- package/dist/ui/scope-install.js +15 -7
- package/dist/ui/selection.js +15 -11
- package/dist/ui/theme.js +37 -14
- package/dist/version.js +6 -3
- package/package.json +24 -11
- package/dist/features/capabilities/index.js +0 -106
- package/dist/features/collaboration/domain.js +0 -90
- package/dist/features/environment/cloud-source.js +0 -27
- package/dist/features/environment/installed.js +0 -124
- package/dist/features/environment/packages.js +0 -120
- package/dist/features/environment/remote.js +0 -71
- package/dist/features/environment/workspace-source.js +0 -19
- package/dist/features/git-hosts/index.js +0 -148
- package/dist/features/git-workspace/assets.js +0 -71
- package/dist/features/git-workspace/git.js +0 -135
- package/dist/features/git-workspace/migrate.js +0 -188
- package/dist/features/git-workspace/source.js +0 -159
- package/dist/features/imports/mcp.js +0 -219
- package/dist/features/knowledge/startup.js +0 -25
- package/dist/features/native/mcp-launch.js +0 -57
- package/dist/features/skills/install.js +0 -25
- package/dist/features/skills/remote.js +0 -177
- package/dist/features/skills/sync.js +0 -121
- package/dist/features/skills/validation.js +0 -34
- /package/dist/features/environment/{source.js → events.js} +0 -0
|
@@ -1,7 +1,22 @@
|
|
|
1
|
-
|
|
1
|
+
import { defined } from "../../shared/lookup.js";
|
|
2
|
+
import { UUID_V4 } from "../../shared/patterns.js";
|
|
3
|
+
/**
|
|
4
|
+
* Enabling or disabling a set that isn't in the selection. Callers that know
|
|
5
|
+
* the origin the person typed turn it into a `CliError` with the install
|
|
6
|
+
* command.
|
|
7
|
+
*/
|
|
8
|
+
export class ScopeNotSelectedError extends Error {
|
|
9
|
+
scope;
|
|
10
|
+
constructor(scope) {
|
|
11
|
+
super(`Scope is not selected: ${scope}`);
|
|
12
|
+
this.name = "ScopeNotSelectedError";
|
|
13
|
+
this.scope = scope;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
2
16
|
function id(value) {
|
|
3
|
-
if (!
|
|
17
|
+
if (!UUID_V4.test(value)) {
|
|
4
18
|
throw new Error(`Expected UUIDv4: ${value}`);
|
|
19
|
+
}
|
|
5
20
|
return value.toLowerCase();
|
|
6
21
|
}
|
|
7
22
|
function origin(value) {
|
|
@@ -11,7 +26,10 @@ function scopeKey(scope) {
|
|
|
11
26
|
return `${scope.type}:${scope.id}`;
|
|
12
27
|
}
|
|
13
28
|
function compare(a, b) {
|
|
14
|
-
|
|
29
|
+
if (a === b) {
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
return a < b ? -1 : 1;
|
|
15
33
|
}
|
|
16
34
|
function ids(values) {
|
|
17
35
|
return [...new Set(values.map(id))].sort(compare);
|
|
@@ -22,8 +40,9 @@ function normalizeState(state) {
|
|
|
22
40
|
scope: origin(subscription.scope),
|
|
23
41
|
}));
|
|
24
42
|
const keys = subscriptions.map((subscription) => scopeKey(subscription.scope));
|
|
25
|
-
if (new Set(keys).size !== keys.length)
|
|
43
|
+
if (new Set(keys).size !== keys.length) {
|
|
26
44
|
throw new Error("Only one subscription per scope is allowed");
|
|
45
|
+
}
|
|
27
46
|
return {
|
|
28
47
|
subscriptions: subscriptions.sort((a, b) => compare(scopeKey(a.scope), scopeKey(b.scope))),
|
|
29
48
|
individualAssetIds: ids(state.individualAssetIds),
|
|
@@ -35,8 +54,9 @@ function prepare(catalog, input) {
|
|
|
35
54
|
const assets = new Map();
|
|
36
55
|
for (const asset of catalog.assets) {
|
|
37
56
|
const assetId = id(asset.id);
|
|
38
|
-
if (assets.has(assetId))
|
|
57
|
+
if (assets.has(assetId)) {
|
|
39
58
|
throw new Error(`Duplicate catalogue asset ID: ${assetId}`);
|
|
59
|
+
}
|
|
40
60
|
assets.set(assetId, {
|
|
41
61
|
...asset,
|
|
42
62
|
id: assetId,
|
|
@@ -47,14 +67,16 @@ function prepare(catalog, input) {
|
|
|
47
67
|
for (const distribution of catalog.distributions) {
|
|
48
68
|
const scope = origin(distribution.scope);
|
|
49
69
|
const key = scopeKey(scope);
|
|
50
|
-
if (distributions.has(key))
|
|
70
|
+
if (distributions.has(key)) {
|
|
51
71
|
throw new Error(`Duplicate distribution scope: ${key}`);
|
|
72
|
+
}
|
|
52
73
|
const entries = new Map();
|
|
53
74
|
for (const entry of distribution.assets) {
|
|
54
75
|
const assetId = id(entry.assetId);
|
|
55
76
|
const previous = entries.get(assetId);
|
|
56
|
-
if (previous && previous !== entry.mode)
|
|
77
|
+
if (previous && previous !== entry.mode) {
|
|
57
78
|
throw new Error(`Conflicting recommendation modes: ${assetId} in ${key}`);
|
|
79
|
+
}
|
|
58
80
|
entries.set(assetId, entry.mode);
|
|
59
81
|
}
|
|
60
82
|
distributions.set(key, {
|
|
@@ -82,8 +104,9 @@ export function resolveAssets(catalog, input) {
|
|
|
82
104
|
missingAssets.add(assetId);
|
|
83
105
|
return;
|
|
84
106
|
}
|
|
85
|
-
if (excluded.has(assetId))
|
|
107
|
+
if (excluded.has(assetId)) {
|
|
86
108
|
return;
|
|
109
|
+
}
|
|
87
110
|
const sources = contributions.get(assetId) ?? [];
|
|
88
111
|
sources.push(contribution);
|
|
89
112
|
contributions.set(assetId, sources);
|
|
@@ -95,18 +118,21 @@ export function resolveAssets(catalog, input) {
|
|
|
95
118
|
continue;
|
|
96
119
|
}
|
|
97
120
|
for (const entry of distribution.assets) {
|
|
98
|
-
if (matches(subscription.mode, entry.mode))
|
|
121
|
+
if (matches(subscription.mode, entry.mode)) {
|
|
99
122
|
contribute(entry.assetId, { type: "subscription", ...subscription });
|
|
123
|
+
}
|
|
100
124
|
}
|
|
101
125
|
}
|
|
102
|
-
for (const assetId of state.individualAssetIds)
|
|
126
|
+
for (const assetId of state.individualAssetIds) {
|
|
103
127
|
contribute(assetId, { type: "individual" });
|
|
104
|
-
|
|
128
|
+
}
|
|
129
|
+
for (const assetId of [...missingAssets].sort(compare)) {
|
|
105
130
|
diagnostics.push({ type: "missing-asset", assetId });
|
|
131
|
+
}
|
|
106
132
|
const effective = [...contributions]
|
|
107
133
|
.sort(([a], [b]) => compare(a, b))
|
|
108
134
|
.map(([assetId, sources]) => ({
|
|
109
|
-
asset: assets.get(assetId),
|
|
135
|
+
asset: defined(assets.get(assetId), `Asset ${assetId} is missing from the catalog`),
|
|
110
136
|
enabled: !disabled.has(assetId) &&
|
|
111
137
|
sources.some((source) => source.type === "individual" || source.enabled),
|
|
112
138
|
individuallyDisabled: disabled.has(assetId),
|
|
@@ -128,15 +154,17 @@ export function applySelectionAction(catalog, input, action, resolution) {
|
|
|
128
154
|
action.type === "switch-team" ||
|
|
129
155
|
action.type === "switch-scope") {
|
|
130
156
|
const distribution = distributions.get(key);
|
|
131
|
-
if (!distribution)
|
|
157
|
+
if (!distribution) {
|
|
132
158
|
throw new Error(`Unknown scope: ${key}`);
|
|
159
|
+
}
|
|
133
160
|
const conflicts = distribution.assets
|
|
134
161
|
.filter((entry) => matches(action.mode, entry.mode))
|
|
135
162
|
.filter((entry) => excluded.has(entry.assetId) || disabled.has(entry.assetId))
|
|
136
163
|
.map((entry) => {
|
|
137
164
|
const asset = assets.get(entry.assetId);
|
|
138
|
-
if (!asset)
|
|
165
|
+
if (!asset) {
|
|
139
166
|
throw new Error(`Cannot resolve overrides for missing asset: ${entry.assetId}`);
|
|
167
|
+
}
|
|
140
168
|
return {
|
|
141
169
|
asset,
|
|
142
170
|
excluded: excluded.has(entry.assetId),
|
|
@@ -147,16 +175,18 @@ export function applySelectionAction(catalog, input, action, resolution) {
|
|
|
147
175
|
if (resolution?.type === "per-asset") {
|
|
148
176
|
for (const decision of resolution.decisions) {
|
|
149
177
|
const assetId = id(decision.assetId);
|
|
150
|
-
if (decisions.has(assetId))
|
|
178
|
+
if (decisions.has(assetId)) {
|
|
151
179
|
throw new Error(`Duplicate override decision: ${assetId}`);
|
|
180
|
+
}
|
|
152
181
|
decisions.set(assetId, decision.choice);
|
|
153
182
|
}
|
|
154
183
|
}
|
|
155
184
|
if (conflicts.length &&
|
|
156
185
|
(!resolution ||
|
|
157
186
|
(resolution.type === "per-asset" &&
|
|
158
|
-
conflicts.some(({ asset }) => !decisions.has(asset.id)))))
|
|
187
|
+
conflicts.some(({ asset }) => !decisions.has(asset.id))))) {
|
|
159
188
|
return { status: "decision-required", conflicts };
|
|
189
|
+
}
|
|
160
190
|
for (const { asset } of conflicts) {
|
|
161
191
|
if (resolution?.type === "clear-all" ||
|
|
162
192
|
decisions.get(asset.id) === "clear") {
|
|
@@ -173,8 +203,9 @@ export function applySelectionAction(catalog, input, action, resolution) {
|
|
|
173
203
|
subscriptions = subscriptions.filter((subscription) => scopeKey(subscription.scope) !== key);
|
|
174
204
|
}
|
|
175
205
|
else {
|
|
176
|
-
if (!subscriptions.some((subscription) => scopeKey(subscription.scope) === key))
|
|
177
|
-
throw new
|
|
206
|
+
if (!subscriptions.some((subscription) => scopeKey(subscription.scope) === key)) {
|
|
207
|
+
throw new ScopeNotSelectedError(key);
|
|
208
|
+
}
|
|
178
209
|
subscriptions = subscriptions.map((subscription) => scopeKey(subscription.scope) === key
|
|
179
210
|
? { ...subscription, enabled: action.enabled }
|
|
180
211
|
: subscription);
|
|
@@ -183,8 +214,9 @@ export function applySelectionAction(catalog, input, action, resolution) {
|
|
|
183
214
|
else {
|
|
184
215
|
const assetId = id(action.assetId);
|
|
185
216
|
if (action.type === "install-asset") {
|
|
186
|
-
if (!assets.has(assetId))
|
|
217
|
+
if (!assets.has(assetId)) {
|
|
187
218
|
throw new Error(`Unknown asset: ${assetId}`);
|
|
219
|
+
}
|
|
188
220
|
individual.add(assetId);
|
|
189
221
|
excluded.delete(assetId);
|
|
190
222
|
disabled.delete(assetId);
|
|
@@ -1,62 +1,95 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { fixSteps, privatePermissions, protectPrivate, removeCommand, } from "../../platform.js";
|
|
2
|
+
import { posixQuote } from "../../shared/shell.js";
|
|
3
|
+
import { POSIX_MODE } from "../../shared/constants.js";
|
|
4
|
+
import { chmod, lstat, mkdir, readFile, rm } from "node:fs/promises";
|
|
5
5
|
import { contextSchema } from "@barndog-ai/api-contract";
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { errorCode } from "../../shared/values.js";
|
|
8
|
+
import { ifExists, writeAtomic } from "../../shared/files.js";
|
|
9
|
+
import { CliError } from "../../errors.js";
|
|
10
|
+
import { barndogPaths } from "../../config/paths.js";
|
|
11
|
+
/**
|
|
12
|
+
* A BarnDog session token: 32 random bytes in unpadded base64url, 43 characters.
|
|
13
|
+
*
|
|
14
|
+
* @internal Exported for its table test in `src/tests/patterns.test.ts`.
|
|
15
|
+
*/
|
|
16
|
+
export const SESSION_TOKEN = /^[\w-]{43}$/;
|
|
17
|
+
const credentialsSchema = z.looseObject({
|
|
18
|
+
version: z.literal(1),
|
|
19
|
+
selectedServer: z.string().optional(),
|
|
20
|
+
servers: z.record(z.string(), z.looseObject({
|
|
21
|
+
token: z.string().regex(SESSION_TOKEN),
|
|
22
|
+
expiresAt: z
|
|
23
|
+
.string()
|
|
24
|
+
.refine((value) => Number.isFinite(Date.parse(value))),
|
|
25
|
+
context: contextSchema,
|
|
26
|
+
})),
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Reads saved sessions under the supplied home; rejects insecure POSIX
|
|
30
|
+
* permissions and returns empty state if absent.
|
|
31
|
+
*/
|
|
32
|
+
export async function readCredentials(runtime) {
|
|
33
|
+
const { home } = runtime;
|
|
34
|
+
const path = barndogPaths(home).credentials;
|
|
35
|
+
const info = await ifExists(lstat(path));
|
|
36
|
+
if (!info) {
|
|
37
|
+
return { version: 1, servers: {} };
|
|
38
|
+
}
|
|
39
|
+
if (!info.isFile()) {
|
|
40
|
+
throw new CliError(`${path} isn't a regular file, so BarnDog can't read your sign-ins.`, "Delete it and sign in again.", {
|
|
41
|
+
command: fixSteps([removeCommand(path, runtime.platform), "barndog login"], runtime.platform),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
// Always passes on Windows, where the ACL set on every write keeps it private.
|
|
45
|
+
if (!privatePermissions(info.mode, runtime.platform)) {
|
|
46
|
+
throw new CliError(`${path} can be read by other users on this machine.`, "Make it readable and writable only by you.", { command: `chmod 600 ${posixQuote(path)}` });
|
|
47
|
+
}
|
|
48
|
+
const parsed = credentialsSchema.safeParse(parseJson(await readFile(path, "utf8")));
|
|
49
|
+
if (!parsed.success) {
|
|
50
|
+
throw new CliError(`${path} is damaged, so BarnDog can't read your sign-ins.`, "Delete the file and sign in again.", {
|
|
51
|
+
command: fixSteps([removeCommand(path, runtime.platform), "barndog login"], runtime.platform),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return parsed.data;
|
|
55
|
+
}
|
|
56
|
+
/** JSON, or undefined when the text isn't JSON, so the schema reports it as damaged. */
|
|
57
|
+
function parseJson(text) {
|
|
8
58
|
try {
|
|
9
|
-
|
|
10
|
-
if (!info.isFile() || (process.platform !== "win32" && info.mode & 0o077))
|
|
11
|
-
throw new Error("Credentials file must be a regular file accessible only to its owner");
|
|
12
|
-
const value = JSON.parse(await readFile(path, "utf8"));
|
|
13
|
-
if (value.version !== 1 ||
|
|
14
|
-
!value.servers ||
|
|
15
|
-
typeof value.servers !== "object" ||
|
|
16
|
-
Array.isArray(value.servers) ||
|
|
17
|
-
(value.selectedServer !== undefined &&
|
|
18
|
-
typeof value.selectedServer !== "string"))
|
|
19
|
-
throw new Error("Invalid credentials file");
|
|
20
|
-
for (const entry of Object.values(value.servers)) {
|
|
21
|
-
if (!entry ||
|
|
22
|
-
!/^[A-Za-z0-9_-]{43}$/.test(entry.token) ||
|
|
23
|
-
!Number.isFinite(Date.parse(entry.expiresAt)))
|
|
24
|
-
throw new Error("Invalid credentials file");
|
|
25
|
-
contextSchema.parse(entry.context);
|
|
26
|
-
}
|
|
27
|
-
return value;
|
|
59
|
+
return JSON.parse(text);
|
|
28
60
|
}
|
|
29
|
-
catch
|
|
30
|
-
|
|
31
|
-
return { version: 1, servers: {} };
|
|
32
|
-
throw error;
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
33
63
|
}
|
|
34
64
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Locks credentials under the supplied home, applies a synchronous update and
|
|
67
|
+
* atomically saves the result.
|
|
68
|
+
*/
|
|
69
|
+
export async function updateCredentials(runtime, update) {
|
|
70
|
+
const { home } = runtime;
|
|
71
|
+
const root = barndogPaths(home).root;
|
|
72
|
+
await mkdir(root, { recursive: true, mode: POSIX_MODE.privateDirectory });
|
|
38
73
|
const info = await lstat(root);
|
|
39
|
-
if (!info.isDirectory())
|
|
40
|
-
throw new
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
await
|
|
44
|
-
|
|
45
|
-
|
|
74
|
+
if (!info.isDirectory()) {
|
|
75
|
+
throw new CliError(`${root} must be a folder.`);
|
|
76
|
+
}
|
|
77
|
+
await chmod(root, POSIX_MODE.privateDirectory);
|
|
78
|
+
await protectPrivate(root, runtime);
|
|
79
|
+
const lock = barndogPaths(home).credentialsLock;
|
|
80
|
+
await mkdir(lock, { mode: POSIX_MODE.privateDirectory }).catch((error) => {
|
|
81
|
+
if (errorCode(error) === "EEXIST") {
|
|
82
|
+
throw new CliError("Another sign-in or sign-out is running. Wait for it to finish, then try again.");
|
|
83
|
+
}
|
|
46
84
|
throw error;
|
|
47
85
|
});
|
|
48
|
-
const temporary = join(root, `credentials.${randomUUID()}.tmp`);
|
|
49
86
|
try {
|
|
50
|
-
const credentials = await readCredentials(
|
|
87
|
+
const credentials = await readCredentials(runtime);
|
|
51
88
|
update(credentials);
|
|
52
|
-
await
|
|
53
|
-
|
|
54
|
-
flag: "wx",
|
|
55
|
-
});
|
|
56
|
-
await rename(temporary, join(root, "credentials.json"));
|
|
89
|
+
await writeAtomic(barndogPaths(home).credentials, JSON.stringify(credentials, null, 2) + "\n");
|
|
90
|
+
await protectPrivate(barndogPaths(home).credentials, runtime);
|
|
57
91
|
}
|
|
58
92
|
finally {
|
|
59
|
-
await rm(temporary, { force: true });
|
|
60
93
|
await rm(lock, { recursive: true });
|
|
61
94
|
}
|
|
62
95
|
}
|
|
@@ -1,30 +1,57 @@
|
|
|
1
|
+
import { MILLISECONDS_PER_SECOND } from "../../shared/constants.js";
|
|
1
2
|
import { hasRemoteSelections } from "../../config/environment.js";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
3
|
import { setTimeout } from "node:timers/promises";
|
|
4
4
|
import { createApiClient, contextSchema, loginPollSchema, loginStartSchema, } from "@barndog-ai/api-contract";
|
|
5
5
|
import { readSettings } from "../../config/settings.js";
|
|
6
6
|
import { readCredentials, updateCredentials } from "./credentials.js";
|
|
7
|
-
import { LoginRequiredError, normalizeServer, serverFetch, } from "./transport.js";
|
|
8
|
-
|
|
7
|
+
import { apiClient, LoginRequiredError, normalizeServer, serverFetch, } from "./transport.js";
|
|
8
|
+
import { CliError } from "../../errors.js";
|
|
9
|
+
/** Bound each device authorization request to ten seconds. */
|
|
10
|
+
const AUTH_REQUEST_TIMEOUT_MS = 10000;
|
|
11
|
+
/**
|
|
12
|
+
* The saved connection's server, else the server last signed in to, as a
|
|
13
|
+
* validated origin.
|
|
14
|
+
*/
|
|
15
|
+
export async function configuredServer(runtime) {
|
|
16
|
+
const { home } = runtime;
|
|
9
17
|
const settings = await readSettings(home);
|
|
10
|
-
const credentials = await readCredentials(
|
|
11
|
-
const value =
|
|
12
|
-
credentials.selectedServer;
|
|
18
|
+
const credentials = await readCredentials(runtime);
|
|
19
|
+
const value = settings?.connection?.server ?? credentials.selectedServer;
|
|
13
20
|
return value ? normalizeServer(value) : undefined;
|
|
14
21
|
}
|
|
15
|
-
async function selectedServer(server,
|
|
16
|
-
const value = server ?? (await configuredServer(
|
|
17
|
-
if (!value)
|
|
18
|
-
throw new
|
|
22
|
+
async function selectedServer(server, runtime) {
|
|
23
|
+
const value = server ?? (await configuredServer(runtime));
|
|
24
|
+
if (!value) {
|
|
25
|
+
throw new CliError("Choose a server for your first sign-in.", "barndog login --server <url>");
|
|
26
|
+
}
|
|
19
27
|
return normalizeServer(value);
|
|
20
28
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
29
|
+
/**
|
|
30
|
+
* A client that attaches no saved credential: sign-in has none yet, and
|
|
31
|
+
* revoking names the token itself, which may not be the saved one.
|
|
32
|
+
*/
|
|
33
|
+
const signInClient = (server, runtime) => {
|
|
34
|
+
return createApiClient({
|
|
25
35
|
baseUrl: server,
|
|
26
|
-
fetch: serverFetch(server,
|
|
36
|
+
fetch: serverFetch(server, runtime, false),
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
/** Ends the session `token` belongs to; throws when the server didn't confirm it. */
|
|
40
|
+
async function revokeSession(client, token) {
|
|
41
|
+
await client.DELETE("/v1/auth/cli/session", {
|
|
42
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
43
|
+
signal: AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS),
|
|
27
44
|
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Starts device login, invokes the verification callback, polls completion and
|
|
48
|
+
* persists the returned session.
|
|
49
|
+
*/
|
|
50
|
+
export async function login(options) {
|
|
51
|
+
const { runtime } = options;
|
|
52
|
+
const { home } = runtime;
|
|
53
|
+
const server = await selectedServer(options.server, options.runtime);
|
|
54
|
+
const client = signInClient(server, options.runtime);
|
|
28
55
|
const started = loginStartSchema.parse((await client.POST("/v1/auth/cli/start", { signal: options.signal })).data);
|
|
29
56
|
await options.verification({
|
|
30
57
|
userCode: started.userCode,
|
|
@@ -37,7 +64,7 @@ export async function login(options) {
|
|
|
37
64
|
]);
|
|
38
65
|
let interval = started.interval;
|
|
39
66
|
while (true) {
|
|
40
|
-
await setTimeout(interval *
|
|
67
|
+
await setTimeout(interval * MILLISECONDS_PER_SECOND, undefined, { signal });
|
|
41
68
|
const result = loginPollSchema.parse((await client.POST("/v1/auth/cli/poll", {
|
|
42
69
|
body: { pollingToken: started.pollingToken },
|
|
43
70
|
signal,
|
|
@@ -46,23 +73,19 @@ export async function login(options) {
|
|
|
46
73
|
interval = result.interval;
|
|
47
74
|
continue;
|
|
48
75
|
}
|
|
49
|
-
const revoke = () =>
|
|
50
|
-
method: "DELETE",
|
|
51
|
-
headers: { Authorization: `Bearer ${result.token}` },
|
|
52
|
-
redirect: "error",
|
|
53
|
-
signal: AbortSignal.timeout(10000),
|
|
54
|
-
});
|
|
76
|
+
const revoke = () => revokeSession(client, result.token);
|
|
55
77
|
try {
|
|
56
78
|
const settings = await readSettings(home);
|
|
57
|
-
if (settings
|
|
79
|
+
if (settings &&
|
|
58
80
|
hasRemoteSelections(settings) &&
|
|
59
81
|
settings.connection &&
|
|
60
82
|
(settings.connection.server !== server ||
|
|
61
83
|
settings.connection.organizationId !==
|
|
62
84
|
result.context.organization.id ||
|
|
63
|
-
settings.connection.developerId !== result.context.developer.id))
|
|
64
|
-
throw new
|
|
65
|
-
|
|
85
|
+
settings.connection.developerId !== result.context.developer.id)) {
|
|
86
|
+
throw new CliError("You have assets selected from the current server. Remove them before switching server, organization or developer.", "barndog status");
|
|
87
|
+
}
|
|
88
|
+
await updateCredentials(options.runtime, (credentials) => {
|
|
66
89
|
credentials.servers[server] = {
|
|
67
90
|
token: result.token,
|
|
68
91
|
expiresAt: result.expiresAt,
|
|
@@ -78,43 +101,55 @@ export async function login(options) {
|
|
|
78
101
|
return { server, context: result.context, expiresAt: result.expiresAt };
|
|
79
102
|
}
|
|
80
103
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
104
|
+
/**
|
|
105
|
+
* Attempts remote session revocation and removes local credentials even if
|
|
106
|
+
* revocation fails; reports that outcome.
|
|
107
|
+
*/
|
|
108
|
+
export async function logout(runtime) {
|
|
109
|
+
const server = await selectedServer(undefined, runtime);
|
|
110
|
+
const credential = (await readCredentials(runtime)).servers[server];
|
|
84
111
|
let revoked = true;
|
|
85
112
|
if (credential) {
|
|
86
113
|
try {
|
|
87
|
-
|
|
88
|
-
method: "DELETE",
|
|
89
|
-
headers: { Authorization: `Bearer ${credential.token}` },
|
|
90
|
-
redirect: "error",
|
|
91
|
-
signal: AbortSignal.timeout(10000),
|
|
92
|
-
});
|
|
93
|
-
revoked = response.ok;
|
|
114
|
+
await revokeSession(signInClient(server, runtime), credential.token);
|
|
94
115
|
}
|
|
95
116
|
catch {
|
|
96
117
|
revoked = false;
|
|
97
118
|
}
|
|
98
119
|
}
|
|
99
|
-
await updateCredentials(
|
|
120
|
+
await updateCredentials(runtime, (credentials) => {
|
|
100
121
|
delete credentials.servers[server];
|
|
101
|
-
if (credentials.selectedServer === server)
|
|
122
|
+
if (credentials.selectedServer === server) {
|
|
102
123
|
delete credentials.selectedServer;
|
|
124
|
+
}
|
|
103
125
|
});
|
|
104
126
|
return { server, revoked };
|
|
105
127
|
}
|
|
106
|
-
|
|
128
|
+
/**
|
|
129
|
+
* Fetches the authenticated server context; missing or expired credentials
|
|
130
|
+
* require login.
|
|
131
|
+
*/
|
|
132
|
+
export async function authStatus(runtime, explicitServer) {
|
|
107
133
|
let server;
|
|
108
134
|
try {
|
|
109
|
-
server = await selectedServer(explicitServer,
|
|
135
|
+
server = await selectedServer(explicitServer, runtime);
|
|
110
136
|
}
|
|
111
137
|
catch {
|
|
112
138
|
throw new LoginRequiredError();
|
|
113
139
|
}
|
|
114
|
-
const
|
|
115
|
-
baseUrl: server,
|
|
116
|
-
fetch: serverFetch(server, home),
|
|
117
|
-
});
|
|
118
|
-
const context = contextSchema.parse((await client.GET("/v1/context")).data);
|
|
140
|
+
const context = contextSchema.parse((await apiClient(server, runtime).GET("/v1/context")).data);
|
|
119
141
|
return { server, context };
|
|
120
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* The organization and developer the saved credential signs in as on `server`;
|
|
145
|
+
* one request to the server.
|
|
146
|
+
*/
|
|
147
|
+
export async function connectionContext(server, runtime) {
|
|
148
|
+
server = normalizeServer(server);
|
|
149
|
+
const context = contextSchema.parse((await apiClient(server, runtime).GET("/v1/context")).data);
|
|
150
|
+
return {
|
|
151
|
+
server,
|
|
152
|
+
organizationId: context.organization.id,
|
|
153
|
+
developerId: context.developer.id,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -1,10 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { HTTP_STATUS } from "../../shared/constants.js";
|
|
2
|
+
import { createApiClient } from "@barndog-ai/api-contract";
|
|
2
3
|
import { readCredentials } from "./credentials.js";
|
|
4
|
+
import { CliError } from "../../errors.js";
|
|
5
|
+
/** CLI policy: stop an API request after thirty seconds. */
|
|
6
|
+
const API_REQUEST_TIMEOUT_MS = 30000;
|
|
7
|
+
/**
|
|
8
|
+
* The request never got an HTTP response: DNS, refused connection, TLS, or the
|
|
9
|
+
* thirty-second timeout. Fetch reports these as a `TypeError` or a
|
|
10
|
+
* `TimeoutError`; this names them once, at the one place the CLI calls the API.
|
|
11
|
+
*/
|
|
12
|
+
class ServerUnreachableError extends CliError {
|
|
13
|
+
constructor(server, options) {
|
|
14
|
+
super(`Can't reach the BarnDog server at ${server}. Check your connection and that the server is running.`, "barndog doctor", options);
|
|
15
|
+
this.name = "ServerUnreachableError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
3
18
|
export class LoginRequiredError extends Error {
|
|
4
19
|
constructor() {
|
|
5
20
|
super("Authentication required. Run barndog login.");
|
|
6
21
|
}
|
|
7
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Validates a bare HTTP(S) origin; HTTP is allowed only on loopback, and
|
|
25
|
+
* credentials or URL suffixes are rejected.
|
|
26
|
+
*/
|
|
8
27
|
export function normalizeServer(value) {
|
|
9
28
|
const url = new URL(value);
|
|
10
29
|
if (!["http:", "https:"].includes(url.protocol) ||
|
|
@@ -12,33 +31,65 @@ export function normalizeServer(value) {
|
|
|
12
31
|
url.password ||
|
|
13
32
|
url.search ||
|
|
14
33
|
url.hash ||
|
|
15
|
-
url.pathname !== "/")
|
|
16
|
-
throw new
|
|
34
|
+
url.pathname !== "/") {
|
|
35
|
+
throw new CliError(`${value} isn't a server address. Use one like https://barndog.dev.`);
|
|
36
|
+
}
|
|
17
37
|
if (url.protocol !== "https:" &&
|
|
18
|
-
!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
19
|
-
throw new
|
|
38
|
+
!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
|
|
39
|
+
throw new CliError(`${value} must use https://. Plain http:// works only for localhost.`);
|
|
40
|
+
}
|
|
20
41
|
return url.origin;
|
|
21
42
|
}
|
|
22
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Creates an origin-bound fetch with optional saved credentials, redirect
|
|
45
|
+
* rejection and a 30-second request timeout.
|
|
46
|
+
*/
|
|
47
|
+
export function serverFetch(server, runtime, authenticated = true) {
|
|
23
48
|
const origin = normalizeServer(server);
|
|
24
49
|
return async (input, init) => {
|
|
25
50
|
const request = new Request(input, init);
|
|
26
|
-
if (new URL(request.url).origin !== origin)
|
|
51
|
+
if (new URL(request.url).origin !== origin) {
|
|
27
52
|
throw new Error("Refusing to send credentials to another server");
|
|
53
|
+
}
|
|
28
54
|
const headers = new Headers(request.headers);
|
|
29
55
|
if (authenticated) {
|
|
30
|
-
const credential = (await readCredentials(
|
|
31
|
-
if (!credential || Date.parse(credential.expiresAt) <= Date.now())
|
|
56
|
+
const credential = (await readCredentials(runtime)).servers[origin];
|
|
57
|
+
if (!credential || Date.parse(credential.expiresAt) <= Date.now()) {
|
|
32
58
|
throw new LoginRequiredError();
|
|
59
|
+
}
|
|
33
60
|
headers.set("Authorization", `Bearer ${credential.token}`);
|
|
34
61
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
62
|
+
let response;
|
|
63
|
+
try {
|
|
64
|
+
response = await fetch(request, {
|
|
65
|
+
headers,
|
|
66
|
+
redirect: "error",
|
|
67
|
+
signal: AbortSignal.any([
|
|
68
|
+
request.signal,
|
|
69
|
+
AbortSignal.timeout(API_REQUEST_TIMEOUT_MS),
|
|
70
|
+
]),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
// A caller's own abort (such as a cancelled sign-in) stays an abort.
|
|
75
|
+
if (request.signal.aborted) {
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
throw new ServerUnreachableError(origin, { cause: error });
|
|
79
|
+
}
|
|
80
|
+
if (response.status === HTTP_STATUS.unauthorized && authenticated) {
|
|
41
81
|
throw new LoginRequiredError();
|
|
82
|
+
}
|
|
42
83
|
return response;
|
|
43
84
|
};
|
|
44
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* A typed client for the BarnDog API that sends the saved credential for
|
|
88
|
+
* `server`, refusing redirects and requests to other origins.
|
|
89
|
+
*/
|
|
90
|
+
export function apiClient(server, runtime) {
|
|
91
|
+
return createApiClient({
|
|
92
|
+
baseUrl: normalizeServer(server),
|
|
93
|
+
fetch: serverFetch(server, runtime),
|
|
94
|
+
});
|
|
95
|
+
}
|