@zjazj/web 0.0.1 → 0.0.2
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 +18 -1
- package/dist/index.d.ts +95 -6
- package/dist/index.js +401 -65
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -16,6 +16,23 @@ import type { AppType } from '../service/server'
|
|
|
16
16
|
export const api = createClient<AppType>()
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
## Sign-in
|
|
20
|
+
|
|
21
|
+
An app writes no sign-in code and serves no sign-in address. With `ENV=dev` the page runs
|
|
22
|
+
with the local dev identity. Otherwise `createApp` signs in at the platform's identity
|
|
23
|
+
provider, a Logto that serves two addresses on the platform's own origin:
|
|
24
|
+
|
|
25
|
+
1. The settings come from `/auth/config`: the identity provider's address and the one
|
|
26
|
+
client id every app on the origin shares.
|
|
27
|
+
2. A visitor who is not signed in is sent to the identity provider. The redirect address is
|
|
28
|
+
always `<origin>/auth/callback`.
|
|
29
|
+
3. That page completes the sign-in and returns to the address the visitor came from. Tokens
|
|
30
|
+
are in browser storage, so every app on the origin is signed in at once.
|
|
31
|
+
4. API calls carry the organization token of the current tenant, replaced before it expires.
|
|
32
|
+
|
|
33
|
+
A route with `staticData: { public: true }` opens without a user.
|
|
34
|
+
|
|
35
|
+
At an address where nothing serves `/auth/config`, the page says that sign-in is not set
|
|
36
|
+
up.
|
|
20
37
|
|
|
21
38
|
Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
|
package/dist/index.d.ts
CHANGED
|
@@ -27,6 +27,11 @@ interface RouteMeta {
|
|
|
27
27
|
permission?: string | string[];
|
|
28
28
|
/** `none` renders the route without the sidebar and header. */
|
|
29
29
|
layout?: 'app' | 'none';
|
|
30
|
+
/**
|
|
31
|
+
* `true` opens the route with nobody signed in. Without a user it renders bare, and no
|
|
32
|
+
* sign-in is started. Every other route requires a signed-in user.
|
|
33
|
+
*/
|
|
34
|
+
public?: boolean;
|
|
30
35
|
}
|
|
31
36
|
interface MenuItem extends MenuMeta {
|
|
32
37
|
to: string;
|
|
@@ -65,15 +70,32 @@ interface CurrentUser {
|
|
|
65
70
|
timeZone?: string;
|
|
66
71
|
isDev?: boolean;
|
|
67
72
|
}
|
|
73
|
+
/** Where the session stands. The shell picks its screen from `state`. */
|
|
74
|
+
interface SessionStatus {
|
|
75
|
+
/**
|
|
76
|
+
* - `loading`: the stored sign-in is being read.
|
|
77
|
+
* - `ready`: a user is signed in.
|
|
78
|
+
* - `signed-out`: nobody is signed in. A page that needs a user starts the sign-in.
|
|
79
|
+
* - `ended`: the user was signed in on this page and no longer is.
|
|
80
|
+
* - `error`: sign-in cannot work here. `code` says why.
|
|
81
|
+
*/
|
|
82
|
+
state: 'loading' | 'ready' | 'signed-out' | 'ended' | 'error';
|
|
83
|
+
/** With `error`: `not_configured`, `no_organization`, `no_tenant` or `sign_in_failed`. */
|
|
84
|
+
code?: string;
|
|
85
|
+
message?: string;
|
|
86
|
+
}
|
|
68
87
|
interface Session {
|
|
69
|
-
/** `dev` for the local dev identity, `
|
|
88
|
+
/** `dev` for the local dev identity, `platform` for sign-in at the identity provider. */
|
|
70
89
|
readonly kind: string;
|
|
71
90
|
getUser(): CurrentUser | null;
|
|
91
|
+
/** The same object until the state changes, so it can back `useSyncExternalStore`. */
|
|
92
|
+
getStatus(): SessionStatus;
|
|
72
93
|
/** The bearer token for API calls, refreshed when needed. */
|
|
73
94
|
getAccessToken(): Promise<string | null>;
|
|
95
|
+
/** Send the browser to the sign-in page. It comes back to the current location. */
|
|
74
96
|
signIn(): Promise<void>;
|
|
75
97
|
signOut(): Promise<void>;
|
|
76
|
-
/** Called whenever the user changes. Returns the unsubscribe function. */
|
|
98
|
+
/** Called whenever the user or the status changes. Returns the unsubscribe function. */
|
|
77
99
|
subscribe(listener: () => void): () => void;
|
|
78
100
|
}
|
|
79
101
|
interface DevSession extends Session {
|
|
@@ -87,7 +109,10 @@ interface DevSession extends Session {
|
|
|
87
109
|
declare function encodeDevToken(user: CurrentUser): string;
|
|
88
110
|
/** The session used in local development. No request to the identity provider is made. */
|
|
89
111
|
declare function createDevSession(base: CurrentUser): DevSession;
|
|
90
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* The session of this page. Created on first use: the dev identity when the dev server
|
|
114
|
+
* provided one, sign-in at the platform's identity provider otherwise.
|
|
115
|
+
*/
|
|
91
116
|
declare function getSession(): Session;
|
|
92
117
|
/** Replace the session. Meant for tests and for custom sign-in implementations. */
|
|
93
118
|
declare function setSession(session: Session | undefined): void;
|
|
@@ -147,6 +172,59 @@ interface CreateAppOptions<TRouteTree extends AnyRoute> {
|
|
|
147
172
|
*/
|
|
148
173
|
declare function createApp<TRouteTree extends AnyRoute>(options: CreateAppOptions<TRouteTree>): WebApp<TRouteTree>;
|
|
149
174
|
|
|
175
|
+
/** The sign-in settings every app on the origin reads. */
|
|
176
|
+
declare const AUTH_CONFIG_PATH = "/auth/config";
|
|
177
|
+
/**
|
|
178
|
+
* The one redirect address registered with the identity provider. Its page completes the
|
|
179
|
+
* sign-in and returns to the address stored under `RETURN_TO_KEY`.
|
|
180
|
+
*/
|
|
181
|
+
declare const AUTH_CALLBACK_PATH = "/auth/callback";
|
|
182
|
+
/**
|
|
183
|
+
* Session storage key of the address to return to after sign-in: a path on this origin. The
|
|
184
|
+
* callback page reads it, so the name is a contract with the identity provider's page.
|
|
185
|
+
*/
|
|
186
|
+
declare const RETURN_TO_KEY = "platform.auth.returnTo";
|
|
187
|
+
/** What `/auth/config` answers. */
|
|
188
|
+
interface AuthConfig {
|
|
189
|
+
/** Address of the identity provider, for example `https://auth.example.com`. */
|
|
190
|
+
endpoint: string;
|
|
191
|
+
/** The one client id that every app on the origin shares. */
|
|
192
|
+
appId: string;
|
|
193
|
+
/** API resource indicator, when the platform has one. */
|
|
194
|
+
resource?: string;
|
|
195
|
+
}
|
|
196
|
+
/** The claims of the identity token that the session reads. */
|
|
197
|
+
interface IdentityClaims {
|
|
198
|
+
organizations?: string[] | null;
|
|
199
|
+
username?: string | null;
|
|
200
|
+
name?: string | null;
|
|
201
|
+
email?: string | null;
|
|
202
|
+
}
|
|
203
|
+
/** The part of the Logto browser client that the session uses. Tests pass a stand-in. */
|
|
204
|
+
interface IdentityClient {
|
|
205
|
+
isAuthenticated(): Promise<boolean>;
|
|
206
|
+
signIn(redirectUri: string): Promise<void>;
|
|
207
|
+
getIdTokenClaims(): Promise<IdentityClaims>;
|
|
208
|
+
getOrganizationToken(organizationId: string): Promise<string>;
|
|
209
|
+
clearAccessToken(): Promise<void>;
|
|
210
|
+
signOut(postLogoutRedirectUri?: string): Promise<void>;
|
|
211
|
+
}
|
|
212
|
+
interface PlatformSessionOptions {
|
|
213
|
+
/** Reads the sign-in settings. Defaults to `GET /auth/config`. */
|
|
214
|
+
loadConfig?: () => Promise<AuthConfig>;
|
|
215
|
+
/** Builds the identity client. Defaults to the Logto browser client. */
|
|
216
|
+
createClient?: (config: AuthConfig) => IdentityClient | Promise<IdentityClient>;
|
|
217
|
+
/** The clock, in milliseconds. */
|
|
218
|
+
now?: () => number;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The session of a deployed app. It reads the sign-in settings, restores a sign-in that any
|
|
222
|
+
* app on the origin completed, and keeps the organization token of the current tenant
|
|
223
|
+
* fresh. With nobody signed in, `signIn()` goes to the identity provider. Its callback page
|
|
224
|
+
* completes the sign-in and comes back to the page that started it.
|
|
225
|
+
*/
|
|
226
|
+
declare function createPlatformSession(options?: PlatformSessionOptions): Session;
|
|
227
|
+
|
|
150
228
|
interface ErrorFields {
|
|
151
229
|
status: number;
|
|
152
230
|
code: string;
|
|
@@ -190,6 +268,8 @@ declare function PlatformProvider(props: PlatformContextValue & {
|
|
|
190
268
|
/** Name, id, title and base path of this app. */
|
|
191
269
|
declare function useAppConfig(): PlatformConfig;
|
|
192
270
|
declare function useSession(): Session;
|
|
271
|
+
/** Where the session stands: loading, ready, signed out, ended or failed. */
|
|
272
|
+
declare function useSessionStatus(): SessionStatus;
|
|
193
273
|
/** The signed-in user, or null before sign-in. Re-renders when the user changes. */
|
|
194
274
|
declare function useOptionalUser(): CurrentUser | null;
|
|
195
275
|
/** The signed-in user. Use it inside the app shell, which renders only when signed in. */
|
|
@@ -240,10 +320,19 @@ declare function permissionMatches(granted: ReadonlySet<string>, code: string):
|
|
|
240
320
|
declare function hasPermissions(granted: Iterable<string>, required: readonly string[]): boolean;
|
|
241
321
|
|
|
242
322
|
/**
|
|
243
|
-
* The current tenant of this browser
|
|
244
|
-
*
|
|
323
|
+
* The current tenant of this browser. One browser profile has one current tenant, and every
|
|
324
|
+
* tab of every app reads the same value. Only the portal changes it.
|
|
245
325
|
*/
|
|
246
326
|
declare const TENANT_STORAGE_KEY = "platform.tenant";
|
|
327
|
+
/** What is stored: the tenant, and the organization its tokens are issued for. */
|
|
328
|
+
interface StoredTenant {
|
|
329
|
+
/** The identity provider's organization id. Tokens are requested for it. */
|
|
330
|
+
organizationId: string;
|
|
331
|
+
/** The tenant's UUID, as the organization token carries it. */
|
|
332
|
+
tenantId: string;
|
|
333
|
+
}
|
|
334
|
+
/** The stored current tenant, or undefined when none is stored or storage is closed. */
|
|
335
|
+
declare function readStoredTenant(): StoredTenant | undefined;
|
|
247
336
|
/**
|
|
248
337
|
* Remember the tenant this tab works in. A tab keeps its tenant for its whole life, so it
|
|
249
338
|
* can never show one tenant's data and write to another.
|
|
@@ -253,4 +342,4 @@ declare function getPinnedTenant(): string | undefined;
|
|
|
253
342
|
/** True once another tab switched tenant. The tab must reload before it sends anything. */
|
|
254
343
|
declare function isTenantChanged(): boolean;
|
|
255
344
|
|
|
256
|
-
export { type ApiClient, ApiError, AppShell, Can, type CanProps, type CreateAppOptions, type CurrentUser, type DevSession, ErrorScreen, Forbidden, type MenuGroup, type MenuItem, type MenuMeta, NotFound, type PlatformConfig, PlatformProvider, type RouteMeta, type Session, TENANT_STORAGE_KEY, type Tenant, type WebApp, apiBaseUrl, buildMenu, createApp, createClient, createDevSession, encodeDevToken, getPinnedTenant, getPlatformConfig, getSession, hasPermissions, isTenantChanged, permissionMatches, pinTenant, platformFetch, setSession, useAppConfig, useCan, useOptionalUser, useSession, useTenant, useUser };
|
|
345
|
+
export { AUTH_CALLBACK_PATH, AUTH_CONFIG_PATH, type ApiClient, ApiError, AppShell, type AuthConfig, Can, type CanProps, type CreateAppOptions, type CurrentUser, type DevSession, ErrorScreen, Forbidden, type IdentityClaims, type IdentityClient, type MenuGroup, type MenuItem, type MenuMeta, NotFound, type PlatformConfig, PlatformProvider, type PlatformSessionOptions, RETURN_TO_KEY, type RouteMeta, type Session, type SessionStatus, type StoredTenant, TENANT_STORAGE_KEY, type Tenant, type WebApp, apiBaseUrl, buildMenu, createApp, createClient, createDevSession, createPlatformSession, encodeDevToken, getPinnedTenant, getPlatformConfig, getSession, hasPermissions, isTenantChanged, permissionMatches, pinTenant, platformFetch, readStoredTenant, setSession, useAppConfig, useCan, useOptionalUser, useSession, useSessionStatus, useTenant, useUser };
|
package/dist/index.js
CHANGED
|
@@ -23,8 +23,17 @@ var en_US_default = {
|
|
|
23
23
|
tenantChangedBody: "You switched tenant in another tab. Reload this page to continue.",
|
|
24
24
|
reload: "Reload",
|
|
25
25
|
backToApps: "Back to Apps",
|
|
26
|
+
signIn: "Sign in",
|
|
27
|
+
signingInTitle: "Signing in",
|
|
28
|
+
signingInBody: "One moment.",
|
|
29
|
+
signedOutTitle: "You are signed out",
|
|
30
|
+
signedOutBody: "Sign in again to continue.",
|
|
26
31
|
signInRequiredTitle: "Sign-in is not available",
|
|
27
|
-
signInRequiredBody: "
|
|
32
|
+
signInRequiredBody: "Sign-in is not set up at this address. For local development, start the app with ENV=dev.",
|
|
33
|
+
signInFailedTitle: "Sign-in failed",
|
|
34
|
+
tryAgain: "Try again",
|
|
35
|
+
noTenantTitle: "No tenant",
|
|
36
|
+
noTenantBody: "Your account does not belong to a tenant yet. Ask an administrator to invite you.",
|
|
28
37
|
errorTitle: "Something went wrong",
|
|
29
38
|
traceId: "Trace id: {{id}}"
|
|
30
39
|
};
|
|
@@ -51,8 +60,17 @@ var zh_CN_default = {
|
|
|
51
60
|
tenantChangedBody: "\u4F60\u5728\u53E6\u4E00\u4E2A\u6807\u7B7E\u9875\u5207\u6362\u4E86\u79DF\u6237\u3002\u8BF7\u5237\u65B0\u672C\u9875\u540E\u7EE7\u7EED\u3002",
|
|
52
61
|
reload: "\u5237\u65B0",
|
|
53
62
|
backToApps: "\u8FD4\u56DE\u5E94\u7528\u5217\u8868",
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
signIn: "\u767B\u5F55",
|
|
64
|
+
signingInTitle: "\u6B63\u5728\u767B\u5F55",
|
|
65
|
+
signingInBody: "\u8BF7\u7A0D\u5019\u3002",
|
|
66
|
+
signedOutTitle: "\u4F60\u5DF2\u9000\u51FA\u767B\u5F55",
|
|
67
|
+
signedOutBody: "\u91CD\u65B0\u767B\u5F55\u540E\u7EE7\u7EED\u3002",
|
|
68
|
+
signInRequiredTitle: "\u65E0\u6CD5\u767B\u5F55",
|
|
69
|
+
signInRequiredBody: "\u8FD9\u4E2A\u5730\u5740\u6CA1\u6709\u914D\u7F6E\u767B\u5F55\u3002\u672C\u5730\u5F00\u53D1\u8BF7\u4EE5 ENV=dev \u542F\u52A8\u5E94\u7528\u3002",
|
|
70
|
+
signInFailedTitle: "\u767B\u5F55\u5931\u8D25",
|
|
71
|
+
tryAgain: "\u91CD\u8BD5",
|
|
72
|
+
noTenantTitle: "\u6CA1\u6709\u79DF\u6237",
|
|
73
|
+
noTenantBody: "\u4F60\u7684\u8D26\u53F7\u8FD8\u4E0D\u5C5E\u4E8E\u4EFB\u4F55\u79DF\u6237\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u9080\u8BF7\u4F60\u3002",
|
|
56
74
|
errorTitle: "\u51FA\u9519\u4E86",
|
|
57
75
|
traceId: "\u8FFD\u8E2A\u53F7\uFF1A{{id}}"
|
|
58
76
|
};
|
|
@@ -91,9 +109,347 @@ function apiBaseUrl(config = getPlatformConfig()) {
|
|
|
91
109
|
return `${origin}${config.basePath}api`;
|
|
92
110
|
}
|
|
93
111
|
|
|
112
|
+
// src/tenant.ts
|
|
113
|
+
var TENANT_STORAGE_KEY = "platform.tenant";
|
|
114
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
115
|
+
var pinned;
|
|
116
|
+
var changed = false;
|
|
117
|
+
function notify() {
|
|
118
|
+
for (const listener of listeners) listener();
|
|
119
|
+
}
|
|
120
|
+
function parseStoredTenant(raw) {
|
|
121
|
+
if (!raw) return void 0;
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(raw);
|
|
124
|
+
if (parsed && typeof parsed === "object") {
|
|
125
|
+
const { organizationId, tenantId } = parsed;
|
|
126
|
+
return {
|
|
127
|
+
...typeof organizationId === "string" && organizationId ? { organizationId } : {},
|
|
128
|
+
...typeof tenantId === "string" && tenantId ? { tenantId } : {}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
return { tenantId: raw };
|
|
134
|
+
}
|
|
135
|
+
function readStoredTenant() {
|
|
136
|
+
try {
|
|
137
|
+
const stored = parseStoredTenant(globalThis.localStorage?.getItem(TENANT_STORAGE_KEY));
|
|
138
|
+
return stored?.organizationId && stored.tenantId ? stored : void 0;
|
|
139
|
+
} catch {
|
|
140
|
+
return void 0;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function writeStoredTenant(value) {
|
|
144
|
+
const current = readStoredTenant();
|
|
145
|
+
if (current?.organizationId === value.organizationId && current.tenantId === value.tenantId) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
globalThis.localStorage?.setItem(TENANT_STORAGE_KEY, JSON.stringify(value));
|
|
150
|
+
} catch {
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function clearStoredTenant() {
|
|
154
|
+
try {
|
|
155
|
+
globalThis.localStorage?.removeItem(TENANT_STORAGE_KEY);
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function pinTenant(tenantId) {
|
|
160
|
+
pinned = tenantId;
|
|
161
|
+
if (changed) {
|
|
162
|
+
changed = false;
|
|
163
|
+
notify();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function getPinnedTenant() {
|
|
167
|
+
return pinned;
|
|
168
|
+
}
|
|
169
|
+
function isTenantChanged() {
|
|
170
|
+
return changed;
|
|
171
|
+
}
|
|
172
|
+
function subscribeTenant(listener) {
|
|
173
|
+
listeners.add(listener);
|
|
174
|
+
return () => {
|
|
175
|
+
listeners.delete(listener);
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function handleTenantStorage(newValue) {
|
|
179
|
+
const tenantId = parseStoredTenant(newValue)?.tenantId;
|
|
180
|
+
if (!pinned || !tenantId || tenantId === pinned || changed) return;
|
|
181
|
+
changed = true;
|
|
182
|
+
notify();
|
|
183
|
+
}
|
|
184
|
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
185
|
+
window.addEventListener("storage", (event) => {
|
|
186
|
+
if (event.key === TENANT_STORAGE_KEY) handleTenantStorage(event.newValue);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/auth.ts
|
|
191
|
+
var AUTH_CONFIG_PATH = "/auth/config";
|
|
192
|
+
var AUTH_CALLBACK_PATH = "/auth/callback";
|
|
193
|
+
var RETURN_TO_KEY = "platform.auth.returnTo";
|
|
194
|
+
var SESSION_CHANNEL = "platform.session";
|
|
195
|
+
var TOKEN_LOCK = "platform.auth.token";
|
|
196
|
+
var EXPIRY_LEEWAY_SECONDS = 60;
|
|
197
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
198
|
+
function strings(value) {
|
|
199
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
200
|
+
}
|
|
201
|
+
function firstString(...values) {
|
|
202
|
+
return values.find((value) => typeof value === "string" && value !== "");
|
|
203
|
+
}
|
|
204
|
+
function messageOf(error) {
|
|
205
|
+
return error instanceof Error ? error.message : String(error);
|
|
206
|
+
}
|
|
207
|
+
async function loadAuthConfig(fetcher = fetch) {
|
|
208
|
+
const response = await fetcher(AUTH_CONFIG_PATH, { headers: { Accept: "application/json" } });
|
|
209
|
+
if (!response.ok) throw new Error(`GET ${AUTH_CONFIG_PATH} answered ${response.status}`);
|
|
210
|
+
let body;
|
|
211
|
+
try {
|
|
212
|
+
body = await response.json();
|
|
213
|
+
} catch {
|
|
214
|
+
throw new Error(`GET ${AUTH_CONFIG_PATH} did not answer with JSON`);
|
|
215
|
+
}
|
|
216
|
+
const { endpoint, appId, resource } = body ?? {};
|
|
217
|
+
if (typeof endpoint !== "string" || !endpoint || typeof appId !== "string" || !appId) {
|
|
218
|
+
throw new Error(`GET ${AUTH_CONFIG_PATH} answered without an endpoint and a client id`);
|
|
219
|
+
}
|
|
220
|
+
return { endpoint, appId, ...typeof resource === "string" && resource ? { resource } : {} };
|
|
221
|
+
}
|
|
222
|
+
async function createLogtoClient(config) {
|
|
223
|
+
const { default: LogtoClient, UserScope } = await import("@logto/browser");
|
|
224
|
+
return new LogtoClient({
|
|
225
|
+
endpoint: config.endpoint,
|
|
226
|
+
appId: config.appId,
|
|
227
|
+
resources: config.resource ? [config.resource] : void 0,
|
|
228
|
+
scopes: [
|
|
229
|
+
UserScope.Email,
|
|
230
|
+
UserScope.Profile,
|
|
231
|
+
UserScope.Organizations,
|
|
232
|
+
UserScope.OrganizationRoles
|
|
233
|
+
]
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
function decodeTokenClaims(token) {
|
|
237
|
+
const part = token.split(".")[1];
|
|
238
|
+
if (!part) throw new Error("The token is not a JWT.");
|
|
239
|
+
const base64 = part.replaceAll("-", "+").replaceAll("_", "/");
|
|
240
|
+
const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
|
|
241
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
242
|
+
const claims = JSON.parse(new TextDecoder().decode(bytes));
|
|
243
|
+
if (!claims || typeof claims !== "object") throw new Error("The token has no claims.");
|
|
244
|
+
return claims;
|
|
245
|
+
}
|
|
246
|
+
function userFromTokenClaims(claims, profile = {}) {
|
|
247
|
+
const { sub, tenant_id: tenantId } = claims;
|
|
248
|
+
if (typeof sub !== "string" || sub === "") throw new Error("The token has no subject.");
|
|
249
|
+
if (typeof tenantId !== "string" || !UUID_PATTERN.test(tenantId)) {
|
|
250
|
+
throw new Error("The token has no tenant.");
|
|
251
|
+
}
|
|
252
|
+
const roles = strings(claims.organization_roles);
|
|
253
|
+
const timeZone = firstString(claims.tenant_time_zone);
|
|
254
|
+
return {
|
|
255
|
+
id: sub,
|
|
256
|
+
tenantId: tenantId.toLowerCase(),
|
|
257
|
+
tenantSlug: firstString(claims.tenant_slug, claims.organization_id) ?? "",
|
|
258
|
+
username: firstString(
|
|
259
|
+
claims.username,
|
|
260
|
+
claims.name,
|
|
261
|
+
claims.email,
|
|
262
|
+
profile.username,
|
|
263
|
+
profile.name,
|
|
264
|
+
profile.email
|
|
265
|
+
) ?? sub,
|
|
266
|
+
roles: roles.length > 0 ? roles : strings(claims.roles),
|
|
267
|
+
permissions: strings(claims.permissions),
|
|
268
|
+
...timeZone ? { timeZone } : {}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function rememberLocation() {
|
|
272
|
+
const { pathname, search, hash } = window.location;
|
|
273
|
+
try {
|
|
274
|
+
window.sessionStorage.setItem(RETURN_TO_KEY, `${pathname}${search}${hash}`);
|
|
275
|
+
} catch {
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function withTokenLock(task) {
|
|
279
|
+
const locks = globalThis.navigator?.locks;
|
|
280
|
+
return locks ? locks.request(TOKEN_LOCK, task) : task();
|
|
281
|
+
}
|
|
282
|
+
function createPlatformSession(options = {}) {
|
|
283
|
+
const loadConfig = options.loadConfig ?? (() => loadAuthConfig());
|
|
284
|
+
const createClient2 = options.createClient ?? createLogtoClient;
|
|
285
|
+
const now = options.now ?? Date.now;
|
|
286
|
+
const listeners2 = /* @__PURE__ */ new Set();
|
|
287
|
+
let status = { state: "loading" };
|
|
288
|
+
let user = null;
|
|
289
|
+
let profile = {};
|
|
290
|
+
let organizationId;
|
|
291
|
+
let token;
|
|
292
|
+
let connecting;
|
|
293
|
+
let refreshing;
|
|
294
|
+
let signingIn;
|
|
295
|
+
const update = (nextUser, nextStatus) => {
|
|
296
|
+
const userChanged = JSON.stringify(nextUser) !== JSON.stringify(user);
|
|
297
|
+
const statusChanged = nextStatus.state !== status.state || nextStatus.code !== status.code || nextStatus.message !== status.message;
|
|
298
|
+
if (userChanged) user = nextUser;
|
|
299
|
+
if (statusChanged) status = nextStatus;
|
|
300
|
+
if (userChanged || statusChanged) for (const listener of listeners2) listener();
|
|
301
|
+
};
|
|
302
|
+
const isReady = () => status.state === "ready";
|
|
303
|
+
const fail = (code, error) => {
|
|
304
|
+
token = void 0;
|
|
305
|
+
update(null, { state: "error", code, message: messageOf(error) });
|
|
306
|
+
};
|
|
307
|
+
const end = () => {
|
|
308
|
+
token = void 0;
|
|
309
|
+
update(null, { state: "ended" });
|
|
310
|
+
};
|
|
311
|
+
const connect = () => {
|
|
312
|
+
if (!connecting) {
|
|
313
|
+
const attempt = (async () => createClient2(await loadConfig()))();
|
|
314
|
+
connecting = attempt;
|
|
315
|
+
attempt.catch(() => {
|
|
316
|
+
if (connecting === attempt) connecting = void 0;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
return connecting;
|
|
320
|
+
};
|
|
321
|
+
const readToken = (value) => {
|
|
322
|
+
const claims = decodeTokenClaims(value);
|
|
323
|
+
const next = userFromTokenClaims(claims, profile);
|
|
324
|
+
token = { value, expiresAt: typeof claims.exp === "number" ? claims.exp : 0 };
|
|
325
|
+
return next;
|
|
326
|
+
};
|
|
327
|
+
const adopt = async (identity) => {
|
|
328
|
+
profile = await identity.getIdTokenClaims() ?? {};
|
|
329
|
+
const organizations = strings(profile.organizations);
|
|
330
|
+
const stored = readStoredTenant();
|
|
331
|
+
const organization = stored && organizations.includes(stored.organizationId) ? stored.organizationId : organizations[0];
|
|
332
|
+
if (!organization) {
|
|
333
|
+
fail("no_organization", "The account is not a member of any tenant.");
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const value = await identity.getOrganizationToken(organization);
|
|
337
|
+
let next;
|
|
338
|
+
try {
|
|
339
|
+
next = readToken(value);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
fail("no_tenant", error);
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
organizationId = organization;
|
|
345
|
+
writeStoredTenant({ organizationId: organization, tenantId: next.tenantId });
|
|
346
|
+
update(next, { state: "ready" });
|
|
347
|
+
};
|
|
348
|
+
const restore = async () => {
|
|
349
|
+
let identity;
|
|
350
|
+
try {
|
|
351
|
+
identity = await connect();
|
|
352
|
+
} catch (error) {
|
|
353
|
+
fail("not_configured", error);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
try {
|
|
357
|
+
if (await identity.isAuthenticated()) {
|
|
358
|
+
await adopt(identity);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
} catch {
|
|
362
|
+
}
|
|
363
|
+
update(null, { state: "signed-out" });
|
|
364
|
+
};
|
|
365
|
+
const started = restore();
|
|
366
|
+
const refresh = () => withTokenLock(async () => {
|
|
367
|
+
const current = token;
|
|
368
|
+
try {
|
|
369
|
+
const identity = await connect();
|
|
370
|
+
await identity.clearAccessToken();
|
|
371
|
+
const value = await identity.getOrganizationToken(organizationId);
|
|
372
|
+
update(readToken(value), { state: "ready" });
|
|
373
|
+
return value;
|
|
374
|
+
} catch {
|
|
375
|
+
if (current && current.expiresAt > now() / 1e3) {
|
|
376
|
+
token = current;
|
|
377
|
+
return current.value;
|
|
378
|
+
}
|
|
379
|
+
end();
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
const startSignIn = async () => {
|
|
384
|
+
let identity;
|
|
385
|
+
try {
|
|
386
|
+
identity = await connect();
|
|
387
|
+
} catch (error) {
|
|
388
|
+
fail("not_configured", error);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
if (!isReady() && await identity.isAuthenticated()) {
|
|
393
|
+
await adopt(identity);
|
|
394
|
+
if (isReady()) return;
|
|
395
|
+
}
|
|
396
|
+
} catch {
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
rememberLocation();
|
|
400
|
+
await identity.signIn(`${window.location.origin}${AUTH_CALLBACK_PATH}`);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
fail("sign_in_failed", error);
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel(SESSION_CHANNEL) : void 0;
|
|
406
|
+
channel?.addEventListener("message", (event) => {
|
|
407
|
+
const type = event.data?.type;
|
|
408
|
+
if (type === "signed-out" && isReady()) end();
|
|
409
|
+
});
|
|
410
|
+
channel?.unref?.();
|
|
411
|
+
return {
|
|
412
|
+
kind: "platform",
|
|
413
|
+
getUser: () => user,
|
|
414
|
+
getStatus: () => status,
|
|
415
|
+
async getAccessToken() {
|
|
416
|
+
await started;
|
|
417
|
+
if (!isReady() || !token) return null;
|
|
418
|
+
if (token.expiresAt - now() / 1e3 > EXPIRY_LEEWAY_SECONDS) return token.value;
|
|
419
|
+
refreshing ??= refresh().finally(() => {
|
|
420
|
+
refreshing = void 0;
|
|
421
|
+
});
|
|
422
|
+
return refreshing;
|
|
423
|
+
},
|
|
424
|
+
signIn() {
|
|
425
|
+
signingIn ??= started.then(startSignIn).finally(() => {
|
|
426
|
+
signingIn = void 0;
|
|
427
|
+
});
|
|
428
|
+
return signingIn;
|
|
429
|
+
},
|
|
430
|
+
async signOut() {
|
|
431
|
+
channel?.postMessage({ type: "signed-out" });
|
|
432
|
+
clearStoredTenant();
|
|
433
|
+
end();
|
|
434
|
+
try {
|
|
435
|
+
const identity = await connect();
|
|
436
|
+
await identity.signOut(window.location.origin);
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
},
|
|
440
|
+
subscribe(listener) {
|
|
441
|
+
listeners2.add(listener);
|
|
442
|
+
return () => {
|
|
443
|
+
listeners2.delete(listener);
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
94
449
|
// src/session.ts
|
|
95
450
|
var DEV_USER_STORAGE_KEY = "platform.dev.user";
|
|
96
451
|
var DEV_TOKEN_PREFIX = "dev.";
|
|
452
|
+
var READY = { state: "ready" };
|
|
97
453
|
function base64Url(value) {
|
|
98
454
|
const bytes = new TextEncoder().encode(value);
|
|
99
455
|
let binary = "";
|
|
@@ -130,6 +486,7 @@ function createDevSession(base) {
|
|
|
130
486
|
return {
|
|
131
487
|
kind: "dev",
|
|
132
488
|
getUser: () => current,
|
|
489
|
+
getStatus: () => READY,
|
|
133
490
|
getAccessToken: async () => encodeDevToken(current),
|
|
134
491
|
signIn: async () => {
|
|
135
492
|
},
|
|
@@ -144,27 +501,11 @@ function createDevSession(base) {
|
|
|
144
501
|
reset: () => update({})
|
|
145
502
|
};
|
|
146
503
|
}
|
|
147
|
-
function createUnavailableSession() {
|
|
148
|
-
return {
|
|
149
|
-
kind: "none",
|
|
150
|
-
getUser: () => null,
|
|
151
|
-
getAccessToken: async () => null,
|
|
152
|
-
signIn: async () => {
|
|
153
|
-
throw new Error(
|
|
154
|
-
"Sign-in is not available in this version of @zjazj/web. Run the app with ENV=dev."
|
|
155
|
-
);
|
|
156
|
-
},
|
|
157
|
-
signOut: async () => {
|
|
158
|
-
},
|
|
159
|
-
subscribe: () => () => {
|
|
160
|
-
}
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
504
|
var active;
|
|
164
505
|
function getSession() {
|
|
165
506
|
if (!active) {
|
|
166
507
|
const dev = getPlatformConfig().dev;
|
|
167
|
-
active = dev ? createDevSession(dev.user) :
|
|
508
|
+
active = dev ? createDevSession(dev.user) : createPlatformSession();
|
|
168
509
|
}
|
|
169
510
|
return active;
|
|
170
511
|
}
|
|
@@ -172,44 +513,6 @@ function setSession(session) {
|
|
|
172
513
|
active = session;
|
|
173
514
|
}
|
|
174
515
|
|
|
175
|
-
// src/tenant.ts
|
|
176
|
-
var TENANT_STORAGE_KEY = "platform.tenant";
|
|
177
|
-
var listeners = /* @__PURE__ */ new Set();
|
|
178
|
-
var pinned;
|
|
179
|
-
var changed = false;
|
|
180
|
-
function notify() {
|
|
181
|
-
for (const listener of listeners) listener();
|
|
182
|
-
}
|
|
183
|
-
function pinTenant(tenantId) {
|
|
184
|
-
pinned = tenantId;
|
|
185
|
-
if (changed) {
|
|
186
|
-
changed = false;
|
|
187
|
-
notify();
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
function getPinnedTenant() {
|
|
191
|
-
return pinned;
|
|
192
|
-
}
|
|
193
|
-
function isTenantChanged() {
|
|
194
|
-
return changed;
|
|
195
|
-
}
|
|
196
|
-
function subscribeTenant(listener) {
|
|
197
|
-
listeners.add(listener);
|
|
198
|
-
return () => {
|
|
199
|
-
listeners.delete(listener);
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
function handleTenantStorage(newValue) {
|
|
203
|
-
if (!pinned || !newValue || newValue === pinned || changed) return;
|
|
204
|
-
changed = true;
|
|
205
|
-
notify();
|
|
206
|
-
}
|
|
207
|
-
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
208
|
-
window.addEventListener("storage", (event) => {
|
|
209
|
-
if (event.key === TENANT_STORAGE_KEY) handleTenantStorage(event.newValue);
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
|
|
213
516
|
// src/client.ts
|
|
214
517
|
var ApiError = class _ApiError extends Error {
|
|
215
518
|
status;
|
|
@@ -263,12 +566,7 @@ async function platformFetch(input, init) {
|
|
|
263
566
|
}
|
|
264
567
|
const response = await fetch(input, { ...init, headers });
|
|
265
568
|
if (response.ok) return response;
|
|
266
|
-
|
|
267
|
-
if (response.status === 401 && session.kind !== "dev") {
|
|
268
|
-
void session.signIn().catch(() => {
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
throw error;
|
|
569
|
+
throw await ApiError.fromResponse(response);
|
|
272
570
|
}
|
|
273
571
|
function createClient(baseUrl = apiBaseUrl()) {
|
|
274
572
|
return hc(baseUrl, { fetch: platformFetch });
|
|
@@ -310,6 +608,10 @@ function useAppConfig() {
|
|
|
310
608
|
function useSession() {
|
|
311
609
|
return usePlatform().session;
|
|
312
610
|
}
|
|
611
|
+
function useSessionStatus() {
|
|
612
|
+
const { session } = usePlatform();
|
|
613
|
+
return useSyncExternalStore(session.subscribe, session.getStatus, session.getStatus);
|
|
614
|
+
}
|
|
313
615
|
function useOptionalUser() {
|
|
314
616
|
const { session } = usePlatform();
|
|
315
617
|
return useSyncExternalStore(session.subscribe, session.getUser, session.getUser);
|
|
@@ -438,6 +740,27 @@ function ErrorScreen({ error }) {
|
|
|
438
740
|
const message = error instanceof Error ? error.message : String(error);
|
|
439
741
|
return /* @__PURE__ */ jsx2(Message, { title: t("errorTitle"), body: message, children: error instanceof ApiError && error.traceId ? /* @__PURE__ */ jsx2("code", { className: "text-muted-foreground text-xs", children: t("traceId", { id: error.traceId }) }) : null });
|
|
440
742
|
}
|
|
743
|
+
function SessionScreen() {
|
|
744
|
+
const t = useT("web");
|
|
745
|
+
const session = useSession();
|
|
746
|
+
const status = useSessionStatus();
|
|
747
|
+
if (status.state === "ended") {
|
|
748
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("signedOutTitle"), body: t("signedOutBody"), children: /* @__PURE__ */ jsx2(Button, { onClick: () => void session.signIn(), children: t("signIn") }) });
|
|
749
|
+
}
|
|
750
|
+
if (status.state === "error" && status.code === "not_configured") {
|
|
751
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("signInRequiredTitle"), body: t("signInRequiredBody") });
|
|
752
|
+
}
|
|
753
|
+
if (status.state === "error" && status.code === "no_organization") {
|
|
754
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("noTenantTitle"), body: t("noTenantBody"), children: /* @__PURE__ */ jsx2(Button, { variant: "outline", onClick: () => void session.signOut(), children: t("signOut") }) });
|
|
755
|
+
}
|
|
756
|
+
if (status.state === "error") {
|
|
757
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("signInFailedTitle"), body: status.message ?? "", children: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
|
|
758
|
+
/* @__PURE__ */ jsx2(Button, { onClick: () => void session.signIn(), children: t("tryAgain") }),
|
|
759
|
+
/* @__PURE__ */ jsx2(Button, { variant: "outline", onClick: () => void session.signOut(), children: t("signOut") })
|
|
760
|
+
] }) });
|
|
761
|
+
}
|
|
762
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("signingInTitle"), body: t("signingInBody") });
|
|
763
|
+
}
|
|
441
764
|
function TenantChanged() {
|
|
442
765
|
const t = useT("web");
|
|
443
766
|
return /* @__PURE__ */ jsx2("div", { className: "bg-background/95 fixed inset-0 z-[100] flex items-center justify-center", children: /* @__PURE__ */ jsx2(Message, { title: t("tenantChangedTitle"), body: t("tenantChangedBody"), children: /* @__PURE__ */ jsx2(Button, { onClick: () => window.location.reload(), children: t("reload") }) }) });
|
|
@@ -513,6 +836,8 @@ function Navigation({ groups, pathname }) {
|
|
|
513
836
|
function AppShell() {
|
|
514
837
|
const t = useT("web");
|
|
515
838
|
const config = useAppConfig();
|
|
839
|
+
const session = useSession();
|
|
840
|
+
const status = useSessionStatus();
|
|
516
841
|
const user = useOptionalUser();
|
|
517
842
|
const router = useRouter();
|
|
518
843
|
const matches = useMatches();
|
|
@@ -533,8 +858,13 @@ function AppShell() {
|
|
|
533
858
|
useEffect(() => {
|
|
534
859
|
document.title = pageTitle ? `${pageTitle} \xB7 ${config.title}` : config.title;
|
|
535
860
|
}, [pageTitle, config.title]);
|
|
861
|
+
const isPublic = leaf?.public === true;
|
|
862
|
+
const mustSignIn = !user && !isPublic && status.state === "signed-out";
|
|
863
|
+
useEffect(() => {
|
|
864
|
+
if (mustSignIn) void session.signIn();
|
|
865
|
+
}, [mustSignIn, session]);
|
|
536
866
|
if (!user) {
|
|
537
|
-
return /* @__PURE__ */ jsx2(
|
|
867
|
+
return isPublic ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(SessionScreen, {});
|
|
538
868
|
}
|
|
539
869
|
if (leaf?.layout === "none") {
|
|
540
870
|
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
@@ -631,6 +961,8 @@ function createApp(options) {
|
|
|
631
961
|
// src/index.ts
|
|
632
962
|
registerMessages2("web", { "en-US": en_US_default, "zh-CN": zh_CN_default });
|
|
633
963
|
export {
|
|
964
|
+
AUTH_CALLBACK_PATH,
|
|
965
|
+
AUTH_CONFIG_PATH,
|
|
634
966
|
ApiError,
|
|
635
967
|
AppShell,
|
|
636
968
|
Can,
|
|
@@ -638,12 +970,14 @@ export {
|
|
|
638
970
|
Forbidden,
|
|
639
971
|
NotFound,
|
|
640
972
|
PlatformProvider,
|
|
973
|
+
RETURN_TO_KEY,
|
|
641
974
|
TENANT_STORAGE_KEY,
|
|
642
975
|
apiBaseUrl,
|
|
643
976
|
buildMenu,
|
|
644
977
|
createApp,
|
|
645
978
|
createClient,
|
|
646
979
|
createDevSession,
|
|
980
|
+
createPlatformSession,
|
|
647
981
|
encodeDevToken,
|
|
648
982
|
getPinnedTenant,
|
|
649
983
|
getPlatformConfig,
|
|
@@ -653,11 +987,13 @@ export {
|
|
|
653
987
|
permissionMatches,
|
|
654
988
|
pinTenant,
|
|
655
989
|
platformFetch,
|
|
990
|
+
readStoredTenant,
|
|
656
991
|
setSession,
|
|
657
992
|
useAppConfig,
|
|
658
993
|
useCan,
|
|
659
994
|
useOptionalUser,
|
|
660
995
|
useSession,
|
|
996
|
+
useSessionStatus,
|
|
661
997
|
useTenant,
|
|
662
998
|
useUser
|
|
663
999
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zjazj/web",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
4
4
|
"description": "Browser runtime for platform apps: session, typed API client, layout shell, guards and hooks.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -24,10 +24,11 @@
|
|
|
24
24
|
"./dist/index.js"
|
|
25
25
|
],
|
|
26
26
|
"dependencies": {
|
|
27
|
+
"@logto/browser": "^3.1.2",
|
|
27
28
|
"hono": "^4.13.17",
|
|
28
29
|
"lucide-react": "^0.545.0",
|
|
29
|
-
"@zjazj/i18n": "^0.0.
|
|
30
|
-
"@zjazj/ui": "^0.0.
|
|
30
|
+
"@zjazj/i18n": "^0.0.2",
|
|
31
|
+
"@zjazj/ui": "^0.0.2"
|
|
31
32
|
},
|
|
32
33
|
"peerDependencies": {
|
|
33
34
|
"@tanstack/react-query": "^5.90.0",
|
|
@@ -44,7 +45,7 @@
|
|
|
44
45
|
"jsdom": "^26.1.0",
|
|
45
46
|
"react": "^19.2.0",
|
|
46
47
|
"react-dom": "^19.2.0",
|
|
47
|
-
"@zjazj/server": "^0.0.
|
|
48
|
+
"@zjazj/server": "^0.0.2"
|
|
48
49
|
},
|
|
49
50
|
"publishConfig": {
|
|
50
51
|
"access": "public",
|