@polaris-auth/client 0.6.1 → 0.8.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.
@@ -0,0 +1,9 @@
1
+ /** The `username` plugin's routes as methods of `client.username`. */
2
+ export function username(client) {
3
+ return {
4
+ /** POST /username/sign-in: Sign in with a username and a password */
5
+ signIn: (...init) => client.POST("/username/sign-in", ...init),
6
+ /** PATCH /username: Set or change your username */
7
+ update: (...init) => client.PATCH("/username", ...init),
8
+ };
9
+ }
@@ -0,0 +1,27 @@
1
+ import type { PolarisClient } from "./index.js";
2
+ interface PasskeyRegistration {
3
+ passkey: Record<string, unknown>;
4
+ recovery_codes: string[];
5
+ }
6
+ export interface SignInWithPasskeyOptions {
7
+ /** Conditional UI: the browser offers the passkey in the form's autofill instead of a prompt (`autocomplete="username webauthn"`). */
8
+ conditional?: boolean;
9
+ signal?: AbortSignal;
10
+ }
11
+ /**
12
+ * Registers a passkey for the signed-in user of `client` and answers the passkey (and the recovery
13
+ * codes when it is the user's first MFA factor).
14
+ */
15
+ export declare function registerPasskey(client: PolarisClient, name?: string): Promise<PasskeyRegistration>;
16
+ /**
17
+ * Signs in with a passkey (discoverable, or from the form's autofill with `conditional`) and answers
18
+ * core's login envelope, or its `mfa_required` ticket when the authenticator did not verify the user.
19
+ */
20
+ export declare function signInWithPasskey(client: PolarisClient, options?: SignInWithPasskeyOptions): Promise<Record<string, unknown>>;
21
+ /**
22
+ * The assertion for a fresh challenge, as the JSON string the routes take (`credential`, or core's `code`).
23
+ */
24
+ export declare function passkeyAssertion(client: PolarisClient, options?: SignInWithPasskeyOptions): Promise<string>;
25
+ /** Whether this browser can autofill a passkey into a form (conditional UI). */
26
+ export declare function passkeyAutofillAvailable(): Promise<boolean>;
27
+ export {};
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Registers a passkey for the signed-in user of `client` and answers the passkey (and the recovery
3
+ * codes when it is the user's first MFA factor).
4
+ */
5
+ export async function registerPasskey(client, name) {
6
+ const options = await client.passkey.registerOptions();
7
+ if (options.data === undefined) {
8
+ throw new Error(describe("POST /passkey/register/options", options.error));
9
+ }
10
+ const credential = await navigator.credentials.create({ publicKey: parseCreationOptions(options.data.data) });
11
+ if (!(credential instanceof PublicKeyCredential)) {
12
+ throw new Error("The browser created no passkey.");
13
+ }
14
+ const body = { credential: serialize(credential) };
15
+ if (name !== undefined) {
16
+ body["name"] = name;
17
+ }
18
+ const registered = await client.passkey.registerVerify({ body });
19
+ if (registered.data === undefined) {
20
+ throw new Error(describe("POST /passkey/register/verify", registered.error));
21
+ }
22
+ return registered.data.data;
23
+ }
24
+ /**
25
+ * Signs in with a passkey (discoverable, or from the form's autofill with `conditional`) and answers
26
+ * core's login envelope, or its `mfa_required` ticket when the authenticator did not verify the user.
27
+ */
28
+ export async function signInWithPasskey(client, options = {}) {
29
+ const credential = await passkeyAssertion(client, options);
30
+ const verified = await client.passkey.authenticateVerify({ body: { credential: JSON.parse(credential) } });
31
+ if (verified.data === undefined) {
32
+ throw new Error(describe("POST /passkey/authenticate/verify", verified.error));
33
+ }
34
+ return verified.data.data;
35
+ }
36
+ /**
37
+ * The assertion for a fresh challenge, as the JSON string the routes take (`credential`, or core's `code`).
38
+ */
39
+ export async function passkeyAssertion(client, options = {}) {
40
+ const request = await client.passkey.authenticateOptions();
41
+ if (request.data === undefined) {
42
+ throw new Error(describe("POST /passkey/authenticate/options", request.error));
43
+ }
44
+ const get = { publicKey: parseRequestOptions(request.data.data) };
45
+ if (options.conditional === true) {
46
+ get.mediation = "conditional";
47
+ }
48
+ if (options.signal !== undefined) {
49
+ get.signal = options.signal;
50
+ }
51
+ const credential = await navigator.credentials.get(get);
52
+ if (!(credential instanceof PublicKeyCredential)) {
53
+ throw new Error("The browser answered no passkey.");
54
+ }
55
+ return JSON.stringify(serialize(credential));
56
+ }
57
+ /** Whether this browser can autofill a passkey into a form (conditional UI). */
58
+ export async function passkeyAutofillAvailable() {
59
+ const api = globalThis.PublicKeyCredential;
60
+ return api?.isConditionalMediationAvailable !== undefined ? api.isConditionalMediationAvailable() : false;
61
+ }
62
+ function parseCreationOptions(json) {
63
+ const api = globalThis.PublicKeyCredential;
64
+ if (api.parseCreationOptionsFromJSON !== undefined) {
65
+ return api.parseCreationOptionsFromJSON(json);
66
+ }
67
+ const user = json["user"];
68
+ return {
69
+ ...json,
70
+ challenge: fromBase64Url(json["challenge"]),
71
+ user: { ...user, id: fromBase64Url(user["id"]) },
72
+ excludeCredentials: descriptors(json["excludeCredentials"]),
73
+ };
74
+ }
75
+ function parseRequestOptions(json) {
76
+ const api = globalThis.PublicKeyCredential;
77
+ if (api.parseRequestOptionsFromJSON !== undefined) {
78
+ return api.parseRequestOptionsFromJSON(json);
79
+ }
80
+ return { ...json, challenge: fromBase64Url(json["challenge"]), allowCredentials: descriptors(json["allowCredentials"]) };
81
+ }
82
+ function descriptors(list) {
83
+ return Array.isArray(list) ? list.map((entry) => ({ ...entry, id: fromBase64Url(entry["id"]) })) : [];
84
+ }
85
+ /** `credential.toJSON()` where the browser has it; the same shape by hand otherwise. */
86
+ function serialize(credential) {
87
+ const withJson = credential;
88
+ if (withJson.toJSON !== undefined) {
89
+ return withJson.toJSON();
90
+ }
91
+ const response = credential.response;
92
+ const body = { clientDataJSON: toBase64Url(response.clientDataJSON) };
93
+ if (response.attestationObject !== undefined) {
94
+ body["attestationObject"] = toBase64Url(response.attestationObject);
95
+ body["transports"] = typeof response.getTransports === "function" ? response.getTransports() : [];
96
+ }
97
+ else {
98
+ body["authenticatorData"] = toBase64Url(response.authenticatorData);
99
+ body["signature"] = toBase64Url(response.signature);
100
+ body["userHandle"] = response.userHandle === null ? null : toBase64Url(response.userHandle);
101
+ }
102
+ return {
103
+ id: credential.id,
104
+ rawId: toBase64Url(credential.rawId),
105
+ type: credential.type,
106
+ authenticatorAttachment: credential.authenticatorAttachment ?? null,
107
+ clientExtensionResults: credential.getClientExtensionResults(),
108
+ response: body,
109
+ };
110
+ }
111
+ function fromBase64Url(encoded) {
112
+ const binary = atob(encoded.replace(/-/g, "+").replace(/_/g, "/"));
113
+ const bytes = new Uint8Array(binary.length);
114
+ for (let i = 0; i < binary.length; i++) {
115
+ bytes[i] = binary.charCodeAt(i);
116
+ }
117
+ return bytes.buffer;
118
+ }
119
+ function toBase64Url(buffer) {
120
+ let binary = "";
121
+ for (const byte of new Uint8Array(buffer)) {
122
+ binary += String.fromCharCode(byte);
123
+ }
124
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
125
+ }
126
+ function describe(route, error) {
127
+ const problem = error;
128
+ return `${route} failed: ${problem?.detail ?? problem?.message ?? problem?.error ?? "unknown error"}`;
129
+ }