vit 0.0.1 → 0.1.3
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 +1 -1
- package/README.md +94 -2
- package/bin/vit.js +7 -0
- package/package.json +29 -18
- package/src/cli.js +52 -0
- package/src/cmd/adopt.js +92 -0
- package/src/cmd/beacon.js +62 -0
- package/src/cmd/config.js +63 -0
- package/src/cmd/doctor.js +193 -0
- package/src/cmd/explore.js +477 -0
- package/src/cmd/firehose.js +159 -0
- package/src/cmd/follow.js +143 -0
- package/src/cmd/hack.js +83 -0
- package/src/cmd/init.js +242 -0
- package/src/cmd/learn.js +244 -0
- package/src/cmd/link.js +75 -0
- package/src/cmd/login.js +267 -0
- package/src/cmd/remix.js +181 -0
- package/src/cmd/scan.js +207 -0
- package/src/cmd/setup.js +76 -0
- package/src/cmd/ship.js +610 -0
- package/src/cmd/skim.js +183 -0
- package/src/cmd/vet.js +609 -0
- package/src/cmd/vouch.js +277 -0
- package/src/lib/agent.js +37 -0
- package/src/lib/beacon.js +97 -0
- package/src/lib/brand.js +20 -0
- package/src/lib/cap-ref.js +23 -0
- package/src/lib/compat.js +20 -0
- package/src/lib/config.js +48 -0
- package/src/lib/constants.js +8 -0
- package/src/lib/json-output.js +13 -0
- package/src/lib/oauth.js +149 -0
- package/src/lib/paths.js +10 -0
- package/src/lib/pds.js +79 -0
- package/src/lib/sandbox.js +37 -0
- package/src/lib/skill-ref.js +37 -0
- package/src/lib/trust-gate.js +39 -0
- package/src/lib/vit-dir.js +69 -0
- package/.npmignore +0 -37
package/src/cmd/learn.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 sol pbc
|
|
3
|
+
|
|
4
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join, dirname } from 'node:path';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { requireDid } from '../lib/config.js';
|
|
8
|
+
import { SKILL_COLLECTION } from '../lib/constants.js';
|
|
9
|
+
import { restoreAgent } from '../lib/oauth.js';
|
|
10
|
+
import { readFollowing, readLog, appendLog } from '../lib/vit-dir.js';
|
|
11
|
+
import { requireAgent, detectCodingAgent } from '../lib/agent.js';
|
|
12
|
+
import { shouldBypassVet } from '../lib/trust-gate.js';
|
|
13
|
+
import { isSkillRef, nameFromSkillRef, isValidSkillRef } from '../lib/skill-ref.js';
|
|
14
|
+
import { mark, name } from '../lib/brand.js';
|
|
15
|
+
import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
|
|
16
|
+
import { loadConfig } from '../lib/config.js';
|
|
17
|
+
import { jsonOk, jsonError } from '../lib/json-output.js';
|
|
18
|
+
|
|
19
|
+
export default function register(program) {
|
|
20
|
+
program
|
|
21
|
+
.command('learn')
|
|
22
|
+
.argument('<ref>', 'Skill reference (e.g. skill-agent-test-patterns)')
|
|
23
|
+
.description('Install a skill from the network into your skill directory')
|
|
24
|
+
.option('--did <did>', 'DID to use')
|
|
25
|
+
.option('--user', 'Install to user-wide ~/.claude/skills/ (requires vet)')
|
|
26
|
+
.option('--json', 'Output as JSON')
|
|
27
|
+
.option('-v, --verbose', 'Show step-by-step details')
|
|
28
|
+
.action(async (ref, opts) => {
|
|
29
|
+
try {
|
|
30
|
+
const gate = requireAgent();
|
|
31
|
+
if (!gate.ok) {
|
|
32
|
+
if (opts.json) {
|
|
33
|
+
jsonError('agent required', 'run vit learn from a coding agent');
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
console.error(`${name} learn should be run by a coding agent (e.g. claude code, gemini cli).`);
|
|
37
|
+
console.error(`open your agent and ask it to run '${name} learn' for you.`);
|
|
38
|
+
process.exitCode = 1;
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const { verbose } = opts;
|
|
43
|
+
const vlog = opts.json ? (...a) => console.error(...a) : console.log;
|
|
44
|
+
|
|
45
|
+
if (!isSkillRef(ref)) {
|
|
46
|
+
if (opts.json) {
|
|
47
|
+
jsonError('invalid skill ref', 'expected format: skill-{name}');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
console.error(`invalid skill ref. expected format: skill-{name} (e.g. skill-agent-test-patterns)`);
|
|
51
|
+
process.exitCode = 1;
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!isValidSkillRef(ref)) {
|
|
56
|
+
if (opts.json) {
|
|
57
|
+
jsonError('invalid skill ref', 'lowercase letters, numbers, hyphens only');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
console.error('invalid skill ref. name must be lowercase letters, numbers, hyphens only.');
|
|
61
|
+
console.error('no leading hyphen, no consecutive hyphens, max 64 chars.');
|
|
62
|
+
process.exitCode = 1;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const skillName = nameFromSkillRef(ref);
|
|
67
|
+
if (verbose) vlog(`[verbose] skill name: ${skillName}`);
|
|
68
|
+
|
|
69
|
+
// Trust gate
|
|
70
|
+
const isUserInstall = !!opts.user;
|
|
71
|
+
const trusted = readLog('trusted.jsonl');
|
|
72
|
+
const trustedEntry = trusted.find(e => e.ref === ref);
|
|
73
|
+
|
|
74
|
+
if (isUserInstall && !trustedEntry) {
|
|
75
|
+
// --user ALWAYS requires vet
|
|
76
|
+
if (opts.json) {
|
|
77
|
+
jsonError(`skill '${ref}' is not yet vetted`, 'user-wide install requires vetting');
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
console.error(`skill '${ref}' is not yet vetted. user-wide install requires vetting.`);
|
|
81
|
+
console.error(`ask the user to vet it first:`);
|
|
82
|
+
console.error('');
|
|
83
|
+
console.error(` vit vet ${ref}`);
|
|
84
|
+
console.error('');
|
|
85
|
+
console.error('after reviewing, they can trust it with:');
|
|
86
|
+
console.error('');
|
|
87
|
+
console.error(` vit vet ${ref} --trust`);
|
|
88
|
+
process.exitCode = 1;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!isUserInstall && !trustedEntry) {
|
|
93
|
+
// Project-level: requires vet UNLESS dangerous-accept
|
|
94
|
+
const trustGate = shouldBypassVet();
|
|
95
|
+
if (!trustGate.bypass) {
|
|
96
|
+
if (opts.json) {
|
|
97
|
+
jsonError(`skill '${ref}' is not yet vetted`, `run 'vit vet ${ref}' first`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
console.error(`skill '${ref}' is not yet vetted.`);
|
|
101
|
+
console.error(`ask the user to vet it first:`);
|
|
102
|
+
console.error('');
|
|
103
|
+
console.error(` vit vet ${ref}`);
|
|
104
|
+
console.error('');
|
|
105
|
+
console.error('after reviewing, they can trust it with:');
|
|
106
|
+
console.error('');
|
|
107
|
+
console.error(` vit vet ${ref} --trust`);
|
|
108
|
+
if (detectCodingAgent()) {
|
|
109
|
+
console.error('');
|
|
110
|
+
console.error('or, to trust all items without review:');
|
|
111
|
+
console.error('');
|
|
112
|
+
console.error(' vit vet --dangerous-accept --confirm');
|
|
113
|
+
}
|
|
114
|
+
process.exitCode = 1;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (verbose) vlog(`[verbose] vet gate bypassed: ${trustGate.reason}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (opts.json && !(opts.did || loadConfig().did)) {
|
|
121
|
+
jsonError('no DID configured', "run 'vit login <handle>' first");
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const did = requireDid(opts);
|
|
125
|
+
if (!did) return;
|
|
126
|
+
if (verbose) vlog(`[verbose] DID: ${did}`);
|
|
127
|
+
|
|
128
|
+
const { agent } = await restoreAgent(did);
|
|
129
|
+
if (verbose) vlog('[verbose] session restored');
|
|
130
|
+
|
|
131
|
+
// Build DID list from following + self
|
|
132
|
+
const following = readFollowing();
|
|
133
|
+
const dids = following.map(e => e.did);
|
|
134
|
+
dids.push(did);
|
|
135
|
+
|
|
136
|
+
// Fetch skills from each DID, find matching ref
|
|
137
|
+
const allRecords = await batchQuery(dids, async (repoDid) => {
|
|
138
|
+
const pds = await resolvePds(repoDid);
|
|
139
|
+
if (verbose) vlog(`[verbose] ${repoDid}: resolved PDS ${pds}`);
|
|
140
|
+
return (await listRecordsFromPds(pds, repoDid, SKILL_COLLECTION, 50)).records;
|
|
141
|
+
}, { verbose });
|
|
142
|
+
|
|
143
|
+
let match = null;
|
|
144
|
+
for (const records of allRecords) {
|
|
145
|
+
for (const rec of records) {
|
|
146
|
+
const recName = rec.value.name;
|
|
147
|
+
if (recName === skillName) {
|
|
148
|
+
if (!match || (rec.value.createdAt || '') > (match.value.createdAt || '')) {
|
|
149
|
+
match = rec;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (!match) {
|
|
156
|
+
if (opts.json) {
|
|
157
|
+
jsonError(`no skill found with ref '${ref}'`);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
console.error(`no skill found with ref '${ref}' from followed accounts.`);
|
|
161
|
+
process.exitCode = 1;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const record = match.value;
|
|
166
|
+
if (verbose) vlog(`[verbose] found skill: ${record.name} from ${match.uri}`);
|
|
167
|
+
|
|
168
|
+
// Determine install path
|
|
169
|
+
let installDir;
|
|
170
|
+
if (isUserInstall) {
|
|
171
|
+
installDir = join(homedir(), '.claude', 'skills', skillName);
|
|
172
|
+
} else {
|
|
173
|
+
installDir = join(process.cwd(), '.claude', 'skills', skillName);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
mkdirSync(installDir, { recursive: true });
|
|
177
|
+
|
|
178
|
+
// Write SKILL.md from text field — verbatim, no reconstruction
|
|
179
|
+
writeFileSync(join(installDir, 'SKILL.md'), record.text);
|
|
180
|
+
if (verbose) vlog(`[verbose] wrote SKILL.md to ${installDir}`);
|
|
181
|
+
|
|
182
|
+
// Download and write resource blobs
|
|
183
|
+
if (record.resources && record.resources.length > 0) {
|
|
184
|
+
const authorDid = match.uri.split('/')[2];
|
|
185
|
+
const pds = await resolvePds(authorDid);
|
|
186
|
+
|
|
187
|
+
for (const resource of record.resources) {
|
|
188
|
+
const resourcePath = join(installDir, resource.path);
|
|
189
|
+
mkdirSync(dirname(resourcePath), { recursive: true });
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
// Download blob from PDS
|
|
193
|
+
const blobCid = resource.blob?.ref?.$link || resource.blob?.cid;
|
|
194
|
+
if (blobCid) {
|
|
195
|
+
const blobUrl = new URL('/xrpc/com.atproto.sync.getBlob', pds);
|
|
196
|
+
blobUrl.searchParams.set('did', authorDid);
|
|
197
|
+
blobUrl.searchParams.set('cid', blobCid);
|
|
198
|
+
const blobRes = await fetch(blobUrl);
|
|
199
|
+
if (!blobRes.ok) throw new Error(`blob fetch failed: ${blobRes.status}`);
|
|
200
|
+
const blobData = Buffer.from(await blobRes.arrayBuffer());
|
|
201
|
+
writeFileSync(resourcePath, blobData);
|
|
202
|
+
if (verbose) vlog(`[verbose] wrote resource: ${resource.path}`);
|
|
203
|
+
}
|
|
204
|
+
} catch (err) {
|
|
205
|
+
console.error(`warning: failed to download resource ${resource.path}: ${err.message}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Log to learned.jsonl
|
|
211
|
+
try {
|
|
212
|
+
appendLog('learned.jsonl', {
|
|
213
|
+
ref,
|
|
214
|
+
name: skillName,
|
|
215
|
+
uri: match.uri,
|
|
216
|
+
cid: match.cid,
|
|
217
|
+
installedTo: installDir,
|
|
218
|
+
scope: isUserInstall ? 'user' : 'project',
|
|
219
|
+
learnedAt: new Date().toISOString(),
|
|
220
|
+
version: record.version || null,
|
|
221
|
+
});
|
|
222
|
+
} catch (logErr) {
|
|
223
|
+
console.error('warning: failed to write learned.jsonl:', logErr.message);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const scope = isUserInstall ? 'user' : 'project';
|
|
227
|
+
if (opts.json) {
|
|
228
|
+
jsonOk({ ref, name: skillName, installedTo: installDir, scope, version: record.version || null });
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
console.log(`${mark} learned: ${ref} (${scope})`);
|
|
232
|
+
console.log(`installed to: ${installDir}`);
|
|
233
|
+
if (record.version) console.log(`version: ${record.version}`);
|
|
234
|
+
} catch (err) {
|
|
235
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
236
|
+
if (opts.json) {
|
|
237
|
+
jsonError(msg);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
console.error(msg);
|
|
241
|
+
process.exitCode = 1;
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
}
|
package/src/cmd/link.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 sol pbc
|
|
3
|
+
|
|
4
|
+
import { existsSync, mkdirSync, symlinkSync, unlinkSync, readlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { mark, name } from '../lib/brand.js';
|
|
7
|
+
|
|
8
|
+
export default function register(program) {
|
|
9
|
+
program
|
|
10
|
+
.command('link')
|
|
11
|
+
.description('Link vit binary into ~/.local/bin (or create .cmd shim on Windows)')
|
|
12
|
+
.action(async () => {
|
|
13
|
+
try {
|
|
14
|
+
const vitBin = resolve(import.meta.dirname, '..', '..', 'bin', 'vit.js');
|
|
15
|
+
if (!existsSync(vitBin)) {
|
|
16
|
+
console.error(`${name} link could not find ${vitBin}`);
|
|
17
|
+
process.exitCode = 1;
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let binDir;
|
|
22
|
+
if (process.platform === 'win32') {
|
|
23
|
+
const home = process.env.USERPROFILE || process.env.HOME;
|
|
24
|
+
binDir = join(home, '.local', 'bin');
|
|
25
|
+
mkdirSync(binDir, { recursive: true });
|
|
26
|
+
const target = join(binDir, 'vit.cmd');
|
|
27
|
+
writeFileSync(target, `@node "${vitBin}" %*\n`);
|
|
28
|
+
console.log(`${mark} link: ${target} -> ${vitBin}`);
|
|
29
|
+
} else {
|
|
30
|
+
binDir = join(process.env.HOME, '.local', 'bin');
|
|
31
|
+
mkdirSync(binDir, { recursive: true });
|
|
32
|
+
const target = join(binDir, 'vit');
|
|
33
|
+
if (existsSync(target)) {
|
|
34
|
+
try {
|
|
35
|
+
const current = readlinkSync(target);
|
|
36
|
+
if (current === vitBin) {
|
|
37
|
+
console.log(`${mark} link: already linked`);
|
|
38
|
+
} else {
|
|
39
|
+
unlinkSync(target);
|
|
40
|
+
symlinkSync(vitBin, target);
|
|
41
|
+
console.log(`${mark} link: ${target} -> ${vitBin}`);
|
|
42
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
unlinkSync(target);
|
|
45
|
+
symlinkSync(vitBin, target);
|
|
46
|
+
console.log(`${mark} link: ${target} -> ${vitBin}`);
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
symlinkSync(vitBin, target);
|
|
50
|
+
console.log(`${mark} link: ${target} -> ${vitBin}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const pathDirs = (process.env.PATH || '').split(process.platform === 'win32' ? ';' : ':');
|
|
55
|
+
if (!pathDirs.includes(binDir)) {
|
|
56
|
+
const shell = (process.env.SHELL || '').split('/').pop();
|
|
57
|
+
let instruction = '[Environment]::SetEnvironmentVariable("PATH", "$env:USERPROFILE\\.local\\bin;" + $env:PATH, "User")';
|
|
58
|
+
if (shell === 'fish') {
|
|
59
|
+
instruction = 'set -Ua fish_user_paths ~/.local/bin';
|
|
60
|
+
} else if (shell === 'zsh') {
|
|
61
|
+
instruction = 'echo \'export PATH="$HOME/.local/bin:$PATH"\' >> ~/.zshrc';
|
|
62
|
+
} else if (shell === 'bash') {
|
|
63
|
+
instruction = 'echo \'export PATH="$HOME/.local/bin:$PATH"\' >> ~/.bashrc';
|
|
64
|
+
}
|
|
65
|
+
console.log(`${mark} note: add ~/.local/bin to your PATH:`);
|
|
66
|
+
console.log(instruction);
|
|
67
|
+
} else {
|
|
68
|
+
console.log(`${mark} PATH: ok`);
|
|
69
|
+
}
|
|
70
|
+
} catch (err) {
|
|
71
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
72
|
+
process.exitCode = 1;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
package/src/cmd/login.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 sol pbc
|
|
3
|
+
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { AtpAgent } from '@atproto/api';
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { loadConfig, saveConfig } from '../lib/config.js';
|
|
11
|
+
import { createOAuthClient, createSessionStore, createStore, checkSession } from '../lib/oauth.js';
|
|
12
|
+
import { configDir, configPath } from '../lib/paths.js';
|
|
13
|
+
import { vitDir } from '../lib/vit-dir.js';
|
|
14
|
+
|
|
15
|
+
function ensureGitignore(dir, entry) {
|
|
16
|
+
const gitignorePath = join(dir, '.gitignore');
|
|
17
|
+
let content = '';
|
|
18
|
+
try { content = readFileSync(gitignorePath, 'utf-8'); } catch {}
|
|
19
|
+
if (!content.split('\n').includes(entry)) {
|
|
20
|
+
writeFileSync(gitignorePath, content + (content.endsWith('\n') ? '' : '\n') + entry + '\n');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export default function register(program) {
|
|
25
|
+
program
|
|
26
|
+
.command('login')
|
|
27
|
+
.description('Log in to Bluesky')
|
|
28
|
+
.argument('<handle>', 'Bluesky handle (e.g. alice.bsky.social)')
|
|
29
|
+
.option('-v, --verbose', 'Show discovery details')
|
|
30
|
+
.option('--force', 'Force re-login, skip session validation')
|
|
31
|
+
.option('--remote', 'Skip browser launch; prompt to paste callback URL (auto-detected over SSH)')
|
|
32
|
+
.option('--browser <command>', 'Browser command to use (e.g. firefox)')
|
|
33
|
+
.option('--app-password <password>', 'Authenticate with an app password (skips browser OAuth)')
|
|
34
|
+
.option('--local', 'Store session in project .vit/ instead of global config')
|
|
35
|
+
.action(async (handle, opts) => {
|
|
36
|
+
const { verbose, force, remote, browser, appPassword, local: localLogin } = opts;
|
|
37
|
+
const isRemote = remote || !!(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT);
|
|
38
|
+
handle = handle.replace(/^@/, '');
|
|
39
|
+
|
|
40
|
+
if (localLogin) {
|
|
41
|
+
const dir = vitDir();
|
|
42
|
+
if (!existsSync(dir)) {
|
|
43
|
+
console.error("no .vit directory found. run 'vit init' first.");
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!force) {
|
|
50
|
+
if (localLogin) {
|
|
51
|
+
const localPath = join(vitDir(), 'login.json');
|
|
52
|
+
if (existsSync(localPath)) {
|
|
53
|
+
try {
|
|
54
|
+
const local = JSON.parse(readFileSync(localPath, 'utf-8'));
|
|
55
|
+
if (local.did) {
|
|
56
|
+
console.log('Checking local session...');
|
|
57
|
+
const validDid = checkSession(local.did);
|
|
58
|
+
if (validDid) {
|
|
59
|
+
console.log(`Already logged in locally as ${validDid}`);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
} catch {}
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
const existing = loadConfig();
|
|
67
|
+
if (existing.did) {
|
|
68
|
+
console.log('Checking session...');
|
|
69
|
+
const validDid = checkSession(existing.did);
|
|
70
|
+
if (validDid) {
|
|
71
|
+
console.log(`Already logged in as ${validDid}`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (appPassword) {
|
|
79
|
+
try {
|
|
80
|
+
const agent = new AtpAgent({ service: 'https://bsky.social' });
|
|
81
|
+
if (verbose) console.log('[verbose] Authenticating with app password...');
|
|
82
|
+
const res = await agent.login({ identifier: handle, password: appPassword });
|
|
83
|
+
const { did, handle: resolvedHandle, accessJwt, refreshJwt } = res.data;
|
|
84
|
+
const session = { accessJwt, refreshJwt, handle: resolvedHandle, did, active: true };
|
|
85
|
+
|
|
86
|
+
if (localLogin) {
|
|
87
|
+
const loginData = { did, handle: resolvedHandle, type: 'app-password', service: 'https://bsky.social', session };
|
|
88
|
+
const dir = vitDir();
|
|
89
|
+
writeFileSync(join(dir, 'login.json'), JSON.stringify(loginData, null, 2) + '\n');
|
|
90
|
+
ensureGitignore(dir, 'login.json');
|
|
91
|
+
} else {
|
|
92
|
+
const sessionFile = configPath('session.json');
|
|
93
|
+
let data = {};
|
|
94
|
+
try { data = JSON.parse(readFileSync(sessionFile, 'utf-8')); } catch {}
|
|
95
|
+
data[did] = { type: 'app-password', service: 'https://bsky.social', session };
|
|
96
|
+
mkdirSync(configDir, { recursive: true });
|
|
97
|
+
writeFileSync(sessionFile, JSON.stringify(data, null, 2) + '\n');
|
|
98
|
+
const config = loadConfig();
|
|
99
|
+
config.did = did;
|
|
100
|
+
saveConfig(config);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
console.log(`Logged in as ${did}`);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
106
|
+
process.exitCode = 1;
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let server;
|
|
112
|
+
let timeout;
|
|
113
|
+
let rl;
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
let resolveCallback;
|
|
117
|
+
let callbackResolved = false;
|
|
118
|
+
const callbackPromise = new Promise((resolve) => {
|
|
119
|
+
resolveCallback = resolve;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
server = createServer((req, res) => {
|
|
123
|
+
const url = new URL(req.url, `http://127.0.0.1`);
|
|
124
|
+
|
|
125
|
+
if (req.method === 'GET' && url.pathname === '/callback') {
|
|
126
|
+
const params = new URLSearchParams(url.searchParams);
|
|
127
|
+
|
|
128
|
+
if (!callbackResolved) {
|
|
129
|
+
callbackResolved = true;
|
|
130
|
+
resolveCallback(params);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
134
|
+
res.end('<!doctype html><html><body><h2>Authorization complete, you can close this tab.</h2></body></html>');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
res.writeHead(404);
|
|
139
|
+
res.end('Not found');
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
143
|
+
const port = server.address().port;
|
|
144
|
+
|
|
145
|
+
if (verbose) {
|
|
146
|
+
console.log(`[verbose] Server started on port ${port}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
150
|
+
|
|
151
|
+
if (verbose) {
|
|
152
|
+
console.log(`[verbose] Redirect URI: ${redirectUri}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const stateStore = createStore();
|
|
156
|
+
const sessionStore = createSessionStore();
|
|
157
|
+
const client = createOAuthClient({ stateStore, sessionStore, redirectUri });
|
|
158
|
+
|
|
159
|
+
const authUrl = await client.authorize(handle, {
|
|
160
|
+
scope: 'atproto transition:generic',
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
if (verbose) {
|
|
164
|
+
console.log(`[verbose] Authorization URL: ${authUrl.toString()}`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (isRemote) {
|
|
168
|
+
console.log("You're on a remote system. Open this URL in your local browser:");
|
|
169
|
+
console.log(` ${authUrl.toString()}\n`);
|
|
170
|
+
} else {
|
|
171
|
+
const platform = process.platform;
|
|
172
|
+
const cmd = browser || (platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open');
|
|
173
|
+
const browserArgs = !browser && platform === 'win32' ? ['/c', 'start', authUrl.toString()] : [authUrl.toString()];
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
const child = spawn(cmd, browserArgs, { stdio: 'ignore', detached: true });
|
|
177
|
+
child.unref();
|
|
178
|
+
} catch {
|
|
179
|
+
// Ignore browser-open failures and rely on printed URL.
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
console.log(`Open this URL in your browser:\n ${authUrl.toString()}\n`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (isRemote) {
|
|
186
|
+
rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
187
|
+
rl.question('Paste the callback URL from your browser: ', (line) => {
|
|
188
|
+
try {
|
|
189
|
+
const url = new URL(line.trim());
|
|
190
|
+
const params = new URLSearchParams(url.searchParams);
|
|
191
|
+
if (!callbackResolved) {
|
|
192
|
+
callbackResolved = true;
|
|
193
|
+
resolveCallback(params);
|
|
194
|
+
}
|
|
195
|
+
} catch {
|
|
196
|
+
console.error('Invalid URL. Please paste the full callback URL.');
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const timeoutMs = 5 * 60 * 1000;
|
|
202
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
203
|
+
timeout = setTimeout(() => {
|
|
204
|
+
reject(new Error('Timed out waiting for callback.'));
|
|
205
|
+
}, timeoutMs);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const params = await Promise.race([callbackPromise, timeoutPromise]);
|
|
209
|
+
|
|
210
|
+
clearTimeout(timeout);
|
|
211
|
+
timeout = undefined;
|
|
212
|
+
server.closeAllConnections?.();
|
|
213
|
+
server.close();
|
|
214
|
+
if (rl) {
|
|
215
|
+
rl.close();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (verbose) {
|
|
219
|
+
console.log(`[verbose] Callback received with params: ${params.toString()}`);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const oauthError = params.get('error');
|
|
223
|
+
if (oauthError) {
|
|
224
|
+
const description = params.get('error_description');
|
|
225
|
+
if (description) {
|
|
226
|
+
throw new Error(`OAuth error: ${oauthError} (${description})`);
|
|
227
|
+
}
|
|
228
|
+
throw new Error(`OAuth error: ${oauthError}`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
console.log('Exchanging token...');
|
|
232
|
+
const { session } = await client.callback(params);
|
|
233
|
+
|
|
234
|
+
if (verbose) {
|
|
235
|
+
console.log(`[verbose] Token exchange result for DID: ${session.did}`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (localLogin) {
|
|
239
|
+
const loginData = { did: session.did, handle, type: 'oauth' };
|
|
240
|
+
const dir = vitDir();
|
|
241
|
+
writeFileSync(join(dir, 'login.json'), JSON.stringify(loginData, null, 2) + '\n');
|
|
242
|
+
ensureGitignore(dir, 'login.json');
|
|
243
|
+
} else {
|
|
244
|
+
const config = loadConfig();
|
|
245
|
+
config.did = session.did;
|
|
246
|
+
saveConfig(config);
|
|
247
|
+
}
|
|
248
|
+
console.log(`Logged in as ${session.did}`);
|
|
249
|
+
} catch (err) {
|
|
250
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
251
|
+
process.exitCode = 1;
|
|
252
|
+
} finally {
|
|
253
|
+
if (timeout) {
|
|
254
|
+
clearTimeout(timeout);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (rl) {
|
|
258
|
+
rl.close();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (server?.listening) {
|
|
262
|
+
server.closeAllConnections?.();
|
|
263
|
+
server.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|