@tereo-io/react 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +167 -2
- package/dist/api.d.ts +11 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +62 -0
- package/dist/api.js.map +1 -0
- package/dist/config.d.ts +69 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +41 -0
- package/dist/config.js.map +1 -0
- package/dist/events.d.ts +48 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +129 -0
- package/dist/events.js.map +1 -0
- package/dist/hooks.d.ts +21 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +46 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/logger.d.ts +3 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +9 -0
- package/dist/logger.js.map +1 -0
- package/dist/markers.d.ts +7 -0
- package/dist/markers.d.ts.map +1 -0
- package/dist/markers.js +15 -0
- package/dist/markers.js.map +1 -0
- package/dist/permissions.d.ts +4 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +64 -0
- package/dist/permissions.js.map +1 -0
- package/dist/provider.d.ts +30 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +213 -0
- package/dist/provider.js.map +1 -0
- package/dist/refresh.d.ts +15 -0
- package/dist/refresh.d.ts.map +1 -0
- package/dist/refresh.js +98 -0
- package/dist/refresh.js.map +1 -0
- package/dist/signIn.d.ts +13 -0
- package/dist/signIn.d.ts.map +1 -0
- package/dist/signIn.js +134 -0
- package/dist/signIn.js.map +1 -0
- package/dist/signOut.d.ts +8 -0
- package/dist/signOut.d.ts.map +1 -0
- package/dist/signOut.js +69 -0
- package/dist/signOut.js.map +1 -0
- package/dist/storage.d.ts +6 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +73 -0
- package/dist/storage.js.map +1 -0
- package/dist/storageLock.d.ts +14 -0
- package/dist/storageLock.d.ts.map +1 -0
- package/dist/storageLock.js +100 -0
- package/dist/storageLock.js.map +1 -0
- package/dist/tokens.d.ts +13 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +27 -0
- package/dist/tokens.js.map +1 -0
- package/package.json +66 -4
- package/src/api.ts +82 -0
- package/src/config.ts +108 -0
- package/src/events.ts +184 -0
- package/src/hooks.ts +62 -0
- package/src/index.ts +34 -0
- package/src/logger.ts +9 -0
- package/src/markers.ts +26 -0
- package/src/permissions.ts +77 -0
- package/src/provider.tsx +291 -0
- package/src/refresh.ts +120 -0
- package/src/signIn.ts +168 -0
- package/src/signOut.ts +85 -0
- package/src/storage.ts +80 -0
- package/src/storageLock.ts +111 -0
- package/src/tokens.ts +38 -0
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readJson, removeKey, writeJson } from "./storage.js";
|
|
2
|
+
import { activeConfig } from "./config.js";
|
|
3
|
+
// Read from storage rather than hook state: mutation closures can hold a
|
|
4
|
+
// stale render's value.
|
|
5
|
+
export const readTokens = () => readJson(activeConfig().keys.tokens);
|
|
6
|
+
export const writeTokens = (t) => {
|
|
7
|
+
const { tokens } = activeConfig().keys;
|
|
8
|
+
if (t === null)
|
|
9
|
+
removeKey(tokens);
|
|
10
|
+
else
|
|
11
|
+
writeJson(tokens, t);
|
|
12
|
+
};
|
|
13
|
+
/** Reads a JWT's claims without verifying it. */
|
|
14
|
+
export const decodeJwt = (token) => {
|
|
15
|
+
try {
|
|
16
|
+
const parts = token.split(".");
|
|
17
|
+
if (parts.length !== 3)
|
|
18
|
+
return null;
|
|
19
|
+
const binary = atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"));
|
|
20
|
+
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
21
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=tokens.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.js","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,yEAAyE;AACzE,wBAAwB;AACxB,MAAM,CAAC,MAAM,UAAU,GAAG,GAAwB,EAAE,CAClD,QAAQ,CAAe,YAAY,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAErD,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAsB,EAAQ,EAAE;IAC1D,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,EAAE,CAAC,IAAI,CAAC;IACvC,IAAI,CAAC,KAAK,IAAI;QAAE,SAAS,CAAC,MAAM,CAAC,CAAC;;QAC7B,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC,CAAC;AAEF,iDAAiD;AACjD,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAa,EAAkC,EAAE;IACzE,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACpC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;QACpE,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9D,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAGhD,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tereo-io/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Sign a React app in through Tereo: OAuth with PKCE, a session shared by tabs, token-renewing API clients, permission checks and live updates",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"tereo",
|
|
8
|
+
"react",
|
|
9
|
+
"oauth",
|
|
10
|
+
"pkce",
|
|
11
|
+
"auth"
|
|
12
|
+
],
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/tereo-io/tereo.git",
|
|
16
|
+
"directory": "packages/tereo-react"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/tereo-io/tereo/tree/master/packages/tereo-react#readme",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/tereo-io/tereo/issues"
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src",
|
|
33
|
+
"!dist/tests",
|
|
34
|
+
"!src/tests",
|
|
35
|
+
"!**/*.tsbuildinfo",
|
|
36
|
+
"NOTICE"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc",
|
|
40
|
+
"check": "tsc --noEmit",
|
|
41
|
+
"clean": "rm -rf dist tsconfig.tsbuildinfo",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"test:watch": "vitest"
|
|
44
|
+
},
|
|
45
|
+
"author": "Aaron Leman",
|
|
46
|
+
"license": "Apache-2.0",
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@tanstack/react-query": "^5",
|
|
52
|
+
"axios": "^1",
|
|
53
|
+
"react": "^19",
|
|
54
|
+
"socket.io-client": "^4"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@tanstack/react-query": "^5.104.2",
|
|
58
|
+
"@testing-library/react": "^16.3.3",
|
|
59
|
+
"@types/react": "^19.3.0",
|
|
60
|
+
"axios": "^1.20.0",
|
|
61
|
+
"jsdom": "^30.1.2",
|
|
62
|
+
"react": "19.3.1",
|
|
63
|
+
"react-dom": "19.3.1",
|
|
64
|
+
"socket.io-client": "^4.8.4",
|
|
65
|
+
"typescript": "^6.0.3",
|
|
66
|
+
"vitest": "^5.0.4"
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { readTokens, writeTokens } from "./tokens.js";
|
|
2
|
+
import { refreshTokens } from "./refresh.js";
|
|
3
|
+
import { activeConfig } from "./config.js";
|
|
4
|
+
import { hasSession } from "./markers.js";
|
|
5
|
+
import axios, {
|
|
6
|
+
type AxiosError,
|
|
7
|
+
type AxiosInstance,
|
|
8
|
+
type InternalAxiosRequestConfig,
|
|
9
|
+
} from "axios";
|
|
10
|
+
|
|
11
|
+
type Retryable = InternalAxiosRequestConfig & { _retry?: boolean };
|
|
12
|
+
|
|
13
|
+
const bearer = (config: InternalAxiosRequestConfig, accessToken: string) => {
|
|
14
|
+
config.headers.Authorization = `Bearer ${accessToken}`;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const attachAuth = (instance: AxiosInstance): void => {
|
|
18
|
+
instance.interceptors.request.use(async (config) => {
|
|
19
|
+
const tokens = readTokens();
|
|
20
|
+
const nearExpiry =
|
|
21
|
+
!tokens ||
|
|
22
|
+
Date.now() > tokens.expiresAt - activeConfig().tokenExpirationBuffer;
|
|
23
|
+
|
|
24
|
+
// A failed refresh fails the request; refreshTokens clears the tokens
|
|
25
|
+
// when core rejected it.
|
|
26
|
+
if (nearExpiry && hasSession()) {
|
|
27
|
+
bearer(config, (await refreshTokens()).access_token);
|
|
28
|
+
} else if (tokens) {
|
|
29
|
+
bearer(config, tokens.access_token);
|
|
30
|
+
}
|
|
31
|
+
return config;
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
instance.interceptors.response.use(
|
|
35
|
+
(response) => response,
|
|
36
|
+
async (error: AxiosError) => {
|
|
37
|
+
const original = error.config as Retryable | undefined;
|
|
38
|
+
if (error.response?.status !== 401 || !original || original._retry) {
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!hasSession()) {
|
|
43
|
+
writeTokens(null);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
original._retry = true;
|
|
48
|
+
// Another tab (or a concurrent request) renewed the token after this
|
|
49
|
+
// request was sent: retry with that one rather than renew again.
|
|
50
|
+
const stored = readTokens()?.access_token;
|
|
51
|
+
if (stored && original.headers.Authorization !== `Bearer ${stored}`) {
|
|
52
|
+
bearer(original, stored);
|
|
53
|
+
return instance(original);
|
|
54
|
+
}
|
|
55
|
+
const tokens = await refreshTokens();
|
|
56
|
+
bearer(original, tokens.access_token);
|
|
57
|
+
return instance(original);
|
|
58
|
+
}
|
|
59
|
+
);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* One client per named API. `authed` sends the access token, renewing it
|
|
64
|
+
* before it expires and once after a 401; `open` sends nothing, for
|
|
65
|
+
* endpoints that need no token or use cookies.
|
|
66
|
+
*/
|
|
67
|
+
export const createApiClients = (
|
|
68
|
+
apis: Record<string, string>
|
|
69
|
+
): {
|
|
70
|
+
authed: Record<string, AxiosInstance>;
|
|
71
|
+
open: Record<string, AxiosInstance>;
|
|
72
|
+
} => {
|
|
73
|
+
const authed: Record<string, AxiosInstance> = {};
|
|
74
|
+
const open: Record<string, AxiosInstance> = {};
|
|
75
|
+
for (const [name, baseURL] of Object.entries(apis)) {
|
|
76
|
+
const instance = axios.create({ baseURL });
|
|
77
|
+
attachAuth(instance);
|
|
78
|
+
authed[name] = instance;
|
|
79
|
+
open[name] = axios.create({ baseURL });
|
|
80
|
+
}
|
|
81
|
+
return { authed, open };
|
|
82
|
+
};
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { AxiosInstance } from "axios";
|
|
2
|
+
|
|
3
|
+
export interface TereoUser {
|
|
4
|
+
permissions: string[];
|
|
5
|
+
[key: string]: unknown;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type TereoEvent =
|
|
9
|
+
| { type: "permissions"; payload: { reason: string; timestamp: number } }
|
|
10
|
+
| {
|
|
11
|
+
type: "organization";
|
|
12
|
+
payload: { reason: string; organizationId?: string; timestamp: number };
|
|
13
|
+
}
|
|
14
|
+
| {
|
|
15
|
+
type: "session-revoked";
|
|
16
|
+
payload: { sessionId: string; timestamp: number };
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export interface TereoAuthConfig {
|
|
20
|
+
coreUrl: string;
|
|
21
|
+
clientId: string;
|
|
22
|
+
redirectUri: string;
|
|
23
|
+
/** Name → base URL of each API the app calls with the user's token. */
|
|
24
|
+
apis: Record<string, string>;
|
|
25
|
+
loadUser: (apis: Record<string, AxiosInstance>) => Promise<TereoUser>;
|
|
26
|
+
/** @default "openid profile email offline_access" */
|
|
27
|
+
scopes?: string;
|
|
28
|
+
/** Path the app is served under, without a trailing slash. @default "" */
|
|
29
|
+
basePath?: string;
|
|
30
|
+
/** Routes that need no session, besides the redirect path and `signedOutPath`, which always are. */
|
|
31
|
+
isPublicPath?: (routePath: string) => boolean;
|
|
32
|
+
/** Where a signed-out visitor lands. Must be public. @default "/" */
|
|
33
|
+
signedOutPath?: string;
|
|
34
|
+
/** @default `tereo_${clientId}` */
|
|
35
|
+
storagePrefix?: string;
|
|
36
|
+
/** Milliseconds before expiry at which a token is renewed. @default 30000 */
|
|
37
|
+
tokenExpirationBuffer?: number;
|
|
38
|
+
/** @default 15000 */
|
|
39
|
+
requestTimeoutMs?: number;
|
|
40
|
+
/** Open core's socket for live updates. @default true */
|
|
41
|
+
live?: boolean;
|
|
42
|
+
/** @default "/ws" */
|
|
43
|
+
wsPath?: string;
|
|
44
|
+
onEvent?: (event: TereoEvent) => void;
|
|
45
|
+
/** @default false */
|
|
46
|
+
debug?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface StorageKeys {
|
|
50
|
+
tokens: string;
|
|
51
|
+
pkce: string;
|
|
52
|
+
loggedOut: string;
|
|
53
|
+
signedIn: string;
|
|
54
|
+
postLoginPath: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type ResolvedConfig = Required<Omit<TereoAuthConfig, "onEvent">> &
|
|
58
|
+
Pick<TereoAuthConfig, "onEvent"> & { keys: StorageKeys };
|
|
59
|
+
|
|
60
|
+
export const pathWithoutBase = (pathname: string, basePath: string): string =>
|
|
61
|
+
basePath && (pathname === basePath || pathname.startsWith(`${basePath}/`))
|
|
62
|
+
? pathname.slice(basePath.length) || "/"
|
|
63
|
+
: pathname;
|
|
64
|
+
|
|
65
|
+
export const resolveConfig = (c: TereoAuthConfig): ResolvedConfig => {
|
|
66
|
+
const basePath = c.basePath ?? "";
|
|
67
|
+
const signedOutPath = c.signedOutPath ?? "/";
|
|
68
|
+
const storagePrefix = c.storagePrefix ?? `tereo_${c.clientId}`;
|
|
69
|
+
const redirectPath = pathWithoutBase(
|
|
70
|
+
new URL(c.redirectUri, "http://localhost").pathname,
|
|
71
|
+
basePath
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
...c,
|
|
76
|
+
scopes: c.scopes ?? "openid profile email offline_access",
|
|
77
|
+
basePath,
|
|
78
|
+
signedOutPath,
|
|
79
|
+
isPublicPath: (routePath) =>
|
|
80
|
+
routePath === redirectPath ||
|
|
81
|
+
routePath === signedOutPath ||
|
|
82
|
+
(c.isPublicPath?.(routePath) ?? false),
|
|
83
|
+
storagePrefix,
|
|
84
|
+
tokenExpirationBuffer: c.tokenExpirationBuffer ?? 30_000,
|
|
85
|
+
requestTimeoutMs: c.requestTimeoutMs ?? 15_000,
|
|
86
|
+
live: c.live ?? true,
|
|
87
|
+
wsPath: c.wsPath ?? "/ws",
|
|
88
|
+
debug: c.debug ?? false,
|
|
89
|
+
keys: {
|
|
90
|
+
tokens: `${storagePrefix}_tokens`,
|
|
91
|
+
pkce: `${storagePrefix}_pkce`,
|
|
92
|
+
loggedOut: `${storagePrefix}_logged_out`,
|
|
93
|
+
signedIn: `${storagePrefix}_signed_in`,
|
|
94
|
+
postLoginPath: `${storagePrefix}_post_login_path`,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
let active: ResolvedConfig | null = null;
|
|
100
|
+
|
|
101
|
+
export const setActiveConfig = (c: ResolvedConfig | null): void => {
|
|
102
|
+
active = c;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export const activeConfig = (): ResolvedConfig => {
|
|
106
|
+
if (!active) throw new Error("TereoAuthProvider is not mounted");
|
|
107
|
+
return active;
|
|
108
|
+
};
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { isRefreshRejected } from "./refresh.js";
|
|
2
|
+
import type { TereoEvent } from "./config.js";
|
|
3
|
+
|
|
4
|
+
/** The slice of a socket.io client socket the live-updates loop uses. */
|
|
5
|
+
export interface EventSocket {
|
|
6
|
+
readonly active: boolean;
|
|
7
|
+
connect(): void;
|
|
8
|
+
disconnect(): void;
|
|
9
|
+
on(event: string, listener: (...args: never[]) => void): void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type SocketAuth = (cb: (data: { token?: string }) => void) => void;
|
|
13
|
+
|
|
14
|
+
export interface TereoEventsDeps {
|
|
15
|
+
/** Builds the socket, not yet connected; `auth` is read at each connect. */
|
|
16
|
+
createSocket: (auth: SocketAuth) => EventSocket;
|
|
17
|
+
/** The stored access token, or null when signed out. */
|
|
18
|
+
accessToken: () => string | null;
|
|
19
|
+
/** Whether the stored token is still good for a handshake. */
|
|
20
|
+
tokenIsFresh: () => boolean;
|
|
21
|
+
/** The current token's session (`sid`, the refresh token's id). */
|
|
22
|
+
sessionId: () => string | null;
|
|
23
|
+
/**
|
|
24
|
+
* Refreshes the token; a refusal clears it, which signs the user out. Must
|
|
25
|
+
* make the new token what `accessToken()` returns before it resolves.
|
|
26
|
+
*/
|
|
27
|
+
refresh: () => Promise<unknown>;
|
|
28
|
+
/** Core revoked this session; it is already over server-side. */
|
|
29
|
+
sessionEnded: () => void;
|
|
30
|
+
/** Every event core sends, including revocations of the user's other sessions. */
|
|
31
|
+
onEvent: (event: TereoEvent) => void;
|
|
32
|
+
/**
|
|
33
|
+
* Core will not admit this session's token: the login client lacks
|
|
34
|
+
* `liveEvents`, or core refused the handshake again after a refresh. The
|
|
35
|
+
* loop stops until the user signs in again.
|
|
36
|
+
*/
|
|
37
|
+
refused?: (reason: string) => void;
|
|
38
|
+
/** Defaults to setTimeout; returns a cancel function. */
|
|
39
|
+
schedule?: (fn: () => void, ms: number) => () => void;
|
|
40
|
+
log?: (message: string, detail?: unknown) => void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Handshake refusals that say nothing about the token (core's
|
|
44
|
+
// websocket/index.ts); any other refusal is about the token.
|
|
45
|
+
const TRANSIENT_REFUSALS = new Set([
|
|
46
|
+
"Too many connections",
|
|
47
|
+
"Server is shutting down",
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
// Refusals no new token can change: the login client is not admitted to
|
|
51
|
+
// live events, or the token is a client's own.
|
|
52
|
+
const FINAL_REFUSALS = new Set([
|
|
53
|
+
"This token is not issued for core's API",
|
|
54
|
+
"Invalid token subject",
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
const RETRY_MIN_MS = 1_000;
|
|
58
|
+
const RETRY_MAX_MS = 60_000;
|
|
59
|
+
|
|
60
|
+
const defaultSchedule = (fn: () => void, ms: number) => {
|
|
61
|
+
const id = setTimeout(fn, ms);
|
|
62
|
+
return () => clearTimeout(id);
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Core's `/ws` events for the signed-in user. Core authenticates a socket
|
|
67
|
+
* once, at the handshake, and closes it when its token expires or is
|
|
68
|
+
* revoked; socket.io does not reconnect after a server-side close or a
|
|
69
|
+
* handshake the server refused, so this does, with a fresh token. Returns a
|
|
70
|
+
* stop function.
|
|
71
|
+
*/
|
|
72
|
+
export const startTereoEvents = (deps: TereoEventsDeps): (() => void) => {
|
|
73
|
+
const schedule = deps.schedule ?? defaultSchedule;
|
|
74
|
+
const log = deps.log ?? (() => {});
|
|
75
|
+
let stopped = false;
|
|
76
|
+
let signedOut = false;
|
|
77
|
+
let retryMs = RETRY_MIN_MS;
|
|
78
|
+
// A token refusal is answered with one refresh; a second refusal stops.
|
|
79
|
+
let refreshedForRefusal = false;
|
|
80
|
+
let cancelRetry: (() => void) | null = null;
|
|
81
|
+
|
|
82
|
+
const socket = deps.createSocket((cb) =>
|
|
83
|
+
cb({ token: deps.accessToken() ?? undefined })
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const signOut = () => {
|
|
87
|
+
if (signedOut) return;
|
|
88
|
+
signedOut = true;
|
|
89
|
+
deps.sessionEnded();
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// "transient" when core did not answer the refresh (offline, timeout,
|
|
93
|
+
// 5xx); a refusal clears the token, which signs the user out.
|
|
94
|
+
const refresh = async (): Promise<"ok" | "rejected" | "transient"> => {
|
|
95
|
+
try {
|
|
96
|
+
await deps.refresh();
|
|
97
|
+
return "ok";
|
|
98
|
+
} catch (error) {
|
|
99
|
+
log("Token refresh for the events socket failed", error);
|
|
100
|
+
return isRefreshRejected(error) ? "rejected" : "transient";
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const connectFresh = async () => {
|
|
105
|
+
if (stopped || !deps.accessToken()) return;
|
|
106
|
+
if (!deps.tokenIsFresh()) {
|
|
107
|
+
const outcome = await refresh();
|
|
108
|
+
if (outcome === "transient") retryLater();
|
|
109
|
+
if (outcome !== "ok") return;
|
|
110
|
+
}
|
|
111
|
+
if (!stopped && deps.accessToken()) socket.connect();
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const retryLater = () => {
|
|
115
|
+
if (stopped || cancelRetry) return;
|
|
116
|
+
const delay = retryMs;
|
|
117
|
+
retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
|
|
118
|
+
cancelRetry = schedule(() => {
|
|
119
|
+
cancelRetry = null;
|
|
120
|
+
void connectFresh();
|
|
121
|
+
}, delay);
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
socket.on("connect", () => {
|
|
125
|
+
retryMs = RETRY_MIN_MS;
|
|
126
|
+
refreshedForRefusal = false;
|
|
127
|
+
});
|
|
128
|
+
socket.on("disconnect", (reason: string) => {
|
|
129
|
+
log("Events socket closed", reason);
|
|
130
|
+
if (reason === "io server disconnect") void connectFresh();
|
|
131
|
+
});
|
|
132
|
+
socket.on("connect_error", (error: Error) => {
|
|
133
|
+
log("Events socket refused", error.message);
|
|
134
|
+
// Still active: socket.io retries by itself (a network error).
|
|
135
|
+
if (socket.active || stopped) return;
|
|
136
|
+
if (TRANSIENT_REFUSALS.has(error.message)) {
|
|
137
|
+
retryLater();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (FINAL_REFUSALS.has(error.message) || refreshedForRefusal) {
|
|
141
|
+
deps.refused?.(error.message);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
refreshedForRefusal = true;
|
|
145
|
+
void refresh().then((outcome) => {
|
|
146
|
+
if (outcome === "transient") {
|
|
147
|
+
// No new token yet: the next refusal still earns a refresh.
|
|
148
|
+
refreshedForRefusal = false;
|
|
149
|
+
retryLater();
|
|
150
|
+
} else if (outcome === "ok" && !stopped && deps.accessToken()) {
|
|
151
|
+
socket.connect();
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
socket.on(
|
|
156
|
+
"auth:permissions:changed",
|
|
157
|
+
(payload: { reason: string; timestamp: number }) =>
|
|
158
|
+
deps.onEvent({ type: "permissions", payload })
|
|
159
|
+
);
|
|
160
|
+
socket.on(
|
|
161
|
+
"auth:organization:changed",
|
|
162
|
+
(payload: { reason: string; organizationId?: string; timestamp: number }) =>
|
|
163
|
+
deps.onEvent({ type: "organization", payload })
|
|
164
|
+
);
|
|
165
|
+
socket.on(
|
|
166
|
+
"auth:session:revoked",
|
|
167
|
+
(payload: { sessionId: string; timestamp: number }) => {
|
|
168
|
+
deps.onEvent({ type: "session-revoked", payload });
|
|
169
|
+
// Sent for each of the user's revoked sessions; only ours signs out.
|
|
170
|
+
if (payload?.sessionId && payload.sessionId === deps.sessionId()) {
|
|
171
|
+
signOut();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
void connectFresh();
|
|
177
|
+
|
|
178
|
+
return () => {
|
|
179
|
+
stopped = true;
|
|
180
|
+
cancelRetry?.();
|
|
181
|
+
cancelRetry = null;
|
|
182
|
+
socket.disconnect();
|
|
183
|
+
};
|
|
184
|
+
};
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type AuthState, ApiContext, AuthContext } from "./provider.js";
|
|
2
|
+
import { useCallback, useContext, useRef, useState } from "react";
|
|
3
|
+
import { completeSignIn } from "./signIn.js";
|
|
4
|
+
import type { TereoUser } from "./config.js";
|
|
5
|
+
import type { AxiosInstance } from "axios";
|
|
6
|
+
|
|
7
|
+
export const useAuth = <U extends TereoUser = TereoUser>(): AuthState<U> => {
|
|
8
|
+
const state = useContext(AuthContext);
|
|
9
|
+
if (!state) throw new Error("useAuth must be used within TereoAuthProvider");
|
|
10
|
+
return state as unknown as AuthState<U>;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const useClient = (
|
|
14
|
+
name: string,
|
|
15
|
+
kind: "authed" | "open",
|
|
16
|
+
hook: string
|
|
17
|
+
): AxiosInstance => {
|
|
18
|
+
const clients = useContext(ApiContext);
|
|
19
|
+
if (!clients)
|
|
20
|
+
throw new Error(`${hook} must be used within TereoAuthProvider`);
|
|
21
|
+
const client = clients[kind][name];
|
|
22
|
+
if (!client) throw new Error(`No API named "${name}" in the Tereo config`);
|
|
23
|
+
return client;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** The named API's client, sending the user's access token. */
|
|
27
|
+
export const useApi = (name: string): AxiosInstance =>
|
|
28
|
+
useClient(name, "authed", "useApi");
|
|
29
|
+
|
|
30
|
+
/** The named API's client with no token, for cookies or open endpoints. */
|
|
31
|
+
export const usePublicApi = (name: string): AxiosInstance =>
|
|
32
|
+
useClient(name, "open", "usePublicApi");
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Finishes sign-in on the callback route. The exchange runs once per mount,
|
|
36
|
+
* however often `complete` is called (React StrictMode runs effects twice,
|
|
37
|
+
* and the PKCE verifier is single-use).
|
|
38
|
+
*/
|
|
39
|
+
export const useCompleteSignIn = (): {
|
|
40
|
+
complete: (search: URLSearchParams) => Promise<{ returnTo: string | null }>;
|
|
41
|
+
error: Error | null;
|
|
42
|
+
isPending: boolean;
|
|
43
|
+
} => {
|
|
44
|
+
const started = useRef<Promise<{ returnTo: string | null }> | null>(null);
|
|
45
|
+
const [error, setError] = useState<Error | null>(null);
|
|
46
|
+
const [isPending, setIsPending] = useState(false);
|
|
47
|
+
|
|
48
|
+
const complete = useCallback((search: URLSearchParams) => {
|
|
49
|
+
if (!started.current) {
|
|
50
|
+
setIsPending(true);
|
|
51
|
+
started.current = completeSignIn(search)
|
|
52
|
+
.catch((e: unknown) => {
|
|
53
|
+
setError(e instanceof Error ? e : new Error(String(e)));
|
|
54
|
+
throw e;
|
|
55
|
+
})
|
|
56
|
+
.finally(() => setIsPending(false));
|
|
57
|
+
}
|
|
58
|
+
return started.current;
|
|
59
|
+
}, []);
|
|
60
|
+
|
|
61
|
+
return { complete, error, isPending };
|
|
62
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export { resolveConfig, setActiveConfig, activeConfig } from "./config.js";
|
|
2
|
+
export type {
|
|
3
|
+
ResolvedConfig,
|
|
4
|
+
StorageKeys,
|
|
5
|
+
TereoAuthConfig,
|
|
6
|
+
TereoEvent,
|
|
7
|
+
TereoUser,
|
|
8
|
+
} from "./config.js";
|
|
9
|
+
export { hasPermission } from "./permissions.js";
|
|
10
|
+
export type { PermissionRequirement } from "./permissions.js";
|
|
11
|
+
export {
|
|
12
|
+
readJson,
|
|
13
|
+
writeJson,
|
|
14
|
+
removeKey,
|
|
15
|
+
subscribeKey,
|
|
16
|
+
useStoredValue,
|
|
17
|
+
} from "./storage.js";
|
|
18
|
+
export { decodeJwt, readTokens, writeTokens } from "./tokens.js";
|
|
19
|
+
export type { StoredTokens } from "./tokens.js";
|
|
20
|
+
export {
|
|
21
|
+
clearLoggedOut,
|
|
22
|
+
clearSignedIn,
|
|
23
|
+
hasSession,
|
|
24
|
+
isLoggedOut,
|
|
25
|
+
markLoggedOut,
|
|
26
|
+
markSignedIn,
|
|
27
|
+
} from "./markers.js";
|
|
28
|
+
export { completeSignIn, signIn } from "./signIn.js";
|
|
29
|
+
export { isRefreshRejected, refreshTokens } from "./refresh.js";
|
|
30
|
+
export { endLocalSession, signOut } from "./signOut.js";
|
|
31
|
+
export { createApiClients } from "./api.js";
|
|
32
|
+
export { TereoAuthProvider } from "./provider.js";
|
|
33
|
+
export type { ApiClients, AuthState } from "./provider.js";
|
|
34
|
+
export { useApi, useAuth, useCompleteSignIn, usePublicApi } from "./hooks.js";
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { activeConfig } from "./config.js";
|
|
2
|
+
|
|
3
|
+
export const debugLog = (...args: unknown[]): void => {
|
|
4
|
+
if (activeConfig().debug) console.log("[tereo]", ...args);
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export const errorLog = (...args: unknown[]): void => {
|
|
8
|
+
console.error("[tereo]", ...args);
|
|
9
|
+
};
|
package/src/markers.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readJson, removeKey, writeJson } from "./storage.js";
|
|
2
|
+
import { activeConfig } from "./config.js";
|
|
3
|
+
import { readTokens } from "./tokens.js";
|
|
4
|
+
|
|
5
|
+
export const markSignedIn = (): void =>
|
|
6
|
+
writeJson(activeConfig().keys.signedIn, "1");
|
|
7
|
+
|
|
8
|
+
export const clearSignedIn = (): void =>
|
|
9
|
+
removeKey(activeConfig().keys.signedIn);
|
|
10
|
+
|
|
11
|
+
// Set by an explicit sign-out and cleared only by the next interactive login
|
|
12
|
+
// (the code exchange). While it is set no session is assumed: if the revoke
|
|
13
|
+
// call failed, the refresh cookie may still be valid, and a silent refresh
|
|
14
|
+
// would sign the user straight back in.
|
|
15
|
+
export const markLoggedOut = (): void =>
|
|
16
|
+
writeJson(activeConfig().keys.loggedOut, "1");
|
|
17
|
+
|
|
18
|
+
export const clearLoggedOut = (): void =>
|
|
19
|
+
removeKey(activeConfig().keys.loggedOut);
|
|
20
|
+
|
|
21
|
+
export const isLoggedOut = (): boolean =>
|
|
22
|
+
readJson(activeConfig().keys.loggedOut) !== null;
|
|
23
|
+
|
|
24
|
+
export const hasSession = (): boolean =>
|
|
25
|
+
!isLoggedOut() &&
|
|
26
|
+
(readJson(activeConfig().keys.signedIn) !== null || readTokens() !== null);
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** One permission, or a list of which any one suffices. */
|
|
2
|
+
export type PermissionRequirement = string | readonly string[];
|
|
3
|
+
|
|
4
|
+
const ADMIN_LEVEL = 5;
|
|
5
|
+
|
|
6
|
+
const holdsPermission = (held: string[], required: string): boolean => {
|
|
7
|
+
if (held.includes("admin")) return true;
|
|
8
|
+
if (held.includes(required)) return true;
|
|
9
|
+
|
|
10
|
+
for (const userPerm of held) {
|
|
11
|
+
if (isAdminCovering(userPerm, required)) return true;
|
|
12
|
+
if (hasPermissionLevel(userPerm, required)) return true;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
return false;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const hasPermission = (
|
|
19
|
+
held: string[],
|
|
20
|
+
required: PermissionRequirement
|
|
21
|
+
): boolean =>
|
|
22
|
+
typeof required === "string"
|
|
23
|
+
? holdsPermission(held, required)
|
|
24
|
+
: required.some((permission) => holdsPermission(held, permission));
|
|
25
|
+
|
|
26
|
+
const isAdminCovering = (
|
|
27
|
+
userPermission: string,
|
|
28
|
+
requiredPermission: string
|
|
29
|
+
): boolean => {
|
|
30
|
+
const userLevel = getPermissionLevel(userPermission);
|
|
31
|
+
if (userLevel !== ADMIN_LEVEL) return false;
|
|
32
|
+
|
|
33
|
+
const userBase = getPermissionBase(userPermission);
|
|
34
|
+
const requiredBase = getPermissionBase(requiredPermission);
|
|
35
|
+
if (!userBase) return false;
|
|
36
|
+
return requiredBase === userBase || requiredBase.startsWith(userBase + ".");
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const getPermissionLevel = (permission: string): number => {
|
|
40
|
+
const suffix = permission.split(".").pop();
|
|
41
|
+
switch (suffix) {
|
|
42
|
+
case "read":
|
|
43
|
+
return 1;
|
|
44
|
+
case "write":
|
|
45
|
+
return 2;
|
|
46
|
+
case "archive":
|
|
47
|
+
return 3;
|
|
48
|
+
case "delete":
|
|
49
|
+
return 4;
|
|
50
|
+
case "admin":
|
|
51
|
+
return ADMIN_LEVEL;
|
|
52
|
+
default:
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const hasPermissionLevel = (
|
|
58
|
+
userPermission: string,
|
|
59
|
+
requiredPermission: string
|
|
60
|
+
): boolean => {
|
|
61
|
+
const userBase = getPermissionBase(userPermission);
|
|
62
|
+
const requiredBase = getPermissionBase(requiredPermission);
|
|
63
|
+
if (userBase !== requiredBase) return false;
|
|
64
|
+
|
|
65
|
+
const userLevel = getPermissionLevel(userPermission);
|
|
66
|
+
const requiredLevel = getPermissionLevel(requiredPermission);
|
|
67
|
+
// Off-ladder permissions (`webhooks.emit`, `services.approve`) are implied by
|
|
68
|
+
// nothing but themselves or an admin covering them.
|
|
69
|
+
if (requiredLevel === 0) return false;
|
|
70
|
+
return userLevel >= requiredLevel;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const getPermissionBase = (permission: string): string => {
|
|
74
|
+
const parts = permission.split(".");
|
|
75
|
+
if (parts.length <= 1) return "";
|
|
76
|
+
return parts.slice(0, -1).join(".");
|
|
77
|
+
};
|