sekura 0.2.0 → 0.3.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 +36 -11
- package/dist/api.js +2 -2
- package/dist/auth.js +46 -19
- package/dist/catalogue.js +20 -0
- package/dist/cli.js +7 -6
- package/dist/commands/init.js +137 -55
- package/dist/commands/login.js +11 -10
- package/dist/device.js +87 -0
- package/dist/guide.js +150 -102
- package/dist/skill.js +6 -4
- package/dist/ui.js +60 -0
- package/dist/writers.js +5 -1
- package/package.json +2 -2
- package/skills/sekura/SKILL.md +79 -38
package/dist/commands/init.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
|
-
// `sekura init
|
|
2
|
-
//
|
|
3
|
-
// none of it is left for the coding
|
|
4
|
-
//
|
|
1
|
+
// `sekura init`, also what a bare `sekura` runs: detect, one question,
|
|
2
|
+
// review, sign in, apply, verify, then the rest of getting started (the
|
|
3
|
+
// Terms, the GitHub App, a repository) so none of it is left for the coding
|
|
4
|
+
// tool. The plan is shown and agreed before the browser opens, with a
|
|
5
|
+
// placeholder where the key will go, so nobody approves a sign-in before
|
|
6
|
+
// they have seen what will be written. Nothing is written before the review
|
|
7
|
+
// is agreed (unless --yes).
|
|
5
8
|
import { Command } from 'commander';
|
|
6
9
|
import { checkbox, confirm, select } from '@inquirer/prompts';
|
|
7
10
|
import { realpathSync } from 'node:fs';
|
|
8
11
|
import { homedir } from 'node:os';
|
|
9
12
|
import { dirname, resolve } from 'node:path';
|
|
10
|
-
import { DOCS, ENDPOINT, TOOLS, carriesKey, home } from '../catalogue.js';
|
|
13
|
+
import { DOCS, ENDPOINT, PENDING_KEY, TOOLS, carriesKey, home, toolById } from '../catalogue.js';
|
|
11
14
|
import { applyStep, buildPlan, describeStep, detectTools } from '../plan.js';
|
|
12
15
|
import { verifyEndpoint } from '../verify.js';
|
|
13
|
-
import {
|
|
16
|
+
import { credentialsPath, readKey } from '../auth.js';
|
|
17
|
+
import { checkAccount, existingSession, howToScan, nextSteps, pickRepository, runToolLogins, signInHere, toolLogin } from '../guide.js';
|
|
14
18
|
import { banner, cross, dot, say, tick } from '../ui.js';
|
|
15
19
|
/** The home folder (or the top of the disk) is no project: project scope
|
|
16
20
|
* there would put AGENTS.md and .mcp.json in it for every tool to find. */
|
|
@@ -24,11 +28,19 @@ export function isProjectDir(cwd) {
|
|
|
24
28
|
const dir = real(cwd);
|
|
25
29
|
return dir !== real(home()) && dir !== real(homedir()) && dirname(dir) !== dir;
|
|
26
30
|
}
|
|
31
|
+
const and = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
|
|
32
|
+
/** The one question: everything init will do, in a sentence. */
|
|
33
|
+
export function summary(o) {
|
|
34
|
+
const where = o.scope === 'user' ? 'for every project' : 'for this project only';
|
|
35
|
+
const sign = o.signIn === 'sign-in' ? ', and sign in to Sekura' : o.signIn === 'saved' ? ', with your saved Sekura key' : '';
|
|
36
|
+
return `Connect ${and(o.names)} ${where}, ${o.skill ? 'with' : 'without'} the skill${sign}?`;
|
|
37
|
+
}
|
|
27
38
|
export async function runInit(opts) {
|
|
28
|
-
const interactive = !opts.yes && process.stdin.isTTY && process.stderr.isTTY;
|
|
39
|
+
const interactive = !opts.yes && !!process.stdin.isTTY && !!process.stderr.isTTY;
|
|
29
40
|
const cwd = opts.cwd ?? process.cwd();
|
|
30
41
|
banner();
|
|
31
|
-
// 1. Detect.
|
|
42
|
+
// 1. Detect. Every detected tool, user scope, the skill and the sign-in
|
|
43
|
+
// are the defaults; a flag answers its own question.
|
|
32
44
|
const detected = detectTools(cwd);
|
|
33
45
|
let chosen;
|
|
34
46
|
if (opts.tools) {
|
|
@@ -39,19 +51,9 @@ export async function runInit(opts) {
|
|
|
39
51
|
say(` Sekura connects to Claude Code, Cursor, GitHub Copilot, OpenAI Codex and nearly forty other tools; the page has every one: ${DOCS}`);
|
|
40
52
|
return { written: 0, byHand: 0, failed: 0 };
|
|
41
53
|
}
|
|
42
|
-
else if (!interactive) {
|
|
43
|
-
chosen = detected.map((t) => t.id);
|
|
44
|
-
}
|
|
45
54
|
else {
|
|
46
|
-
|
|
47
|
-
say();
|
|
48
|
-
chosen = await checkbox({
|
|
49
|
-
message: 'Connect Sekura to',
|
|
50
|
-
choices: detected.map((t) => ({ name: t.name, value: t.id, checked: true })),
|
|
51
|
-
required: true,
|
|
52
|
-
});
|
|
55
|
+
chosen = detected.map((t) => t.id);
|
|
53
56
|
}
|
|
54
|
-
// 2. Scope and skill.
|
|
55
57
|
let scope = opts.scope ?? 'user';
|
|
56
58
|
const inProject = isProjectDir(cwd);
|
|
57
59
|
if (scope === 'project' && !inProject) {
|
|
@@ -59,34 +61,87 @@ export async function runInit(opts) {
|
|
|
59
61
|
say(' Nothing was changed.');
|
|
60
62
|
return { written: 0, byHand: 0, failed: 1 };
|
|
61
63
|
}
|
|
62
|
-
if (!opts.scope && interactive && inProject) {
|
|
63
|
-
scope = await select({
|
|
64
|
-
message: 'Where',
|
|
65
|
-
choices: [
|
|
66
|
-
{ name: 'For me, in every project (your user configuration)', value: 'user' },
|
|
67
|
-
{ name: `This project only (${cwd})`, value: 'project' },
|
|
68
|
-
],
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
64
|
let skill = opts.skill !== false;
|
|
72
|
-
|
|
73
|
-
|
|
65
|
+
let login = opts.login !== false;
|
|
66
|
+
const hasKey = !!readKey();
|
|
67
|
+
// 2. One question, with Edit for the four it stands for.
|
|
68
|
+
if (interactive) {
|
|
69
|
+
const open = { tools: !opts.tools, scope: !opts.scope && inProject, skill: opts.skill === undefined, login: opts.login === undefined };
|
|
70
|
+
if (open.tools) {
|
|
71
|
+
say(` Found ${detected.length === 1 ? 'one tool' : `${detected.length} tools`}: ${detected.map((t) => t.name).join(', ')}`);
|
|
72
|
+
say();
|
|
73
|
+
}
|
|
74
|
+
if (open.tools || open.scope || open.skill || open.login) {
|
|
75
|
+
const names = chosen.map((id) => toolById(id)?.name ?? id);
|
|
76
|
+
const answer = await select({
|
|
77
|
+
message: summary({ names, scope, skill, signIn: login && scope === 'user' ? (hasKey ? 'saved' : 'sign-in') : null }),
|
|
78
|
+
choices: [
|
|
79
|
+
{ name: 'Yes', value: 'yes' },
|
|
80
|
+
{ name: 'Edit: choose the tools, where, the skill and the sign-in', value: 'edit' },
|
|
81
|
+
{ name: 'No, change nothing', value: 'no' },
|
|
82
|
+
],
|
|
83
|
+
});
|
|
84
|
+
if (answer === 'no') {
|
|
85
|
+
say(' Nothing was changed.');
|
|
86
|
+
return { written: 0, byHand: 0, failed: 0 };
|
|
87
|
+
}
|
|
88
|
+
if (answer === 'edit') {
|
|
89
|
+
if (open.tools) {
|
|
90
|
+
chosen = await checkbox({
|
|
91
|
+
message: 'Connect Sekura to',
|
|
92
|
+
choices: detected.map((t) => ({ name: t.name, value: t.id, checked: chosen.includes(t.id) })),
|
|
93
|
+
required: true,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (open.scope) {
|
|
97
|
+
scope = await select({
|
|
98
|
+
message: 'Where',
|
|
99
|
+
choices: [
|
|
100
|
+
{ name: 'For me, in every project (your user configuration)', value: 'user' },
|
|
101
|
+
{ name: `This project only (${cwd})`, value: 'project' },
|
|
102
|
+
],
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
if (open.skill)
|
|
106
|
+
skill = await confirm({ message: 'Also install the sekura skill, which teaches the agent the quote-then-confirm rule?', default: true });
|
|
107
|
+
// Project files never carry the key (they are committed), so there
|
|
108
|
+
// is no sign-in to ask about in project scope.
|
|
109
|
+
if (open.login && scope === 'user') {
|
|
110
|
+
login = await confirm({
|
|
111
|
+
message: hasKey
|
|
112
|
+
? 'Give your tools your saved Sekura key, so they do not ask you to sign in?'
|
|
113
|
+
: 'Sign in to Sekura once you have reviewed the plan, so your tools do not have to?',
|
|
114
|
+
default: true,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
74
119
|
}
|
|
75
|
-
// 3.
|
|
76
|
-
//
|
|
77
|
-
// scope skips this. A dry run uses a key it already has, never a browser.
|
|
120
|
+
// 3. A key already here is used as it is; a sign-in waits for the review.
|
|
121
|
+
// A dry run never signs in.
|
|
78
122
|
let session = null;
|
|
79
|
-
|
|
123
|
+
const keyed = login && scope === 'user';
|
|
124
|
+
if (keyed && hasKey) {
|
|
80
125
|
say();
|
|
81
|
-
session = await
|
|
126
|
+
session = await existingSession();
|
|
82
127
|
}
|
|
83
|
-
|
|
84
|
-
|
|
128
|
+
const willSignIn = keyed && !session && interactive;
|
|
129
|
+
// 4. The plan, shown before anything happens, with a placeholder for the
|
|
130
|
+
// key the sign-in will bring.
|
|
131
|
+
const shown = buildPlan({ tools: chosen, scope, skill, cwd, key: session?.key ?? (willSignIn ? PENDING_KEY : undefined) });
|
|
85
132
|
say();
|
|
86
133
|
say(opts.dryRun ? ' Dry run. This would:' : ' This will:');
|
|
87
|
-
|
|
134
|
+
if (willSignIn)
|
|
135
|
+
say(`${dot} sign in to Sekura in your browser (or with a code on another device) after you agree, and keep the key in ${credentialsPath()}`);
|
|
136
|
+
for (const s of shown.steps)
|
|
88
137
|
say(`${dot} ${describeStep(s, !!opts.dryRun)}`);
|
|
89
|
-
|
|
138
|
+
if (willSignIn || session)
|
|
139
|
+
for (const s of shown.steps) {
|
|
140
|
+
const cmd = toolLogin(s);
|
|
141
|
+
if (cmd && s.kind === 'tool')
|
|
142
|
+
say(`${dot} ${s.tool.name}: ${opts.dryRun ? 'would ' : ''}run ${cmd}, approved in the browser`);
|
|
143
|
+
}
|
|
144
|
+
for (const s of shown.skipped)
|
|
90
145
|
say(`${dot} ${s.tool.name}: skipped, ${s.why}`);
|
|
91
146
|
say(`${dot} touch nothing else: other servers, settings and files stay as they are`);
|
|
92
147
|
say();
|
|
@@ -96,9 +151,21 @@ export async function runInit(opts) {
|
|
|
96
151
|
say(' Nothing was changed.');
|
|
97
152
|
return { written: 0, byHand: 0, failed: 0 };
|
|
98
153
|
}
|
|
99
|
-
// 5.
|
|
154
|
+
// 5. Sign in, now that the plan is agreed, and put the key where the
|
|
155
|
+
// placeholder was. Without a key the same entries are written plain, and
|
|
156
|
+
// each tool signs in on first use, as it always could.
|
|
157
|
+
let plan = shown;
|
|
158
|
+
if (willSignIn) {
|
|
159
|
+
session = await signInHere({ device: opts.device });
|
|
160
|
+
if (!session)
|
|
161
|
+
say(' Applying the plan without a key instead: each tool signs in the first time it uses Sekura.');
|
|
162
|
+
plan = buildPlan({ tools: chosen, scope, skill, cwd, key: session?.key });
|
|
163
|
+
}
|
|
164
|
+
// 6. Apply, one step at a time, saying what each did.
|
|
165
|
+
say();
|
|
100
166
|
let written = 0, byHand = 0, failed = 0;
|
|
101
167
|
const signIns = new Map();
|
|
168
|
+
const connected = [];
|
|
102
169
|
for (const s of plan.steps) {
|
|
103
170
|
const r = applyStep(s);
|
|
104
171
|
switch (r.status) {
|
|
@@ -123,28 +190,32 @@ export async function runInit(opts) {
|
|
|
123
190
|
say(`${cross} ${r.where}: ${r.why}`);
|
|
124
191
|
break;
|
|
125
192
|
}
|
|
126
|
-
if (s.kind === 'tool' && (r.status === 'written' || r.status === 'ran' || r.status === 'unchanged'))
|
|
193
|
+
if (s.kind === 'tool' && (r.status === 'written' || r.status === 'ran' || r.status === 'unchanged')) {
|
|
127
194
|
signIns.set(s.tool.name, carriesKey(s.target) ? null : s.tool.signIn);
|
|
195
|
+
connected.push(s.tool);
|
|
196
|
+
}
|
|
128
197
|
}
|
|
129
198
|
// Tools whose entry cannot carry the key sign in with their own command,
|
|
130
|
-
// now, while the browser is signed in to sekura.ai.
|
|
131
|
-
|
|
132
|
-
|
|
199
|
+
// now, while the browser is signed in to sekura.ai. A sign-in agreed in
|
|
200
|
+
// the one question covers them; a saved key asks first.
|
|
201
|
+
if (session) {
|
|
202
|
+
const steps = plan.steps.filter((s) => s.kind === 'tool' && signIns.has(s.tool.name));
|
|
203
|
+
for (const name of await runToolLogins(steps, interactive, !willSignIn))
|
|
133
204
|
signIns.set(name, null);
|
|
134
|
-
|
|
205
|
+
}
|
|
206
|
+
// 7. Verify the address.
|
|
135
207
|
if (opts.verify !== false) {
|
|
136
208
|
const v = await verifyEndpoint(ENDPOINT);
|
|
137
209
|
say(`${v.ok ? tick : cross} ${v.detail}`);
|
|
138
210
|
}
|
|
139
|
-
//
|
|
211
|
+
// 8. The account and a repository, with the key.
|
|
140
212
|
let repo = null;
|
|
141
213
|
if (session && signIns.size) {
|
|
142
214
|
say();
|
|
143
|
-
await checkAccount(session, interactive);
|
|
144
|
-
repo = await pickRepository(session, cwd, interactive);
|
|
145
|
-
await offerFreeScan(session, repo, interactive);
|
|
215
|
+
await checkAccount(session, interactive, opts.wait);
|
|
216
|
+
repo = await pickRepository(session, cwd, interactive, opts.wait);
|
|
146
217
|
}
|
|
147
|
-
//
|
|
218
|
+
// 9. What is left, per tool.
|
|
148
219
|
say();
|
|
149
220
|
if (signIns.size) {
|
|
150
221
|
const ready = [...signIns].filter(([, how]) => how === null).map(([name]) => name);
|
|
@@ -157,6 +228,8 @@ export async function runInit(opts) {
|
|
|
157
228
|
say(`${dot} ${name}: ${how}`);
|
|
158
229
|
}
|
|
159
230
|
say();
|
|
231
|
+
nextSteps(connected);
|
|
232
|
+
say();
|
|
160
233
|
howToScan([...signIns.keys()], repo);
|
|
161
234
|
say();
|
|
162
235
|
}
|
|
@@ -164,17 +237,26 @@ export async function runInit(opts) {
|
|
|
164
237
|
say();
|
|
165
238
|
return { written, byHand, failed };
|
|
166
239
|
}
|
|
240
|
+
/** A --no-x flag's value only when it was typed: commander fills in true
|
|
241
|
+
* otherwise, which would read as an answer to a question never asked. */
|
|
242
|
+
export function typedOnly(opts, cmd, names) {
|
|
243
|
+
for (const n of names)
|
|
244
|
+
if (cmd.getOptionValueSource(n) !== 'cli')
|
|
245
|
+
delete opts[n];
|
|
246
|
+
return opts;
|
|
247
|
+
}
|
|
167
248
|
export const initCommand = new Command('init')
|
|
168
|
-
.description('Connect the coding tools on this machine to Sekura, and install the sekura skill.')
|
|
249
|
+
.description('Connect the coding tools on this machine to Sekura, and install the sekura skill. What a bare `sekura` runs.')
|
|
169
250
|
.option('-y, --yes', 'apply without asking; every detected tool, user scope, with the skill, and the key in SEKURA_API_KEY or saved by sekura login')
|
|
170
251
|
.option('--no-skill', 'the MCP server only: no skill, no guidance block')
|
|
171
252
|
.option('--scope <scope>', 'user (every project) or project (this directory)', (v) => { if (v !== 'user' && v !== 'project')
|
|
172
253
|
throw new Error('--scope is user or project'); return v; })
|
|
173
254
|
.option('--tools <ids>', `only these, comma-separated: ${TOOLS.map((t) => t.id.replace('tools-', '')).join(', ')}`)
|
|
174
|
-
.option('--dry-run', 'show the plan and change nothing')
|
|
255
|
+
.option('--dry-run', 'show the plan and change nothing; never signs in')
|
|
175
256
|
.option('--no-verify', 'do not check that the Sekura server answers')
|
|
176
|
-
.option('--no-login', 'do not sign in here; each tool signs in on first use')
|
|
177
|
-
.
|
|
178
|
-
|
|
257
|
+
.option('--no-login', 'do not sign in here; each tool signs in on first use (0.1.x behaviour)')
|
|
258
|
+
.option('--device', 'sign in with a code on another device (the default over SSH and in containers)')
|
|
259
|
+
.action(async (opts, cmd) => {
|
|
260
|
+
const r = await runInit(typedOnly(opts, cmd, ['skill', 'login']));
|
|
179
261
|
process.exitCode = r.failed ? 1 : 0;
|
|
180
262
|
});
|
package/dist/commands/login.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
// `sekura login`: sign in here
|
|
2
|
-
//
|
|
3
|
-
// who skipped the sign-in during
|
|
4
|
-
// repository. `sekura logout`:
|
|
1
|
+
// `sekura login`: sign in here (in the browser, or with a code on another
|
|
2
|
+
// device) and put the key into every tool already connected, then the
|
|
3
|
+
// account and a repository. For someone who skipped the sign-in during
|
|
4
|
+
// init, revoked the key, or wants another repository. `sekura logout`:
|
|
5
|
+
// forget the saved key.
|
|
5
6
|
import { Command } from 'commander';
|
|
6
7
|
import { applyStep, buildPlan, detectTools, stepPresent } from '../plan.js';
|
|
7
8
|
import { carriesKey } from '../catalogue.js';
|
|
8
9
|
import { credentialsPath, forgetKey } from '../auth.js';
|
|
9
|
-
import { checkAccount, howToScan, obtainKey,
|
|
10
|
+
import { checkAccount, howToScan, obtainKey, pickRepository, runToolLogins } from '../guide.js';
|
|
10
11
|
import { cross, dot, say, tick } from '../ui.js';
|
|
11
12
|
export async function runLogin(opts) {
|
|
12
13
|
const cwd = opts.cwd ?? process.cwd();
|
|
13
14
|
const interactive = !!(process.stdin.isTTY && process.stderr.isTTY);
|
|
14
15
|
say();
|
|
15
|
-
const session = await obtainKey({ interactive,
|
|
16
|
+
const session = await obtainKey({ interactive, device: opts.device });
|
|
16
17
|
if (!session) {
|
|
17
18
|
say(' Not signed in; nothing was changed.');
|
|
18
19
|
say();
|
|
@@ -50,9 +51,8 @@ export async function runLogin(opts) {
|
|
|
50
51
|
if (!names.length)
|
|
51
52
|
say(`${dot} No tool on this machine has Sekura yet: run sekura init.`);
|
|
52
53
|
say();
|
|
53
|
-
await checkAccount(session, interactive);
|
|
54
|
-
const repo = await pickRepository(session, cwd, interactive);
|
|
55
|
-
await offerFreeScan(session, repo, interactive);
|
|
54
|
+
await checkAccount(session, interactive, opts.wait);
|
|
55
|
+
const repo = await pickRepository(session, cwd, interactive, opts.wait);
|
|
56
56
|
if (names.length) {
|
|
57
57
|
say();
|
|
58
58
|
howToScan(names, repo);
|
|
@@ -62,7 +62,8 @@ export async function runLogin(opts) {
|
|
|
62
62
|
}
|
|
63
63
|
export const loginCommand = new Command('login')
|
|
64
64
|
.description('Sign in to Sekura here, give the key to every connected tool, and pick a repository.')
|
|
65
|
-
.
|
|
65
|
+
.option('--device', 'sign in with a code on another device (the default over SSH and in containers)')
|
|
66
|
+
.action(async (opts) => { process.exitCode = (await runLogin({ device: opts.device })) ? 1 : 0; });
|
|
66
67
|
export const logoutCommand = new Command('logout')
|
|
67
68
|
.description('Forget the Sekura key saved on this machine.')
|
|
68
69
|
.action(() => {
|
package/dist/device.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Signing in on a machine that has no browser of its own: over SSH, in a
|
|
2
|
+
// devcontainer or Codespace, on a remote dev box. The loopback redirect in
|
|
3
|
+
// auth.ts cannot work there, because the browser that approves runs on
|
|
4
|
+
// another machine and 127.0.0.1 is not this one. So the OAuth device
|
|
5
|
+
// authorization grant (RFC 8628): sekura.ai hands out a short code, the
|
|
6
|
+
// person enters it at sekura.ai/connect/device on any device, and this
|
|
7
|
+
// process asks the token endpoint until the answer is a key.
|
|
8
|
+
//
|
|
9
|
+
// The client is the one auth.ts registers for both grants, so a person
|
|
10
|
+
// sees one "Sekura CLI" client whichever way they signed in. The
|
|
11
|
+
// device_code is the secret half of the pair and is never printed; only the
|
|
12
|
+
// user_code is meant for eyes.
|
|
13
|
+
import { ENDPOINT } from './catalogue.js';
|
|
14
|
+
export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
15
|
+
const ISSUER = new URL(ENDPOINT).origin;
|
|
16
|
+
/** The variables that say this terminal is not on the machine with the
|
|
17
|
+
* browser. The first one set is named, so the person hears why. */
|
|
18
|
+
export const REMOTE_VARS = ['SSH_CONNECTION', 'SSH_TTY', 'CODESPACES', 'REMOTE_CONTAINERS', 'GITPOD_WORKSPACE_ID'];
|
|
19
|
+
export function remoteSession(env = process.env) {
|
|
20
|
+
for (const v of REMOTE_VARS)
|
|
21
|
+
if (env[v]?.trim())
|
|
22
|
+
return v;
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const form = (o) => ({
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
28
|
+
body: new URLSearchParams(o).toString(),
|
|
29
|
+
});
|
|
30
|
+
export async function startDeviceAuthorization(clientId) {
|
|
31
|
+
const r = await fetch(`${ISSUER}/oauth/device_authorization`, form({ client_id: clientId, scope: 'read write', resource: ENDPOINT }));
|
|
32
|
+
const data = (await r.json().catch(() => ({})));
|
|
33
|
+
if (!r.ok)
|
|
34
|
+
throw new Error(`sekura.ai refused the sign-in (/oauth/device_authorization): ${data.error_description || data.error || r.status}`);
|
|
35
|
+
if (typeof data.device_code !== 'string' || typeof data.user_code !== 'string' || typeof data.verification_uri !== 'string') {
|
|
36
|
+
throw new Error('sekura.ai answered the device sign-in without a code');
|
|
37
|
+
}
|
|
38
|
+
return data;
|
|
39
|
+
}
|
|
40
|
+
const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
41
|
+
/**
|
|
42
|
+
* Asks the token endpoint every `interval` seconds until the person has
|
|
43
|
+
* approved, declined, or let the code expire (RFC 8628 §3.4-3.5). Returns
|
|
44
|
+
* the key.
|
|
45
|
+
*/
|
|
46
|
+
export async function pollDeviceToken(clientId, code, opts = {}) {
|
|
47
|
+
const sleep = opts.sleep ?? realSleep;
|
|
48
|
+
const now = opts.now ?? Date.now;
|
|
49
|
+
// The RFC's default when the server names none.
|
|
50
|
+
let interval = Math.max(1, code.interval ?? 5) * 1000;
|
|
51
|
+
const deadline = now() + Math.max(1, code.expires_in) * 1000;
|
|
52
|
+
for (;;) {
|
|
53
|
+
await sleep(interval);
|
|
54
|
+
if (now() >= deadline)
|
|
55
|
+
throw new Error('the code expired before it was approved; run the command again for a new one');
|
|
56
|
+
let r;
|
|
57
|
+
try {
|
|
58
|
+
r = await fetch(`${ISSUER}/oauth/token`, form({ grant_type: DEVICE_GRANT, device_code: code.device_code, client_id: clientId, resource: ENDPOINT }));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
continue; // the network blinked; the code is still good until it expires
|
|
62
|
+
}
|
|
63
|
+
const data = (await r.json().catch(() => ({})));
|
|
64
|
+
if (r.ok) {
|
|
65
|
+
const key = String(data.access_token ?? '');
|
|
66
|
+
if (!key)
|
|
67
|
+
throw new Error('sekura.ai answered without a key');
|
|
68
|
+
return key;
|
|
69
|
+
}
|
|
70
|
+
if (r.status >= 500)
|
|
71
|
+
continue;
|
|
72
|
+
switch (data.error) {
|
|
73
|
+
case 'authorization_pending': continue;
|
|
74
|
+
case 'slow_down':
|
|
75
|
+
interval += 5000;
|
|
76
|
+
continue;
|
|
77
|
+
case 'access_denied': throw new Error('the sign-in was declined on sekura.ai');
|
|
78
|
+
case 'expired_token': throw new Error('the code expired before it was approved; run the command again for a new one');
|
|
79
|
+
default: throw new Error(`sekura.ai refused the sign-in (/oauth/token): ${data.error_description || data.error || r.status}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export async function deviceSignIn(clientId, opts = {}) {
|
|
84
|
+
const code = await startDeviceAuthorization(clientId);
|
|
85
|
+
opts.onCode?.({ userCode: code.user_code, uri: code.verification_uri, complete: code.verification_uri_complete });
|
|
86
|
+
return pollDeviceToken(clientId, code, opts);
|
|
87
|
+
}
|