@wow-two-beta/fe 0.0.37 → 0.0.38
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/auth/AuthSession.d.ts +25 -1
- package/dist/auth/AuthSession.js.map +1 -1
- package/dist/auth/BffSession.d.ts +55 -0
- package/dist/auth/BffSession.js +73 -0
- package/dist/auth/BffSession.js.map +1 -0
- package/dist/auth/BffSessionSync.d.ts +57 -0
- package/dist/auth/BffSessionSync.js +160 -0
- package/dist/auth/BffSessionSync.js.map +1 -0
- package/dist/auth/BffStrategy.d.ts +53 -0
- package/dist/auth/BffStrategy.js +95 -0
- package/dist/auth/BffStrategy.js.map +1 -0
- package/dist/auth/RedirectStrategy.js +3 -6
- package/dist/auth/RedirectStrategy.js.map +1 -1
- package/dist/auth/ReturnUrlExtensions.d.ts +7 -0
- package/dist/auth/ReturnUrlExtensions.js +15 -0
- package/dist/auth/ReturnUrlExtensions.js.map +1 -0
- package/dist/auth/UseBffAuth.d.ts +31 -0
- package/dist/auth/UseBffAuth.js +39 -0
- package/dist/auth/UseBffAuth.js.map +1 -0
- package/dist/auth/index.d.ts +5 -1
- package/dist/auth/index.js +11 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/providers/AuthProvider.vue.js +74 -5
- package/dist/auth/providers/AuthProvider.vue.js.map +1 -1
- package/dist/foundation/http/Antiforgery.d.ts +5 -0
- package/dist/foundation/http/Antiforgery.js.map +1 -1
- package/dist/foundation/http/CreateApiClient.js +1 -1
- package/dist/foundation/http/CreateApiClient.js.map +1 -1
- package/dist/index.js +2 -1
- package/dist/presentation/overlays/alertModal/AlertModalContent.vue.js +1 -0
- package/dist/presentation/overlays/alertModal/AlertModalContent.vue.js.map +1 -1
- package/dist/presentation/overlays/index.js +2 -1
- package/dist/presentation/overlays/modal/ModalContent.vue.d.ts +17 -0
- package/dist/presentation/overlays/modal/ModalContent.vue.js +23 -2
- package/dist/presentation/overlays/modal/ModalContent.vue.js.map +1 -1
- package/dist/presentation/overlays/modal/ModalContent2.vue.js +2 -1
- package/dist/presentation/overlays/modal/index.d.ts +1 -1
- package/package.json +1 -1
|
@@ -23,11 +23,29 @@ export interface AuthResolveContext {
|
|
|
23
23
|
/** An optional cancellation signal for the underlying request. */
|
|
24
24
|
readonly signal?: AbortSignal;
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Defines what the provider lends a strategy once it runs in a browser: the session to read and watch, and a
|
|
28
|
+
* silent re-read. Absent under SSR — the provider connects from `onMounted`.
|
|
29
|
+
*/
|
|
30
|
+
export interface AuthStrategyHost<TUser = unknown> {
|
|
31
|
+
/** Reads the current snapshot. */
|
|
32
|
+
readonly getSession: () => AuthSession<TUser>;
|
|
33
|
+
/** Receives every snapshot after it is applied; returns a disposer. */
|
|
34
|
+
readonly subscribe: (listener: (session: AuthSession<TUser>) => void) => () => void;
|
|
35
|
+
/**
|
|
36
|
+
* Re-runs the me-resolve without leaving a settled session for `resolving`, so a background check never
|
|
37
|
+
* unmounts the page. A found user replaces the snapshot; a signed-out answer ends a signed-in session as an
|
|
38
|
+
* expiry; an expected failure keeps the session and reports through `onResolveError`. Resolves cancelled while
|
|
39
|
+
* a sign-in or sign-out runs or after a newer operation.
|
|
40
|
+
*/
|
|
41
|
+
readonly revalidate: () => Promise<Result<TUser | null, AppError>>;
|
|
42
|
+
}
|
|
26
43
|
/**
|
|
27
44
|
* Defines the pluggable transport half of the session — how the current user is resolved,
|
|
28
45
|
* established, and torn down. Ship shapes: `createCookieStrategy` (me-resolve over a cookie
|
|
29
46
|
* session), `createBearerStrategy` (token storage + `getAuthToken` wiring), and
|
|
30
|
-
* `createRedirectStrategy` (sign-in = full-page OAuth redirect)
|
|
47
|
+
* `createRedirectStrategy` (sign-in = full-page OAuth redirect), and `createBffStrategy` (a BFF session with
|
|
48
|
+
* CSRF, tab sync and refresh). Any object matching this
|
|
31
49
|
* contract works — write delegates directly for bespoke flows.
|
|
32
50
|
*/
|
|
33
51
|
export interface AuthStrategy<TUser = unknown, TSignInInput = unknown> {
|
|
@@ -45,4 +63,10 @@ export interface AuthStrategy<TUser = unknown, TSignInInput = unknown> {
|
|
|
45
63
|
signOut?(context: AuthResolveContext): Promise<Result<void, AppError>> | Result<void, AppError>;
|
|
46
64
|
/** Reacts to a bridged 401 (e.g. clears a stored bearer token) just before the session flips to anonymous. */
|
|
47
65
|
onUnauthorized?(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Starts background work that needs the live session — cross-tab sync, refresh timers, focus checks. The
|
|
68
|
+
* provider calls it once mounted (and again for a replacement strategy), then calls the returned disposer on
|
|
69
|
+
* unmount or replacement.
|
|
70
|
+
*/
|
|
71
|
+
connect?(host: AuthStrategyHost<TUser>): () => void;
|
|
48
72
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthSession.js","sources":["../../src/auth/AuthSession.ts"],"sourcesContent":["import type { AppError, Result } from '../foundation/results';\n/** Defines the lifecycle phase of the app session state machine. */\nexport const AuthStatus = {\n /** Refers to a session not yet examined — provider mounted with `resolveOnMount: false`, no action run yet. */\n Unknown: 'unknown',\n /** Refers to an in-flight me-resolve — render a splash/spinner, not the login gate. */\n Resolving: 'resolving',\n /** Refers to a settled, signed-in session carrying a user. */\n Authenticated: 'authenticated',\n /** Refers to a settled, signed-out session. */\n Anonymous: 'anonymous',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\n/** Defines a snapshot of the session — `user` is non-null exactly when `status` is `authenticated`. */\nexport interface AuthSession<TUser = unknown> {\n /** The current machine phase (`unknown → resolving → authenticated | anonymous`). */\n readonly status: AuthStatus;\n\n /** The signed-in user, or `null` outside `authenticated`. */\n readonly user: TUser | null;\n}\n\n/** Defines the call context passed to strategy delegates — forward `signal` to the transport when present. */\nexport interface AuthResolveContext {\n /** An optional cancellation signal for the underlying request. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Defines the pluggable transport half of the session — how the current user is resolved,\n * established, and torn down. Ship shapes: `createCookieStrategy` (me-resolve over a cookie\n * session), `createBearerStrategy` (token storage + `getAuthToken` wiring), and\n * `createRedirectStrategy` (sign-in = full-page OAuth redirect). Any object matching this\n * contract works — write delegates directly for bespoke flows.\n */\nexport interface AuthStrategy<TUser = unknown, TSignInInput = unknown> {\n /**\n * Resolves the current user — a successful `null` means signed out; an expected failure settles anonymous\n * (reported via the provider's `onResolveError`).\n */\n resolveUser(context: AuthResolveContext): Promise<Result<TUser | null, AppError>>;\n\n /**\n * Establishes a session. Return a successful user to authenticate immediately; return successful `null`/`void`\n * to leave state unchanged (redirect flows navigate away instead).\n */\n signIn?(\n input: TSignInInput,\n context: AuthResolveContext,\n ): Promise<Result<TUser | null | void, AppError>> | Result<TUser | null | void, AppError>;\n\n /** Tears the session down (server sign-out, token revoke) — state flips to anonymous regardless. */\n signOut?(context: AuthResolveContext): Promise<Result<void, AppError>> | Result<void, AppError>;\n\n /** Reacts to a bridged 401 (e.g. clears a stored bearer token) just before the session flips to anonymous. */\n onUnauthorized?(): void;\n}\n"],"names":[],"mappings":"AAEO,MAAM,aAAa;AAAA;AAAA,EAExB,SAAS;AAAA;AAAA,EAET,WAAW;AAAA;AAAA,EAEX,eAAe;AAAA;AAAA,EAEf,WAAW;AACb;"}
|
|
1
|
+
{"version":3,"file":"AuthSession.js","sources":["../../src/auth/AuthSession.ts"],"sourcesContent":["import type { AppError, Result } from '../foundation/results';\n/** Defines the lifecycle phase of the app session state machine. */\nexport const AuthStatus = {\n /** Refers to a session not yet examined — provider mounted with `resolveOnMount: false`, no action run yet. */\n Unknown: 'unknown',\n /** Refers to an in-flight me-resolve — render a splash/spinner, not the login gate. */\n Resolving: 'resolving',\n /** Refers to a settled, signed-in session carrying a user. */\n Authenticated: 'authenticated',\n /** Refers to a settled, signed-out session. */\n Anonymous: 'anonymous',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\n/** Defines a snapshot of the session — `user` is non-null exactly when `status` is `authenticated`. */\nexport interface AuthSession<TUser = unknown> {\n /** The current machine phase (`unknown → resolving → authenticated | anonymous`). */\n readonly status: AuthStatus;\n\n /** The signed-in user, or `null` outside `authenticated`. */\n readonly user: TUser | null;\n}\n\n/** Defines the call context passed to strategy delegates — forward `signal` to the transport when present. */\nexport interface AuthResolveContext {\n /** An optional cancellation signal for the underlying request. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Defines what the provider lends a strategy once it runs in a browser: the session to read and watch, and a\n * silent re-read. Absent under SSR — the provider connects from `onMounted`.\n */\nexport interface AuthStrategyHost<TUser = unknown> {\n /** Reads the current snapshot. */\n readonly getSession: () => AuthSession<TUser>;\n\n /** Receives every snapshot after it is applied; returns a disposer. */\n readonly subscribe: (listener: (session: AuthSession<TUser>) => void) => () => void;\n\n /**\n * Re-runs the me-resolve without leaving a settled session for `resolving`, so a background check never\n * unmounts the page. A found user replaces the snapshot; a signed-out answer ends a signed-in session as an\n * expiry; an expected failure keeps the session and reports through `onResolveError`. Resolves cancelled while\n * a sign-in or sign-out runs or after a newer operation.\n */\n readonly revalidate: () => Promise<Result<TUser | null, AppError>>;\n}\n\n/**\n * Defines the pluggable transport half of the session — how the current user is resolved,\n * established, and torn down. Ship shapes: `createCookieStrategy` (me-resolve over a cookie\n * session), `createBearerStrategy` (token storage + `getAuthToken` wiring), and\n * `createRedirectStrategy` (sign-in = full-page OAuth redirect), and `createBffStrategy` (a BFF session with\n * CSRF, tab sync and refresh). Any object matching this\n * contract works — write delegates directly for bespoke flows.\n */\nexport interface AuthStrategy<TUser = unknown, TSignInInput = unknown> {\n /**\n * Resolves the current user — a successful `null` means signed out; an expected failure settles anonymous\n * (reported via the provider's `onResolveError`).\n */\n resolveUser(context: AuthResolveContext): Promise<Result<TUser | null, AppError>>;\n\n /**\n * Establishes a session. Return a successful user to authenticate immediately; return successful `null`/`void`\n * to leave state unchanged (redirect flows navigate away instead).\n */\n signIn?(\n input: TSignInInput,\n context: AuthResolveContext,\n ): Promise<Result<TUser | null | void, AppError>> | Result<TUser | null | void, AppError>;\n\n /** Tears the session down (server sign-out, token revoke) — state flips to anonymous regardless. */\n signOut?(context: AuthResolveContext): Promise<Result<void, AppError>> | Result<void, AppError>;\n\n /** Reacts to a bridged 401 (e.g. clears a stored bearer token) just before the session flips to anonymous. */\n onUnauthorized?(): void;\n\n /**\n * Starts background work that needs the live session — cross-tab sync, refresh timers, focus checks. The\n * provider calls it once mounted (and again for a replacement strategy), then calls the returned disposer on\n * unmount or replacement.\n */\n connect?(host: AuthStrategyHost<TUser>): () => void;\n}\n"],"names":[],"mappings":"AAEO,MAAM,aAAa;AAAA;AAAA,EAExB,SAAS;AAAA;AAAA,EAET,WAAW;AAAA;AAAA,EAEX,eAAe;AAAA;AAAA,EAEf,WAAW;AACb;"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ApiFailure } from '../foundation/http';
|
|
2
|
+
import { Result } from '../foundation/results';
|
|
3
|
+
/** Defines the signed-in person a BFF session names. */
|
|
4
|
+
export interface BffPerson {
|
|
5
|
+
/** The stable subject id — the identity key, never the display name. */
|
|
6
|
+
readonly sub: string;
|
|
7
|
+
readonly name: string | null;
|
|
8
|
+
readonly email: string | null;
|
|
9
|
+
readonly phoneNumber: string | null;
|
|
10
|
+
}
|
|
11
|
+
/** Defines the organization the session acts in, and the person's role there. */
|
|
12
|
+
export interface BffOrganization {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly role: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Defines the user a BFF session resolves to. The CSRF token is deliberately absent: it never renders, so the
|
|
18
|
+
* strategy keeps it and the HTTP layer echoes it.
|
|
19
|
+
*/
|
|
20
|
+
export interface BffUser {
|
|
21
|
+
readonly person: BffPerson;
|
|
22
|
+
/** `null` for a person acting in no organization. */
|
|
23
|
+
readonly organization: BffOrganization | null;
|
|
24
|
+
readonly permissions: readonly string[];
|
|
25
|
+
/** When the session ends (ISO 8601); `null` when the server sent none that parses. */
|
|
26
|
+
readonly expiresAt: string | null;
|
|
27
|
+
}
|
|
28
|
+
/** Defines one decoded `GET {prefix}/session` response. */
|
|
29
|
+
export interface BffSessionSnapshot {
|
|
30
|
+
/** `null` while signed out. */
|
|
31
|
+
readonly user: BffUser | null;
|
|
32
|
+
/** The token unsafe requests echo; `null` while signed out. */
|
|
33
|
+
readonly csrfToken: string | null;
|
|
34
|
+
}
|
|
35
|
+
/** Defines one decoded `POST {prefix}/logout` response. */
|
|
36
|
+
export interface BffLogout {
|
|
37
|
+
/** Where the page navigates to end the identity provider's session. */
|
|
38
|
+
readonly endSessionUrl: string;
|
|
39
|
+
}
|
|
40
|
+
/** Decodes the session response; a payload that breaks the contract is a `protocol` failure. */
|
|
41
|
+
export declare function decodeBffSession(value: unknown): Result<BffSessionSnapshot, ApiFailure>;
|
|
42
|
+
/** Decodes the logout response; an end-session URL the page may not navigate to is a `protocol` failure. */
|
|
43
|
+
export declare function decodeBffLogout(value: unknown): Result<BffLogout, ApiFailure>;
|
|
44
|
+
/** Extends a {@link BffUser} with the checks a screen and a bridge need. */
|
|
45
|
+
export declare const BffSessionExtensions: {
|
|
46
|
+
/** Whether the user holds `permission`; `false` while signed out. */
|
|
47
|
+
readonly hasPermission: (user: BffUser | null | undefined, permission: string) => boolean;
|
|
48
|
+
/**
|
|
49
|
+
* The stable user-and-organization key: pass it as `createAuthBridge({ getIdentity })` so a refreshed session
|
|
50
|
+
* keeps its caches and a person or organization switch drops them.
|
|
51
|
+
*/
|
|
52
|
+
readonly identity: (user: BffUser) => string;
|
|
53
|
+
/** The session end as epoch milliseconds; `null` when the server sent none that parses. */
|
|
54
|
+
readonly expiresAtMs: (user: BffUser) => number | null;
|
|
55
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { ApiFailureFactory } from "../foundation/http/ApiFailure.js";
|
|
2
|
+
import { ResultExtensions } from "../foundation/results/ResultExtensions.js";
|
|
3
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
const isText = (value) => typeof value === "string" && value !== "";
|
|
5
|
+
const optionalText = (value) => typeof value === "string" ? value : null;
|
|
6
|
+
const protocol = () => ApiFailureFactory.create("protocol");
|
|
7
|
+
function decodeBffSession(value) {
|
|
8
|
+
if (!isRecord(value) || typeof value["isAuthenticated"] !== "boolean") return ResultExtensions.fail(protocol());
|
|
9
|
+
if (!value["isAuthenticated"]) return ResultExtensions.ok({ user: null, csrfToken: null });
|
|
10
|
+
const person = value["person"];
|
|
11
|
+
const organization = value["organization"];
|
|
12
|
+
const permissions = value["permissions"] ?? [];
|
|
13
|
+
const expiresAt = value["expiresAt"];
|
|
14
|
+
if (!isRecord(person) || !isText(person["sub"]) || !isText(value["csrfToken"])) {
|
|
15
|
+
return ResultExtensions.fail(protocol());
|
|
16
|
+
}
|
|
17
|
+
if (organization != null && (!isRecord(organization) || !isText(organization["id"]))) {
|
|
18
|
+
return ResultExtensions.fail(protocol());
|
|
19
|
+
}
|
|
20
|
+
if (!Array.isArray(permissions) || !permissions.every(isText)) return ResultExtensions.fail(protocol());
|
|
21
|
+
return ResultExtensions.ok({
|
|
22
|
+
csrfToken: value["csrfToken"],
|
|
23
|
+
user: {
|
|
24
|
+
person: {
|
|
25
|
+
sub: person["sub"],
|
|
26
|
+
name: optionalText(person["name"]),
|
|
27
|
+
email: optionalText(person["email"]),
|
|
28
|
+
phoneNumber: optionalText(person["phoneNumber"])
|
|
29
|
+
},
|
|
30
|
+
organization: isRecord(organization) ? { id: organization["id"], role: optionalText(organization["role"]) ?? "" } : null,
|
|
31
|
+
permissions: Object.freeze([...permissions]),
|
|
32
|
+
expiresAt: typeof expiresAt === "string" && Number.isFinite(Date.parse(expiresAt)) ? expiresAt : null
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function isNavigable(url) {
|
|
37
|
+
if (url.startsWith("/")) return !url.startsWith("//") && !url.includes("\\");
|
|
38
|
+
try {
|
|
39
|
+
const { protocol: scheme } = new URL(url);
|
|
40
|
+
return scheme === "https:" || scheme === "http:";
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function decodeBffLogout(value) {
|
|
46
|
+
if (!isRecord(value) || !isText(value["endSessionUrl"]) || !isNavigable(value["endSessionUrl"])) {
|
|
47
|
+
return ResultExtensions.fail(protocol());
|
|
48
|
+
}
|
|
49
|
+
return ResultExtensions.ok({ endSessionUrl: value["endSessionUrl"] });
|
|
50
|
+
}
|
|
51
|
+
const BffSessionExtensions = {
|
|
52
|
+
/** Whether the user holds `permission`; `false` while signed out. */
|
|
53
|
+
hasPermission(user, permission) {
|
|
54
|
+
return user?.permissions.includes(permission) ?? false;
|
|
55
|
+
},
|
|
56
|
+
/**
|
|
57
|
+
* The stable user-and-organization key: pass it as `createAuthBridge({ getIdentity })` so a refreshed session
|
|
58
|
+
* keeps its caches and a person or organization switch drops them.
|
|
59
|
+
*/
|
|
60
|
+
identity(user) {
|
|
61
|
+
return `${user.person.sub}\0${user.organization?.id ?? ""}`;
|
|
62
|
+
},
|
|
63
|
+
/** The session end as epoch milliseconds; `null` when the server sent none that parses. */
|
|
64
|
+
expiresAtMs(user) {
|
|
65
|
+
return user.expiresAt === null ? null : Date.parse(user.expiresAt);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
export {
|
|
69
|
+
BffSessionExtensions,
|
|
70
|
+
decodeBffLogout,
|
|
71
|
+
decodeBffSession
|
|
72
|
+
};
|
|
73
|
+
//# sourceMappingURL=BffSession.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BffSession.js","sources":["../../src/auth/BffSession.ts"],"sourcesContent":["import { ApiFailureFactory, type ApiFailure } from '../foundation/http';\nimport { ResultExtensions, type Result } from '../foundation/results';\n\n/** Defines the signed-in person a BFF session names. */\nexport interface BffPerson {\n /** The stable subject id — the identity key, never the display name. */\n readonly sub: string;\n readonly name: string | null;\n readonly email: string | null;\n readonly phoneNumber: string | null;\n}\n\n/** Defines the organization the session acts in, and the person's role there. */\nexport interface BffOrganization {\n readonly id: string;\n readonly role: string;\n}\n\n/**\n * Defines the user a BFF session resolves to. The CSRF token is deliberately absent: it never renders, so the\n * strategy keeps it and the HTTP layer echoes it.\n */\nexport interface BffUser {\n readonly person: BffPerson;\n /** `null` for a person acting in no organization. */\n readonly organization: BffOrganization | null;\n readonly permissions: readonly string[];\n /** When the session ends (ISO 8601); `null` when the server sent none that parses. */\n readonly expiresAt: string | null;\n}\n\n/** Defines one decoded `GET {prefix}/session` response. */\nexport interface BffSessionSnapshot {\n /** `null` while signed out. */\n readonly user: BffUser | null;\n /** The token unsafe requests echo; `null` while signed out. */\n readonly csrfToken: string | null;\n}\n\n/** Defines one decoded `POST {prefix}/logout` response. */\nexport interface BffLogout {\n /** Where the page navigates to end the identity provider's session. */\n readonly endSessionUrl: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\nconst isText = (value: unknown): value is string => typeof value === 'string' && value !== '';\n/** Reads an optional text field; anything but text reads as absent. */\nconst optionalText = (value: unknown): string | null => (typeof value === 'string' ? value : null);\nconst protocol = (): ApiFailure => ApiFailureFactory.create('protocol');\n\n/** Decodes the session response; a payload that breaks the contract is a `protocol` failure. */\nexport function decodeBffSession(value: unknown): Result<BffSessionSnapshot, ApiFailure> {\n if (!isRecord(value) || typeof value['isAuthenticated'] !== 'boolean') return ResultExtensions.fail(protocol());\n if (!value['isAuthenticated']) return ResultExtensions.ok({ user: null, csrfToken: null });\n\n const person = value['person'];\n const organization = value['organization'];\n const permissions = value['permissions'] ?? [];\n const expiresAt = value['expiresAt'];\n if (!isRecord(person) || !isText(person['sub']) || !isText(value['csrfToken'])) {\n return ResultExtensions.fail(protocol());\n }\n if (organization != null && (!isRecord(organization) || !isText(organization['id']))) {\n return ResultExtensions.fail(protocol());\n }\n if (!Array.isArray(permissions) || !permissions.every(isText)) return ResultExtensions.fail(protocol());\n\n return ResultExtensions.ok({\n csrfToken: value['csrfToken'],\n user: {\n person: {\n sub: person['sub'],\n name: optionalText(person['name']),\n email: optionalText(person['email']),\n phoneNumber: optionalText(person['phoneNumber']),\n },\n organization: isRecord(organization)\n ? { id: organization['id'] as string, role: optionalText(organization['role']) ?? '' }\n : null,\n permissions: Object.freeze([...(permissions as string[])]),\n expiresAt: typeof expiresAt === 'string' && Number.isFinite(Date.parse(expiresAt)) ? expiresAt : null,\n },\n });\n}\n\n/** Whether a page may navigate to `url` to end the provider session: a local path, or an absolute http(s) URL. */\nfunction isNavigable(url: string): boolean {\n if (url.startsWith('/')) return !url.startsWith('//') && !url.includes('\\\\');\n try {\n const { protocol: scheme } = new URL(url);\n return scheme === 'https:' || scheme === 'http:';\n } catch {\n return false;\n }\n}\n\n/** Decodes the logout response; an end-session URL the page may not navigate to is a `protocol` failure. */\nexport function decodeBffLogout(value: unknown): Result<BffLogout, ApiFailure> {\n if (!isRecord(value) || !isText(value['endSessionUrl']) || !isNavigable(value['endSessionUrl'])) {\n return ResultExtensions.fail(protocol());\n }\n return ResultExtensions.ok({ endSessionUrl: value['endSessionUrl'] });\n}\n\n/** Extends a {@link BffUser} with the checks a screen and a bridge need. */\nexport const BffSessionExtensions = {\n /** Whether the user holds `permission`; `false` while signed out. */\n hasPermission(user: BffUser | null | undefined, permission: string): boolean {\n return user?.permissions.includes(permission) ?? false;\n },\n\n /**\n * The stable user-and-organization key: pass it as `createAuthBridge({ getIdentity })` so a refreshed session\n * keeps its caches and a person or organization switch drops them.\n */\n identity(user: BffUser): string {\n return `${user.person.sub}\\u0000${user.organization?.id ?? ''}`;\n },\n\n /** The session end as epoch milliseconds; `null` when the server sent none that parses. */\n expiresAtMs(user: BffUser): number | null {\n return user.expiresAt === null ? null : Date.parse(user.expiresAt);\n },\n} as const;\n"],"names":[],"mappings":";;AA6CA,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU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
|
+
import { BffUser } from './BffSession';
|
|
4
|
+
/** Names what one tab tells the others. The message is a hint to re-read the session, never a credential. */
|
|
5
|
+
export declare const BffSyncKind: {
|
|
6
|
+
readonly SignedIn: "signed-in";
|
|
7
|
+
readonly SignedOut: "signed-out";
|
|
8
|
+
};
|
|
9
|
+
export type BffSyncKind = (typeof BffSyncKind)[keyof typeof BffSyncKind];
|
|
10
|
+
/** Defines the cross-tab message. A peer is another copy of the page: receivers re-read the server, not the message. */
|
|
11
|
+
export interface BffSyncMessage {
|
|
12
|
+
readonly kind: BffSyncKind;
|
|
13
|
+
}
|
|
14
|
+
/** Defines the cross-tab sync options; the channel is `BroadcastChannel`, falling back to the `storage` event. */
|
|
15
|
+
export interface BffSyncOptions extends SyncChannelOptions {
|
|
16
|
+
/** The channel name shared by this app's tabs. Default `wow-two.auth.bff`. */
|
|
17
|
+
readonly channelName?: string;
|
|
18
|
+
/** Opens this tab's endpoint. Default `createSyncChannel(channelName, options)`; tests inject a hub channel. */
|
|
19
|
+
readonly open?: (name: string) => SyncChannel<BffSyncMessage>;
|
|
20
|
+
}
|
|
21
|
+
/** Defines when a signed-in session is re-read without the person doing anything. */
|
|
22
|
+
export interface BffRefreshOptions {
|
|
23
|
+
/** How long before `expiresAt` the pre-expiry refresh runs. Default 60 s. */
|
|
24
|
+
readonly leadMs?: number;
|
|
25
|
+
/** The least time between two timer-driven refreshes — the floor under any schedule. Default 15 s. */
|
|
26
|
+
readonly minIntervalMs?: number;
|
|
27
|
+
/** How old the last read must be before a focus or visibility change re-reads it. Default 30 s. */
|
|
28
|
+
readonly staleAfterMs?: number;
|
|
29
|
+
/** The first retry delay after a failed refresh; it doubles up to 5 min. Default 30 s. */
|
|
30
|
+
readonly retryMs?: number;
|
|
31
|
+
/** Consecutive failed refreshes after which the timer stops until the next focus or peer hint. Default 5. */
|
|
32
|
+
readonly maxRetries?: number;
|
|
33
|
+
}
|
|
34
|
+
/** Defines the options of {@link connectBffSession}. */
|
|
35
|
+
export interface BffSessionLinkOptions {
|
|
36
|
+
readonly sync: BffSyncOptions | false;
|
|
37
|
+
readonly refresh: BffRefreshOptions | false;
|
|
38
|
+
readonly now: () => number;
|
|
39
|
+
}
|
|
40
|
+
/** Defines the live connection of one strategy to its provider. */
|
|
41
|
+
export interface BffSessionLink {
|
|
42
|
+
/** Tells the other tabs the session ended. Silent while this tab applies a peer's hint, so tabs never echo. */
|
|
43
|
+
readonly announce: (kind: BffSyncKind) => void;
|
|
44
|
+
readonly dispose: () => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Connects a BFF strategy to its provider for the life of a mounted app:
|
|
48
|
+
*
|
|
49
|
+
* - Tab sync: a sign-in here tells the other tabs, a sign-out or expiry here tells them, and a tab that hears a hint
|
|
50
|
+
* re-reads `GET /auth/session`. The hint carries no identity, and a tab applying one never announces, so two tabs
|
|
51
|
+
* cannot ping-pong.
|
|
52
|
+
* - Refresh: one timer per `expiresAt` fires at most twice (`lead`, then `expiry`) and never again for the same
|
|
53
|
+
* value, so a server that does not extend its session cannot make it loop; a new `expiresAt` earns a new pair, and
|
|
54
|
+
* `minIntervalMs` floors the pace. A failed refresh retries with doubling delay and stops after `maxRetries`.
|
|
55
|
+
* - Wake: a focus or visibility change re-reads a session older than `staleAfterMs`, signed in or out.
|
|
56
|
+
*/
|
|
57
|
+
export declare function connectBffSession(host: AuthStrategyHost<BffUser>, options: BffSessionLinkOptions): BffSessionLink;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { createSyncChannel } from "../foundation/channels/CreateSyncChannel.js";
|
|
2
|
+
import { AppErrorFactory } from "../foundation/results/AppErrorFactory.js";
|
|
3
|
+
import { ResultExtensions } from "../foundation/results/ResultExtensions.js";
|
|
4
|
+
import { AuthStatus } from "./AuthSession.js";
|
|
5
|
+
import { BffSessionExtensions } from "./BffSession.js";
|
|
6
|
+
const BffSyncKind = {
|
|
7
|
+
SignedIn: "signed-in",
|
|
8
|
+
SignedOut: "signed-out"
|
|
9
|
+
};
|
|
10
|
+
const DefaultChannelName = "wow-two.auth.bff";
|
|
11
|
+
const RefreshDefaults = { leadMs: 6e4, minIntervalMs: 15e3, staleAfterMs: 3e4, retryMs: 3e4, maxRetries: 5 };
|
|
12
|
+
const MaxRetryDelayMs = 3e5;
|
|
13
|
+
const MaxTimerMs = 2147483647;
|
|
14
|
+
const isHint = (message) => typeof message === "object" && message !== null && (message.kind === BffSyncKind.SignedIn || message.kind === BffSyncKind.SignedOut);
|
|
15
|
+
function connectBffSession(host, options) {
|
|
16
|
+
const refresh = options.refresh === false ? null : { ...RefreshDefaults, ...options.refresh };
|
|
17
|
+
const now = options.now;
|
|
18
|
+
const disposers = [];
|
|
19
|
+
let closed = false;
|
|
20
|
+
let lastKey;
|
|
21
|
+
let peerDepth = 0;
|
|
22
|
+
let lastLoadedAt = Number.NEGATIVE_INFINITY;
|
|
23
|
+
let lastFireAt = Number.NEGATIVE_INFINITY;
|
|
24
|
+
let fired = null;
|
|
25
|
+
let failures = 0;
|
|
26
|
+
let timer;
|
|
27
|
+
const sync = options.sync === false ? null : options.sync;
|
|
28
|
+
let channel = null;
|
|
29
|
+
if (sync) {
|
|
30
|
+
const name = sync.channelName ?? DefaultChannelName;
|
|
31
|
+
channel = sync.open ? sync.open(name) : createSyncChannel(name, sync);
|
|
32
|
+
}
|
|
33
|
+
let pending = null;
|
|
34
|
+
function revalidate() {
|
|
35
|
+
if (pending) return pending;
|
|
36
|
+
const read = (async () => {
|
|
37
|
+
try {
|
|
38
|
+
const outcome = await host.revalidate();
|
|
39
|
+
if (outcome.ok) lastLoadedAt = now();
|
|
40
|
+
return outcome;
|
|
41
|
+
} catch {
|
|
42
|
+
return ResultExtensions.fail(AppErrorFactory.unexpected());
|
|
43
|
+
}
|
|
44
|
+
})().finally(() => {
|
|
45
|
+
if (pending === read) pending = null;
|
|
46
|
+
});
|
|
47
|
+
pending = read;
|
|
48
|
+
return read;
|
|
49
|
+
}
|
|
50
|
+
function clearTimer() {
|
|
51
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
52
|
+
timer = void 0;
|
|
53
|
+
}
|
|
54
|
+
function arm(stage, target) {
|
|
55
|
+
clearTimer();
|
|
56
|
+
if (!refresh || closed) return;
|
|
57
|
+
const due = Math.max(target, lastFireAt + refresh.minIntervalMs);
|
|
58
|
+
const wake2 = () => {
|
|
59
|
+
timer = void 0;
|
|
60
|
+
if (closed) return;
|
|
61
|
+
if (now() < due) timer = setTimeout(wake2, Math.min(Math.max(due - now(), 1), MaxTimerMs));
|
|
62
|
+
else void fire(stage);
|
|
63
|
+
};
|
|
64
|
+
timer = setTimeout(wake2, Math.min(Math.max(due - now(), 0), MaxTimerMs));
|
|
65
|
+
}
|
|
66
|
+
function schedule(session) {
|
|
67
|
+
clearTimer();
|
|
68
|
+
if (!refresh || closed || session.status !== AuthStatus.Authenticated || session.user === null) return;
|
|
69
|
+
const expiresAt = BffSessionExtensions.expiresAtMs(session.user);
|
|
70
|
+
if (expiresAt === null) return;
|
|
71
|
+
const done = fired?.expiresAt === session.user.expiresAt ? fired.stage : null;
|
|
72
|
+
if (done === "expiry") return;
|
|
73
|
+
if (done === "lead") arm("expiry", expiresAt);
|
|
74
|
+
else arm("lead", expiresAt - refresh.leadMs);
|
|
75
|
+
}
|
|
76
|
+
async function fire(stage) {
|
|
77
|
+
const session = host.getSession();
|
|
78
|
+
if (session.status !== AuthStatus.Authenticated || session.user === null) return;
|
|
79
|
+
const before = fired;
|
|
80
|
+
fired = { expiresAt: session.user.expiresAt, stage };
|
|
81
|
+
lastFireAt = now();
|
|
82
|
+
const outcome = await revalidate();
|
|
83
|
+
if (closed) return;
|
|
84
|
+
if (outcome.ok) {
|
|
85
|
+
failures = 0;
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (outcome.failure.type === "cancelled") return;
|
|
89
|
+
fired = before;
|
|
90
|
+
failures += 1;
|
|
91
|
+
if (!refresh || failures > refresh.maxRetries) return;
|
|
92
|
+
arm(stage, now() + Math.min(refresh.retryMs * 2 ** (failures - 1), MaxRetryDelayMs));
|
|
93
|
+
}
|
|
94
|
+
function onSession(session) {
|
|
95
|
+
if (closed) return;
|
|
96
|
+
if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;
|
|
97
|
+
lastLoadedAt = now();
|
|
98
|
+
const key = session.status === AuthStatus.Authenticated && session.user !== null ? BffSessionExtensions.identity(session.user) : null;
|
|
99
|
+
const previous = lastKey;
|
|
100
|
+
lastKey = key;
|
|
101
|
+
if (key !== null && key !== previous && peerDepth === 0) channel?.post({ kind: BffSyncKind.SignedIn });
|
|
102
|
+
schedule(session);
|
|
103
|
+
}
|
|
104
|
+
function wake() {
|
|
105
|
+
if (closed || !refresh) return;
|
|
106
|
+
const session = host.getSession();
|
|
107
|
+
if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;
|
|
108
|
+
if (now() - lastLoadedAt < refresh.staleAfterMs) return;
|
|
109
|
+
failures = 0;
|
|
110
|
+
void revalidate();
|
|
111
|
+
}
|
|
112
|
+
async function applyHint() {
|
|
113
|
+
peerDepth += 1;
|
|
114
|
+
failures = 0;
|
|
115
|
+
try {
|
|
116
|
+
await revalidate();
|
|
117
|
+
} finally {
|
|
118
|
+
peerDepth -= 1;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
disposers.push(host.subscribe(onSession));
|
|
122
|
+
onSession(host.getSession());
|
|
123
|
+
if (channel) {
|
|
124
|
+
const open = channel;
|
|
125
|
+
disposers.push(
|
|
126
|
+
open.subscribe((message) => {
|
|
127
|
+
if (isHint(message)) void applyHint();
|
|
128
|
+
}),
|
|
129
|
+
() => open.close()
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (refresh && typeof window !== "undefined" && typeof document !== "undefined") {
|
|
133
|
+
const onVisibility = () => {
|
|
134
|
+
if (document.visibilityState === "visible") wake();
|
|
135
|
+
};
|
|
136
|
+
window.addEventListener("focus", wake);
|
|
137
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
138
|
+
disposers.push(
|
|
139
|
+
() => window.removeEventListener("focus", wake),
|
|
140
|
+
() => document.removeEventListener("visibilitychange", onVisibility)
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
announce: (kind) => {
|
|
145
|
+
if (closed || peerDepth > 0) return;
|
|
146
|
+
channel?.post({ kind });
|
|
147
|
+
},
|
|
148
|
+
dispose: () => {
|
|
149
|
+
if (closed) return;
|
|
150
|
+
closed = true;
|
|
151
|
+
clearTimer();
|
|
152
|
+
for (const dispose of disposers.splice(0)) dispose();
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
export {
|
|
157
|
+
BffSyncKind,
|
|
158
|
+
connectBffSession
|
|
159
|
+
};
|
|
160
|
+
//# sourceMappingURL=BffSessionSync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BffSessionSync.js","sources":["../../src/auth/BffSessionSync.ts"],"sourcesContent":["import { createSyncChannel, type SyncChannel, type SyncChannelOptions } from '../foundation/channels';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport { AuthStatus, type AuthSession, type AuthStrategyHost } from './AuthSession';\nimport { BffSessionExtensions, type BffUser } from './BffSession';\n\n/** Names what one tab tells the others. The message is a hint to re-read the session, never a credential. */\nexport const BffSyncKind = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n} as const;\nexport type BffSyncKind = (typeof BffSyncKind)[keyof typeof BffSyncKind];\n\n/** Defines the cross-tab message. A peer is another copy of the page: receivers re-read the server, not the message. */\nexport interface BffSyncMessage {\n readonly kind: BffSyncKind;\n}\n\n/** Defines the cross-tab sync options; the channel is `BroadcastChannel`, falling back to the `storage` event. */\nexport interface BffSyncOptions extends SyncChannelOptions {\n /** The channel name shared by this app's tabs. Default `wow-two.auth.bff`. */\n readonly channelName?: string;\n\n /** Opens this tab's endpoint. Default `createSyncChannel(channelName, options)`; tests inject a hub channel. */\n readonly open?: (name: string) => SyncChannel<BffSyncMessage>;\n}\n\n/** Defines when a signed-in session is re-read without the person doing anything. */\nexport interface BffRefreshOptions {\n /** How long before `expiresAt` the pre-expiry refresh runs. Default 60 s. */\n readonly leadMs?: number;\n\n /** The least time between two timer-driven refreshes — the floor under any schedule. Default 15 s. */\n readonly minIntervalMs?: number;\n\n /** How old the last read must be before a focus or visibility change re-reads it. Default 30 s. */\n readonly staleAfterMs?: number;\n\n /** The first retry delay after a failed refresh; it doubles up to 5 min. Default 30 s. */\n readonly retryMs?: number;\n\n /** Consecutive failed refreshes after which the timer stops until the next focus or peer hint. Default 5. */\n readonly maxRetries?: number;\n}\n\nconst DefaultChannelName = 'wow-two.auth.bff';\nconst RefreshDefaults = { leadMs: 60_000, minIntervalMs: 15_000, staleAfterMs: 30_000, retryMs: 30_000, maxRetries: 5 };\nconst MaxRetryDelayMs = 300_000;\n/** The longest `setTimeout` delay browsers honour (a 32-bit signed millisecond count). */\nconst MaxTimerMs = 2_147_483_647;\n\n/** Defines the options of {@link connectBffSession}. */\nexport interface BffSessionLinkOptions {\n readonly sync: BffSyncOptions | false;\n readonly refresh: BffRefreshOptions | false;\n readonly now: () => number;\n}\n\n/** Defines the live connection of one strategy to its provider. */\nexport interface BffSessionLink {\n /** Tells the other tabs the session ended. Silent while this tab applies a peer's hint, so tabs never echo. */\n readonly announce: (kind: BffSyncKind) => void;\n readonly dispose: () => void;\n}\n\n/** `lead`: the refresh before `expiresAt`; `expiry`: the one check at it. A stage never repeats for one `expiresAt`. */\ntype Stage = 'lead' | 'expiry';\n\nconst isHint = (message: unknown): message is BffSyncMessage =>\n typeof message === 'object' &&\n message !== null &&\n ((message as BffSyncMessage).kind === BffSyncKind.SignedIn ||\n (message as BffSyncMessage).kind === BffSyncKind.SignedOut);\n\n/**\n * Connects a BFF strategy to its provider for the life of a mounted app:\n *\n * - Tab sync: a sign-in here tells the other tabs, a sign-out or expiry here tells them, and a tab that hears a hint\n * re-reads `GET /auth/session`. The hint carries no identity, and a tab applying one never announces, so two tabs\n * cannot ping-pong.\n * - Refresh: one timer per `expiresAt` fires at most twice (`lead`, then `expiry`) and never again for the same\n * value, so a server that does not extend its session cannot make it loop; a new `expiresAt` earns a new pair, and\n * `minIntervalMs` floors the pace. A failed refresh retries with doubling delay and stops after `maxRetries`.\n * - Wake: a focus or visibility change re-reads a session older than `staleAfterMs`, signed in or out.\n */\nexport function connectBffSession(host: AuthStrategyHost<BffUser>, options: BffSessionLinkOptions): BffSessionLink {\n const refresh = options.refresh === false ? null : { ...RefreshDefaults, ...options.refresh };\n const now = options.now;\n const disposers: Array<() => void> = [];\n\n let closed = false;\n // `undefined` before the first settled snapshot, `null` while signed out, else the signed-in identity key.\n let lastKey: string | null | undefined;\n let peerDepth = 0;\n let lastLoadedAt = Number.NEGATIVE_INFINITY;\n let lastFireAt = Number.NEGATIVE_INFINITY;\n let fired: { readonly expiresAt: string | null; readonly stage: Stage } | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const sync = options.sync === false ? null : options.sync;\n let channel: SyncChannel<BffSyncMessage> | null = null;\n if (sync) {\n const name = sync.channelName ?? DefaultChannelName;\n channel = sync.open ? sync.open(name) : createSyncChannel<BffSyncMessage>(name, sync);\n }\n\n let pending: Promise<Result<BffUser | null, AppError>> | null = null;\n /**\n * Re-reads the session; callers that arrive mid-read share it. A throwing strategy counts as a failure, so a timer\n * never leaks an unhandled rejection.\n */\n function revalidate(): Promise<Result<BffUser | null, AppError>> {\n if (pending) return pending;\n const read = (async (): Promise<Result<BffUser | null, AppError>> => {\n try {\n const outcome = await host.revalidate();\n if (outcome.ok) lastLoadedAt = now();\n return outcome;\n } catch {\n return ResultExtensions.fail(AppErrorFactory.unexpected());\n }\n })().finally(() => {\n if (pending === read) pending = null;\n });\n pending = read;\n return read;\n }\n\n function clearTimer(): void {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n }\n\n /** Arms the timer for `stage` at `target`, never sooner than `minIntervalMs` after the previous fire. */\n function arm(stage: Stage, target: number): void {\n clearTimer();\n if (!refresh || closed) return;\n const due = Math.max(target, lastFireAt + refresh.minIntervalMs);\n const wake = (): void => {\n timer = undefined;\n if (closed) return;\n // A clamped or early timer fires before `due`: wait out the rest instead of firing early.\n if (now() < due) timer = setTimeout(wake, Math.min(Math.max(due - now(), 1), MaxTimerMs));\n else void fire(stage);\n };\n timer = setTimeout(wake, Math.min(Math.max(due - now(), 0), MaxTimerMs));\n }\n\n /** Schedules the next stage for the current session, or nothing when it has no end or both stages ran. */\n function schedule(session: AuthSession<BffUser>): void {\n clearTimer();\n if (!refresh || closed || session.status !== AuthStatus.Authenticated || session.user === null) return;\n const expiresAt = BffSessionExtensions.expiresAtMs(session.user);\n if (expiresAt === null) return;\n const done = fired?.expiresAt === session.user.expiresAt ? fired.stage : null;\n if (done === 'expiry') return;\n if (done === 'lead') arm('expiry', expiresAt);\n else arm('lead', expiresAt - refresh.leadMs);\n }\n\n async function fire(stage: Stage): Promise<void> {\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated || session.user === null) return;\n const before = fired;\n // Recorded before the read: the read republishes the session, and the republish must see this stage as done.\n fired = { expiresAt: session.user.expiresAt, stage };\n lastFireAt = now();\n const outcome = await revalidate();\n if (closed) return;\n if (outcome.ok) {\n failures = 0;\n return;\n }\n // A cancelled read was superseded by a sign-in, sign-out or newer read, which reschedules on its own.\n if (outcome.failure.type === 'cancelled') return;\n fired = before;\n failures += 1;\n if (!refresh || failures > refresh.maxRetries) return;\n arm(stage, now() + Math.min(refresh.retryMs * 2 ** (failures - 1), MaxRetryDelayMs));\n }\n\n function onSession(session: AuthSession<BffUser>): void {\n if (closed) return;\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n lastLoadedAt = now();\n const key =\n session.status === AuthStatus.Authenticated && session.user !== null\n ? BffSessionExtensions.identity(session.user)\n : null;\n const previous = lastKey;\n lastKey = key;\n // A signed-out change is announced by the strategy once the server has processed it; announcing here would race it.\n if (key !== null && key !== previous && peerDepth === 0) channel?.post({ kind: BffSyncKind.SignedIn });\n schedule(session);\n }\n\n /** Re-reads when the last read is stale. Both a focus and a visibility event arrive; the second finds it fresh. */\n function wake(): void {\n if (closed || !refresh) return;\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n if (now() - lastLoadedAt < refresh.staleAfterMs) return;\n failures = 0;\n void revalidate();\n }\n\n async function applyHint(): Promise<void> {\n peerDepth += 1;\n failures = 0;\n try {\n await revalidate();\n } finally {\n peerDepth -= 1;\n }\n }\n\n disposers.push(host.subscribe(onSession));\n onSession(host.getSession());\n\n if (channel) {\n const open = channel;\n disposers.push(\n open.subscribe((message) => {\n if (isHint(message)) void applyHint();\n }),\n () => open.close(),\n );\n }\n\n if (refresh && typeof window !== 'undefined' && typeof document !== 'undefined') {\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') wake();\n };\n window.addEventListener('focus', wake);\n document.addEventListener('visibilitychange', onVisibility);\n disposers.push(\n () => window.removeEventListener('focus', wake),\n () => document.removeEventListener('visibilitychange', onVisibility),\n );\n }\n\n return {\n announce: (kind) => {\n if (closed || peerDepth > 0) return;\n channel?.post({ kind });\n },\n dispose: () => {\n if (closed) return;\n closed = true;\n clearTimer();\n for (const dispose of disposers.splice(0)) dispose();\n },\n };\n}\n"],"names":["wake"],"mappings":";;;;;AAMO,MAAM,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,WAAW;AACb;AAmCA,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB,EAAE,QAAQ,KAAQ,eAAe,MAAQ,cAAc,KAAQ,SAAS,KAAQ,YAAY,EAAA;AACpH,MAAM,kBAAkB;AAExB,MAAM,aAAa;AAmBnB,MAAM,SAAS,CAAC,YACd,OAAO,YAAY,YACnB,YAAY,SACV,QAA2B,SAAS,YAAY,YAC/C,QAA2B,SAAS,YAAY;AAa9C,SA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AG;AAC7B,eAAS,KAAK,EAAE,MAAM;AAAA,IACxB;AAAA,IACA,SAAS,MAAM;AACb,UAAI,OAAQ;AACZ,eAAS;AACT,iBAAA;AACA,iBAAW,WAAW,UAAU,OAAO,CAAC,EAAG,SAAA;AAAA,IAC7C;AAAA,EAAA;AAEJ;"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { ApiAntiforgeryOptions } from '../foundation/http';
|
|
2
|
+
import { SessionExpiredListener } from './AuthBridge';
|
|
3
|
+
import { AuthStrategy } from './AuthSession';
|
|
4
|
+
import { BffUser } from './BffSession';
|
|
5
|
+
import { BffRefreshOptions, BffSyncOptions } from './BffSessionSync';
|
|
6
|
+
/** Defines the options for {@link createBffStrategy}. */
|
|
7
|
+
export interface CreateBffStrategyOptions {
|
|
8
|
+
/** The route prefix of the BFF's auth endpoints. Default `/auth`. */
|
|
9
|
+
readonly prefix?: string;
|
|
10
|
+
/** The origin the auth endpoints live on. Default `''`: the SPA's own origin, the BFF's served shape. */
|
|
11
|
+
readonly baseUrl?: string;
|
|
12
|
+
/** The request header the CSRF token travels in. Default `X-Csrf-Token`. */
|
|
13
|
+
readonly csrfHeaderName?: string;
|
|
14
|
+
/** Sent with every auth request. Default is the browser's `same-origin`. */
|
|
15
|
+
readonly credentials?: RequestCredentials;
|
|
16
|
+
/** Replaces `fetch` — a mocked one in tests. */
|
|
17
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
18
|
+
/** Navigates the page. Default `window.location.assign`; inject to drive the strategy without a DOM. */
|
|
19
|
+
readonly navigate?: (url: string) => void;
|
|
20
|
+
/** Cross-tab sync. Default on, over `BroadcastChannel` with a `storage`-event fallback; `false` turns it off. */
|
|
21
|
+
readonly sync?: BffSyncOptions | false;
|
|
22
|
+
/** Session refresh before `expiresAt` and on focus. Default on; `false` turns it off. */
|
|
23
|
+
readonly refresh?: BffRefreshOptions | false;
|
|
24
|
+
/** The clock refresh scheduling reads. Default `Date.now`. */
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
}
|
|
27
|
+
/** Defines the BFF strategy — an {@link AuthStrategy} plus the pieces the rest of the app wires. */
|
|
28
|
+
export interface BffStrategy extends AuthStrategy<BffUser, string | undefined> {
|
|
29
|
+
/**
|
|
30
|
+
* Feeds `createApiClient({ antiforgery })`, so every unsafe request echoes the session's CSRF token. The token
|
|
31
|
+
* is read per request, so a refreshed session and a sign-out take effect at once.
|
|
32
|
+
*/
|
|
33
|
+
readonly antiforgery: ApiAntiforgeryOptions;
|
|
34
|
+
/** Reads the current CSRF token; `null` while signed out. */
|
|
35
|
+
readonly getCsrfToken: () => string | null;
|
|
36
|
+
/** Builds `{prefix}/login?returnUrl=…` for a local path; a path that is not local falls back to `/`. */
|
|
37
|
+
readonly loginUrl: (returnUrl?: string) => string;
|
|
38
|
+
/**
|
|
39
|
+
* Sends the person to sign-in with the page they were on. Subscribe it to the bridge:
|
|
40
|
+
* `bridge.subscribeExpired(bff.redirectToLogin)`.
|
|
41
|
+
*/
|
|
42
|
+
readonly redirectToLogin: SessionExpiredListener;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Creates the BFF session strategy for an SPA served on its BFF's origin. The BFF owns the session cookie; the SPA
|
|
46
|
+
* reads `GET {prefix}/session`, signs in by navigating to `{prefix}/login?returnUrl=…`, and signs out with
|
|
47
|
+
* `POST {prefix}/logout`, then navigates to the returned `endSessionUrl`.
|
|
48
|
+
*
|
|
49
|
+
* Its own HTTP client carries the auth calls, with no request scope — a sign-out must not cancel itself. The app's
|
|
50
|
+
* client takes {@link BffStrategy.antiforgery} so its writes carry the CSRF token. Pair it with
|
|
51
|
+
* `createAuthBridge({ getIdentity: BffSessionExtensions.identity })`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function createBffStrategy(options?: CreateBffStrategyOptions): BffStrategy;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createApiClient } from "../foundation/http/CreateApiClient.js";
|
|
2
|
+
import { AppErrorFactory } from "../foundation/results/AppErrorFactory.js";
|
|
3
|
+
import { ResultExtensions } from "../foundation/results/ResultExtensions.js";
|
|
4
|
+
import { decodeBffLogout, decodeBffSession } from "./BffSession.js";
|
|
5
|
+
import { connectBffSession } from "./BffSessionSync.js";
|
|
6
|
+
import { ReturnUrlExtensions } from "./ReturnUrlExtensions.js";
|
|
7
|
+
function createBffStrategy(options = {}) {
|
|
8
|
+
const {
|
|
9
|
+
prefix = "/auth",
|
|
10
|
+
baseUrl = "",
|
|
11
|
+
csrfHeaderName = "X-Csrf-Token",
|
|
12
|
+
sync = {},
|
|
13
|
+
refresh = {},
|
|
14
|
+
now = () => Date.now()
|
|
15
|
+
} = options;
|
|
16
|
+
const root = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
|
|
17
|
+
let csrfToken = null;
|
|
18
|
+
let generation = 0;
|
|
19
|
+
let link;
|
|
20
|
+
const antiforgery = { headerName: csrfHeaderName, getToken: () => csrfToken };
|
|
21
|
+
const clientOptions = {
|
|
22
|
+
baseUrl,
|
|
23
|
+
antiforgery,
|
|
24
|
+
...options.credentials !== void 0 ? { credentials: options.credentials } : {},
|
|
25
|
+
...options.fetch !== void 0 ? { fetch: options.fetch } : {}
|
|
26
|
+
};
|
|
27
|
+
const client = createApiClient(clientOptions);
|
|
28
|
+
const cancelled = () => ResultExtensions.fail(AppErrorFactory.cancelled());
|
|
29
|
+
const navigate = options.navigate ?? ((url) => {
|
|
30
|
+
if (typeof window === "undefined") {
|
|
31
|
+
throw new Error("createBffStrategy: navigating needs a browser. Pass `navigate` to drive it elsewhere.");
|
|
32
|
+
}
|
|
33
|
+
window.location.assign(url);
|
|
34
|
+
});
|
|
35
|
+
const loginUrl = (returnUrl = ReturnUrlExtensions.current()) => `${baseUrl}${root}/login?returnUrl=${encodeURIComponent(ReturnUrlExtensions.isLocal(returnUrl) ? returnUrl : "/")}`;
|
|
36
|
+
return {
|
|
37
|
+
antiforgery,
|
|
38
|
+
getCsrfToken: () => csrfToken,
|
|
39
|
+
loginUrl,
|
|
40
|
+
redirectToLogin: ({ returnUrl }) => navigate(loginUrl(returnUrl)),
|
|
41
|
+
async resolveUser(context) {
|
|
42
|
+
const current = ++generation;
|
|
43
|
+
const outcome = await client.get(`${root}/session`, { ...context, decode: decodeBffSession });
|
|
44
|
+
if (current !== generation || context.signal?.aborted) return cancelled();
|
|
45
|
+
if (!outcome.ok) {
|
|
46
|
+
if (outcome.failure.status !== 401) return outcome;
|
|
47
|
+
csrfToken = null;
|
|
48
|
+
return ResultExtensions.ok(null);
|
|
49
|
+
}
|
|
50
|
+
csrfToken = outcome.value.csrfToken;
|
|
51
|
+
return ResultExtensions.ok(outcome.value.user);
|
|
52
|
+
},
|
|
53
|
+
// Returns void on purpose: the session stays as it is while the browser navigates to the BFF.
|
|
54
|
+
signIn(returnUrl) {
|
|
55
|
+
const target = returnUrl ?? ReturnUrlExtensions.current();
|
|
56
|
+
if (!ReturnUrlExtensions.isLocal(target)) return ResultExtensions.fail(AppErrorFactory.validation());
|
|
57
|
+
if (!options.navigate && typeof window === "undefined")
|
|
58
|
+
return ResultExtensions.fail(AppErrorFactory.unavailable());
|
|
59
|
+
navigate(loginUrl(target));
|
|
60
|
+
return ResultExtensions.ok(void 0);
|
|
61
|
+
},
|
|
62
|
+
async signOut(context) {
|
|
63
|
+
++generation;
|
|
64
|
+
try {
|
|
65
|
+
const outcome = await client.post(`${root}/logout`, { ...context, decode: decodeBffLogout });
|
|
66
|
+
if (!outcome.ok) {
|
|
67
|
+
return outcome.failure.status === 401 ? ResultExtensions.ok(void 0) : outcome;
|
|
68
|
+
}
|
|
69
|
+
navigate(outcome.value.endSessionUrl);
|
|
70
|
+
return ResultExtensions.ok(void 0);
|
|
71
|
+
} finally {
|
|
72
|
+
csrfToken = null;
|
|
73
|
+
link?.announce("signed-out");
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
onUnauthorized() {
|
|
77
|
+
generation += 1;
|
|
78
|
+
csrfToken = null;
|
|
79
|
+
link?.announce("signed-out");
|
|
80
|
+
},
|
|
81
|
+
connect(host) {
|
|
82
|
+
link?.dispose();
|
|
83
|
+
const own = connectBffSession(host, { sync, refresh, now });
|
|
84
|
+
link = own;
|
|
85
|
+
return () => {
|
|
86
|
+
own.dispose();
|
|
87
|
+
if (link === own) link = void 0;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export {
|
|
93
|
+
createBffStrategy
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=BffStrategy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BffStrategy.js","sources":["../../src/auth/BffStrategy.ts"],"sourcesContent":["import { createApiClient, type ApiAntiforgeryOptions, type ApiClientOptions } from '../foundation/http';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport type { SessionExpiredListener } from './AuthBridge';\nimport type { AuthResolveContext, AuthStrategy, AuthStrategyHost } from './AuthSession';\nimport { decodeBffLogout, decodeBffSession, type BffUser } from './BffSession';\nimport { connectBffSession, type BffRefreshOptions, type BffSessionLink, type BffSyncOptions } from './BffSessionSync';\nimport { ReturnUrlExtensions } from './ReturnUrlExtensions';\n\n/** Defines the options for {@link createBffStrategy}. */\nexport interface CreateBffStrategyOptions {\n /** The route prefix of the BFF's auth endpoints. Default `/auth`. */\n readonly prefix?: string;\n\n /** The origin the auth endpoints live on. Default `''`: the SPA's own origin, the BFF's served shape. */\n readonly baseUrl?: string;\n\n /** The request header the CSRF token travels in. Default `X-Csrf-Token`. */\n readonly csrfHeaderName?: string;\n\n /** Sent with every auth request. Default is the browser's `same-origin`. */\n readonly credentials?: RequestCredentials;\n\n /** Replaces `fetch` — a mocked one in tests. */\n readonly fetch?: typeof globalThis.fetch;\n\n /** Navigates the page. Default `window.location.assign`; inject to drive the strategy without a DOM. */\n readonly navigate?: (url: string) => void;\n\n /** Cross-tab sync. Default on, over `BroadcastChannel` with a `storage`-event fallback; `false` turns it off. */\n readonly sync?: BffSyncOptions | false;\n\n /** Session refresh before `expiresAt` and on focus. Default on; `false` turns it off. */\n readonly refresh?: BffRefreshOptions | false;\n\n /** The clock refresh scheduling reads. Default `Date.now`. */\n readonly now?: () => number;\n}\n\n/** Defines the BFF strategy — an {@link AuthStrategy} plus the pieces the rest of the app wires. */\nexport interface BffStrategy extends AuthStrategy<BffUser, string | undefined> {\n /**\n * Feeds `createApiClient({ antiforgery })`, so every unsafe request echoes the session's CSRF token. The token\n * is read per request, so a refreshed session and a sign-out take effect at once.\n */\n readonly antiforgery: ApiAntiforgeryOptions;\n\n /** Reads the current CSRF token; `null` while signed out. */\n readonly getCsrfToken: () => string | null;\n\n /** Builds `{prefix}/login?returnUrl=…` for a local path; a path that is not local falls back to `/`. */\n readonly loginUrl: (returnUrl?: string) => string;\n\n /**\n * Sends the person to sign-in with the page they were on. Subscribe it to the bridge:\n * `bridge.subscribeExpired(bff.redirectToLogin)`.\n */\n readonly redirectToLogin: SessionExpiredListener;\n}\n\n/**\n * Creates the BFF session strategy for an SPA served on its BFF's origin. The BFF owns the session cookie; the SPA\n * reads `GET {prefix}/session`, signs in by navigating to `{prefix}/login?returnUrl=…`, and signs out with\n * `POST {prefix}/logout`, then navigates to the returned `endSessionUrl`.\n *\n * Its own HTTP client carries the auth calls, with no request scope — a sign-out must not cancel itself. The app's\n * client takes {@link BffStrategy.antiforgery} so its writes carry the CSRF token. Pair it with\n * `createAuthBridge({ getIdentity: BffSessionExtensions.identity })`.\n */\nexport function createBffStrategy(options: CreateBffStrategyOptions = {}): BffStrategy {\n const {\n prefix = '/auth',\n baseUrl = '',\n csrfHeaderName = 'X-Csrf-Token',\n sync = {},\n refresh = {},\n now = () => Date.now(),\n } = options;\n const root = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n\n let csrfToken: string | null = null;\n let generation = 0;\n let link: BffSessionLink | undefined;\n\n const antiforgery: ApiAntiforgeryOptions = { headerName: csrfHeaderName, getToken: () => csrfToken };\n const clientOptions: ApiClientOptions = {\n baseUrl,\n antiforgery,\n ...(options.credentials !== undefined ? { credentials: options.credentials } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n const client = createApiClient(clientOptions);\n const cancelled = () => ResultExtensions.fail(AppErrorFactory.cancelled());\n\n const navigate =\n options.navigate ??\n ((url: string) => {\n if (typeof window === 'undefined') {\n throw new Error('createBffStrategy: navigating needs a browser. Pass `navigate` to drive it elsewhere.');\n }\n window.location.assign(url);\n });\n const loginUrl = (returnUrl: string = ReturnUrlExtensions.current()): string =>\n `${baseUrl}${root}/login?returnUrl=${encodeURIComponent(ReturnUrlExtensions.isLocal(returnUrl) ? returnUrl : '/')}`;\n\n return {\n antiforgery,\n getCsrfToken: () => csrfToken,\n loginUrl,\n redirectToLogin: ({ returnUrl }) => navigate(loginUrl(returnUrl)),\n\n async resolveUser(context: AuthResolveContext): Promise<Result<BffUser | null, AppError>> {\n const current = ++generation;\n const outcome = await client.get(`${root}/session`, { ...context, decode: decodeBffSession });\n if (current !== generation || context.signal?.aborted) return cancelled();\n if (!outcome.ok) {\n // A BFF answers a signed-out `GET /session` with 200; a 401 from a proxy in front still means signed out.\n if (outcome.failure.status !== 401) return outcome;\n csrfToken = null;\n return ResultExtensions.ok(null);\n }\n csrfToken = outcome.value.csrfToken;\n return ResultExtensions.ok(outcome.value.user);\n },\n\n // Returns void on purpose: the session stays as it is while the browser navigates to the BFF.\n signIn(returnUrl?: string): Result<void, AppError> {\n const target = returnUrl ?? ReturnUrlExtensions.current();\n if (!ReturnUrlExtensions.isLocal(target)) return ResultExtensions.fail(AppErrorFactory.validation());\n if (!options.navigate && typeof window === 'undefined')\n return ResultExtensions.fail(AppErrorFactory.unavailable());\n navigate(loginUrl(target));\n return ResultExtensions.ok(undefined);\n },\n\n async signOut(context: AuthResolveContext): Promise<Result<void, AppError>> {\n ++generation;\n try {\n // The token is read when the request is sent, so it must outlive the call and clear only afterwards.\n const outcome = await client.post(`${root}/logout`, { ...context, decode: decodeBffLogout });\n if (!outcome.ok) {\n // A 401 means the server session was already gone: signed out either way, with no provider session to end.\n return outcome.failure.status === 401 ? ResultExtensions.ok(undefined) : outcome;\n }\n navigate(outcome.value.endSessionUrl);\n return ResultExtensions.ok(undefined);\n } finally {\n csrfToken = null;\n // Told after the server answered: a hint sent earlier would let a tab read the session before it ended.\n link?.announce('signed-out');\n }\n },\n\n onUnauthorized(): void {\n generation += 1;\n csrfToken = null;\n link?.announce('signed-out');\n },\n\n connect(host: AuthStrategyHost<BffUser>): () => void {\n link?.dispose();\n const own = connectBffSession(host, { sync, refresh, now });\n link = own;\n return () => {\n own.dispose();\n if (link === own) link = undefined;\n };\n },\n };\n}\n"],"names":[],"mappings":";;;;;;AAoEO,SAAS,kBAAkB,UAAoC,IAAiB;AACrF,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,OAAO,CAAA;AAAA,IACP,UAAU,CAAA;AAAA,IACV,MAAM,MAAM,KAAK,IAAA;AAAA,EAAI,IACnB;AACJ,QAAM,OAAO,OAAO,SAAS,GAAG,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI;AAE1D,MAAI,YAA2B;AAC/B,MAAI,aAAa;AACjB,MAAI;AAEJ,QAAM,cAAqC,EAAE,YAAY,gBAAgB,UAAU,MAAM,UAAA;AACzF,QAAM,gBAAkC;AAAA,IACtC;AAAA,IACA;AAAA,IACA,GAAI,QAAQ,gBAAgB,SAAY,EAAE,aAAa,QAAQ,YAAA,IAAgB,CAAA;AAAA,IAC/E,GAAI,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,UAAU,CAAA;AAAA,EAAC;AAEhE,QAAM,SAAS,gBAAgB,aAAa;AAC5C,QAAM,YAAY,MAAM,iBAAiB,KAAK,gBAAgB,WAAW;AAEzE,QAAM,WACJ,QAAQ,aACP,CAAC,QAAgB;AAChB,QAAI,OAAO,WAAW,aAAa;AACjC,YAAM,IAAI,MAAM,u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