@chabi/js 0.0.0-stage → 0.1.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/dist/node.js ADDED
@@ -0,0 +1,117 @@
1
+ import {
2
+ ChabiBase,
3
+ ChabiError,
4
+ DEFAULT_BASE_URL,
5
+ SessionCore,
6
+ challengeFor,
7
+ describeError,
8
+ describeResponse,
9
+ randomString
10
+ } from "./chunk-PTMH3FUL.js";
11
+
12
+ // src/node.ts
13
+ import http from "http";
14
+ var DEFAULT_TIMEOUT_MS = 5 * 6e4;
15
+ var Chabi = class extends ChabiBase {
16
+ opts;
17
+ baseUrl;
18
+ constructor(opts) {
19
+ const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
20
+ super(new SessionCore({ baseUrl, clientId: opts.clientId, storage: opts.storage, lock: processLock() }));
21
+ this.opts = opts;
22
+ this.baseUrl = baseUrl;
23
+ }
24
+ /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */
25
+ load() {
26
+ return this.core.load();
27
+ }
28
+ /**
29
+ * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a
30
+ * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.
31
+ */
32
+ async signIn() {
33
+ const verifier = randomString();
34
+ const state = randomString(16);
35
+ const server = http.createServer();
36
+ await new Promise((ready, fail) => {
37
+ server.once("error", fail);
38
+ server.listen(0, "127.0.0.1", ready);
39
+ });
40
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
41
+ let timer;
42
+ try {
43
+ const returned = new Promise((done, fail) => {
44
+ timer = setTimeout(
45
+ () => fail(new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_timeout", message: "Sign-in timed out. Please try again." })),
46
+ this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
47
+ );
48
+ server.on("request", (req, res) => {
49
+ const url2 = new URL(req.url ?? "/", redirectUri);
50
+ if (url2.pathname !== "/callback") return void res.writeHead(404).end();
51
+ const p2 = url2.searchParams;
52
+ const outcome = p2.get("state") !== state || !p2.get("code") && !p2.get("error") ? "failed" : p2.get("error") === "access_denied" ? "denied" : p2.get("error") ? "failed" : "signed_in";
53
+ this.opts.onReturn?.();
54
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", Connection: "close" });
55
+ res.end((this.opts.returnPage ?? defaultReturnPage)(outcome));
56
+ done(p2);
57
+ });
58
+ });
59
+ returned.catch(() => {
60
+ });
61
+ const url = new URL(`${this.baseUrl}/oauth/authorize`);
62
+ url.search = new URLSearchParams({
63
+ response_type: "code",
64
+ client_id: this.opts.clientId,
65
+ redirect_uri: redirectUri,
66
+ code_challenge: await challengeFor(verifier),
67
+ code_challenge_method: "S256",
68
+ state
69
+ }).toString();
70
+ await this.opts.openBrowser(url.toString());
71
+ const p = await returned;
72
+ if (p.get("state") !== state) {
73
+ throw new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_not_started", message: "That sign-in didn't start here. Please try again." });
74
+ }
75
+ if (p.get("error") === "access_denied") {
76
+ throw new ChabiError({ kind: "access_denied", status: 0, code: "access_denied", message: "You chose not to let this app use your Chabi plan." });
77
+ }
78
+ const code = p.get("code");
79
+ if (p.get("error") || !code) {
80
+ throw new ChabiError({ kind: "signed_out", status: 0, code: p.get("error") ?? "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
81
+ }
82
+ await this.core.exchangeCode({ code, redirectUri, verifier });
83
+ } finally {
84
+ clearTimeout(timer);
85
+ server.close();
86
+ server.closeAllConnections();
87
+ }
88
+ }
89
+ };
90
+ function memoryStorage(initial = null) {
91
+ let tokens = initial;
92
+ return {
93
+ load: () => tokens,
94
+ save: (t) => void (tokens = t),
95
+ clear: () => void (tokens = null)
96
+ };
97
+ }
98
+ function processLock() {
99
+ let tail = Promise.resolve();
100
+ return (run) => {
101
+ const next = tail.then(run, run);
102
+ tail = next.catch(() => void 0);
103
+ return next;
104
+ };
105
+ }
106
+ function defaultReturnPage(outcome) {
107
+ const [title, body] = outcome === "signed_in" ? ["You're signed in", "You can close this tab and go back to the app."] : outcome === "denied" ? ["Sign-in cancelled", "The app won't use your Chabi plan. You can close this tab."] : ["Sign-in didn't finish", "Go back to the app and try again."];
108
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#fff;color:#121212}@media (prefers-color-scheme:dark){body{background:#121212;color:#fff}}main{max-width:420px;padding:32px 28px}h1{margin:0 0 6px;font-size:22px}p{margin:0;opacity:.75}</style></head><body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;
109
+ }
110
+ export {
111
+ Chabi,
112
+ ChabiError,
113
+ describeError,
114
+ describeResponse,
115
+ memoryStorage
116
+ };
117
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts"],"sourcesContent":["// \"Sign in with Chabi\" for Node and Electron (main process): sign-in in the system browser with a loopback\n// redirect (RFC 8252), tokens kept wherever the app's storage puts them (the OS keychain, ideally).\nimport http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { ChabiBase, DEFAULT_BASE_URL } from \"./client.js\";\nimport { ChabiError } from \"./errors.js\";\nimport { challengeFor, randomString } from \"./pkce.js\";\nimport { SessionCore } from \"./session.js\";\nimport type { RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\nexport { ChabiError, describeError, describeResponse } from \"./errors.js\";\nexport type * from \"./types.js\";\nexport type { ChabiBase } from \"./client.js\";\n\n/** What the browser tab shows once it has handed the sign-in back. */\nexport type Outcome = \"signed_in\" | \"denied\" | \"failed\";\n\nexport type NodeOptions = {\n clientId: string;\n baseUrl?: string;\n /** Where tokens live. In Electron, encrypt them with safeStorage; `memoryStorage()` keeps them for this run only. */\n storage: TokenStorage;\n /** Opens the sign-in page in the system browser (Electron: `shell.openExternal`). Never a web view in the app. */\n openBrowser: (url: string) => void | Promise<void>;\n /** Called the moment the browser comes back, before the tab is answered: bring the app's window to the front. */\n onReturn?: () => void;\n /** The HTML the tab shows afterwards. The default says the user can close the tab. */\n returnPage?: (outcome: Outcome) => string;\n /** How long to wait for the user to finish in the browser. Default 5 minutes. */\n timeoutMs?: number;\n};\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport class Chabi extends ChabiBase {\n private readonly opts: NodeOptions;\n private readonly baseUrl: string;\n\n constructor(opts: NodeOptions) {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n super(new SessionCore({ baseUrl, clientId: opts.clientId, storage: opts.storage, lock: processLock() }));\n this.opts = opts;\n this.baseUrl = baseUrl;\n }\n\n /** Reads the saved tokens. Await it once at start, before checking `signedIn`. */\n load(): Promise<void> {\n return this.core.load();\n }\n\n /**\n * Opens Chabi in the system browser and waits for the user to come back. Resolves once signed in; throws a\n * ChabiError if they declined (`access_denied`), the sign-in didn't come from here, or it timed out.\n */\n async signIn(): Promise<void> {\n const verifier = randomString();\n const state = randomString(16);\n const server = http.createServer();\n await new Promise<void>((ready, fail) => {\n server.once(\"error\", fail);\n server.listen(0, \"127.0.0.1\", ready);\n });\n // Any free port: the registered redirect is http://127.0.0.1/callback and the port doesn't have to match.\n const redirectUri = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const returned = new Promise<URLSearchParams>((done, fail) => {\n timer = setTimeout(\n () => fail(new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_timeout\", message: \"Sign-in timed out. Please try again.\" })),\n this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n );\n server.on(\"request\", (req, res) => {\n const url = new URL(req.url ?? \"/\", redirectUri);\n if (url.pathname !== \"/callback\") return void res.writeHead(404).end();\n const p = url.searchParams;\n const outcome: Outcome =\n p.get(\"state\") !== state || (!p.get(\"code\") && !p.get(\"error\")) ? \"failed\"\n : p.get(\"error\") === \"access_denied\" ? \"denied\"\n : p.get(\"error\") ? \"failed\"\n : \"signed_in\";\n this.opts.onReturn?.(); // in front of the tab by the time it finishes loading\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\", \"Cache-Control\": \"no-store\", Connection: \"close\" });\n res.end((this.opts.returnPage ?? defaultReturnPage)(outcome));\n done(p);\n });\n });\n\n returned.catch(() => {}); // a timeout while openBrowser is still running is handled below, not unhandled\n const url = new URL(`${this.baseUrl}/oauth/authorize`);\n url.search = new URLSearchParams({\n response_type: \"code\",\n client_id: this.opts.clientId,\n redirect_uri: redirectUri,\n code_challenge: await challengeFor(verifier),\n code_challenge_method: \"S256\",\n state,\n }).toString();\n await this.opts.openBrowser(url.toString());\n\n const p = await returned;\n if (p.get(\"state\") !== state) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_not_started\", message: \"That sign-in didn't start here. Please try again.\" });\n }\n if (p.get(\"error\") === \"access_denied\") {\n throw new ChabiError({ kind: \"access_denied\", status: 0, code: \"access_denied\", message: \"You chose not to let this app use your Chabi plan.\" });\n }\n const code = p.get(\"code\");\n if (p.get(\"error\") || !code) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: p.get(\"error\") ?? \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n await this.core.exchangeCode({ code, redirectUri, verifier });\n } finally {\n clearTimeout(timer);\n server.close();\n server.closeAllConnections();\n }\n }\n}\n\n/** Tokens kept in memory for this run only (tests, or when the OS has no keychain). */\nexport function memoryStorage(initial: Tokens | null = null): TokenStorage {\n let tokens = initial;\n return {\n load: () => tokens,\n save: (t) => void (tokens = t),\n clear: () => void (tokens = null),\n };\n}\n\n// One process owns the tokens, so a promise chain is enough to keep refreshes one at a time.\nfunction processLock(): RefreshLock {\n let tail: Promise<unknown> = Promise.resolve();\n return (run) => {\n const next = tail.then(run, run);\n tail = next.catch(() => undefined);\n return next;\n };\n}\n\nfunction defaultReturnPage(outcome: Outcome): string {\n const [title, body] =\n outcome === \"signed_in\" ? [\"You're signed in\", \"You can close this tab and go back to the app.\"]\n : outcome === \"denied\" ? [\"Sign-in cancelled\", \"The app won't use your Chabi plan. You can close this tab.\"]\n : [\"Sign-in didn't finish\", \"Go back to the app and try again.\"];\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>${title}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#fff;color:#121212}@media (prefers-color-scheme:dark){body{background:#121212;color:#fff}}main{max-width:420px;padding:32px 28px}h1{margin:0 0 6px;font-size:22px}p{margin:0;opacity:.75}</style></head><body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;\n}\n"],"mappings":";;;;;;;;;;;;AAEA,OAAO,UAAU;AA8BjB,IAAM,qBAAqB,IAAI;AAExB,IAAM,QAAN,cAAoB,UAAU;AAAA,EAClB;AAAA,EACA;AAAA,EAEjB,YAAY,MAAmB;AAC7B,UAAM,WAAW,KAAK,WAAW,kBAAkB,QAAQ,QAAQ,EAAE;AACrE,UAAM,IAAI,YAAY,EAAE,SAAS,UAAU,KAAK,UAAU,SAAS,KAAK,SAAS,MAAM,YAAY,EAAE,CAAC,CAAC;AACvG,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA,EAGA,OAAsB;AACpB,WAAO,KAAK,KAAK,KAAK;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAwB;AAC5B,UAAM,WAAW,aAAa;AAC9B,UAAM,QAAQ,aAAa,EAAE;AAC7B,UAAM,SAAS,KAAK,aAAa;AACjC,UAAM,IAAI,QAAc,CAAC,OAAO,SAAS;AACvC,aAAO,KAAK,SAAS,IAAI;AACzB,aAAO,OAAO,GAAG,aAAa,KAAK;AAAA,IACrC,CAAC;AAED,UAAM,c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AAO,yIAAyI,KAAK,uVAAuV,KAAK,WAAW,IAAI;AAClgB;","names":["url","p"]}
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@chabi/js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Sign in with Chabi: your users bring their own AI. Works with the official OpenAI and Anthropic SDKs.",
5
+ "keywords": [
6
+ "chabi",
7
+ "sign in",
8
+ "oauth",
9
+ "pkce",
10
+ "openai",
11
+ "anthropic",
12
+ "ai"
13
+ ],
14
+ "homepage": "https://chabi.dev/docs#sign-in",
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "files": [
18
+ "dist",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/browser.d.ts",
25
+ "default": "./dist/browser.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/browser.d.cts",
29
+ "default": "./dist/browser.cjs"
30
+ }
31
+ },
32
+ "./node": {
33
+ "import": {
34
+ "types": "./dist/node.d.ts",
35
+ "default": "./dist/node.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/node.d.cts",
39
+ "default": "./dist/node.cjs"
40
+ }
41
+ }
42
+ },
43
+ "main": "./dist/browser.cjs",
44
+ "module": "./dist/browser.js",
45
+ "types": "./dist/browser.d.ts",
46
+ "sideEffects": false,
47
+ "engines": {
48
+ "node": ">=20"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup",
52
+ "test": "vitest run",
53
+ "typecheck": "tsc --noEmit"
54
+ },
55
+ "devDependencies": {
56
+ "@anthropic-ai/sdk": "^0.135.0",
57
+ "@types/node": "^26.6.11",
58
+ "happy-dom": "^21.0.4",
59
+ "openai": "^7.65.0",
60
+ "tsup": "^9.0.0",
61
+ "typescript": "^6.0.3",
62
+ "vitest": "^5.1.2"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public"
66
+ }
67
+ }