@polaris-auth/client 0.0.0-stage → 0.6.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/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
- "name": "@polaris-auth/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@polaris-auth/client",
3
+ "version": "0.6.1",
4
+ "description": "Typed TypeScript client for Polaris for PHP, generated from the route manifest",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "2am.tech",
8
+ "url": "https://2am.tech"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/univeros/polaris-core.git",
13
+ "directory": "packages/client-ts"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "src",
27
+ "openapi.json"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20"
31
+ },
32
+ "scripts": {
33
+ "generate": "php ../../bin/polaris manifest --format=openapi --bootstrap=polaris.php > openapi.json && openapi-typescript openapi.json -o src/schema.d.ts && node scripts/generate-namespaces.mjs",
34
+ "typecheck": "tsc --noEmit",
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "test": "vitest run"
37
+ },
38
+ "dependencies": {
39
+ "openapi-fetch": "^0.17.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.20.2",
43
+ "openapi-typescript": "^7.13.0",
44
+ "typescript": "^5.9.3",
45
+ "vitest": "^4.1.11"
46
+ }
47
+ }
package/src/admin.ts ADDED
@@ -0,0 +1,70 @@
1
+ /* Generated by scripts/generate-namespaces.mjs from openapi.json; do not edit. */
2
+ import type { Client } from "openapi-fetch";
3
+ import type { paths } from "./schema.js";
4
+ import type { Init } from "./namespace.js";
5
+
6
+ /** The `admin` plugin's routes as methods of `client.admin`. */
7
+ export function admin(client: Client<paths>) {
8
+ return {
9
+ /** POST /admin/users/{id}/ban: Ban a user */
10
+ banUser: (...init: Init<"/admin/users/{id}/ban", "post">) => client.POST("/admin/users/{id}/ban", ...init),
11
+ /** POST /admin/organizations/{id}/drains: Create an audit drain */
12
+ createDrain: (...init: Init<"/admin/organizations/{id}/drains", "post">) => client.POST("/admin/organizations/{id}/drains", ...init),
13
+ /** POST /admin/grants: Grant an admin role */
14
+ createGrant: (...init: Init<"/admin/grants", "post">) => client.POST("/admin/grants", ...init),
15
+ /** POST /admin/keys: Create an API key */
16
+ createKey: (...init: Init<"/admin/keys", "post">) => client.POST("/admin/keys", ...init),
17
+ /** DELETE /admin/organizations/{id}/drains/{drainId}: Delete an audit drain */
18
+ deleteDrain: (...init: Init<"/admin/organizations/{id}/drains/{drainId}", "delete">) => client.DELETE("/admin/organizations/{id}/drains/{drainId}", ...init),
19
+ /** DELETE /admin/grants/{id}: Revoke an admin grant */
20
+ deleteGrant: (...init: Init<"/admin/grants/{id}", "delete">) => client.DELETE("/admin/grants/{id}", ...init),
21
+ /** DELETE /admin/keys/{id}: Delete an API key */
22
+ deleteKey: (...init: Init<"/admin/keys/{id}", "delete">) => client.DELETE("/admin/keys/{id}", ...init),
23
+ /** DELETE /admin/organizations/{id}: Delete an organization */
24
+ deleteOrganization: (...init: Init<"/admin/organizations/{id}", "delete">) => client.DELETE("/admin/organizations/{id}", ...init),
25
+ /** DELETE /admin/users/{id}: Delete a user */
26
+ deleteUser: (...init: Init<"/admin/users/{id}", "delete">) => client.DELETE("/admin/users/{id}", ...init),
27
+ /** POST /admin/users/{id}/impersonate: Impersonate a user */
28
+ impersonateUser: (...init: Init<"/admin/users/{id}/impersonate", "post">) => client.POST("/admin/users/{id}/impersonate", ...init),
29
+ /** GET /admin/organizations/{id}/drains: List an organization's audit drains */
30
+ listDrains: (...init: Init<"/admin/organizations/{id}/drains", "get">) => client.GET("/admin/organizations/{id}/drains", ...init),
31
+ /** GET /admin/users/{id}/mfa: List a user's MFA factors */
32
+ listFactors: (...init: Init<"/admin/users/{id}/mfa", "get">) => client.GET("/admin/users/{id}/mfa", ...init),
33
+ /** GET /admin/grants: List the admin grants */
34
+ listGrants: (...init: Init<"/admin/grants", "get">) => client.GET("/admin/grants", ...init),
35
+ /** GET /admin/keys: List the API keys */
36
+ listKeys: (...init: Init<"/admin/keys", "get">) => client.GET("/admin/keys", ...init),
37
+ /** GET /admin/organizations: List the organizations */
38
+ listOrganizations: (...init: Init<"/admin/organizations", "get">) => client.GET("/admin/organizations", ...init),
39
+ /** GET /admin/users/{id}/sessions: List a user's sessions */
40
+ listSessions: (...init: Init<"/admin/users/{id}/sessions", "get">) => client.GET("/admin/users/{id}/sessions", ...init),
41
+ /** GET /admin/users: List the users */
42
+ listUsers: (...init: Init<"/admin/users", "get">) => client.GET("/admin/users", ...init),
43
+ /** GET /admin/audit: Query the audit trail */
44
+ queryAudit: (...init: Init<"/admin/audit", "get">) => client.GET("/admin/audit", ...init),
45
+ /** GET /admin/organizations/{id}: Read an organization */
46
+ readOrganization: (...init: Init<"/admin/organizations/{id}", "get">) => client.GET("/admin/organizations/{id}", ...init),
47
+ /** GET /admin/users/{id}: Read a user */
48
+ readUser: (...init: Init<"/admin/users/{id}", "get">) => client.GET("/admin/users/{id}", ...init),
49
+ /** DELETE /admin/users/{id}/mfa/{factorId}: Remove an MFA factor */
50
+ removeFactor: (...init: Init<"/admin/users/{id}/mfa/{factorId}", "delete">) => client.DELETE("/admin/users/{id}/mfa/{factorId}", ...init),
51
+ /** DELETE /admin/users/{id}/mfa: Reset a user's MFA */
52
+ resetMfa: (...init: Init<"/admin/users/{id}/mfa", "delete">) => client.DELETE("/admin/users/{id}/mfa", ...init),
53
+ /** DELETE /admin/users/{id}/sessions: Revoke every session */
54
+ revokeAllSessions: (...init: Init<"/admin/users/{id}/sessions", "delete">) => client.DELETE("/admin/users/{id}/sessions", ...init),
55
+ /** DELETE /admin/users/{id}/sessions/{sessionId}: Revoke a session */
56
+ revokeSession: (...init: Init<"/admin/users/{id}/sessions/{sessionId}", "delete">) => client.DELETE("/admin/users/{id}/sessions/{sessionId}", ...init),
57
+ /** POST /admin/users/{id}/password: Set a user's password */
58
+ setPassword: (...init: Init<"/admin/users/{id}/password", "post">) => client.POST("/admin/users/{id}/password", ...init),
59
+ /** GET /admin/stats: Read the instance statistics */
60
+ stats: (...init: Init<"/admin/stats", "get">) => client.GET("/admin/stats", ...init),
61
+ /** POST /admin/organizations/{id}/drains/{drainId}/test: Test an audit drain */
62
+ testDrain: (...init: Init<"/admin/organizations/{id}/drains/{drainId}/test", "post">) => client.POST("/admin/organizations/{id}/drains/{drainId}/test", ...init),
63
+ /** POST /admin/users/{id}/unban: Unban a user */
64
+ unbanUser: (...init: Init<"/admin/users/{id}/unban", "post">) => client.POST("/admin/users/{id}/unban", ...init),
65
+ /** PATCH /admin/organizations/{id}/members/{userId}/roles: Set a member's roles */
66
+ updateMemberRoles: (...init: Init<"/admin/organizations/{id}/members/{userId}/roles", "patch">) => client.PATCH("/admin/organizations/{id}/members/{userId}/roles", ...init),
67
+ };
68
+ }
69
+
70
+ export type AdminApi = ReturnType<typeof admin>;
package/src/audit.ts ADDED
@@ -0,0 +1,18 @@
1
+ /* Generated by scripts/generate-namespaces.mjs from openapi.json; do not edit. */
2
+ import type { Client } from "openapi-fetch";
3
+ import type { paths } from "./schema.js";
4
+ import type { Init } from "./namespace.js";
5
+
6
+ /** The `audit` plugin's routes as methods of `client.audit`. */
7
+ export function audit(client: Client<paths>) {
8
+ return {
9
+ /** GET /audit/me: List the audit events where the caller is the actor or the subject */
10
+ me: (...init: Init<"/audit/me", "get">) => client.GET("/audit/me", ...init),
11
+ /** GET /audit/organization/{id}: List an organization's audit events */
12
+ organization: (...init: Init<"/audit/organization/{id}", "get">) => client.GET("/audit/organization/{id}", ...init),
13
+ /** GET /audit/types: List the audit event names and their descriptions */
14
+ types: (...init: Init<"/audit/types", "get">) => client.GET("/audit/types", ...init),
15
+ };
16
+ }
17
+
18
+ export type AuditApi = ReturnType<typeof audit>;
@@ -0,0 +1,80 @@
1
+ import type { Middleware } from "openapi-fetch";
2
+
3
+ /** How the client answers a challenge of `polaris/sentinel`. */
4
+ export interface ChallengeOptions {
5
+ /**
6
+ * Asked for a captcha token when a request answers `403` with the `sentinel/challenge_required` problem
7
+ * and `challenge: captcha`; the same request is then sent once more with `captcha_token` added to its
8
+ * JSON body. The token comes from the captcha widget the host renders (Turnstile, hCaptcha).
9
+ */
10
+ captcha: () => Promise<string>;
11
+ }
12
+
13
+ const CHALLENGE_ERROR = "sentinel_challenge_required";
14
+ const CAPTCHA = "captcha";
15
+
16
+ /**
17
+ * The transparent challenge retry: the body of every request is kept by its id until the response is
18
+ * in; a captcha challenge asks the host for a token and replays the request once with it. Any other
19
+ * response, and the retried response itself, come back as they are, so a wrong token is one problem
20
+ * document and never a loop. A request without a JSON object body is not retried (nothing to add the token to).
21
+ */
22
+ export function challengeRetry(challenge: ChallengeOptions): Middleware {
23
+ const bodies = new Map<string, string>();
24
+
25
+ return {
26
+ async onRequest({ id, request }) {
27
+ bodies.set(id, await request.clone().text());
28
+ },
29
+ async onResponse({ id, request, response, options }) {
30
+ const fields = jsonFields(bodies.get(id) ?? "");
31
+ bodies.delete(id);
32
+ if (fields === null || response.status !== 403 || !(await isCaptchaChallenge(response))) {
33
+ return undefined;
34
+ }
35
+ const token = await challenge.captcha();
36
+
37
+ return options.fetch(
38
+ new Request(request.url, {
39
+ method: request.method,
40
+ headers: request.headers,
41
+ body: JSON.stringify({ ...fields, captcha_token: token }),
42
+ credentials: request.credentials,
43
+ signal: request.signal,
44
+ }),
45
+ );
46
+ },
47
+ onError({ id }) {
48
+ bodies.delete(id);
49
+ },
50
+ };
51
+ }
52
+
53
+ async function isCaptchaChallenge(response: Response): Promise<boolean> {
54
+ try {
55
+ const problem: unknown = await response.clone().json();
56
+
57
+ return (
58
+ typeof problem === "object" &&
59
+ problem !== null &&
60
+ (problem as { error?: unknown }).error === CHALLENGE_ERROR &&
61
+ (problem as { challenge?: unknown }).challenge === CAPTCHA
62
+ );
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+
68
+ /** The fields of a JSON object body; null for an empty or non-JSON-object body, which cannot take a `captcha_token`. */
69
+ function jsonFields(body: string): Record<string, unknown> | null {
70
+ if (body === "") {
71
+ return null;
72
+ }
73
+ try {
74
+ const parsed: unknown = JSON.parse(body);
75
+
76
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
package/src/index.ts ADDED
@@ -0,0 +1,87 @@
1
+ import createOpenApiClient, { type Client, type ClientOptions } from "openapi-fetch";
2
+ import { admin, type AdminApi } from "./admin.js";
3
+ import { audit, type AuditApi } from "./audit.js";
4
+ import { challengeRetry, type ChallengeOptions } from "./challenge.js";
5
+ import { sentinel, type SentinelApi } from "./sentinel.js";
6
+ import { scim, type ScimApi } from "./scim.js";
7
+ import { sso, type SsoApi } from "./sso.js";
8
+ import type { components, paths } from "./schema.js";
9
+
10
+ export type { components, operations, paths } from "./schema.js";
11
+ export { admin, type AdminApi } from "./admin.js";
12
+ export { audit, type AuditApi } from "./audit.js";
13
+ export { challengeRetry, type ChallengeOptions } from "./challenge.js";
14
+ export { sentinel, type SentinelApi } from "./sentinel.js";
15
+ export { scim, type ScimApi } from "./scim.js";
16
+ export { sso, type SsoApi } from "./sso.js";
17
+
18
+ /** The `{ error, message }` envelope every non-2xx response of a core route carries. */
19
+ export type ErrorBody = components["schemas"]["Error"];
20
+ /** The `{ errors: [...] }` envelope of a core route's 422. */
21
+ export type ValidationErrorBody = components["schemas"]["ValidationError"];
22
+ /** The RFC 9457 problem document every non-2xx response of a plugin route (`audit`, `admin`, `sentinel`, `sso`, `scim`) carries. */
23
+ export type ProblemBody = components["schemas"]["Problem"];
24
+
25
+ export interface PolarisClientOptions extends ClientOptions {
26
+ /** Where Polaris is mounted: `https://app.example.com`, or `https://app.example.com/api/auth` behind a prefix. */
27
+ baseUrl: string;
28
+ /** Sent as `Authorization: Bearer` on every request: an access token, the `mfa_token` for the MFA gate, or an admin API key (`pak_...`). */
29
+ token?: string | null;
30
+ /**
31
+ * How to answer a `polaris/sentinel` challenge: with `captcha`, a `403 sentinel/challenge_required`
32
+ * with `challenge: captcha` asks it for a token and retries the request once with `captcha_token`
33
+ * in the body. Without it the problem document is returned as any other error.
34
+ */
35
+ challenge?: ChallengeOptions;
36
+ }
37
+
38
+ export interface PolarisClient extends Client<paths> {
39
+ /** The token this client sends; null when anonymous. */
40
+ readonly token: string | null;
41
+ /** The `polaris/audit` routes: `client.audit.me()`, `organization()`, `types()`. */
42
+ readonly audit: AuditApi;
43
+ /** The `polaris/admin` routes for an operator (an admin user's token or an API key): `client.admin.listUsers()`, ... */
44
+ readonly admin: AdminApi;
45
+ /** The `polaris/sentinel` operator routes: `client.sentinel.listDecisions()`, `listIpRules()`, `createIpRule()`, `deleteIpRule()`, `unblock()`. */
46
+ readonly sentinel: SentinelApi;
47
+ /** The `polaris/sso` routes: `client.sso.signIn()`, `exchange()`, the organization's providers and domains, the operators' list. */
48
+ readonly sso: SsoApi;
49
+ /** The `polaris/scim` routes: the organization's connections, the operators' list, and the SCIM server itself for a directory client. */
50
+ readonly scim: ScimApi;
51
+ /** A new client on the same options bound to another token (null for anonymous); this one is unchanged. */
52
+ withToken(token: string | null): PolarisClient;
53
+ }
54
+
55
+ /**
56
+ * An `openapi-fetch` client typed by `paths` (generated from `polaris manifest --format=openapi`), so
57
+ * `client.POST("/auth/login", { body })` checks the body and types `data` and `error`; the plugins' routes
58
+ * are also methods of `client.audit`, `client.admin`, `client.sentinel`, `client.sso` and `client.scim`; `challenge.captcha`
59
+ * answers a sentinel captcha challenge with one retry. No refresh loop and no storage: when to refresh
60
+ * and where to keep tokens is the application's policy.
61
+ */
62
+ export function createClient(options: PolarisClientOptions): PolarisClient {
63
+ const { token = null, challenge, ...clientOptions } = options;
64
+ const client = createOpenApiClient<paths>(clientOptions);
65
+ if (challenge !== undefined) {
66
+ client.use(challengeRetry(challenge));
67
+ }
68
+ if (token !== null) {
69
+ client.use({
70
+ onRequest({ request }) {
71
+ request.headers.set("Authorization", `Bearer ${token}`);
72
+ return request;
73
+ },
74
+ });
75
+ }
76
+
77
+ return {
78
+ ...client,
79
+ token,
80
+ audit: audit(client),
81
+ admin: admin(client),
82
+ sentinel: sentinel(client),
83
+ sso: sso(client),
84
+ scim: scim(client),
85
+ withToken: (next: string | null) => createClient({ ...options, token: next }),
86
+ };
87
+ }
@@ -0,0 +1,13 @@
1
+ import type { MaybeOptionalInit } from "openapi-fetch";
2
+ import type { paths } from "./schema.js";
3
+
4
+ type RequiredKeysOf<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];
5
+
6
+ /**
7
+ * The argument list of a namespaced method: `openapi-fetch`'s init for the route, required when the
8
+ * route has required params or a body, optional otherwise (the same rule as `client.GET(url, init)`).
9
+ */
10
+ export type Init<Path extends keyof paths, Method extends keyof paths[Path]> =
11
+ RequiredKeysOf<MaybeOptionalInit<paths[Path], Method>> extends never
12
+ ? [(MaybeOptionalInit<paths[Path], Method> & { [key: string]: unknown })?]
13
+ : [MaybeOptionalInit<paths[Path], Method> & { [key: string]: unknown }];