mirror of
https://github.com/bitbaum/accountkit.git
synced 2026-12-04 04:57:12 +01:00
A free, Bitcoin-native way in: the person's own Lightning wallet signs a one-time challenge shown as a QR code (or opened through a lightning: link on the same device). No key, no third party, nothing paid. The signed key is a sign-in method (providerId "lightning"), never an email. - /lightning/start mints a challenge (five minutes, used once) and binds it to the asking browser with a signed cookie; /lightning/callback is the wallet's LUD-04 call and checks the DER secp256k1 signature of k1; /sign-in/lightning (polled) signs in or creates the person; /lightning/link adds a wallet to the signed-in person, never one that already signs in to someone else. - A second factor applies; minting and the wallet's call spend the credential bucket. - SignInForm and SignUpForm offer "Sign in with a Lightning wallet", AccountPanel "Add Lightning wallet"; words in all six languages. - Off until ACCOUNTKIT_LIGHTNING=1. Tests: LUD-01's own LNURL both ways, a signature made by OpenSSL, and the whole flow on a real database (PGlite) with a wallet that signs as LUD-04 says: sign-in and sign-in again, a forged signature, an onlooker without the browser's cookie, a second factor, linking and a taken wallet, and nothing mounted without the opt-in. Browser: QR, wallet link, 44px, no sideways scroll at 320 and 390px. Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9 Co-authored-by: Claude <noreply@anthropic.com>
113 lines
6.0 KiB
JavaScript
113 lines
6.0 KiB
JavaScript
import { createAuthMiddleware, getOAuthState } from "better-auth/api";
|
|
import { twoFactor } from "better-auth/plugins";
|
|
import { deleteSessionCookie } from "better-auth/cookies";
|
|
import { returnPath } from "../paths.js";
|
|
/** Resolve only app-local challenge UI and return URLs; never carry bearer values. */
|
|
export function factorDestination(origin, screen, next) {
|
|
const local = (value, fallback) => {
|
|
try {
|
|
const url = new URL(typeof value === "string" ? value : fallback, origin);
|
|
if (url.origin !== new URL(origin).origin)
|
|
return new URL(fallback, origin);
|
|
return new URL(returnPath(url.pathname + url.search + url.hash, fallback), origin);
|
|
}
|
|
catch {
|
|
return new URL(fallback, origin);
|
|
}
|
|
};
|
|
const target = local(screen, "/sign-in");
|
|
const destination = local(next, "/");
|
|
for (const key of ["error", "error_description", "token", "code", "state"])
|
|
target.searchParams.delete(key);
|
|
target.searchParams.set("twoFactor", "1");
|
|
target.searchParams.set("next", destination.pathname === target.pathname
|
|
? "/"
|
|
: destination.pathname + destination.search + destination.hash);
|
|
return target.toString();
|
|
}
|
|
/** Reuse BetterAuth's challenge/trusted-device policy for every primary method. */
|
|
export function factorForAllMethods(site) {
|
|
const plugin = twoFactor({ issuer: site.title, allowPasswordless: true });
|
|
const native = plugin.hooks.after[0];
|
|
return {
|
|
...plugin,
|
|
hooks: {
|
|
...plugin.hooks,
|
|
after: [
|
|
...plugin.hooks.after,
|
|
{
|
|
matcher: ({ path }) => path === "/magic-link/verify" ||
|
|
path === "/sign-in/email-otp" ||
|
|
path === "/sign-in/lightning" ||
|
|
path === "/verify-email" ||
|
|
path === "/passkey/verify-authentication" ||
|
|
/^\/(?:oauth2\/)?callback\/[^/]+$/.test(path ?? ""),
|
|
handler: createAuthMiddleware(async (ctx) => {
|
|
const pending = ctx.context.newSession;
|
|
if (!pending ||
|
|
!("twoFactorEnabled" in pending.user) ||
|
|
!pending.user.twoFactorEnabled)
|
|
return;
|
|
// Delegate cookie revocation, signed challenge creation, expiry,
|
|
// attempt limits and trusted-device validation to the native plugin.
|
|
let delegated;
|
|
try {
|
|
// BetterCall's runtime supports returnHeaders even where the
|
|
// middleware declaration exposes only its body. Validate it.
|
|
const result = await native.handler({
|
|
...ctx,
|
|
returnHeaders: true,
|
|
});
|
|
if (!result ||
|
|
typeof result !== "object" ||
|
|
!("headers" in result) ||
|
|
!(result.headers instanceof Headers) ||
|
|
!("response" in result))
|
|
throw new Error("Unsupported BetterAuth factor middleware envelope");
|
|
const body = result.response;
|
|
if (body !== undefined &&
|
|
(!body ||
|
|
typeof body !== "object" ||
|
|
!("twoFactorRedirect" in body) ||
|
|
body.twoFactorRedirect !== true ||
|
|
!("twoFactorMethods" in body) ||
|
|
!Array.isArray(body.twoFactorMethods) ||
|
|
!body.twoFactorMethods.every((method) => typeof method === "string")))
|
|
throw new Error("Unsupported BetterAuth factor challenge body");
|
|
delegated = {
|
|
headers: result.headers,
|
|
response: body,
|
|
};
|
|
}
|
|
catch (error) {
|
|
// Never leave the primary session usable on an SDK failure.
|
|
await ctx.context.internalAdapter.deleteSession(pending.session.token);
|
|
ctx.context.setNewSession(null);
|
|
deleteSessionCookie(ctx, true);
|
|
throw error;
|
|
}
|
|
// Middleware invocations return their own headers and body. Keep
|
|
// each Set-Cookie separate, including session revocation + challenge.
|
|
for (const [name, value] of delegated.headers) {
|
|
if (name !== "set-cookie")
|
|
ctx.responseHeaders.set(name, value);
|
|
}
|
|
for (const cookie of delegated.headers.getSetCookie())
|
|
ctx.responseHeaders.append("set-cookie", cookie);
|
|
// Methods answered in the page's own request (fetch, not a
|
|
// navigation) get the challenge as JSON, like a password.
|
|
if (ctx.context.newSession ||
|
|
ctx.path === "/passkey/verify-authentication" ||
|
|
ctx.path === "/sign-in/email-otp" ||
|
|
ctx.path === "/sign-in/lightning")
|
|
return delegated.response;
|
|
const state = await getOAuthState();
|
|
const target = factorDestination(site.url, ctx.query?.errorCallbackURL ?? state?.errorURL, ctx.query?.callbackURL ?? state?.callbackURL);
|
|
throw ctx.redirect(target);
|
|
}),
|
|
},
|
|
],
|
|
},
|
|
};
|
|
}
|
|
//# sourceMappingURL=factor.js.map
|