@useauthio/react 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/README.md +52 -19
- package/dist/index.cjs +303 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +265 -25
- package/dist/index.d.ts +265 -25
- package/dist/index.js +296 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/activity.ts +95 -0
- package/src/device-signals.ts +86 -0
- package/src/index.ts +29 -2
- package/src/lobby-context.ts +8 -0
- package/src/locate.ts +42 -0
- package/src/provider.tsx +109 -14
- package/src/refresh.ts +41 -0
- package/src/sign-in.ts +189 -2
- package/src/telemetry.ts +11 -0
- package/src/types.ts +71 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
package/src/activity.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { isBrowser, isTabHidden } from "./ssr";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* DOM events that count as "the user is here". All are registered
|
|
5
|
+
* passive + capture so we never delay the page's own handlers, and
|
|
6
|
+
* `scroll` is the only high-frequency one — the throttle below keeps
|
|
7
|
+
* it from churning.
|
|
8
|
+
*/
|
|
9
|
+
const ACTIVITY_EVENTS = [
|
|
10
|
+
"pointerdown",
|
|
11
|
+
"keydown",
|
|
12
|
+
"touchstart",
|
|
13
|
+
"scroll",
|
|
14
|
+
"focus",
|
|
15
|
+
] as const;
|
|
16
|
+
|
|
17
|
+
/** Minimum gap between two recorded activity timestamps. */
|
|
18
|
+
const THROTTLE_MS = 1000;
|
|
19
|
+
|
|
20
|
+
export type ActivityListener = (at: number) => void;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Tracks the last moment the user interacted with the page. Used by the
|
|
24
|
+
* provider to decide whether a scheduled silent refresh should run or
|
|
25
|
+
* be deferred: when the project/org has an inactivity (idle) timeout,
|
|
26
|
+
* refreshing on a timer while nobody is at the keyboard would bump the
|
|
27
|
+
* server's `last_active_at` and defeat that policy. See `RefreshScheduler`.
|
|
28
|
+
*
|
|
29
|
+
* SSR-safe — under SSR `lastActivityAt()` is `0` and listeners are never
|
|
30
|
+
* attached.
|
|
31
|
+
*/
|
|
32
|
+
export class ActivityTracker {
|
|
33
|
+
private last = 0;
|
|
34
|
+
private listeners = new Set<ActivityListener>();
|
|
35
|
+
private handler: (() => void) | null = null;
|
|
36
|
+
private visibilityHandler: (() => void) | null = null;
|
|
37
|
+
private destroyed = false;
|
|
38
|
+
|
|
39
|
+
constructor(now: () => number = Date.now) {
|
|
40
|
+
this.now = now;
|
|
41
|
+
if (!isBrowser()) return;
|
|
42
|
+
this.handler = () => this.mark();
|
|
43
|
+
for (const ev of ACTIVITY_EVENTS) {
|
|
44
|
+
window.addEventListener(ev, this.handler, { passive: true, capture: true });
|
|
45
|
+
}
|
|
46
|
+
this.visibilityHandler = () => {
|
|
47
|
+
if (!isTabHidden()) this.mark();
|
|
48
|
+
};
|
|
49
|
+
document.addEventListener("visibilitychange", this.visibilityHandler);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private readonly now: () => number;
|
|
53
|
+
|
|
54
|
+
/** Unix ms of the most recent recorded interaction, `0` if none yet. */
|
|
55
|
+
lastActivityAt(): number {
|
|
56
|
+
return this.last;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Record activity now. Throttled to one write per second; listeners
|
|
61
|
+
* fire only when a write actually happens. Exposed so tests (and
|
|
62
|
+
* embedders with their own activity signal) can poke it directly.
|
|
63
|
+
*/
|
|
64
|
+
mark(): void {
|
|
65
|
+
if (this.destroyed) return;
|
|
66
|
+
const t = this.now();
|
|
67
|
+
if (t - this.last < THROTTLE_MS) return;
|
|
68
|
+
this.last = t;
|
|
69
|
+
for (const l of this.listeners) l(t);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Subscribe to recorded activity. Returns an unsubscribe function. */
|
|
73
|
+
onActivity(listener: ActivityListener): () => void {
|
|
74
|
+
this.listeners.add(listener);
|
|
75
|
+
return () => {
|
|
76
|
+
this.listeners.delete(listener);
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
destroy(): void {
|
|
81
|
+
this.destroyed = true;
|
|
82
|
+
this.listeners.clear();
|
|
83
|
+
if (!isBrowser()) return;
|
|
84
|
+
if (this.handler) {
|
|
85
|
+
for (const ev of ACTIVITY_EVENTS) {
|
|
86
|
+
window.removeEventListener(ev, this.handler, { capture: true });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (this.visibilityHandler) {
|
|
90
|
+
document.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
91
|
+
}
|
|
92
|
+
this.handler = null;
|
|
93
|
+
this.visibilityHandler = null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional browser device signals for Authio risk / device fingerprinting.
|
|
3
|
+
*
|
|
4
|
+
* Web browsers do not expose a hardware ID (IMEI, serial, MAC). These
|
|
5
|
+
* coarse, non-PII signals improve device recognition alongside the
|
|
6
|
+
* server-parsed user agent. auth-core hashes them server-side — never
|
|
7
|
+
* send a precomputed fingerprint from the client.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface DeviceSignalsCapture {
|
|
11
|
+
timezone?: string;
|
|
12
|
+
screen_resolution?: string;
|
|
13
|
+
language?: string;
|
|
14
|
+
platform?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Collect coarse device signals available in a browser context. */
|
|
18
|
+
export function collectDeviceSignals(): DeviceSignalsCapture {
|
|
19
|
+
if (typeof window === "undefined") {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
const out: DeviceSignalsCapture = {};
|
|
23
|
+
try {
|
|
24
|
+
out.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
25
|
+
} catch {
|
|
26
|
+
/* ignore */
|
|
27
|
+
}
|
|
28
|
+
if (typeof screen !== "undefined") {
|
|
29
|
+
out.screen_resolution = `${screen.width}x${screen.height}`;
|
|
30
|
+
}
|
|
31
|
+
if (typeof navigator !== "undefined") {
|
|
32
|
+
if (navigator.language) {
|
|
33
|
+
out.language = navigator.language;
|
|
34
|
+
}
|
|
35
|
+
if (navigator.platform) {
|
|
36
|
+
out.platform = navigator.platform;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Encode signals for the `X-Authio-Device-Signals` request header. */
|
|
43
|
+
export function encodeDeviceSignalsHeader(
|
|
44
|
+
signals: DeviceSignalsCapture,
|
|
45
|
+
): string {
|
|
46
|
+
const json = JSON.stringify(signals);
|
|
47
|
+
if (typeof btoa === "function") {
|
|
48
|
+
return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
49
|
+
}
|
|
50
|
+
// Node / test fallback. Typed structurally off globalThis so the browser
|
|
51
|
+
// SDK doesn't need @types/node just for this branch.
|
|
52
|
+
const nodeBuffer = (
|
|
53
|
+
globalThis as {
|
|
54
|
+
Buffer?: {
|
|
55
|
+
from(input: string, encoding: string): { toString(encoding: string): string };
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
).Buffer;
|
|
59
|
+
if (!nodeBuffer) {
|
|
60
|
+
throw new Error("No base64 encoder available in this environment.");
|
|
61
|
+
}
|
|
62
|
+
return nodeBuffer
|
|
63
|
+
.from(json, "utf8")
|
|
64
|
+
.toString("base64")
|
|
65
|
+
.replace(/\+/g, "-")
|
|
66
|
+
.replace(/\//g, "_")
|
|
67
|
+
.replace(/=+$/, "");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Header name auth-core reads for optional client device signals. */
|
|
71
|
+
export const DEVICE_SIGNALS_HEADER = "X-Authio-Device-Signals";
|
|
72
|
+
|
|
73
|
+
export function deviceSignalsExtraHeaders(
|
|
74
|
+
signals?: DeviceSignalsCapture,
|
|
75
|
+
): Record<string, string> {
|
|
76
|
+
const s = signals ?? collectDeviceSignals();
|
|
77
|
+
if (
|
|
78
|
+
!s.timezone &&
|
|
79
|
+
!s.screen_resolution &&
|
|
80
|
+
!s.language &&
|
|
81
|
+
!s.platform
|
|
82
|
+
) {
|
|
83
|
+
return {};
|
|
84
|
+
}
|
|
85
|
+
return { [DEVICE_SIGNALS_HEADER]: encodeDeviceSignalsHeader(s) };
|
|
86
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -17,7 +17,12 @@ export type {
|
|
|
17
17
|
RedirectToSignInProps,
|
|
18
18
|
} from "./gates";
|
|
19
19
|
|
|
20
|
-
export {
|
|
20
|
+
export {
|
|
21
|
+
signInWithMagicLink,
|
|
22
|
+
signInWithPasskey,
|
|
23
|
+
sendEmailOtp,
|
|
24
|
+
verifyEmailOtp,
|
|
25
|
+
} from "./sign-in";
|
|
21
26
|
|
|
22
27
|
export {
|
|
23
28
|
addPasskey,
|
|
@@ -46,20 +51,37 @@ export type {
|
|
|
46
51
|
SignInWithMagicLinkOptions,
|
|
47
52
|
SignInWithPasskeyOptions,
|
|
48
53
|
SignInWithPasskeyResult,
|
|
54
|
+
SendEmailOtpOptions,
|
|
55
|
+
VerifyEmailOtpOptions,
|
|
56
|
+
VerifyEmailOtpResult,
|
|
49
57
|
} from "./sign-in";
|
|
50
58
|
|
|
51
|
-
export { captureClientLocation } from "./locate";
|
|
59
|
+
export { captureClientLocation, verifyLocate } from "./locate";
|
|
52
60
|
export type {
|
|
53
61
|
ClientLocationCapture,
|
|
54
62
|
CaptureClientLocationOptions,
|
|
63
|
+
LocateAction,
|
|
64
|
+
VerifyLocateOptions,
|
|
65
|
+
LocateVerifyResult,
|
|
55
66
|
} from "./locate";
|
|
56
67
|
|
|
68
|
+
export {
|
|
69
|
+
collectDeviceSignals,
|
|
70
|
+
encodeDeviceSignalsHeader,
|
|
71
|
+
deviceSignalsExtraHeaders,
|
|
72
|
+
DEVICE_SIGNALS_HEADER,
|
|
73
|
+
} from "./device-signals";
|
|
74
|
+
export type { DeviceSignalsCapture } from "./device-signals";
|
|
75
|
+
|
|
57
76
|
export { AuthioError, wrapFetchError } from "./errors";
|
|
58
77
|
|
|
59
78
|
export type {
|
|
60
79
|
AuthioUser,
|
|
61
80
|
AuthioStatus,
|
|
62
81
|
AuthioStorageMode,
|
|
82
|
+
AuthioIdleRefreshMode,
|
|
83
|
+
SessionPolicy,
|
|
84
|
+
RawSessionPolicy,
|
|
63
85
|
AuthioContextValue,
|
|
64
86
|
AuthioProviderProps,
|
|
65
87
|
AuthioTokenVerification,
|
|
@@ -67,3 +89,8 @@ export type {
|
|
|
67
89
|
} from "./types";
|
|
68
90
|
|
|
69
91
|
export type { AuthioTelemetryEvent } from "./telemetry";
|
|
92
|
+
|
|
93
|
+
export { coerceSessionPolicy } from "./types";
|
|
94
|
+
export { ActivityTracker } from "./activity";
|
|
95
|
+
export type { ActivityListener } from "./activity";
|
|
96
|
+
export type { RefreshDeferReason } from "./refresh";
|
package/src/lobby-context.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface MintLobbySignInUrlOptions {
|
|
|
7
7
|
redirectUri: string;
|
|
8
8
|
/** Post-login path threaded separately from redirect_uri (BFF ?next=). */
|
|
9
9
|
next?: string;
|
|
10
|
+
/** Org scope for org_policies.disabled_methods on the Lobby surface. */
|
|
11
|
+
organizationId?: string;
|
|
10
12
|
fetchImpl?: typeof fetch;
|
|
11
13
|
}
|
|
12
14
|
|
|
@@ -37,6 +39,9 @@ export async function mintLobbySignInUrl(
|
|
|
37
39
|
project_id: opts.projectId,
|
|
38
40
|
redirect_uri: opts.redirectUri,
|
|
39
41
|
...(opts.next ? { next: opts.next } : {}),
|
|
42
|
+
...(opts.organizationId
|
|
43
|
+
? { organization_id: opts.organizationId }
|
|
44
|
+
: {}),
|
|
40
45
|
}),
|
|
41
46
|
},
|
|
42
47
|
);
|
|
@@ -59,5 +64,8 @@ export async function mintLobbySignInUrl(
|
|
|
59
64
|
if (opts.next) {
|
|
60
65
|
target.searchParams.set("next", opts.next);
|
|
61
66
|
}
|
|
67
|
+
if (opts.organizationId) {
|
|
68
|
+
target.searchParams.set("organization_id", opts.organizationId);
|
|
69
|
+
}
|
|
62
70
|
return target.toString();
|
|
63
71
|
}
|
package/src/locate.ts
CHANGED
|
@@ -55,3 +55,45 @@ export function captureClientLocation(
|
|
|
55
55
|
);
|
|
56
56
|
});
|
|
57
57
|
}
|
|
58
|
+
|
|
59
|
+
export type LocateAction = "sign_in" | "wager_placed" | "contest_entry" | string;
|
|
60
|
+
|
|
61
|
+
export interface VerifyLocateOptions {
|
|
62
|
+
apiUrl: string;
|
|
63
|
+
projectId: string;
|
|
64
|
+
accessToken: string;
|
|
65
|
+
action: LocateAction;
|
|
66
|
+
clientLocation?: ClientLocationCapture;
|
|
67
|
+
idempotencyKey?: string;
|
|
68
|
+
fetchImpl?: typeof fetch;
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface LocateVerifyResult {
|
|
73
|
+
verification_id: string;
|
|
74
|
+
decision: "allow" | "block";
|
|
75
|
+
confidence: number;
|
|
76
|
+
method: string;
|
|
77
|
+
location: { country: string; region: string; source: string };
|
|
78
|
+
network_signals: {
|
|
79
|
+
vpn: boolean;
|
|
80
|
+
datacenter: boolean;
|
|
81
|
+
tor: boolean;
|
|
82
|
+
anonymous_proxy: boolean;
|
|
83
|
+
satellite: boolean;
|
|
84
|
+
};
|
|
85
|
+
evasion_signals: string[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const VERIFY_LOCATE_BACKEND_ONLY =
|
|
89
|
+
"verifyLocate() is not supported in @useauthio/react: POST /v1/locate/verify requires a project secret key (sk_live_/sk_test_), not a user JWT. " +
|
|
90
|
+
"Capture GPS with captureClientLocation(), POST to your backend, and call authio.locate.verify() via @useauthio/node. " +
|
|
91
|
+
"See authio_locate/docs/JB_MIGRATION_GUIDE.md.";
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @deprecated Use backend proxy with `@useauthio/node` `authio.locate.verify()` — see JB migration guide.
|
|
95
|
+
* This helper always throws; it must not send a user JWT to the sk_-only verify route.
|
|
96
|
+
*/
|
|
97
|
+
export async function verifyLocate(_opts: VerifyLocateOptions): Promise<LocateVerifyResult> {
|
|
98
|
+
throw new Error(VERIFY_LOCATE_BACKEND_ONLY);
|
|
99
|
+
}
|
package/src/provider.tsx
CHANGED
|
@@ -9,17 +9,21 @@ import React, {
|
|
|
9
9
|
import { AuthioError } from "@useauthio/node";
|
|
10
10
|
import { authioFetch } from "./fetch";
|
|
11
11
|
import { createDefaultVerifier, readJwtExp } from "./jwt";
|
|
12
|
+
import { ActivityTracker } from "./activity";
|
|
12
13
|
import { RefreshScheduler } from "./refresh";
|
|
13
14
|
import { isBrowser } from "./ssr";
|
|
14
15
|
import { createTokenStorage, type TokenStorage } from "./storage";
|
|
15
16
|
import { mintLobbySignInUrl } from "./lobby-context";
|
|
16
17
|
import { noopEmitter, type TelemetryEmitter } from "./telemetry";
|
|
17
|
-
import
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
import {
|
|
19
|
+
coerceSessionPolicy,
|
|
20
|
+
type AuthioContextValue,
|
|
21
|
+
type AuthioProviderProps,
|
|
22
|
+
type AuthioStatus,
|
|
23
|
+
type AuthioTokenVerifier,
|
|
24
|
+
type AuthioUser,
|
|
25
|
+
type RawSessionPolicy,
|
|
26
|
+
type SessionPolicy,
|
|
23
27
|
} from "./types";
|
|
24
28
|
|
|
25
29
|
export const AuthioContext = createContext<AuthioContextValue | null>(null);
|
|
@@ -30,8 +34,17 @@ interface RefreshEnvelope {
|
|
|
30
34
|
refresh_token?: string;
|
|
31
35
|
expires_at?: string;
|
|
32
36
|
user?: RawUser | null;
|
|
37
|
+
session_policy?: RawSessionPolicy;
|
|
33
38
|
}
|
|
34
39
|
|
|
40
|
+
/**
|
|
41
|
+
* Grace window around a refresh inside which user activity still counts
|
|
42
|
+
* as "after" it. The tracker throttles writes to 1/s, so an interaction
|
|
43
|
+
* landing just after a refresh may carry a timestamp just before it;
|
|
44
|
+
* we err toward refreshing.
|
|
45
|
+
*/
|
|
46
|
+
const ACTIVITY_GRACE_MS = 1000;
|
|
47
|
+
|
|
35
48
|
interface RawUser {
|
|
36
49
|
id?: string;
|
|
37
50
|
user_id?: string;
|
|
@@ -77,6 +90,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
77
90
|
projectId,
|
|
78
91
|
storage: storageMode = "memory",
|
|
79
92
|
refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
|
|
93
|
+
idleRefresh = "defer",
|
|
80
94
|
onTelemetryEvent,
|
|
81
95
|
fetch: fetchImpl,
|
|
82
96
|
signInUrl,
|
|
@@ -116,8 +130,24 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
116
130
|
fetchImpl,
|
|
117
131
|
signInUrl,
|
|
118
132
|
emit,
|
|
133
|
+
idleRefresh,
|
|
119
134
|
});
|
|
120
|
-
propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
|
|
135
|
+
propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit, idleRefresh };
|
|
136
|
+
|
|
137
|
+
// User-activity tracker + the two timestamps the idle-deferral rule
|
|
138
|
+
// compares. Refs, not state: the scheduler reads them from a timer
|
|
139
|
+
// callback and a re-render must never re-create the tracker.
|
|
140
|
+
const activityRef = useRef<ActivityTracker | null>(null);
|
|
141
|
+
// Lazily (re)created so a StrictMode double-mount, which destroys the
|
|
142
|
+
// tracker in the simulated unmount, gets a fresh one on the re-run.
|
|
143
|
+
const getTracker = useCallback((): ActivityTracker => {
|
|
144
|
+
if (activityRef.current === null) {
|
|
145
|
+
activityRef.current = new ActivityTracker();
|
|
146
|
+
}
|
|
147
|
+
return activityRef.current;
|
|
148
|
+
}, []);
|
|
149
|
+
const lastRefreshAtRef = useRef(0);
|
|
150
|
+
const policyRef = useRef<SessionPolicy | null>(null);
|
|
121
151
|
|
|
122
152
|
useEffect(() => {
|
|
123
153
|
if (!projectId) {
|
|
@@ -143,6 +173,20 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
143
173
|
skipInitialRefresh ? "unauthenticated" : "loading",
|
|
144
174
|
);
|
|
145
175
|
const [accessToken, setAccessToken] = useState<string | null>(null);
|
|
176
|
+
const [sessionPolicy, setSessionPolicy] = useState<SessionPolicy | null>(null);
|
|
177
|
+
|
|
178
|
+
/** Adopt a policy from an envelope and mark "refreshed now". */
|
|
179
|
+
const adoptPolicy = useCallback((policy: SessionPolicy | null) => {
|
|
180
|
+
policyRef.current = policy;
|
|
181
|
+
setSessionPolicy(policy);
|
|
182
|
+
lastRefreshAtRef.current = Date.now();
|
|
183
|
+
}, []);
|
|
184
|
+
|
|
185
|
+
const clearPolicy = useCallback(() => {
|
|
186
|
+
policyRef.current = null;
|
|
187
|
+
setSessionPolicy(null);
|
|
188
|
+
lastRefreshAtRef.current = 0;
|
|
189
|
+
}, []);
|
|
146
190
|
|
|
147
191
|
/**
|
|
148
192
|
* Single refresh attempt. Returns `true` on success (state has
|
|
@@ -199,6 +243,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
199
243
|
setAccessToken(token);
|
|
200
244
|
if (env.user) setUser(coerceUser(env.user));
|
|
201
245
|
setStatus("authenticated");
|
|
246
|
+
// Older auth-core omits session_policy; keep whatever we last saw
|
|
247
|
+
// rather than flapping to null and re-enabling timer refresh.
|
|
248
|
+
adoptPolicy(
|
|
249
|
+
env.session_policy !== undefined
|
|
250
|
+
? coerceSessionPolicy(env.session_policy)
|
|
251
|
+
: policyRef.current,
|
|
252
|
+
);
|
|
202
253
|
p.emit({
|
|
203
254
|
kind: "refresh_succeeded",
|
|
204
255
|
timestamp: Date.now(),
|
|
@@ -222,16 +273,17 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
222
273
|
});
|
|
223
274
|
return false;
|
|
224
275
|
}
|
|
225
|
-
}, []);
|
|
276
|
+
}, [adoptPolicy]);
|
|
226
277
|
|
|
227
278
|
// Re-spin the scheduler whenever the lead window changes.
|
|
228
279
|
useEffect(() => {
|
|
229
|
-
|
|
280
|
+
const scheduler = new RefreshScheduler({
|
|
230
281
|
leadSeconds: refreshLeadSeconds,
|
|
231
282
|
run: performRefresh,
|
|
232
283
|
onGiveUp: () => {
|
|
233
284
|
storageRef.current!.clear();
|
|
234
285
|
refreshTokenRef.current = null;
|
|
286
|
+
clearPolicy();
|
|
235
287
|
setAccessToken(null);
|
|
236
288
|
setUser(null);
|
|
237
289
|
setStatus("unauthenticated");
|
|
@@ -242,12 +294,48 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
242
294
|
timestamp: Date.now(),
|
|
243
295
|
runAt,
|
|
244
296
|
}),
|
|
297
|
+
// Idle rule: hold the timer refresh when the effective policy has
|
|
298
|
+
// an inactivity timeout and the user hasn't touched the page since
|
|
299
|
+
// the last refresh. Without a policy (legacy projects, old
|
|
300
|
+
// auth-core) this is never true and behaviour is unchanged.
|
|
301
|
+
shouldDefer: () => {
|
|
302
|
+
if (propsRef.current.idleRefresh === "always") return false;
|
|
303
|
+
const policy = policyRef.current;
|
|
304
|
+
if (!policy || policy.idleTimeoutMin <= 0) return false;
|
|
305
|
+
const lastActivity = getTracker().lastActivityAt();
|
|
306
|
+
return lastActivity + ACTIVITY_GRACE_MS < lastRefreshAtRef.current;
|
|
307
|
+
},
|
|
308
|
+
onDeferred: (reason) =>
|
|
309
|
+
propsRef.current.emit({
|
|
310
|
+
kind: "refresh_deferred",
|
|
311
|
+
timestamp: Date.now(),
|
|
312
|
+
reason,
|
|
313
|
+
}),
|
|
314
|
+
});
|
|
315
|
+
schedulerRef.current = scheduler;
|
|
316
|
+
// The next interaction after an idle deferral re-arms the timer —
|
|
317
|
+
// immediately, if the token is already inside its lead window.
|
|
318
|
+
const tracker = getTracker();
|
|
319
|
+
const unsubscribe = tracker.onActivity(() => {
|
|
320
|
+
if (scheduler.deferredReason() !== "idle") return;
|
|
321
|
+
propsRef.current.emit({ kind: "refresh_resumed", timestamp: Date.now() });
|
|
322
|
+
scheduler.resume();
|
|
245
323
|
});
|
|
246
324
|
return () => {
|
|
247
|
-
|
|
248
|
-
|
|
325
|
+
unsubscribe();
|
|
326
|
+
scheduler.destroy();
|
|
327
|
+
if (schedulerRef.current === scheduler) schedulerRef.current = null;
|
|
249
328
|
};
|
|
250
|
-
}, [refreshLeadSeconds, performRefresh]);
|
|
329
|
+
}, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
|
|
330
|
+
|
|
331
|
+
// Tear the activity tracker down with the provider.
|
|
332
|
+
useEffect(() => {
|
|
333
|
+
const tracker = getTracker();
|
|
334
|
+
return () => {
|
|
335
|
+
tracker.destroy();
|
|
336
|
+
if (activityRef.current === tracker) activityRef.current = null;
|
|
337
|
+
};
|
|
338
|
+
}, [getTracker]);
|
|
251
339
|
|
|
252
340
|
// Initial bootstrap.
|
|
253
341
|
useEffect(() => {
|
|
@@ -390,12 +478,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
390
478
|
storageRef.current!.clear();
|
|
391
479
|
refreshTokenRef.current = null;
|
|
392
480
|
schedulerRef.current?.clear();
|
|
481
|
+
clearPolicy();
|
|
393
482
|
setAccessToken(null);
|
|
394
483
|
setUser(null);
|
|
395
484
|
setStatus("unauthenticated");
|
|
396
485
|
p.emit({ kind: "sign_out", timestamp: Date.now() });
|
|
397
486
|
}
|
|
398
|
-
}, []);
|
|
487
|
+
}, [clearPolicy]);
|
|
399
488
|
|
|
400
489
|
const refresh = useCallback(
|
|
401
490
|
(): Promise<boolean> => performRefresh(),
|
|
@@ -407,6 +496,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
407
496
|
accessToken: string;
|
|
408
497
|
refreshToken?: string | null;
|
|
409
498
|
user?: AuthioUser | null;
|
|
499
|
+
sessionPolicy?: SessionPolicy | null;
|
|
410
500
|
}): Promise<void> => {
|
|
411
501
|
const p = propsRef.current;
|
|
412
502
|
const verification = await verifierRef
|
|
@@ -441,6 +531,9 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
441
531
|
setAccessToken(input.accessToken);
|
|
442
532
|
if (input.user) setUser(input.user);
|
|
443
533
|
setStatus("authenticated");
|
|
534
|
+
adoptPolicy(
|
|
535
|
+
input.sessionPolicy !== undefined ? input.sessionPolicy : policyRef.current,
|
|
536
|
+
);
|
|
444
537
|
p.emit({
|
|
445
538
|
kind: "sign_in_completed",
|
|
446
539
|
timestamp: Date.now(),
|
|
@@ -451,7 +544,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
451
544
|
schedulerRef.current?.scheduleAt(exp);
|
|
452
545
|
}
|
|
453
546
|
},
|
|
454
|
-
[],
|
|
547
|
+
[adoptPolicy],
|
|
455
548
|
);
|
|
456
549
|
|
|
457
550
|
const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
|
|
@@ -461,6 +554,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
461
554
|
user,
|
|
462
555
|
status,
|
|
463
556
|
accessToken,
|
|
557
|
+
sessionPolicy,
|
|
464
558
|
apiUrl,
|
|
465
559
|
projectId,
|
|
466
560
|
signInUrl: resolvedSignInUrl,
|
|
@@ -475,6 +569,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
475
569
|
user,
|
|
476
570
|
status,
|
|
477
571
|
accessToken,
|
|
572
|
+
sessionPolicy,
|
|
478
573
|
apiUrl,
|
|
479
574
|
projectId,
|
|
480
575
|
resolvedSignInUrl,
|
package/src/refresh.ts
CHANGED
|
@@ -10,6 +10,8 @@ const BACKOFF_DELAYS_MS = [1000, 2000, 4000, 8000, 16000, 30000];
|
|
|
10
10
|
/** After five consecutive failures we surrender and transition to unauthenticated. */
|
|
11
11
|
const MAX_ATTEMPTS = 5;
|
|
12
12
|
|
|
13
|
+
export type RefreshDeferReason = "hidden" | "idle";
|
|
14
|
+
|
|
13
15
|
export interface RefreshSchedulerOptions {
|
|
14
16
|
/** Schedule the silent refresh this many seconds before `exp`. */
|
|
15
17
|
leadSeconds: number;
|
|
@@ -19,6 +21,15 @@ export interface RefreshSchedulerOptions {
|
|
|
19
21
|
onGiveUp: () => void;
|
|
20
22
|
/** Optional sink for "next refresh scheduled at" telemetry. */
|
|
21
23
|
onScheduled?: (runAt: number) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Consulted when the timer fires (after the hidden-tab check). Return
|
|
26
|
+
* `true` to hold the refresh until `resume()` is called — the
|
|
27
|
+
* provider uses this to skip refreshing while the user is idle under
|
|
28
|
+
* an inactivity policy. Omit for the legacy always-refresh behaviour.
|
|
29
|
+
*/
|
|
30
|
+
shouldDefer?: () => boolean;
|
|
31
|
+
/** Fired when a tick is held back, with the reason. */
|
|
32
|
+
onDeferred?: (reason: RefreshDeferReason) => void;
|
|
22
33
|
}
|
|
23
34
|
|
|
24
35
|
/**
|
|
@@ -30,6 +41,10 @@ export interface RefreshSchedulerOptions {
|
|
|
30
41
|
* - When the timer fires, if the tab is hidden, we DEFER — the
|
|
31
42
|
* visibilitychange listener picks up where we left off when the
|
|
32
43
|
* tab returns. Saves battery on a sleeping background tab.
|
|
44
|
+
* - If `shouldDefer()` says so (user idle under an inactivity
|
|
45
|
+
* policy), we also DEFER and wait for `resume()` — the provider
|
|
46
|
+
* calls it on the next user interaction, which re-runs the tick
|
|
47
|
+
* immediately when the token is inside its lead window.
|
|
33
48
|
* - On failure we walk the `BACKOFF_DELAYS_MS` step list. After
|
|
34
49
|
* `MAX_ATTEMPTS` failures the scheduler calls `onGiveUp` and
|
|
35
50
|
* stops — the provider then transitions to `unauthenticated`.
|
|
@@ -41,6 +56,7 @@ export class RefreshScheduler {
|
|
|
41
56
|
private attempts = 0;
|
|
42
57
|
private lastExp: number | null = null;
|
|
43
58
|
private destroyed = false;
|
|
59
|
+
private deferred: RefreshDeferReason | null = null;
|
|
44
60
|
private visibilityHandler: (() => void) | null = null;
|
|
45
61
|
|
|
46
62
|
constructor(private readonly opts: RefreshSchedulerOptions) {
|
|
@@ -55,10 +71,16 @@ export class RefreshScheduler {
|
|
|
55
71
|
}
|
|
56
72
|
}
|
|
57
73
|
|
|
74
|
+
/** Whether the last tick was held back (and why). `null` when not deferred. */
|
|
75
|
+
deferredReason(): RefreshDeferReason | null {
|
|
76
|
+
return this.deferred;
|
|
77
|
+
}
|
|
78
|
+
|
|
58
79
|
scheduleAt(exp: number): void {
|
|
59
80
|
if (this.destroyed) return;
|
|
60
81
|
this.lastExp = exp;
|
|
61
82
|
this.attempts = 0;
|
|
83
|
+
this.deferred = null;
|
|
62
84
|
this.clear();
|
|
63
85
|
const now = Math.floor(Date.now() / 1000);
|
|
64
86
|
const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1000);
|
|
@@ -66,14 +88,33 @@ export class RefreshScheduler {
|
|
|
66
88
|
this.timer = setTimeout(() => void this.tick(), delayMs);
|
|
67
89
|
}
|
|
68
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Re-arm after a deferral. No-op unless a tick is currently held
|
|
93
|
+
* back. Re-schedules against the remembered `exp`, so a token that
|
|
94
|
+
* is already inside its lead window refreshes immediately.
|
|
95
|
+
*/
|
|
96
|
+
resume(): void {
|
|
97
|
+
if (this.destroyed || this.deferred === null || this.lastExp === null) return;
|
|
98
|
+
this.scheduleAt(this.lastExp);
|
|
99
|
+
}
|
|
100
|
+
|
|
69
101
|
private async tick(): Promise<void> {
|
|
70
102
|
this.timer = null;
|
|
71
103
|
if (this.destroyed) return;
|
|
72
104
|
if (isTabHidden()) {
|
|
73
105
|
// Defer until the tab is visible again; the visibility handler
|
|
74
106
|
// will call scheduleAt when the user returns.
|
|
107
|
+
this.deferred = "hidden";
|
|
108
|
+
this.opts.onDeferred?.("hidden");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (this.opts.shouldDefer?.()) {
|
|
112
|
+
// User is idle under an inactivity policy. Hold until resume().
|
|
113
|
+
this.deferred = "idle";
|
|
114
|
+
this.opts.onDeferred?.("idle");
|
|
75
115
|
return;
|
|
76
116
|
}
|
|
117
|
+
this.deferred = null;
|
|
77
118
|
let ok = false;
|
|
78
119
|
try {
|
|
79
120
|
ok = await this.opts.run();
|