cauthy-auth 0.10.0 → 0.12.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/svelte.mjs CHANGED
@@ -1,3 +1,79 @@
1
+ // src/passkey.ts
2
+ function canUsePasskeys() {
3
+ return typeof window !== "undefined" && typeof window.PublicKeyCredential === "function" && typeof navigator !== "undefined" && typeof navigator.credentials?.get === "function";
4
+ }
5
+ async function canAutofillPasskeys() {
6
+ if (!canUsePasskeys()) return false;
7
+ const pkc = window.PublicKeyCredential;
8
+ try {
9
+ return typeof pkc.isConditionalMediationAvailable === "function" && await pkc.isConditionalMediationAvailable() === true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ function bytes(text2) {
15
+ const b64 = text2.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(text2.length / 4) * 4, "=");
16
+ const bin = atob(b64);
17
+ const out = new Uint8Array(bin.length);
18
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
19
+ return out.buffer;
20
+ }
21
+ function text(buf) {
22
+ if (!buf) return null;
23
+ const view = new Uint8Array(buf);
24
+ let bin = "";
25
+ for (let i = 0; i < view.byteLength; i++) bin += String.fromCharCode(view[i]);
26
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
27
+ }
28
+ var withId = (list) => (list ?? []).map((c) => ({ ...c, id: bytes(c.id) }));
29
+ async function getPasskey(options, how = {}) {
30
+ const publicKey = { ...options, challenge: bytes(options.challenge), allowCredentials: withId(options.allowCredentials) };
31
+ const cred = await navigator.credentials.get({ publicKey, ...how });
32
+ if (cred === null) throw new DOMException("No passkey was chosen.", "NotAllowedError");
33
+ const r = cred.response;
34
+ return {
35
+ id: cred.id,
36
+ rawId: text(cred.rawId),
37
+ type: cred.type,
38
+ response: {
39
+ authenticatorData: text(r.authenticatorData),
40
+ clientDataJSON: text(r.clientDataJSON),
41
+ signature: text(r.signature),
42
+ userHandle: text(r.userHandle)
43
+ },
44
+ clientExtensionResults: cred.getClientExtensionResults?.() ?? {}
45
+ };
46
+ }
47
+ async function makePasskey(options) {
48
+ const publicKey = {
49
+ ...options,
50
+ challenge: bytes(options.challenge),
51
+ user: { ...options.user, id: bytes(options.user.id) },
52
+ excludeCredentials: withId(options.excludeCredentials)
53
+ };
54
+ const cred = await navigator.credentials.create({ publicKey });
55
+ if (cred === null) throw new DOMException("No passkey was made.", "NotAllowedError");
56
+ const r = cred.response;
57
+ return {
58
+ id: cred.id,
59
+ rawId: text(cred.rawId),
60
+ type: cred.type,
61
+ response: {
62
+ clientDataJSON: text(r.clientDataJSON),
63
+ attestationObject: text(r.attestationObject),
64
+ transports: typeof r.getTransports === "function" ? r.getTransports() : []
65
+ },
66
+ clientExtensionResults: cred.getClientExtensionResults?.() ?? {}
67
+ };
68
+ }
69
+ function ceremonyError(e) {
70
+ const name = e instanceof Error || e instanceof DOMException ? e.name : "";
71
+ if (name === "NotAllowedError" || name === "AbortError") return { code: "cancelled", message: "The passkey was not used. Try again when you are ready." };
72
+ if (name === "InvalidStateError") return { code: "passkey_exists", message: "This device already has a passkey for this account." };
73
+ if (name === "SecurityError") return { code: "passkey_unavailable", message: "Passkeys cannot be used on this page." };
74
+ return { code: "passkey_failed", message: "The passkey could not be used. Try again, or sign in another way." };
75
+ }
76
+
1
77
  // src/theme.ts
2
78
  function fromWire(wire) {
3
79
  const names = {
@@ -72,6 +148,24 @@ function firstProblem(...checks) {
72
148
  }
73
149
 
74
150
  // src/client.ts
151
+ var googleScript = null;
152
+ function loadGoogleIdentity() {
153
+ const ready = () => window.google?.accounts?.id;
154
+ if (ready()) return Promise.resolve(ready());
155
+ googleScript ??= new Promise((resolve, reject) => {
156
+ const script = document.createElement("script");
157
+ script.src = "https://accounts.google.com/gsi/client";
158
+ script.async = true;
159
+ script.onload = () => ready() ? resolve(ready()) : reject(new Error("google identity services did not load"));
160
+ script.onerror = () => {
161
+ googleScript = null;
162
+ reject(new Error("google identity services did not load"));
163
+ };
164
+ document.head.appendChild(script);
165
+ });
166
+ return googleScript;
167
+ }
168
+ var PASSKEY_SECONDS = 300;
75
169
  var UNAVAILABLE = { code: "unavailable", message: "Sign-in is unavailable right now. Try again in a moment." };
76
170
  function createAuthClient(options = {}) {
77
171
  const base = (options.basePath ?? "/api/auth").replace(/\/+$/, "");
@@ -114,6 +208,28 @@ function createAuthClient(options = {}) {
114
208
  if (o.locale) q.set("locale", o.locale);
115
209
  return `${base}/login?${q}`;
116
210
  };
211
+ async function methods() {
212
+ try {
213
+ const res = await doFetch(`${base}/methods`, { credentials: "same-origin", headers: { accept: "application/json" } });
214
+ if (res.ok) {
215
+ const m = await res.json();
216
+ return { providers: [], signUp: true, magicLink: false, passkey: false, ...m, passkeyHere: m.passkeyHere === true, passkeyOnCauthy: m.passkeyOnCauthy ?? m.passkey === true };
217
+ }
218
+ } catch {
219
+ }
220
+ return { providers: [], signUp: true, magicLink: false, passkey: false, passkeyHere: false, passkeyOnCauthy: false };
221
+ }
222
+ async function ceremony(begin, finish, form, run, more = {}) {
223
+ const begun = await post(begin, form, null);
224
+ if (!begun.ok) return begun;
225
+ let credential;
226
+ try {
227
+ credential = await run(begun.options);
228
+ } catch (e) {
229
+ return { ok: false, error: ceremonyError(e) };
230
+ }
231
+ return post(finish, { credential, ...more }, null);
232
+ }
117
233
  return {
118
234
  signIn: {
119
235
  email: (f) => post("/sign-in/email", { email: f.email, password: f.password }, firstProblem(checkEmail(f.email), checkPassword(f.password))),
@@ -122,8 +238,76 @@ function createAuthClient(options = {}) {
122
238
  magicLinkVerify: (f) => post("/sign-in/magic-link/verify", { token: f.token }, null),
123
239
  emailCode: (f) => post("/sign-in/email-code", { code: f.code }, checkCode(f.code)),
124
240
  passkeyUrl,
125
- passkey(o) {
241
+ async passkey(o) {
242
+ const m = await methods();
243
+ if (m.passkeyHere && canUsePasskeys()) {
244
+ const r = await ceremony("/sign-in/passkey/begin", "/sign-in/passkey/finish", {}, getPasskey);
245
+ if (r.ok || r.error.code !== "passkey_unavailable" || !m.passkeyOnCauthy) return r;
246
+ } else if (!m.passkeyOnCauthy) {
247
+ return { ok: false, error: { code: "passkey_unavailable", message: "Passkeys cannot be used here." } };
248
+ }
126
249
  window.location.assign(passkeyUrl(o));
250
+ return { ok: true, status: "redirected" };
251
+ },
252
+ async passkeyAutofill(o = {}) {
253
+ const cancelled = { ok: false, error: { code: "cancelled", message: "No passkey was chosen." } };
254
+ const m = await methods();
255
+ if (!m.passkeyHere || !await canAutofillPasskeys()) return cancelled;
256
+ for (; ; ) {
257
+ if (o.signal?.aborted) return cancelled;
258
+ const begun = await post("/sign-in/passkey/begin", {}, null);
259
+ if (!begun.ok) return begun;
260
+ const renew = new AbortController();
261
+ const stop = () => renew.abort();
262
+ o.signal?.addEventListener("abort", stop, { once: true });
263
+ const timer = setTimeout(stop, (PASSKEY_SECONDS - 30) * 1e3);
264
+ let credential;
265
+ try {
266
+ credential = await getPasskey(begun.options, { mediation: "conditional", signal: renew.signal });
267
+ } catch (e) {
268
+ if (o.signal?.aborted) return cancelled;
269
+ if (renew.signal.aborted) continue;
270
+ return { ok: false, error: ceremonyError(e) };
271
+ } finally {
272
+ clearTimeout(timer);
273
+ o.signal?.removeEventListener("abort", stop);
274
+ }
275
+ return post("/sign-in/passkey/finish", { credential }, null);
276
+ }
277
+ },
278
+ async googleOneTap(o = {}) {
279
+ const cancelled = { ok: false, error: { code: "cancelled", message: "No Google account was chosen." } };
280
+ if (typeof window === "undefined" || o.signal?.aborted) return cancelled;
281
+ const begun = await post("/sign-in/google-one-tap/begin", {}, null);
282
+ if (!begun.ok) return begun;
283
+ let gis;
284
+ try {
285
+ gis = await loadGoogleIdentity();
286
+ } catch {
287
+ return { ok: false, error: { code: "unavailable", message: "Google could not be reached. Try again, or sign in another way." } };
288
+ }
289
+ const credential = await new Promise((done) => {
290
+ o.signal?.addEventListener("abort", () => {
291
+ gis.cancel();
292
+ done(null);
293
+ }, { once: true });
294
+ gis.initialize({
295
+ client_id: begun.clientId,
296
+ nonce: begun.nonce,
297
+ context: o.context ?? "signin",
298
+ callback: (r) => done(r.credential ?? null),
299
+ auto_select: false,
300
+ cancel_on_tap_outside: true,
301
+ itp_support: true,
302
+ use_fedcm_for_prompt: true
303
+ });
304
+ gis.prompt((moment) => {
305
+ if (moment.isNotDisplayed?.() || moment.isSkippedMoment?.()) done(null);
306
+ else if (moment.isDismissedMoment?.() && moment.getDismissedReason?.() !== "credential_returned") done(null);
307
+ });
308
+ });
309
+ if (credential === null) return cancelled;
310
+ return post("/sign-in/google-one-tap", { credential }, null);
127
311
  },
128
312
  socialUrl,
129
313
  social(provider, o) {
@@ -167,7 +351,16 @@ function createAuthClient(options = {}) {
167
351
  const body = await read("/me/sessions");
168
352
  return body && Array.isArray(body.sessions) ? body.sessions : [];
169
353
  },
170
- signOutEverywhere: () => post("/me/sessions/end", {}, null)
354
+ signOutEverywhere: () => post("/me/sessions/end", {}, null),
355
+ async passkeys() {
356
+ const body = await read("/me/passkeys");
357
+ return body && Array.isArray(body.passkeys) ? body.passkeys : [];
358
+ },
359
+ addPasskey(f = {}) {
360
+ if (!canUsePasskeys()) return Promise.resolve({ ok: false, error: { code: "passkey_unavailable", message: "This browser cannot make passkeys." } });
361
+ return ceremony("/me/passkeys/add/begin", "/me/passkeys/add/finish", { password: f.password ?? "" }, makePasskey, { name: f.name ?? "" });
362
+ },
363
+ removePasskey: (id) => post("/me/passkeys/remove", { id }, null)
171
364
  },
172
365
  async getSession() {
173
366
  try {
@@ -182,14 +375,7 @@ function createAuthClient(options = {}) {
182
375
  looked ??= read("/look").then((wire) => wire && typeof wire === "object" ? fromWire(wire) : null);
183
376
  return looked;
184
377
  },
185
- async methods() {
186
- try {
187
- const res = await doFetch(`${base}/methods`, { credentials: "same-origin", headers: { accept: "application/json" } });
188
- if (res.ok) return await res.json();
189
- } catch {
190
- }
191
- return { providers: [], signUp: true, magicLink: false, passkey: false };
192
- }
378
+ methods
193
379
  };
194
380
  }
195
381
 
@@ -285,7 +471,8 @@ function createSessionStore(options = {}) {
285
471
  email: (f) => then(client.signIn.email(f)),
286
472
  mfa: (f) => then(client.signIn.mfa(f)),
287
473
  magicLinkVerify: (f) => then(client.signIn.magicLinkVerify(f)),
288
- emailCode: (f) => then(client.signIn.emailCode(f))
474
+ emailCode: (f) => then(client.signIn.emailCode(f)),
475
+ passkey: (o) => then(client.signIn.passkey(o))
289
476
  },
290
477
  signUp: { email: (f) => then(client.signUp.email(f)) },
291
478
  signOut: () => then(client.signOut()),