ink-framework-auth 0.0.0-stage → 0.1.0-alpha.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vandam Dinh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,9 @@
1
+ {
2
+ "version": 1,
3
+ "modules": {
4
+ "*": [
5
+ "network",
6
+ "external"
7
+ ]
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "ink-framework-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "exports": {
5
+ ".": "./src/index.ts"
6
+ },
7
+ "peerDependencies": {
8
+ "ink": "npm:ink-framework@0.1.0-alpha.1"
9
+ },
10
+ "license": "MIT",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/No-Scrolling/ink.git",
14
+ "directory": "packages/auth"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "*.json",
19
+ "*.ts"
20
+ ]
21
+ }
package/src/index.ts ADDED
@@ -0,0 +1,143 @@
1
+ import type { Snapshot, SnapshotSource } from "ink";
2
+ import { callNative, onNativeMessage } from "ink/native";
3
+
4
+ const observers = new Map<string, Set<() => void>>();
5
+ onNativeMessage("auth-changed", message => {
6
+ if (typeof message.id === "string") for (const refresh of observers.get(message.id) ?? []) refresh();
7
+ });
8
+
9
+ export interface OAuthConfig {
10
+ id: string;
11
+ clientId: string;
12
+ tokenEndpoint: string;
13
+ scopes?: string[];
14
+ deviceAuthorizationEndpoint?: string;
15
+ authorizationEndpoint?: string;
16
+ redirectUri?: string;
17
+ }
18
+ export type AccountState = { status: "signed-out" | "signed-in" };
19
+ type Options = { signal?: AbortSignal };
20
+ type DeviceResponse = { error?: string; device_code: string; user_code: string; verification_uri: string; verification_uri_complete?: string; expires_in: number; interval?: number };
21
+ export interface DeviceSignIn {
22
+ verificationUri: string;
23
+ verificationUriComplete?: string;
24
+ userCode: string;
25
+ expiresAt: number;
26
+ complete(options?: Options): Promise<void>;
27
+ }
28
+ export interface OAuthClient extends SnapshotSource<AccountState> {
29
+ startDeviceSignIn(options?: Options): Promise<DeviceSignIn>;
30
+ signIn(options?: Options): Promise<void>;
31
+ getAccessToken(options?: Options): Promise<string>;
32
+ signOut(): Promise<void>;
33
+ }
34
+
35
+ function delay(ms: number, signal: AbortSignal): Promise<void> {
36
+ return new Promise((resolve, reject) => {
37
+ if (signal.aborted) { reject(signal.reason); return; }
38
+ const abort = () => { clearTimeout(timer); reject(signal.reason); };
39
+ const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, ms);
40
+ signal.addEventListener("abort", abort, { once: true });
41
+ });
42
+ }
43
+
44
+ export function createOAuthClient(configuration: OAuthConfig): OAuthClient {
45
+ const config = { ...configuration, scopes: [...(configuration.scopes ?? [])] };
46
+ if (!config.id || !config.clientId || !config.tokenEndpoint) throw new Error("Account ID, client ID and token endpoint are required");
47
+ let snapshot: Snapshot<AccountState> = { status: "loading" };
48
+ const listeners = new Set<() => void>();
49
+ const work = new Set<AbortController>();
50
+ function publish(value: Snapshot<AccountState>) { snapshot = value; for (const listener of listeners) listener(); }
51
+ async function invoke<T = unknown>(operation: string, payload = {}, options: Options = {}): Promise<T> {
52
+ return JSON.parse(await callNative("auth", operation, { config, ...payload }, { ...options, timeoutMs: 120_000 }));
53
+ }
54
+ async function refreshSnapshot() {
55
+ try { publish({ status: "ready", data: await invoke<AccountState>("status") }); }
56
+ catch (error) { publish({ status: "error", error: error instanceof Error ? error : new Error(String(error)) }); }
57
+ }
58
+ async function owned<T>(options: Options, run: (signal: AbortSignal) => Promise<T>): Promise<T> {
59
+ const controller = new AbortController(); work.add(controller);
60
+ const abort = () => controller.abort(options.signal?.reason);
61
+ options.signal?.addEventListener("abort", abort, { once: true });
62
+ if (options.signal?.aborted) abort();
63
+ try { return await run(controller.signal); }
64
+ finally { work.delete(controller); options.signal?.removeEventListener("abort", abort); }
65
+ }
66
+ async function exchange(generation: number, fields: Record<string, string>, signal: AbortSignal) {
67
+ const result = await invoke<{ error?: string }>("exchange", { generation, fields }, { signal });
68
+ if (result.error) return result.error;
69
+ await refreshSnapshot();
70
+ return null;
71
+ }
72
+ return {
73
+ getSnapshot: () => snapshot,
74
+ subscribe(listener) {
75
+ listeners.add(listener);
76
+ let accountObservers = observers.get(config.id);
77
+ if (!accountObservers) { accountObservers = new Set(); observers.set(config.id, accountObservers); }
78
+ accountObservers.add(refreshSnapshot);
79
+ void refreshSnapshot();
80
+ return () => {
81
+ listeners.delete(listener);
82
+ if (!listeners.size) {
83
+ accountObservers.delete(refreshSnapshot);
84
+ if (!accountObservers.size) observers.delete(config.id);
85
+ }
86
+ };
87
+ },
88
+ async getAccessToken(options = {}) {
89
+ const result: unknown = await invoke("token", {}, options);
90
+ if (typeof result !== "string") throw new Error("Token refresh failed; interactive sign-in may be required");
91
+ await refreshSnapshot();
92
+ return result;
93
+ },
94
+ async signOut() {
95
+ for (const controller of work) controller.abort(new Error("Signed out"));
96
+ await invoke("sign-out");
97
+ await refreshSnapshot();
98
+ },
99
+ async signIn(options = {}) {
100
+ if (!config.authorizationEndpoint || !config.redirectUri) throw new Error("Browser sign-in requires authorisation endpoint and redirect URI");
101
+ await owned(options, async signal => {
102
+ const { generation } = await invoke<{ generation: number }>("begin", {}, { signal });
103
+ const fields: Record<string, string> = JSON.parse(await callNative("external", "browser-auth", { config }, { signal, timeoutMs: 900_000 }));
104
+ const error = await exchange(generation, fields, signal);
105
+ if (error) throw new Error(`Sign-in failed: ${error}`);
106
+ });
107
+ },
108
+ async startDeviceSignIn(options = {}) {
109
+ if (!config.deviceAuthorizationEndpoint) throw new Error("Device sign-in requires a device authorisation endpoint");
110
+ const { generation } = await invoke<{ generation: number }>("begin", {}, options);
111
+ const result = await invoke<DeviceResponse>("device-start", {}, options);
112
+ if (result.error) throw new Error(`Device authorisation failed: ${result.error}`);
113
+ if (typeof result.device_code !== "string" || !result.device_code || typeof result.user_code !== "string" || !result.user_code || typeof result.verification_uri !== "string"
114
+ || !Number.isFinite(result.expires_in) || result.expires_in <= 0 || result.expires_in > 31_536_000
115
+ || (result.interval !== undefined && (!Number.isFinite(result.interval) || result.interval <= 0 || result.interval > 86_400))
116
+ || (result.verification_uri_complete !== undefined && typeof result.verification_uri_complete !== "string")) throw new Error("Invalid device authorisation response");
117
+ const expiresAt = Date.now() + result.expires_in * 1000;
118
+ let interval = Math.max(5, result.interval ?? 5) * 1000;
119
+ let completion: Promise<void> | undefined;
120
+ return {
121
+ verificationUri: result.verification_uri,
122
+ verificationUriComplete: result.verification_uri_complete,
123
+ userCode: result.user_code,
124
+ expiresAt,
125
+ complete(completionOptions = {}) {
126
+ if (completion) return completion;
127
+ completion = owned(completionOptions, async signal => {
128
+ while (Date.now() < expiresAt) {
129
+ await delay(Math.min(interval, Math.max(0, expiresAt - Date.now())), signal);
130
+ if (Date.now() >= expiresAt) break;
131
+ const error = await exchange(generation, { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: result.device_code }, signal);
132
+ if (error === null) return;
133
+ if (error === "slow_down") interval += 5000;
134
+ else if (error !== "authorization_pending") throw new Error(`Device sign-in failed: ${error}`);
135
+ }
136
+ throw new Error("Device sign-in expired");
137
+ });
138
+ return completion;
139
+ },
140
+ };
141
+ },
142
+ };
143
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.