@ptkl/toolkit 1.3.0 → 1.4.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 +37 -30
- package/dist/bin/toolkit.js +37 -3
- package/dist/commands/__tests__/apiUsers.test.js +16 -0
- package/dist/commands/__tests__/forge-requires.test.js +58 -0
- package/dist/commands/__tests__/profile.test.js +65 -0
- package/dist/commands/apiUsers.js +12 -0
- package/dist/commands/forge.js +82 -6
- package/dist/commands/profile.js +84 -76
- package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
- package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
- package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
- package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
- package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
- package/dist/lib/kortex/config/loader.js +129 -0
- package/dist/lib/kortex/config/schema.js +60 -0
- package/dist/lib/kortex/controller.js +60 -0
- package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
- package/dist/lib/kortex/conversation/types.js +13 -0
- package/dist/lib/kortex/events/index.js +1 -0
- package/dist/lib/kortex/events/reducer.js +86 -0
- package/dist/lib/kortex/events/types.js +7 -0
- package/dist/lib/kortex/events/writer.js +76 -0
- package/dist/lib/kortex/mcp/index.js +1 -0
- package/dist/lib/kortex/orchestration/index.js +1 -0
- package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
- package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
- package/dist/lib/kortex/orchestration/plan.js +133 -0
- package/dist/lib/kortex/orchestration/scheduler.js +124 -0
- package/dist/lib/kortex/persistence/index.js +1 -0
- package/dist/lib/kortex/persistence/run-journal.js +94 -0
- package/dist/lib/kortex/providers/anthropic.js +34 -0
- package/dist/lib/kortex/providers/index.js +1 -0
- package/dist/lib/kortex/providers/openai-compatible.js +190 -0
- package/dist/lib/kortex/providers/protokol.js +204 -0
- package/dist/lib/kortex/providers/registry.js +61 -0
- package/dist/lib/kortex/providers/types.js +13 -0
- package/dist/lib/kortex/runtime/agent-runner.js +241 -0
- package/dist/lib/kortex/runtime/approval-queue.js +95 -0
- package/dist/lib/kortex/runtime/budget-controller.js +105 -0
- package/dist/lib/kortex/runtime/index.js +1 -0
- package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
- package/dist/lib/kortex/runtime/workspace.js +52 -0
- package/dist/lib/kortex/tools/index.js +1 -0
- package/dist/lib/kortex/tools.js +226 -34
- package/dist/lib/kortex/types.js +7 -0
- package/dist/lib/kortex/ui/index.js +1 -0
- package/dist/lib/oauth/CallbackPages.js +82 -0
- package/dist/lib/oauth/CallbackServer.js +84 -0
- package/dist/lib/oauth/OAuthClient.js +81 -0
- package/dist/lib/oauth/OAuthError.js +17 -0
- package/dist/lib/oauth/OAuthLogin.js +60 -0
- package/dist/lib/oauth/OAuthSession.js +100 -0
- package/dist/lib/oauth/Pkce.js +19 -0
- package/dist/lib/oauth/ProfileLogin.js +76 -0
- package/dist/lib/oauth/RefreshLock.js +61 -0
- package/dist/lib/oauth/ScopePreset.js +38 -0
- package/dist/lib/oauth/__tests__/mockServer.js +29 -0
- package/dist/lib/oauth/__tests__/oauth.test.js +347 -0
- package/dist/lib/util.js +9 -2
- package/package.json +6 -4
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
5
|
+
import { startMock } from "./mockServer.js";
|
|
6
|
+
const home = mkdtempSync(join(tmpdir(), "ptkl-oauth-"));
|
|
7
|
+
process.env.HOME = home;
|
|
8
|
+
mkdirSync(join(home, ".ptkl"));
|
|
9
|
+
const profilesFile = join(home, ".ptkl", "profiles.json");
|
|
10
|
+
const { default: Pkce } = await import("../Pkce.js");
|
|
11
|
+
const { default: CallbackServer } = await import("../CallbackServer.js");
|
|
12
|
+
const { default: OAuthClient } = await import("../OAuthClient.js");
|
|
13
|
+
const { default: ScopePreset } = await import("../ScopePreset.js");
|
|
14
|
+
const { default: OAuthLogin } = await import("../OAuthLogin.js");
|
|
15
|
+
const { default: OAuthSession } = await import("../OAuthSession.js");
|
|
16
|
+
const { default: RefreshLock } = await import("../RefreshLock.js");
|
|
17
|
+
const { default: ProfileLogin } = await import("../ProfileLogin.js");
|
|
18
|
+
const { default: CallbackPages, PAGE_HEADERS, GUIDE_URL } = await import("../CallbackPages.js");
|
|
19
|
+
const { default: OAuthError } = await import("../OAuthError.js");
|
|
20
|
+
const { default: Util } = await import("../../util.js");
|
|
21
|
+
const ctx = { name: "dev", host: "http://h", project: "proj-uuid", isNew: false };
|
|
22
|
+
const seed = (p) => writeFileSync(profilesFile, JSON.stringify([p]));
|
|
23
|
+
const stored = () => JSON.parse(readFileSync(profilesFile, "utf8"))[0];
|
|
24
|
+
const oauthProfile = (base, over = {}) => ({
|
|
25
|
+
name: "o", host: base, project: "p", current: true, auth: "oauth",
|
|
26
|
+
token: "old-access", refresh_token: "old-refresh", expires_at: Date.now() + 3_600_000,
|
|
27
|
+
client_id: "pk_cli_x", token_endpoint: `${base}/v1/oauth/token`, revocation_endpoint: `${base}/v1/oauth/revoke`, ...over,
|
|
28
|
+
});
|
|
29
|
+
describe("Pkce", () => {
|
|
30
|
+
it("derives an S256 challenge (RFC 7636 appendix B)", () => {
|
|
31
|
+
expect(Pkce.challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
|
|
32
|
+
});
|
|
33
|
+
it("generates distinct verifier/state values within spec length", () => {
|
|
34
|
+
const a = Pkce.generate(), b = Pkce.generate();
|
|
35
|
+
expect(a.verifier.length).toBeGreaterThanOrEqual(43);
|
|
36
|
+
expect(a.verifier).not.toBe(b.verifier);
|
|
37
|
+
expect(a.state).not.toBe(b.state);
|
|
38
|
+
expect(a.challenge).toBe(Pkce.challengeFor(a.verifier));
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
describe("ScopePreset", () => {
|
|
42
|
+
it("encodes offline_access and typed entries", () => {
|
|
43
|
+
expect(ScopePreset.toWire(["read base_users", "pattern:read .*"])).toBe(`offline_access perm64:${Buffer.from("read base_users").toString("base64url")} pattern64:${Buffer.from("read .*").toString("base64url")}`);
|
|
44
|
+
});
|
|
45
|
+
it("defaults to the preset, --scope replaces, --add-scope extends", () => {
|
|
46
|
+
expect(ScopePreset.resolve({})).toEqual(ScopePreset.permissions);
|
|
47
|
+
expect(ScopePreset.resolve({ scope: "a b, c" })).toEqual(["a b", "c"]);
|
|
48
|
+
expect(ScopePreset.resolve({ scope: "x", addScope: "y,x" })).toEqual(["x", "y"]);
|
|
49
|
+
expect(ScopePreset.resolve({ addScope: "edit base_users" })).toContain("edit base_users");
|
|
50
|
+
});
|
|
51
|
+
it("asks for API-user management and secrets by default", () => {
|
|
52
|
+
expect(ScopePreset.permissions).toEqual(expect.arrayContaining(["edit base_users", "manage_secrets base_users", "dev env_access"]));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
describe("authorize URL", () => {
|
|
56
|
+
it("carries every required parameter", () => {
|
|
57
|
+
const u = new URL(new OAuthClient().authorizeUrl({ issuer: "i", authorization_endpoint: "http://h/v1/oauth/authorize", token_endpoint: "t" }, { clientId: "c", redirectUri: "http://127.0.0.1:1/callback", project: "proj", state: "s", challenge: "ch", scope: "offline_access" }));
|
|
58
|
+
const q = u.searchParams;
|
|
59
|
+
expect(u.pathname).toBe("/v1/oauth/authorize");
|
|
60
|
+
expect(Object.fromEntries(q)).toEqual({
|
|
61
|
+
response_type: "code", client_id: "c", redirect_uri: "http://127.0.0.1:1/callback", project_id: "proj",
|
|
62
|
+
state: "s", code_challenge: "ch", code_challenge_method: "S256", scope: "offline_access",
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe("CallbackServer", () => {
|
|
67
|
+
it("binds loopback and resolves on a matching state", async () => {
|
|
68
|
+
const s = await CallbackServer.start("st", ctx);
|
|
69
|
+
expect(s.redirectUri).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/);
|
|
70
|
+
const r = fetch(`${s.redirectUri}?code=abc&state=st&iss=x`);
|
|
71
|
+
expect(await s.wait()).toEqual({ code: "abc", iss: "x" });
|
|
72
|
+
s.finish();
|
|
73
|
+
await r;
|
|
74
|
+
await s.close();
|
|
75
|
+
});
|
|
76
|
+
it("rejects a state mismatch", async () => {
|
|
77
|
+
const s = await CallbackServer.start("st", ctx);
|
|
78
|
+
const r = await fetch(`${s.redirectUri}?code=abc&state=evil`);
|
|
79
|
+
expect(r.status).toBe(400);
|
|
80
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "state_mismatch" });
|
|
81
|
+
await s.close();
|
|
82
|
+
});
|
|
83
|
+
it("surfaces an error parameter", async () => {
|
|
84
|
+
const s = await CallbackServer.start("st", ctx);
|
|
85
|
+
await fetch(`${s.redirectUri}?error=access_denied&error_description=nope&state=st`);
|
|
86
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "access_denied", description: "nope" });
|
|
87
|
+
await s.close();
|
|
88
|
+
});
|
|
89
|
+
it("times out", async () => {
|
|
90
|
+
const s = await CallbackServer.start("st", ctx, 0, 50);
|
|
91
|
+
await expect(s.wait()).rejects.toMatchObject({ code: "timeout" });
|
|
92
|
+
await s.close();
|
|
93
|
+
});
|
|
94
|
+
it("answers 404 to other paths and settles only once", async () => {
|
|
95
|
+
const s = await CallbackServer.start("st", ctx);
|
|
96
|
+
expect((await fetch(s.redirectUri.replace("/callback", "/other"))).status).toBe(404);
|
|
97
|
+
const r1 = fetch(`${s.redirectUri}?code=1&state=st`);
|
|
98
|
+
expect((await s.wait()).code).toBe("1");
|
|
99
|
+
expect((await fetch(`${s.redirectUri}?code=2&state=st`)).status).toBe(404);
|
|
100
|
+
s.finish();
|
|
101
|
+
await r1;
|
|
102
|
+
await s.close();
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
describe("OAuthLogin.run", () => {
|
|
106
|
+
it("completes the code flow against a mock server (no browser)", async () => {
|
|
107
|
+
const mock = await startMock();
|
|
108
|
+
const printed = [];
|
|
109
|
+
const login = new OAuthLogin().run({
|
|
110
|
+
host: mock.base, name: "n", clientId: "pk_cli_x", project: "proj", scope: "offline_access", noBrowser: true,
|
|
111
|
+
print: l => printed.push(l),
|
|
112
|
+
});
|
|
113
|
+
// wait for the URL, then play the browser
|
|
114
|
+
while (!printed.some(l => l.includes("/authorize")))
|
|
115
|
+
await new Promise(r => setTimeout(r, 10));
|
|
116
|
+
const url = new URL(printed.find(l => l.includes("/authorize")));
|
|
117
|
+
const redirect = new URL(url.searchParams.get("redirect_uri"));
|
|
118
|
+
redirect.searchParams.set("code", "the-code");
|
|
119
|
+
redirect.searchParams.set("state", url.searchParams.get("state"));
|
|
120
|
+
redirect.searchParams.set("iss", mock.base);
|
|
121
|
+
await fetch(redirect);
|
|
122
|
+
const { tokens } = await login;
|
|
123
|
+
expect(tokens.accessToken).toBe("at");
|
|
124
|
+
expect(tokens.refreshToken).toBe("rt");
|
|
125
|
+
const exchange = mock.calls.find(c => c.path === "/v1/oauth/token").form;
|
|
126
|
+
expect(exchange).toMatchObject({ grant_type: "authorization_code", client_id: "pk_cli_x", code: "the-code", redirect_uri: redirect.origin + "/callback" });
|
|
127
|
+
expect(Pkce.challengeFor(exchange.code_verifier)).toBe(url.searchParams.get("code_challenge"));
|
|
128
|
+
expect(exchange).not.toHaveProperty("client_secret");
|
|
129
|
+
await mock.close();
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
describe("OAuthClient errors", () => {
|
|
133
|
+
it("exposes the platform error body", async () => {
|
|
134
|
+
const mock = await startMock({ token: () => [400, { error: "invalid_grant", error_description: "bad code" }] });
|
|
135
|
+
await expect(new OAuthClient().exchangeCode(`${mock.base}/v1/oauth/token`, { clientId: "c", code: "x", redirectUri: "r", verifier: "v" }))
|
|
136
|
+
.rejects.toMatchObject({ code: "invalid_grant", description: "bad code", status: 400 });
|
|
137
|
+
await mock.close();
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
describe("OAuthSession", () => {
|
|
141
|
+
let mock;
|
|
142
|
+
beforeAll(async () => { mock = await startMock({ token: (f, n) => f.refresh_token === "old-refresh" ? [200, { access_token: `new-access-${n}`, expires_in: 900, refresh_token: "rotated", scope: "s" }] : [400, { error: "invalid_grant" }] }); });
|
|
143
|
+
afterAll(() => mock.close());
|
|
144
|
+
it("leaves a fresh token alone", async () => {
|
|
145
|
+
const p = oauthProfile(mock.base);
|
|
146
|
+
seed(p);
|
|
147
|
+
const out = await new OAuthSession().ensureFresh(p);
|
|
148
|
+
expect(out.token).toBe("old-access");
|
|
149
|
+
expect(mock.calls.filter(c => c.path === "/v1/oauth/token")).toHaveLength(0);
|
|
150
|
+
});
|
|
151
|
+
it("refreshes an expired token and persists the rotated refresh token", async () => {
|
|
152
|
+
const p = oauthProfile(mock.base, { expires_at: Date.now() - 1000 });
|
|
153
|
+
seed(p);
|
|
154
|
+
const out = await new OAuthSession().ensureFresh(p);
|
|
155
|
+
expect(out.token).toMatch(/^new-access/);
|
|
156
|
+
expect(stored()).toMatchObject({ token: out.token, refresh_token: "rotated" });
|
|
157
|
+
expect(stored().expires_at).toBeGreaterThan(Date.now());
|
|
158
|
+
});
|
|
159
|
+
it("refreshes inside the 60s skew window", async () => {
|
|
160
|
+
const p = oauthProfile(mock.base, { expires_at: Date.now() + 30_000 });
|
|
161
|
+
seed(p);
|
|
162
|
+
expect((await new OAuthSession().ensureFresh(p)).refresh_token).toBe("rotated");
|
|
163
|
+
});
|
|
164
|
+
it("reuses a copy another process already refreshed", async () => {
|
|
165
|
+
const before = mock.calls.length;
|
|
166
|
+
seed(oauthProfile(mock.base, { token: "other-process" }));
|
|
167
|
+
const stale = oauthProfile(mock.base, { expires_at: 1 });
|
|
168
|
+
expect((await new OAuthSession().ensureFresh(stale)).token).toBe("other-process");
|
|
169
|
+
expect(mock.calls.length).toBe(before);
|
|
170
|
+
});
|
|
171
|
+
it("tells the user to log in again on invalid_grant", async () => {
|
|
172
|
+
const p = oauthProfile(mock.base, { expires_at: 1, refresh_token: "dead" });
|
|
173
|
+
seed(p);
|
|
174
|
+
await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow(/ptkl profile oauth/);
|
|
175
|
+
});
|
|
176
|
+
it("logout revokes the refresh token and clears stored tokens", async () => {
|
|
177
|
+
const p = oauthProfile(mock.base);
|
|
178
|
+
seed(p);
|
|
179
|
+
await new OAuthSession().logout(p);
|
|
180
|
+
const call = mock.calls.filter(c => c.path === "/v1/oauth/revoke").pop();
|
|
181
|
+
expect(call.form).toMatchObject({ token: "old-refresh", token_type_hint: "refresh_token", client_id: "pk_cli_x" });
|
|
182
|
+
expect(stored().token).toBe("");
|
|
183
|
+
expect(stored().refresh_token).toBeUndefined();
|
|
184
|
+
});
|
|
185
|
+
it("masks tokens", () => {
|
|
186
|
+
const m = OAuthSession.masked(oauthProfile("http://x"));
|
|
187
|
+
expect(JSON.stringify(m)).not.toContain("old-access");
|
|
188
|
+
expect(JSON.stringify(m)).not.toContain("old-refresh");
|
|
189
|
+
});
|
|
190
|
+
it("maps 403 insufficient_scope to an unavailable-to-OAuth message", () => {
|
|
191
|
+
const err = { response: { status: 403, headers: { "www-authenticate": 'Bearer error="insufficient_scope"' } } };
|
|
192
|
+
expect(OAuthSession.describeApiError(err)).toMatch(/isn't available to OAuth tokens/);
|
|
193
|
+
expect(OAuthSession.describeApiError({ response: { status: 403, headers: {} } })).toBeUndefined();
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
describe("refresh serialization", () => {
|
|
197
|
+
const lockPath = join(home, ".ptkl", "o.refresh.lock");
|
|
198
|
+
it("two concurrent refreshes send one request and share the new token", async () => {
|
|
199
|
+
const mock = await startMock({ token: (f, n) => [200, { access_token: `a${n}`, expires_in: 900, refresh_token: `r${n}` }] });
|
|
200
|
+
const p = oauthProfile(mock.base, { expires_at: 1 });
|
|
201
|
+
seed(p);
|
|
202
|
+
const [a, b] = await Promise.all([new OAuthSession().ensureFresh(p), new OAuthSession().ensureFresh(p)]);
|
|
203
|
+
expect(mock.calls.filter(c => c.path === "/v1/oauth/token")).toHaveLength(1);
|
|
204
|
+
expect(a.token).toBe("a1");
|
|
205
|
+
expect(b.token).toBe("a1");
|
|
206
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
207
|
+
await mock.close();
|
|
208
|
+
});
|
|
209
|
+
it("takes over a stale lock (dead pid or old)", async () => {
|
|
210
|
+
writeFileSync(lockPath, JSON.stringify({ pid: 2 ** 22 + 12345, at: Date.now() }));
|
|
211
|
+
(await RefreshLock.acquire(lockPath, 500)).release();
|
|
212
|
+
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, at: Date.now() - 60_000 }));
|
|
213
|
+
(await RefreshLock.acquire(lockPath, 500)).release();
|
|
214
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
215
|
+
});
|
|
216
|
+
it("times out on a live lock", async () => {
|
|
217
|
+
const l = await RefreshLock.acquire(lockPath);
|
|
218
|
+
await expect(RefreshLock.acquire(lockPath, 100)).rejects.toMatchObject({ code: "lock_timeout" });
|
|
219
|
+
l.release();
|
|
220
|
+
});
|
|
221
|
+
it("releases the lock when the refresh fails", async () => {
|
|
222
|
+
const mock = await startMock({ token: () => [500, { error: "server_error" }] });
|
|
223
|
+
const p = oauthProfile(mock.base, { expires_at: 1 });
|
|
224
|
+
seed(p);
|
|
225
|
+
await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow();
|
|
226
|
+
expect(existsSync(lockPath)).toBe(false);
|
|
227
|
+
await mock.close();
|
|
228
|
+
});
|
|
229
|
+
});
|
|
230
|
+
describe("ProfileLogin routing", () => {
|
|
231
|
+
it("defaults to OAuth", () => {
|
|
232
|
+
expect(ProfileLogin.useLegacy({})).toBe(false);
|
|
233
|
+
expect(ProfileLogin.useLegacy({ browser: false, scope: "x" })).toBe(false);
|
|
234
|
+
});
|
|
235
|
+
it("--legacy, -t, -p (flag with or without value) and -u select legacy", () => {
|
|
236
|
+
expect(ProfileLogin.useLegacy({ legacy: true })).toBe(true);
|
|
237
|
+
expect(ProfileLogin.useLegacy({ token: "t" })).toBe(true);
|
|
238
|
+
expect(ProfileLogin.useLegacy({ password: true })).toBe(true);
|
|
239
|
+
expect(ProfileLogin.useLegacy({ password: "pw" })).toBe(true);
|
|
240
|
+
expect(ProfileLogin.useLegacy({ username: "u@x" })).toBe(true);
|
|
241
|
+
});
|
|
242
|
+
it("resolves client id: flag > profile > env > built-in", () => {
|
|
243
|
+
const prof = { client_id: "stored" };
|
|
244
|
+
expect(ProfileLogin.resolveClientId("flag", prof, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("flag");
|
|
245
|
+
expect(ProfileLogin.resolveClientId(undefined, prof, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("stored");
|
|
246
|
+
expect(ProfileLogin.resolveClientId(undefined, undefined, { PTKL_OAUTH_CLIENT_ID: "env" })).toBe("env");
|
|
247
|
+
expect(ProfileLogin.resolveClientId(undefined, undefined, {})).toBe(ProfileLogin.defaultClientId);
|
|
248
|
+
});
|
|
249
|
+
it("OAuth login stores no username, dropping a legacy or placeholder one", async () => {
|
|
250
|
+
const run = vi.spyOn(OAuthLogin.prototype, "run").mockResolvedValue({
|
|
251
|
+
discovery: { issuer: "i", authorization_endpoint: "a", token_endpoint: "t", revocation_endpoint: "r" },
|
|
252
|
+
tokens: { accessToken: "at", refreshToken: "rt", expiresAt: 1, scope: "s" },
|
|
253
|
+
});
|
|
254
|
+
const base = { name: "o", host: "http://h", project: "p" };
|
|
255
|
+
for (const old of [{ username: "me@x.io" }, { username: "oauth" }, {}]) {
|
|
256
|
+
seed({ name: "o", host: "http://h", project: "p", current: true, token: "legacy", ...old });
|
|
257
|
+
const out = await ProfileLogin.login(base, {}, () => { });
|
|
258
|
+
expect(out).not.toHaveProperty("username");
|
|
259
|
+
expect(stored()).not.toHaveProperty("username");
|
|
260
|
+
expect(stored()).toMatchObject({ auth: "oauth", token: "at", current: true });
|
|
261
|
+
}
|
|
262
|
+
run.mockRestore();
|
|
263
|
+
});
|
|
264
|
+
it("toLegacy strips every OAuth field and sets token/username", () => {
|
|
265
|
+
const out = ProfileLogin.toLegacy(oauthProfile("http://h", { scope: "s", username: "oauth" }), { username: "me@x.io", token: "SESSION:t" });
|
|
266
|
+
expect(out).toEqual({ name: "o", host: "http://h", project: "p", current: true, token: "SESSION:t", username: "me@x.io" });
|
|
267
|
+
});
|
|
268
|
+
it("toLegacy with a token only keeps a real stored username, never the OAuth placeholder", () => {
|
|
269
|
+
expect(ProfileLogin.toLegacy(oauthProfile("http://h", { username: "oauth" }), { token: "t" })).not.toHaveProperty("username");
|
|
270
|
+
const legacy = { name: "l", host: "h", project: "p", current: false, token: "old", username: "me@x.io" };
|
|
271
|
+
expect(ProfileLogin.toLegacy(legacy, { token: "t" })).toEqual({ ...legacy, token: "t" });
|
|
272
|
+
});
|
|
273
|
+
it("legacyUsername: -u wins, OAuth profile's stored name ignored, legacy's used", () => {
|
|
274
|
+
const oauth = oauthProfile("http://h", { username: "oauth" });
|
|
275
|
+
const legacy = { name: "l", username: "stored@x.io" };
|
|
276
|
+
expect(ProfileLogin.legacyUsername(oauth, "me@x.io")).toBe("me@x.io");
|
|
277
|
+
expect(ProfileLogin.legacyUsername(oauth)).toBeUndefined();
|
|
278
|
+
expect(ProfileLogin.legacyUsername(legacy)).toBe("stored@x.io");
|
|
279
|
+
expect(ProfileLogin.legacyUsername(legacy, "other")).toBe("other");
|
|
280
|
+
});
|
|
281
|
+
it("fails with a --legacy hint when discovery is unavailable", async () => {
|
|
282
|
+
const mock = await startMock();
|
|
283
|
+
await mock.close(); // nothing listening: connection refused
|
|
284
|
+
await expect(new OAuthLogin().run({ host: mock.base, name: "n", clientId: "c", project: "p", scope: "offline_access", noBrowser: true, print: () => { } }))
|
|
285
|
+
.rejects.toThrow(`OAuth login isn't available on ${mock.base}; use \`ptkl profile auth --legacy\``);
|
|
286
|
+
});
|
|
287
|
+
it("fails the same way on a 404 (OAuth disabled)", async () => {
|
|
288
|
+
const http = await import("node:http");
|
|
289
|
+
const srv = http.createServer((_, res) => res.writeHead(404).end());
|
|
290
|
+
await new Promise(r => srv.listen(0, "127.0.0.1", r));
|
|
291
|
+
const host = `http://127.0.0.1:${srv.address().port}`;
|
|
292
|
+
await expect(new OAuthLogin().run({ host, name: "n", clientId: "c", project: "p", scope: "s", noBrowser: true, print: () => { } })).rejects.toThrow(/use `ptkl profile auth --legacy`/);
|
|
293
|
+
srv.close();
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
describe("CallbackPages", () => {
|
|
297
|
+
const c = { name: "dev", host: "https://api.x", project: "11111111-2222", isNew: false };
|
|
298
|
+
it("each error variant has its title and retry command", () => {
|
|
299
|
+
expect(CallbackPages.forError(c, "access_denied").html).toContain("You declined access");
|
|
300
|
+
expect(CallbackPages.forError(c, "access_denied").html).toContain("ptkl profile auth dev");
|
|
301
|
+
expect(CallbackPages.forError(c, "state_mismatch").html).toContain("This login link is no longer valid");
|
|
302
|
+
expect(CallbackPages.forError(c, "timeout").html).toContain("This login timed out");
|
|
303
|
+
const f = CallbackPages.forError({ ...c, isNew: true }, "server_error", "boom").html;
|
|
304
|
+
expect(f).toContain("server_error");
|
|
305
|
+
expect(f).toContain("ptkl profile new -n dev -h https://api.x -P 11111111-2222");
|
|
306
|
+
});
|
|
307
|
+
it("renders hostile error text inert and caps its length", () => {
|
|
308
|
+
const h = CallbackPages.forError(c, "<script>x()</script>", `<script>alert(1)</script>${"a".repeat(500)}`).html;
|
|
309
|
+
expect(h).not.toContain("<script");
|
|
310
|
+
expect(h).toContain("<script>alert(1)");
|
|
311
|
+
expect(h.length).toBeLessThan(CallbackPages.forError(c, "x", "a".repeat(100)).html.length + 800);
|
|
312
|
+
});
|
|
313
|
+
it("loads nothing external", () => {
|
|
314
|
+
const h = CallbackPages.forError(c, "access_denied").html;
|
|
315
|
+
expect(h).not.toMatch(/(src|href)=|url\(|@import|<script/i);
|
|
316
|
+
});
|
|
317
|
+
it("success answers the tab with a 302 to the guide", async () => {
|
|
318
|
+
const s = await CallbackServer.start("st", c);
|
|
319
|
+
const pendingRes = fetch(`${s.redirectUri}?code=SECRETCODE&state=st`, { redirect: "manual" });
|
|
320
|
+
await s.wait();
|
|
321
|
+
s.finish();
|
|
322
|
+
const r = await pendingRes;
|
|
323
|
+
expect(r.status).toBe(302);
|
|
324
|
+
expect(r.headers.get("location")).toBe(GUIDE_URL);
|
|
325
|
+
expect(r.headers.get("referrer-policy")).toBe("no-referrer");
|
|
326
|
+
expect(r.headers.get("cache-control")).toBe("no-store");
|
|
327
|
+
expect(await r.text()).toBe("");
|
|
328
|
+
await s.close();
|
|
329
|
+
});
|
|
330
|
+
it("error responses carry the headers and no raw query values", async () => {
|
|
331
|
+
const s = await CallbackServer.start("st", c);
|
|
332
|
+
const r = await fetch(`${s.redirectUri}?error=access_denied&error_description=%3Cb%3Ehi&state=st&code=LEAK`);
|
|
333
|
+
const body = await r.text();
|
|
334
|
+
expect(r.status).toBe(400);
|
|
335
|
+
expect(r.headers.get("content-security-policy")).toContain("default-src 'none'");
|
|
336
|
+
expect(body).toContain("You declined access");
|
|
337
|
+
expect(body).not.toContain("LEAK");
|
|
338
|
+
await s.wait().catch(() => { });
|
|
339
|
+
await s.close();
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
describe("Util profile writes", () => {
|
|
343
|
+
it("is atomic: no temp file left behind", () => {
|
|
344
|
+
Util.updateProfiles([{ name: "a" }]);
|
|
345
|
+
expect(readFileSync(profilesFile, "utf8")).toContain('"a"');
|
|
346
|
+
});
|
|
347
|
+
});
|
package/dist/lib/util.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
|
|
2
2
|
import { Platform } from '@ptkl/sdk';
|
|
3
3
|
export default class Util {
|
|
4
4
|
static profilePath = `${process.env.HOME}/.ptkl`;
|
|
5
5
|
static fileName = "profiles.json";
|
|
6
|
+
static profileDir() {
|
|
7
|
+
return Util.profilePath;
|
|
8
|
+
}
|
|
6
9
|
static getProfiles() {
|
|
7
10
|
try {
|
|
8
11
|
const contents = JSON.parse(readFileSync(`${Util.profilePath}/${Util.fileName}`).toString());
|
|
@@ -15,7 +18,11 @@ export default class Util {
|
|
|
15
18
|
static updateProfiles(profiles) {
|
|
16
19
|
try {
|
|
17
20
|
const contents = JSON.stringify(profiles);
|
|
18
|
-
|
|
21
|
+
// temp + rename so a crash or parallel run never leaves a torn file
|
|
22
|
+
const target = `${Util.profilePath}/${Util.fileName}`;
|
|
23
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
24
|
+
writeFileSync(tmp, contents, { mode: 0o600 });
|
|
25
|
+
renameSync(tmp, target);
|
|
19
26
|
return profiles;
|
|
20
27
|
}
|
|
21
28
|
catch (err) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ptkl/toolkit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"protokol",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"homepage": "https://your-gitea-instance.com/your-org/protokol-toolkit#readme",
|
|
23
23
|
"type": "module",
|
|
24
24
|
"scripts": {
|
|
25
|
-
"test": "
|
|
25
|
+
"test": "vitest run",
|
|
26
|
+
"test:watch": "vitest",
|
|
26
27
|
"build": "npx tsc",
|
|
27
28
|
"postbuild": "chmod +x dist/bin/toolkit.js",
|
|
28
29
|
"toolkit": "tsc --build && node dist/bin/toolkit",
|
|
@@ -37,7 +38,6 @@
|
|
|
37
38
|
"@babel/standalone": "^7.26.10",
|
|
38
39
|
"@inquirer/password": "^4.0.21",
|
|
39
40
|
"@ptkl/sdk": "^1.14.0",
|
|
40
|
-
"@ptkl/toolkit": "file:",
|
|
41
41
|
"@rollup/plugin-babel": "^6.1.0",
|
|
42
42
|
"@rollup/plugin-commonjs": "^29.0.0",
|
|
43
43
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"marked": "^15.0.12",
|
|
60
60
|
"marked-terminal": "^7.3.0",
|
|
61
61
|
"open": "^10.1.2",
|
|
62
|
+
"openai": "^7.1.0",
|
|
62
63
|
"react": "^18.3.1",
|
|
63
64
|
"rollup": "^4.34.6",
|
|
64
65
|
"sass": "^1.95.1",
|
|
@@ -73,7 +74,8 @@
|
|
|
73
74
|
"@types/node": "^22.3.0",
|
|
74
75
|
"@types/react": "^18.3.29",
|
|
75
76
|
"@types/ws": "^8.5.12",
|
|
76
|
-
"typescript": "^5.5.4"
|
|
77
|
+
"typescript": "^5.5.4",
|
|
78
|
+
"vitest": "^4.1.10"
|
|
77
79
|
},
|
|
78
80
|
"files": [
|
|
79
81
|
"dist"
|