@polaris-auth/client 0.0.0-stage → 0.7.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/dist/audit.js ADDED
@@ -0,0 +1,11 @@
1
+ /** The `audit` plugin's routes as methods of `client.audit`. */
2
+ export function audit(client) {
3
+ return {
4
+ /** GET /audit/me: List the audit events where the caller is the actor or the subject */
5
+ me: (...init) => client.GET("/audit/me", ...init),
6
+ /** GET /audit/organization/{id}: List an organization's audit events */
7
+ organization: (...init) => client.GET("/audit/organization/{id}", ...init),
8
+ /** GET /audit/types: List the audit event names and their descriptions */
9
+ types: (...init) => client.GET("/audit/types", ...init),
10
+ };
11
+ }
@@ -0,0 +1,17 @@
1
+ import type { Middleware } from "openapi-fetch";
2
+ /** How the client answers a challenge of `polaris/sentinel`. */
3
+ export interface ChallengeOptions {
4
+ /**
5
+ * Asked for a captcha token when a request answers `403` with the `sentinel/challenge_required` problem
6
+ * and `challenge: captcha`; the same request is then sent once more with `captcha_token` added to its
7
+ * JSON body. The token comes from the captcha widget the host renders (Turnstile, hCaptcha).
8
+ */
9
+ captcha: () => Promise<string>;
10
+ }
11
+ /**
12
+ * The transparent challenge retry: the body of every request is kept by its id until the response is
13
+ * in; a captcha challenge asks the host for a token and replays the request once with it. Any other
14
+ * response, and the retried response itself, come back as they are, so a wrong token is one problem
15
+ * document and never a loop. A request without a JSON object body is not retried (nothing to add the token to).
16
+ */
17
+ export declare function challengeRetry(challenge: ChallengeOptions): Middleware;
@@ -0,0 +1,59 @@
1
+ const CHALLENGE_ERROR = "sentinel_challenge_required";
2
+ const CAPTCHA = "captcha";
3
+ /**
4
+ * The transparent challenge retry: the body of every request is kept by its id until the response is
5
+ * in; a captcha challenge asks the host for a token and replays the request once with it. Any other
6
+ * response, and the retried response itself, come back as they are, so a wrong token is one problem
7
+ * document and never a loop. A request without a JSON object body is not retried (nothing to add the token to).
8
+ */
9
+ export function challengeRetry(challenge) {
10
+ const bodies = new Map();
11
+ return {
12
+ async onRequest({ id, request }) {
13
+ bodies.set(id, await request.clone().text());
14
+ },
15
+ async onResponse({ id, request, response, options }) {
16
+ const fields = jsonFields(bodies.get(id) ?? "");
17
+ bodies.delete(id);
18
+ if (fields === null || response.status !== 403 || !(await isCaptchaChallenge(response))) {
19
+ return undefined;
20
+ }
21
+ const token = await challenge.captcha();
22
+ return options.fetch(new Request(request.url, {
23
+ method: request.method,
24
+ headers: request.headers,
25
+ body: JSON.stringify({ ...fields, captcha_token: token }),
26
+ credentials: request.credentials,
27
+ signal: request.signal,
28
+ }));
29
+ },
30
+ onError({ id }) {
31
+ bodies.delete(id);
32
+ },
33
+ };
34
+ }
35
+ async function isCaptchaChallenge(response) {
36
+ try {
37
+ const problem = await response.clone().json();
38
+ return (typeof problem === "object" &&
39
+ problem !== null &&
40
+ problem.error === CHALLENGE_ERROR &&
41
+ problem.challenge === CAPTCHA);
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ /** The fields of a JSON object body; null for an empty or non-JSON-object body, which cannot take a `captcha_token`. */
48
+ function jsonFields(body) {
49
+ if (body === "") {
50
+ return null;
51
+ }
52
+ try {
53
+ const parsed = JSON.parse(body);
54
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
@@ -0,0 +1,77 @@
1
+ import { type Client, type ClientOptions } from "openapi-fetch";
2
+ import { type AdminApi } from "./admin.js";
3
+ import { type AnonymousApi } from "./anonymous.js";
4
+ import { type AuditApi } from "./audit.js";
5
+ import { type ChallengeOptions } from "./challenge.js";
6
+ import { type MultiSessionApi } from "./multi-session.js";
7
+ import { type PasswordlessApi } from "./passwordless.js";
8
+ import { type SentinelApi } from "./sentinel.js";
9
+ import { type ScimApi } from "./scim.js";
10
+ import { type SsoApi } from "./sso.js";
11
+ import { type UsernameApi } from "./username.js";
12
+ import type { components, paths } from "./schema.js";
13
+ export type { components, operations, paths } from "./schema.js";
14
+ export { admin, type AdminApi } from "./admin.js";
15
+ export { anonymous, type AnonymousApi } from "./anonymous.js";
16
+ export { audit, type AuditApi } from "./audit.js";
17
+ export { challengeRetry, type ChallengeOptions } from "./challenge.js";
18
+ export { multiSession, type MultiSessionApi } from "./multi-session.js";
19
+ export { passwordless, type PasswordlessApi } from "./passwordless.js";
20
+ export { sentinel, type SentinelApi } from "./sentinel.js";
21
+ export { scim, type ScimApi } from "./scim.js";
22
+ export { sso, type SsoApi } from "./sso.js";
23
+ export { username, type UsernameApi } from "./username.js";
24
+ /** The `{ error, message }` envelope every non-2xx response of a core route carries. */
25
+ export type ErrorBody = components["schemas"]["Error"];
26
+ /** The `{ errors: [...] }` envelope of a core route's 422. */
27
+ export type ValidationErrorBody = components["schemas"]["ValidationError"];
28
+ /** The RFC 9457 problem document every non-2xx response of a plugin route (`audit`, `admin`, `sentinel`, `sso`, `scim`, `passwordless`, `username`, `anonymous`, `multi-session`) carries. */
29
+ export type ProblemBody = components["schemas"]["Problem"];
30
+ export interface PolarisClientOptions extends ClientOptions {
31
+ /** Where Polaris is mounted: `https://app.example.com`, or `https://app.example.com/api/auth` behind a prefix. */
32
+ baseUrl: string;
33
+ /** Sent as `Authorization: Bearer` on every request: an access token, the `mfa_token` for the MFA gate, or an admin API key (`pak_...`). */
34
+ token?: string | null;
35
+ /**
36
+ * How to answer a `polaris/sentinel` challenge: with `captcha`, a `403 sentinel/challenge_required`
37
+ * with `challenge: captcha` asks it for a token and retries the request once with `captcha_token`
38
+ * in the body. Without it the problem document is returned as any other error.
39
+ */
40
+ challenge?: ChallengeOptions;
41
+ }
42
+ export interface PolarisClient extends Client<paths> {
43
+ /** The token this client sends; null when anonymous. */
44
+ readonly token: string | null;
45
+ /** The `polaris/audit` routes: `client.audit.me()`, `organization()`, `types()`. */
46
+ readonly audit: AuditApi;
47
+ /** The `polaris/admin` routes for an operator (an admin user's token or an API key): `client.admin.listUsers()`, ... */
48
+ readonly admin: AdminApi;
49
+ /** The `polaris/sentinel` operator routes: `client.sentinel.listDecisions()`, `listIpRules()`, `createIpRule()`, `deleteIpRule()`, `unblock()`. */
50
+ readonly sentinel: SentinelApi;
51
+ /** The `polaris/sso` routes: `client.sso.signIn()`, `exchange()`, the organization's providers and domains, the operators' list. */
52
+ readonly sso: SsoApi;
53
+ /** The `polaris/scim` routes: the organization's connections, the operators' list, and the SCIM server itself for a directory client. */
54
+ readonly scim: ScimApi;
55
+ /** The `polaris/passwordless` routes: `client.passwordless.magicLinkSend()`, `magicLinkExchange()`, `emailOtpSend()`, `emailOtpVerify()`, `phoneSend()`, `phoneVerify()`, `oneTimeTokenGenerate()`, ... */
56
+ readonly passwordless: PasswordlessApi;
57
+ /** The `polaris/username` routes: `client.username.signIn()` (a username or an email) and `update()`. */
58
+ readonly username: UsernameApi;
59
+ /** The `polaris/anonymous` routes: `client.anonymous.signIn()` for a guest and `convert()` once it has an account. */
60
+ readonly anonymous: AnonymousApi;
61
+ /**
62
+ * The `polaris/multi-session` routes: `client.multiSession.list()`, `switch()`, `revoke()`, `lastMethod()`.
63
+ * The device travels as the `X-Polaris-Device` header a sign-in answers (or the HttpOnly cookie in a browser).
64
+ */
65
+ readonly multiSession: MultiSessionApi;
66
+ /** A new client on the same options bound to another token (null for anonymous); this one is unchanged. */
67
+ withToken(token: string | null): PolarisClient;
68
+ }
69
+ /**
70
+ * An `openapi-fetch` client typed by `paths` (generated from `polaris manifest --format=openapi`), so
71
+ * `client.POST("/auth/login", { body })` checks the body and types `data` and `error`; the plugins' routes
72
+ * are also methods of `client.audit`, `client.admin`, `client.sentinel`, `client.sso`, `client.scim`, `client.passwordless`,
73
+ * `client.username`, `client.anonymous` and `client.multiSession`; `challenge.captcha`
74
+ * answers a sentinel captcha challenge with one retry. No refresh loop and no storage: when to refresh
75
+ * and where to keep tokens is the application's policy.
76
+ */
77
+ export declare function createClient(options: PolarisClientOptions): PolarisClient;
package/dist/index.js ADDED
@@ -0,0 +1,58 @@
1
+ import createOpenApiClient from "openapi-fetch";
2
+ import { admin } from "./admin.js";
3
+ import { anonymous } from "./anonymous.js";
4
+ import { audit } from "./audit.js";
5
+ import { challengeRetry } from "./challenge.js";
6
+ import { multiSession } from "./multi-session.js";
7
+ import { passwordless } from "./passwordless.js";
8
+ import { sentinel } from "./sentinel.js";
9
+ import { scim } from "./scim.js";
10
+ import { sso } from "./sso.js";
11
+ import { username } from "./username.js";
12
+ export { admin } from "./admin.js";
13
+ export { anonymous } from "./anonymous.js";
14
+ export { audit } from "./audit.js";
15
+ export { challengeRetry } from "./challenge.js";
16
+ export { multiSession } from "./multi-session.js";
17
+ export { passwordless } from "./passwordless.js";
18
+ export { sentinel } from "./sentinel.js";
19
+ export { scim } from "./scim.js";
20
+ export { sso } from "./sso.js";
21
+ export { username } from "./username.js";
22
+ /**
23
+ * An `openapi-fetch` client typed by `paths` (generated from `polaris manifest --format=openapi`), so
24
+ * `client.POST("/auth/login", { body })` checks the body and types `data` and `error`; the plugins' routes
25
+ * are also methods of `client.audit`, `client.admin`, `client.sentinel`, `client.sso`, `client.scim`, `client.passwordless`,
26
+ * `client.username`, `client.anonymous` and `client.multiSession`; `challenge.captcha`
27
+ * answers a sentinel captcha challenge with one retry. No refresh loop and no storage: when to refresh
28
+ * and where to keep tokens is the application's policy.
29
+ */
30
+ export function createClient(options) {
31
+ const { token = null, challenge, ...clientOptions } = options;
32
+ const client = createOpenApiClient(clientOptions);
33
+ if (challenge !== undefined) {
34
+ client.use(challengeRetry(challenge));
35
+ }
36
+ if (token !== null) {
37
+ client.use({
38
+ onRequest({ request }) {
39
+ request.headers.set("Authorization", `Bearer ${token}`);
40
+ return request;
41
+ },
42
+ });
43
+ }
44
+ return {
45
+ ...client,
46
+ token,
47
+ audit: audit(client),
48
+ admin: admin(client),
49
+ sentinel: sentinel(client),
50
+ sso: sso(client),
51
+ scim: scim(client),
52
+ passwordless: passwordless(client),
53
+ username: username(client),
54
+ anonymous: anonymous(client),
55
+ multiSession: multiSession(client),
56
+ withToken: (next) => createClient({ ...options, token: next }),
57
+ };
58
+ }