@lilbox/client 0.0.4 → 0.0.6
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 +57 -2
- package/dist/openapi.d.ts +2 -2
- package/dist/session/dashboard-client.d.ts +57 -0
- package/dist/session/dashboard-client.js +181 -0
- package/dist/session/index.d.ts +4 -0
- package/dist/session/index.js +11 -0
- package/dist/session/locks.d.ts +11 -0
- package/dist/session/locks.js +33 -0
- package/dist/session/store.d.ts +12 -0
- package/dist/session/store.js +42 -0
- package/dist/session/types.d.ts +64 -0
- package/dist/session/types.js +3 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -67,8 +67,8 @@ If the token can change (an OAuth token you refresh), pass a function. It's call
|
|
|
67
67
|
const lilbox = createLilboxClient({ token: async () => tokenStore.currentAccessToken() });
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
The lilbox dashboard
|
|
71
|
-
|
|
70
|
+
The lilbox dashboard doesn't pass a token: it uses `@lilbox/client/session`, which owns the signed-in session
|
|
71
|
+
([below](#dashboard-sessions-lilboxclientsession)). lilbox uses no cookies.
|
|
72
72
|
|
|
73
73
|
**Scopes.** Each credential carries scopes, and most operations need one (see the
|
|
74
74
|
[endpoint reference](#endpoint-reference)). A call without the right scope fails with `forbidden_scope`, and
|
|
@@ -88,6 +88,59 @@ own access.
|
|
|
88
88
|
`GET /v1/whoami` returns the signed-in user and the current credential's kind, scopes and expiry. Call it first
|
|
89
89
|
to check a token.
|
|
90
90
|
|
|
91
|
+
## Dashboard sessions: `@lilbox/client/session`
|
|
92
|
+
|
|
93
|
+
For the lilbox dashboard: a client that signs a person in and keeps them signed in. It stores the token pair,
|
|
94
|
+
sends the access token, refreshes it before it expires (and once on a `401`, then retries), and ends the
|
|
95
|
+
session cleanly when a refresh is refused. Page code never touches a token, and only sees a `401` when the
|
|
96
|
+
person has to sign in again. Scripts, CI and agents use the plain client with an API key or an OAuth token.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { browserSessionStore, createDashboardClient } from "@lilbox/client/session";
|
|
100
|
+
|
|
101
|
+
declare function goToSignIn(): void;
|
|
102
|
+
|
|
103
|
+
const lilbox = createDashboardClient({
|
|
104
|
+
store: browserSessionStore(), // localStorage, shared by every tab
|
|
105
|
+
onSessionEnded: () => goToSignIn(), // session_expired, token_reused, or signed out in another tab
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// /signin/magic: the Continue button (never on page load)
|
|
109
|
+
const { data: signedIn, error } = await lilbox.auth.verifyMagicLink("ml_...");
|
|
110
|
+
if (error) console.log(error.error.code); // e.g. "invalid_token", with details.email to resend
|
|
111
|
+
|
|
112
|
+
// Every other call is the usual typed client: the session is handled for you
|
|
113
|
+
const { data: me } = await lilbox.GET("/v1/whoami");
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`lilbox.auth` covers the rest of the dashboard's sign-in flows (`/auth/*`, [docs](https://github.com/lilbox-ai/lilbox-platform/tree/main/docs/frontend)):
|
|
117
|
+
|
|
118
|
+
| Method | Does |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `requestMagicLink(email, returnTo?)` | Emails a sign-in link |
|
|
121
|
+
| `verifyMagicLink(token)` | Signs in with the link's token; stores the session |
|
|
122
|
+
| `signInUrl("google" \| "github", { returnTo?, prompt? })` | The URL "Continue with Google / GitHub" navigates to |
|
|
123
|
+
| `exchangeCode(code)` | On `/signin/callback`: swaps the code from Google or GitHub; stores the session |
|
|
124
|
+
| `signOut({ everywhere? })` | Signs out this browser or all of them; the store is cleared even if the call fails |
|
|
125
|
+
| `listSessions()`, `revokeSession(id)` | The signed-in browsers, and signing one out |
|
|
126
|
+
| `currentUser()` | The signed-in user from the stored session, without a request |
|
|
127
|
+
|
|
128
|
+
**Refreshing across tabs.** Refresh tokens are single use: if two tabs refreshed with the same one, the API
|
|
129
|
+
would treat it as theft and end the session (`token_reused`). So refreshes run one at a time, under a lock.
|
|
130
|
+
By default that's `webLock()` (the Web Locks API, across every tab) where the browser has `navigator.locks`,
|
|
131
|
+
and `inTabLock()` otherwise. Pass `lock` to choose, and `store` to keep the session somewhere else:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { browserSessionStore, createDashboardClient, inTabLock } from "@lilbox/client/session";
|
|
135
|
+
|
|
136
|
+
const lilbox = createDashboardClient({
|
|
137
|
+
store: browserSessionStore({ storage: sessionStorage }), // the session ends when the tab closes
|
|
138
|
+
lock: inTabLock(),
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
A store is any `{ read, write, clear, subscribe? }`, and a lock any `{ run(fn) }`.
|
|
143
|
+
|
|
91
144
|
## Options
|
|
92
145
|
|
|
93
146
|
```text
|
|
@@ -187,6 +240,8 @@ Error codes. New codes may be added; existing ones never change meaning.
|
|
|
187
240
|
| `payment_required` | The account must subscribe (trial ended, or the feature needs a paid plan). `checkout_url` when available |
|
|
188
241
|
| `quota_exceeded` | A plan limit is used up this billing period. `meter`, `used`, `limit`, `resets_at` |
|
|
189
242
|
| `rate_limited` | Too many requests from this credential or IP. `retry_after_seconds` |
|
|
243
|
+
| `terms_required` | The user hasn't accepted the Terms yet; a person accepts them in the dashboard |
|
|
244
|
+
| `reauth_required` | The action needs a sign-in in the last 15 minutes (dashboard only) |
|
|
190
245
|
| `suspended` | lilbox suspended the app or account. `reason` |
|
|
191
246
|
| `invalid_request` | The input failed validation. `issues`, each with a path |
|
|
192
247
|
| `invalid_manifest` | `app.yaml` is invalid. `issues` |
|
package/dist/openapi.d.ts
CHANGED
|
@@ -812,7 +812,7 @@ export interface components {
|
|
|
812
812
|
};
|
|
813
813
|
ApiError: {
|
|
814
814
|
/** @enum {string} */
|
|
815
|
-
code: "unauthenticated" | "forbidden_scope" | "approval_required" | "payment_required" | "quota_exceeded" | "rate_limited" | "suspended" | "invalid_request" | "invalid_manifest" | "not_found" | "conflict" | "not_available" | "plan_unavailable" | "source_too_large" | "build_failed" | "image_too_large" | "migration_failed" | "healthcheck_failed" | "app_crashed_on_start" | "deploy_timeout" | "capability_requires_plan" | "capability_unconfirmed" | "domain_unverified" | "cert_pending" | "db_quota_exceeded" | "internal";
|
|
815
|
+
code: "unauthenticated" | "forbidden_scope" | "approval_required" | "payment_required" | "quota_exceeded" | "rate_limited" | "terms_required" | "reauth_required" | "suspended" | "invalid_request" | "invalid_manifest" | "not_found" | "conflict" | "not_available" | "plan_unavailable" | "source_too_large" | "build_failed" | "image_too_large" | "migration_failed" | "healthcheck_failed" | "app_crashed_on_start" | "deploy_timeout" | "capability_requires_plan" | "capability_unconfirmed" | "domain_unverified" | "cert_pending" | "db_quota_exceeded" | "internal";
|
|
816
816
|
/** @description What went wrong, for a human. */
|
|
817
817
|
message: string;
|
|
818
818
|
/** @description True if the same call may succeed later unchanged. */
|
|
@@ -928,7 +928,7 @@ export interface components {
|
|
|
928
928
|
/** @enum {string} */
|
|
929
929
|
result: "succeeded" | "failed";
|
|
930
930
|
/** @enum {string} */
|
|
931
|
-
error_code?: "unauthenticated" | "forbidden_scope" | "approval_required" | "payment_required" | "quota_exceeded" | "rate_limited" | "suspended" | "invalid_request" | "invalid_manifest" | "not_found" | "conflict" | "not_available" | "plan_unavailable" | "source_too_large" | "build_failed" | "image_too_large" | "migration_failed" | "healthcheck_failed" | "app_crashed_on_start" | "deploy_timeout" | "capability_requires_plan" | "capability_unconfirmed" | "domain_unverified" | "cert_pending" | "db_quota_exceeded" | "internal";
|
|
931
|
+
error_code?: "unauthenticated" | "forbidden_scope" | "approval_required" | "payment_required" | "quota_exceeded" | "rate_limited" | "terms_required" | "reauth_required" | "suspended" | "invalid_request" | "invalid_manifest" | "not_found" | "conflict" | "not_available" | "plan_unavailable" | "source_too_large" | "build_failed" | "image_too_large" | "migration_failed" | "healthcheck_failed" | "app_crashed_on_start" | "deploy_timeout" | "capability_requires_plan" | "capability_unconfirmed" | "domain_unverified" | "cert_pending" | "db_quota_exceeded" | "internal";
|
|
932
932
|
request_id: string;
|
|
933
933
|
ip?: string;
|
|
934
934
|
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type LilboxClient, type LilboxClientOptions } from "../index.js";
|
|
2
|
+
import type { AuthResult, AuthUser, DashboardSession, MagicLinkVerifyResponse, SessionEndReason, SessionLock, SessionStore, TokenPair } from "./types.js";
|
|
3
|
+
/** The /auth/* paths (docs/frontend/05; AUTH_PATHS in @lilbox/contracts). */
|
|
4
|
+
export declare const AUTH_PATHS: {
|
|
5
|
+
readonly magicLink: "/auth/magic-link";
|
|
6
|
+
readonly verifyMagicLink: "/auth/magic-link/verify";
|
|
7
|
+
readonly exchangeCode: "/auth/token";
|
|
8
|
+
readonly refresh: "/auth/refresh";
|
|
9
|
+
readonly logout: "/auth/logout";
|
|
10
|
+
readonly sessions: "/auth/sessions";
|
|
11
|
+
};
|
|
12
|
+
export interface DashboardClientOptions extends Omit<LilboxClientOptions, "token"> {
|
|
13
|
+
/** Where the session lives: browserSessionStore() in the dashboard. */
|
|
14
|
+
store: SessionStore;
|
|
15
|
+
/** Default: webLock() when the browser has navigator.locks, inTabLock() otherwise. */
|
|
16
|
+
lock?: SessionLock;
|
|
17
|
+
/**
|
|
18
|
+
* The session is over: a refresh was refused (session_expired, token_reused) or another tab signed out. The
|
|
19
|
+
* store is already cleared. Send the person to sign in. Not called for this tab's own signOut().
|
|
20
|
+
*/
|
|
21
|
+
onSessionEnded?: (reason: SessionEndReason) => void;
|
|
22
|
+
/** Refresh this many seconds before the access token expires. Default 60. */
|
|
23
|
+
refreshMarginSeconds?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface DashboardAuth {
|
|
26
|
+
/** Emails a sign-in link. Answers { data } whether or not the email has an account. */
|
|
27
|
+
requestMagicLink(email: string, returnTo?: string): Promise<AuthResult<void>>;
|
|
28
|
+
/** The Continue button on /signin/magic. Stores the session. */
|
|
29
|
+
verifyMagicLink(token: string): Promise<AuthResult<MagicLinkVerifyResponse>>;
|
|
30
|
+
/** /signin/callback: swaps the one-time code from Google or GitHub. Stores the session. */
|
|
31
|
+
exchangeCode(code: string): Promise<AuthResult<TokenPair>>;
|
|
32
|
+
/** Where "Continue with Google / GitHub" navigates to (a full page navigation, not a fetch). */
|
|
33
|
+
signInUrl(provider: "google" | "github", options?: {
|
|
34
|
+
returnTo?: string;
|
|
35
|
+
prompt?: "login";
|
|
36
|
+
}): string;
|
|
37
|
+
/** Signs out this browser, or every browser. The store is cleared even if the call fails. */
|
|
38
|
+
signOut(options?: {
|
|
39
|
+
everywhere?: boolean;
|
|
40
|
+
}): Promise<void>;
|
|
41
|
+
listSessions(): Promise<AuthResult<DashboardSession[]>>;
|
|
42
|
+
revokeSession(id: string): Promise<AuthResult<void>>;
|
|
43
|
+
/** The signed-in user from the stored session, or null. No request. */
|
|
44
|
+
currentUser(): Promise<AuthUser | null>;
|
|
45
|
+
}
|
|
46
|
+
export type DashboardClient = LilboxClient & {
|
|
47
|
+
auth: DashboardAuth;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The lilbox client for the dashboard: the same typed /v1 client, but it owns the signed-in session. It sends the
|
|
51
|
+
* access token, refreshes it before it expires (one refresh at a time, across tabs with webLock()), refreshes
|
|
52
|
+
* and retries once on a 401, and ends the session cleanly when a refresh is refused. Page code only sees a 401
|
|
53
|
+
* when the person has to sign in again.
|
|
54
|
+
*
|
|
55
|
+
* const lilbox = createDashboardClient({ store: browserSessionStore(), onSessionEnded: () => goToSignIn() });
|
|
56
|
+
*/
|
|
57
|
+
export declare function createDashboardClient(options: DashboardClientOptions): DashboardClient;
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { createLilboxClient, DEFAULT_BASE_URL } from "../index.js";
|
|
2
|
+
import { defaultLock } from "./locks.js";
|
|
3
|
+
/** The /auth/* paths (docs/frontend/05; AUTH_PATHS in @lilbox/contracts). */
|
|
4
|
+
export const AUTH_PATHS = {
|
|
5
|
+
magicLink: "/auth/magic-link",
|
|
6
|
+
verifyMagicLink: "/auth/magic-link/verify",
|
|
7
|
+
exchangeCode: "/auth/token",
|
|
8
|
+
refresh: "/auth/refresh",
|
|
9
|
+
logout: "/auth/logout",
|
|
10
|
+
sessions: "/auth/sessions",
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The lilbox client for the dashboard: the same typed /v1 client, but it owns the signed-in session. It sends the
|
|
14
|
+
* access token, refreshes it before it expires (one refresh at a time, across tabs with webLock()), refreshes
|
|
15
|
+
* and retries once on a 401, and ends the session cleanly when a refresh is refused. Page code only sees a 401
|
|
16
|
+
* when the person has to sign in again.
|
|
17
|
+
*
|
|
18
|
+
* const lilbox = createDashboardClient({ store: browserSessionStore(), onSessionEnded: () => goToSignIn() });
|
|
19
|
+
*/
|
|
20
|
+
export function createDashboardClient(options) {
|
|
21
|
+
const { store, lock = defaultLock(), onSessionEnded, refreshMarginSeconds = 60, ...clientOptions } = options;
|
|
22
|
+
const baseUrl = (clientOptions.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
23
|
+
const baseFetch = clientOptions.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
24
|
+
const expiring = (s) => s.access_expires_at - Date.now() <= refreshMarginSeconds * 1000;
|
|
25
|
+
// Several requests in this tab that need a refresh share one.
|
|
26
|
+
let inFlight = null;
|
|
27
|
+
/**
|
|
28
|
+
* A valid session, refreshed if needed, or null if it's over. With `stale`, the access token the server just
|
|
29
|
+
* refused: refresh unless another refresh already replaced it.
|
|
30
|
+
*/
|
|
31
|
+
function refresh(stale) {
|
|
32
|
+
inFlight ??= lock
|
|
33
|
+
.run(async () => {
|
|
34
|
+
// Another tab may have refreshed while we waited for the lock: use its result.
|
|
35
|
+
const current = await store.read();
|
|
36
|
+
if (!current)
|
|
37
|
+
return null;
|
|
38
|
+
const replaced = stale !== undefined ? current.access_token !== stale : !expiring(current);
|
|
39
|
+
if (replaced)
|
|
40
|
+
return current;
|
|
41
|
+
const res = await baseFetch(jsonRequest(`${baseUrl}${AUTH_PATHS.refresh}`, "POST", { refresh_token: current.refresh_token }));
|
|
42
|
+
if (res.ok) {
|
|
43
|
+
const next = toStored((await res.json()));
|
|
44
|
+
await store.write(next);
|
|
45
|
+
return next;
|
|
46
|
+
}
|
|
47
|
+
if (res.status === 401) {
|
|
48
|
+
const code = errorCode(await readJson(res));
|
|
49
|
+
await store.clear();
|
|
50
|
+
onSessionEnded?.(code === "token_reused" ? "token_reused" : "session_expired");
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
// A server or network problem isn't the end of the session: keep it, let this request fail.
|
|
54
|
+
throw new Error(`lilbox: refreshing the session failed with HTTP ${res.status}`);
|
|
55
|
+
})
|
|
56
|
+
.finally(() => {
|
|
57
|
+
inFlight = null;
|
|
58
|
+
});
|
|
59
|
+
return inFlight;
|
|
60
|
+
}
|
|
61
|
+
/** fetch with the session: the token, refreshed ahead of expiry, one retry on a 401. */
|
|
62
|
+
async function sessionFetch(input, init) {
|
|
63
|
+
const request = new Request(input, init);
|
|
64
|
+
const retry = request.clone();
|
|
65
|
+
let session = await store.read();
|
|
66
|
+
if (session && expiring(session))
|
|
67
|
+
session = await refresh();
|
|
68
|
+
if (session)
|
|
69
|
+
request.headers.set("Authorization", `Bearer ${session.access_token}`);
|
|
70
|
+
const response = await baseFetch(request);
|
|
71
|
+
if (response.status !== 401 || !session)
|
|
72
|
+
return response;
|
|
73
|
+
// The token was refused (expired early, clock skew…). A 401 comes from the guard, before any handler
|
|
74
|
+
// runs, so retrying is safe even for a POST.
|
|
75
|
+
const fresh = await refresh(session.access_token);
|
|
76
|
+
if (!fresh)
|
|
77
|
+
return response;
|
|
78
|
+
retry.headers.set("Authorization", `Bearer ${fresh.access_token}`);
|
|
79
|
+
return baseFetch(retry);
|
|
80
|
+
}
|
|
81
|
+
async function callAuth(path, method, body, withSession = false) {
|
|
82
|
+
const request = jsonRequest(`${baseUrl}${path}`, method, body);
|
|
83
|
+
const res = await (withSession ? sessionFetch(request) : baseFetch(request));
|
|
84
|
+
const payload = await readJson(res);
|
|
85
|
+
if (!res.ok)
|
|
86
|
+
return { error: toAuthError(payload, res.status) };
|
|
87
|
+
return { data: payload };
|
|
88
|
+
}
|
|
89
|
+
const auth = {
|
|
90
|
+
async requestMagicLink(email, returnTo) {
|
|
91
|
+
const result = await callAuth(AUTH_PATHS.magicLink, "POST", { email, return_to: returnTo });
|
|
92
|
+
return result.error ? result : { data: undefined };
|
|
93
|
+
},
|
|
94
|
+
async verifyMagicLink(token) {
|
|
95
|
+
const result = await callAuth(AUTH_PATHS.verifyMagicLink, "POST", { token });
|
|
96
|
+
if (result.data)
|
|
97
|
+
await store.write(toStored(result.data));
|
|
98
|
+
return result;
|
|
99
|
+
},
|
|
100
|
+
async exchangeCode(code) {
|
|
101
|
+
const result = await callAuth(AUTH_PATHS.exchangeCode, "POST", { code });
|
|
102
|
+
if (result.data)
|
|
103
|
+
await store.write(toStored(result.data));
|
|
104
|
+
return result;
|
|
105
|
+
},
|
|
106
|
+
signInUrl(provider, opts = {}) {
|
|
107
|
+
const url = new URL(`${baseUrl}/auth/${provider}`);
|
|
108
|
+
if (opts.returnTo)
|
|
109
|
+
url.searchParams.set("return_to", opts.returnTo);
|
|
110
|
+
if (opts.prompt)
|
|
111
|
+
url.searchParams.set("prompt", opts.prompt);
|
|
112
|
+
return url.toString();
|
|
113
|
+
},
|
|
114
|
+
async signOut(opts = {}) {
|
|
115
|
+
try {
|
|
116
|
+
const session = await store.read();
|
|
117
|
+
if (session) {
|
|
118
|
+
await callAuth(AUTH_PATHS.logout, "POST", { refresh_token: session.refresh_token, everywhere: opts.everywhere }, true);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
await store.clear();
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
async listSessions() {
|
|
126
|
+
const result = await callAuth(AUTH_PATHS.sessions, "GET", undefined, true);
|
|
127
|
+
return result.error ? result : { data: result.data.sessions };
|
|
128
|
+
},
|
|
129
|
+
async revokeSession(id) {
|
|
130
|
+
const result = await callAuth(`${AUTH_PATHS.sessions}/${encodeURIComponent(id)}`, "DELETE", undefined, true);
|
|
131
|
+
return result.error ? result : { data: undefined };
|
|
132
|
+
},
|
|
133
|
+
async currentUser() {
|
|
134
|
+
return (await store.read())?.user ?? null;
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
// A sign-out (or a refused refresh) in another tab clears the shared store: end this tab's session too.
|
|
138
|
+
store.subscribe?.((session) => {
|
|
139
|
+
if (session === null)
|
|
140
|
+
onSessionEnded?.("signed_out_elsewhere");
|
|
141
|
+
});
|
|
142
|
+
const client = createLilboxClient({ ...clientOptions, fetch: sessionFetch });
|
|
143
|
+
return Object.assign(client, { auth });
|
|
144
|
+
}
|
|
145
|
+
const toStored = (pair) => ({
|
|
146
|
+
access_token: pair.access_token,
|
|
147
|
+
refresh_token: pair.refresh_token,
|
|
148
|
+
access_expires_at: Date.now() + pair.expires_in * 1000,
|
|
149
|
+
user: pair.user,
|
|
150
|
+
});
|
|
151
|
+
function jsonRequest(url, method, body) {
|
|
152
|
+
return new Request(url, {
|
|
153
|
+
method,
|
|
154
|
+
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
|
155
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
async function readJson(res) {
|
|
159
|
+
const text = await res.text();
|
|
160
|
+
if (!text)
|
|
161
|
+
return undefined;
|
|
162
|
+
try {
|
|
163
|
+
return JSON.parse(text);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function errorCode(payload) {
|
|
170
|
+
if (typeof payload !== "object" || payload === null || !("error" in payload))
|
|
171
|
+
return undefined;
|
|
172
|
+
const error = payload.error;
|
|
173
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
174
|
+
? error.code
|
|
175
|
+
: undefined;
|
|
176
|
+
}
|
|
177
|
+
function toAuthError(payload, status) {
|
|
178
|
+
if (errorCode(payload))
|
|
179
|
+
return payload;
|
|
180
|
+
return { error: { code: "internal", message: `HTTP ${status}`, retryable: status >= 500 } };
|
|
181
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { AUTH_PATHS, createDashboardClient, type DashboardAuth, type DashboardClient, type DashboardClientOptions, } from "./dashboard-client.js";
|
|
2
|
+
export { browserSessionStore, type BrowserSessionStoreOptions } from "./store.js";
|
|
3
|
+
export { defaultLock, inTabLock, webLock } from "./locks.js";
|
|
4
|
+
export type * from "./types.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @lilbox/client/session: the lilbox client for the dashboard, which owns the signed-in session (sign-in,
|
|
2
|
+
// refresh, sign-out). Scripts, CI and agents with an API key or an OAuth token use @lilbox/client instead.
|
|
3
|
+
//
|
|
4
|
+
// import { browserSessionStore, createDashboardClient } from "@lilbox/client/session";
|
|
5
|
+
//
|
|
6
|
+
// const lilbox = createDashboardClient({ store: browserSessionStore(), onSessionEnded: () => goToSignIn() });
|
|
7
|
+
// await lilbox.auth.verifyMagicLink(token);
|
|
8
|
+
// const { data } = await lilbox.GET("/v1/apps");
|
|
9
|
+
export { AUTH_PATHS, createDashboardClient, } from "./dashboard-client.js";
|
|
10
|
+
export { browserSessionStore } from "./store.js";
|
|
11
|
+
export { defaultLock, inTabLock, webLock } from "./locks.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SessionLock } from "./types.js";
|
|
2
|
+
/** One refresh at a time within this tab (or process). Enough for scripts and the CLI. */
|
|
3
|
+
export declare function inTabLock(): SessionLock;
|
|
4
|
+
/**
|
|
5
|
+
* One refresh at a time across every tab of the dashboard, with the Web Locks API (navigator.locks). Refresh
|
|
6
|
+
* tokens are single use, so two tabs refreshing with the same one would end the session (token_reused).
|
|
7
|
+
* Throws if the browser has no navigator.locks; createDashboardClient falls back to inTabLock() by itself.
|
|
8
|
+
*/
|
|
9
|
+
export declare function webLock(name?: string): SessionLock;
|
|
10
|
+
/** webLock() where the browser supports it, inTabLock() otherwise. */
|
|
11
|
+
export declare function defaultLock(): SessionLock;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** One refresh at a time within this tab (or process). Enough for scripts and the CLI. */
|
|
2
|
+
export function inTabLock() {
|
|
3
|
+
let tail = Promise.resolve();
|
|
4
|
+
return {
|
|
5
|
+
run(fn) {
|
|
6
|
+
const result = tail.then(fn, fn);
|
|
7
|
+
tail = result.catch(() => undefined);
|
|
8
|
+
return result;
|
|
9
|
+
},
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* One refresh at a time across every tab of the dashboard, with the Web Locks API (navigator.locks). Refresh
|
|
14
|
+
* tokens are single use, so two tabs refreshing with the same one would end the session (token_reused).
|
|
15
|
+
* Throws if the browser has no navigator.locks; createDashboardClient falls back to inTabLock() by itself.
|
|
16
|
+
*/
|
|
17
|
+
export function webLock(name = "lilbox-session-refresh") {
|
|
18
|
+
const locks = typeof navigator === "undefined" ? undefined : navigator.locks;
|
|
19
|
+
if (!locks)
|
|
20
|
+
throw new Error("webLock(): navigator.locks isn't available here; use inTabLock()");
|
|
21
|
+
return {
|
|
22
|
+
run(fn) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
// The lock is held until the callback's promise settles; the result is passed out through ours.
|
|
25
|
+
locks.request(name, () => fn().then(resolve, reject)).catch(reject);
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** webLock() where the browser supports it, inTabLock() otherwise. */
|
|
31
|
+
export function defaultLock() {
|
|
32
|
+
return typeof navigator !== "undefined" && navigator.locks ? webLock() : inTabLock();
|
|
33
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SessionStore } from "./types.js";
|
|
2
|
+
export interface BrowserSessionStoreOptions {
|
|
3
|
+
/** Default localStorage, shared by every tab. sessionStorage ends the session when the tab closes. */
|
|
4
|
+
storage?: Storage;
|
|
5
|
+
/** Default "lilbox.session". */
|
|
6
|
+
key?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The dashboard's session store: the session as JSON in localStorage. subscribe() reports changes made in other
|
|
10
|
+
* tabs (the browser's storage event), so a sign-out in one tab reaches the others.
|
|
11
|
+
*/
|
|
12
|
+
export declare function browserSessionStore(options?: BrowserSessionStoreOptions): SessionStore;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dashboard's session store: the session as JSON in localStorage. subscribe() reports changes made in other
|
|
3
|
+
* tabs (the browser's storage event), so a sign-out in one tab reaches the others.
|
|
4
|
+
*/
|
|
5
|
+
export function browserSessionStore(options = {}) {
|
|
6
|
+
const storage = options.storage ?? globalThis.localStorage;
|
|
7
|
+
const key = options.key ?? "lilbox.session";
|
|
8
|
+
return {
|
|
9
|
+
read: () => parse(storage.getItem(key)),
|
|
10
|
+
write: (session) => storage.setItem(key, JSON.stringify(session)),
|
|
11
|
+
clear: () => storage.removeItem(key),
|
|
12
|
+
subscribe(listener) {
|
|
13
|
+
if (typeof globalThis.addEventListener !== "function")
|
|
14
|
+
return () => undefined;
|
|
15
|
+
const onStorage = (event) => {
|
|
16
|
+
if (event.key === key || event.key === null)
|
|
17
|
+
listener(parse(event.newValue));
|
|
18
|
+
};
|
|
19
|
+
globalThis.addEventListener("storage", onStorage);
|
|
20
|
+
return () => globalThis.removeEventListener("storage", onStorage);
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The stored session, or null for anything missing or malformed. */
|
|
25
|
+
function parse(value) {
|
|
26
|
+
if (!value)
|
|
27
|
+
return null;
|
|
28
|
+
try {
|
|
29
|
+
const s = JSON.parse(value);
|
|
30
|
+
if (typeof s === "object" && s !== null &&
|
|
31
|
+
"access_token" in s && typeof s.access_token === "string" &&
|
|
32
|
+
"refresh_token" in s && typeof s.refresh_token === "string" &&
|
|
33
|
+
"access_expires_at" in s && typeof s.access_expires_at === "number" &&
|
|
34
|
+
"user" in s && typeof s.user === "object" && s.user !== null) {
|
|
35
|
+
return s;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// fall through
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export interface AuthUser {
|
|
2
|
+
id: string;
|
|
3
|
+
email: string;
|
|
4
|
+
name: string | null;
|
|
5
|
+
terms_accepted: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface TokenPair {
|
|
8
|
+
access_token: string;
|
|
9
|
+
refresh_token: string;
|
|
10
|
+
expires_in: number;
|
|
11
|
+
user: AuthUser;
|
|
12
|
+
}
|
|
13
|
+
export interface MagicLinkVerifyResponse extends TokenPair {
|
|
14
|
+
return_to: string;
|
|
15
|
+
}
|
|
16
|
+
export interface DashboardSession {
|
|
17
|
+
id: string;
|
|
18
|
+
current: boolean;
|
|
19
|
+
browser: string;
|
|
20
|
+
os: string;
|
|
21
|
+
created_at: string;
|
|
22
|
+
last_active_at: string;
|
|
23
|
+
}
|
|
24
|
+
/** The error body of an /auth/* call: the API's error shape, with the /auth codes (invalid_token, …) too. */
|
|
25
|
+
export interface AuthErrorResponse {
|
|
26
|
+
error: {
|
|
27
|
+
code: string;
|
|
28
|
+
message: string;
|
|
29
|
+
retryable: boolean;
|
|
30
|
+
suggestion?: string;
|
|
31
|
+
request_id?: string;
|
|
32
|
+
details?: Record<string, unknown>;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Like the /v1 calls: `{ data }` or `{ error }`, never a throw for an API error. Network failures still throw. */
|
|
36
|
+
export type AuthResult<T> = {
|
|
37
|
+
data: T;
|
|
38
|
+
error?: undefined;
|
|
39
|
+
} | {
|
|
40
|
+
data?: undefined;
|
|
41
|
+
error: AuthErrorResponse;
|
|
42
|
+
};
|
|
43
|
+
/** What the store keeps: the pair, with the access token's expiry as a time instead of a duration. */
|
|
44
|
+
export interface StoredSession {
|
|
45
|
+
access_token: string;
|
|
46
|
+
refresh_token: string;
|
|
47
|
+
/** When the access token expires, in milliseconds since the epoch. */
|
|
48
|
+
access_expires_at: number;
|
|
49
|
+
user: AuthUser;
|
|
50
|
+
}
|
|
51
|
+
/** Where the session lives. browserSessionStore() is the dashboard's; anything with these methods works. */
|
|
52
|
+
export interface SessionStore {
|
|
53
|
+
read(): StoredSession | null | Promise<StoredSession | null>;
|
|
54
|
+
write(session: StoredSession): void | Promise<void>;
|
|
55
|
+
clear(): void | Promise<void>;
|
|
56
|
+
/** Called when another tab (or process) changes the session; returns an unsubscribe function. */
|
|
57
|
+
subscribe?(listener: (session: StoredSession | null) => void): () => void;
|
|
58
|
+
}
|
|
59
|
+
/** Makes refreshes run one at a time. webLock() (across tabs) and inTabLock() ship with the client. */
|
|
60
|
+
export interface SessionLock {
|
|
61
|
+
run<T>(fn: () => Promise<T>): Promise<T>;
|
|
62
|
+
}
|
|
63
|
+
/** Why a session ended, for onSessionEnded. */
|
|
64
|
+
export type SessionEndReason = "session_expired" | "token_reused" | "signed_out_elsewhere";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lilbox/client",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"description": "Typed HTTP client for the lilbox API, generated from @lilbox/contracts' OpenAPI document.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
".": {
|
|
14
14
|
"types": "./dist/index.d.ts",
|
|
15
15
|
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./session": {
|
|
18
|
+
"types": "./dist/session/index.d.ts",
|
|
19
|
+
"default": "./dist/session/index.js"
|
|
16
20
|
}
|
|
17
21
|
},
|
|
18
22
|
"files": [
|