Skip to content

Commit e3ab4e0

Browse files
committed
feat(plugin-auth): mobile sign-in hand-off over better-auth's one-time-token plugin (WIP)
Claude-Session: https://claude.ai/code/session_01JQwxbZkE4E6sE72j23Afwx Co-authored-by: Claude <noreply@anthropic.com>
1 parent 87956dc commit e3ab4e0

7 files changed

Lines changed: 735 additions & 0 deletions

File tree

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
* `phoneNumber`, `magicLink`, the generic OAuth providers, the OIDC provider
1515
* with its `jwt` plugin, `sso`, `scim`, device authorization and the custom
1616
* session — each with its own failure tier, as the method's docblock states.
17+
* (Since the move one plugin joined the list: the one-time token, ahead of
18+
* the custom session, for the mobile sign-in hand-off.)
1719
* The `organization` factory's body was moved out by cut 15; its arrow, which
1820
* hands that body its host, moves here with the rest.
1921
*
@@ -79,6 +81,11 @@ import {
7981
buildTwoFactorPluginSchema,
8082
} from './auth-schema-config.js';
8183
import { isPlaceholderEmail } from './placeholder-email.js';
84+
import {
85+
ONE_TIME_TOKEN_EXPIRES_IN_MINUTES,
86+
oneTimeTokenStoreHasher,
87+
registeredAppSchemesOf,
88+
} from './one-time-token-handoff.js';
8289
import { userInfoLocaleClaim } from './oidc-userinfo-locale-claim.js';
8390
import { buildTurnstileSignUpPlugin, reportHalfConfiguredTurnstile, resolveTurnstileKeys } from './turnstile-sign-up.js';
8491

@@ -802,6 +809,26 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
802809
});
803810
}
804811

812+
// One-time token — the mobile sign-in hand-off (maintainer ruling, option
813+
// B: better-auth's own plugin, no hand-written exchange endpoint). Mounted
814+
// only when the deployment registers at least one app scheme, because the
815+
// hand-off has nowhere to send a token otherwise. Generation is refused
816+
// over HTTP (`disableClientRequest`): the only minter is the ObjectStack
817+
// hand-off route, which binds each token to the shell's PKCE challenge
818+
// through `storeToken`'s custom hasher, so an intercepted callback cannot
819+
// be redeemed. Lifetime and the binding are argued in
820+
// `one-time-token-handoff.ts`.
821+
if (registeredAppSchemesOf(this.config).length > 0) {
822+
await this.addOptionalPlugin(plugins, 'oneTimeToken', async () => {
823+
const { oneTimeToken } = await import('better-auth/plugins/one-time-token');
824+
return oneTimeToken({
825+
expiresIn: ONE_TIME_TOKEN_EXPIRES_IN_MINUTES,
826+
disableClientRequest: true,
827+
storeToken: { type: 'custom-hasher', hash: oneTimeTokenStoreHasher },
828+
});
829+
});
830+
}
831+
805832
// customSession() — augments the session payload with the canonical
806833
// `positions: string[]` array (ADR-0068 D1/D2, renamed ADR-0090 D3) and its
807834
// derived `isPlatformAdmin` alias.

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ import { createAuthInstance, type AuthInstanceHost } from './auth-manager-auth-i
209209
// with it.
210210
import { buildPluginList, type PluginListHost } from './auth-manager-plugin-list.js';
211211
import { resolveTurnstileKeys } from './turnstile-sign-up.js';
212+
import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js';
212213

213214
/**
214215
* Detect WebContainer (StackBlitz) environment.
@@ -665,6 +666,13 @@ export function readInvitationPlacementIntent(
665666
}
666667

667668
export interface AuthManagerOptions extends Partial<AuthConfig> {
669+
/**
670+
* The app schemes the mobile sign-in hand-off may redirect a one-time token
671+
* to (`one-time-token-handoff.ts`). Declared here only until the spec's
672+
* `AuthConfig` carries the key; then this line goes and the spec's wins.
673+
*/
674+
trustedAppSchemes?: string[];
675+
668676
/**
669677
* Better-Auth instance (for advanced use cases)
670678
* If not provided, one will be created from config
@@ -1603,6 +1611,12 @@ export class AuthManager {
16031611
// appear after boot.
16041612
assertScimAdminCoherence(config.plugins);
16051613

1614+
// The mobile sign-in hand-off's registered app schemes — same
1615+
// boot-loudly rationale: an entry that is not a reverse-domain app scheme
1616+
// is refused here, never dropped (`one-time-token-handoff.ts`).
1617+
// `applyConfigPatch` re-runs it on the merged result.
1618+
assertTrustedAppSchemes(config.trustedAppSchemes);
1619+
16061620
// WebContainer (StackBlitz) compatibility — install a synchronous
16071621
// AsyncLocalStorage polyfill for better-auth's request-state global
16081622
// BEFORE better-auth ever instantiates its own. See the helper for the
@@ -1782,6 +1796,15 @@ export class AuthManager {
17821796
* fine but could not actually sign (#3585) — the plugin's endpoints are
17831797
* mounted, they just cannot mint a token.
17841798
*/
1799+
/**
1800+
* The app schemes the mobile sign-in hand-off may redirect a token to,
1801+
* normalised — the same reading the plugin list mounts the one-time-token
1802+
* plugin from, so the route and the plugin cannot disagree.
1803+
*/
1804+
getRegisteredAppSchemes(): string[] {
1805+
return registeredAppSchemesOf(this.config);
1806+
}
1807+
17851808
getDegradedAuthFeatures(): Array<{ feature: string; error: string }> {
17861809
return Array.from(this.degradedFeatures, ([feature, error]) => ({ feature, error }));
17871810
}
@@ -2059,6 +2082,9 @@ export class AuthManager {
20592082
if ('plugins' in patch) {
20602083
assertScimAdminCoherence(next.plugins);
20612084
}
2085+
if ('trustedAppSchemes' in patch) {
2086+
assertTrustedAppSchemes(next.trustedAppSchemes);
2087+
}
20622088

20632089
this.config = next;
20642090
this.deploymentDeclaredVerificationOff = deploymentDeclaredVerificationOff;

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import { runSetInitialPassword } from './set-initial-password.js';
8181
import { runRegisterSsoProviderFromForm, runRegisterSamlProviderFromForm, runRequestDomainVerification, runVerifyDomain, type AuthRequestHandler } from './register-sso-provider.js';
8282
import { runResendVerificationEmail } from './send-verification-email.js';
8383
import { runSysSessionRevoke, sysSessionRevokeDepsFor } from './sys-session-revoke.js';
84+
import { runOneTimeTokenHandoff } from './one-time-token-handoff.js';
8485
import { readJsonRequestBody } from './request-json-body.js';
8586
import {
8687
seedCreatedOrganizationCurrency,
@@ -4013,6 +4014,47 @@ export class AuthPlugin implements Plugin {
40134014
}
40144015
});
40154016

4017+
// ────────────────────────────────────────────────────────────────────
4018+
// The mobile sign-in hand-off: a session signed in in the SYSTEM browser
4019+
// is handed to a REGISTERED app scheme as a single-use, one-minute token
4020+
// the app redeems at better-auth's own `/one-time-token/verify`, bound to
4021+
// the shell's PKCE challenge so an intercepted callback cannot be
4022+
// redeemed. Mounted unconditionally: with no registered scheme every
4023+
// target is refused with a 400 that says how to register one. Session
4024+
// required; the reasons for every refusal live in
4025+
// `one-time-token-handoff.ts`. Ledgered in auth-route-ledger.ts.
4026+
rawApp.get(`${basePath}/one-time-token/handoff`, async (c: any) => {
4027+
try {
4028+
const manager = this.authManager!;
4029+
const answer = await runOneTimeTokenHandoff(
4030+
{
4031+
registeredSchemes: manager.getRegisteredAppSchemes(),
4032+
hasSession: async (headers) => {
4033+
const api: any = await manager.getApi();
4034+
return Boolean(await api.getSession({ headers }));
4035+
},
4036+
generate: async (headers) => {
4037+
const api: any = await manager.getApi();
4038+
return api.generateOneTimeToken({ headers });
4039+
},
4040+
},
4041+
{ queries: (c.req.queries() ?? {}) as Record<string, string[]>, headers: c.req.raw.headers },
4042+
);
4043+
if (answer.status === 302) {
4044+
return new Response(null, { status: 302, headers: answer.headers });
4045+
}
4046+
return c.json(answer.body, answer.status as any, answer.headers);
4047+
} catch (error) {
4048+
const err = error instanceof Error ? error : new Error(String(error));
4049+
ctx.logger.error('[AuthPlugin] one-time-token/handoff failed', err);
4050+
return c.json(
4051+
{ success: false, error: { code: 'INTERNAL_ERROR', message: 'The sign-in hand-off is unavailable.' } },
4052+
500,
4053+
{ 'Cache-Control': 'no-store' },
4054+
);
4055+
}
4056+
});
4057+
40164058
// ────────────────────────────────────────────────────────────────────
40174059
// ADR-0069 P3 — register a SAML 2.0 IdP. Mirrors the OIDC bridge above:
40184060
// the metadata `register_saml_provider` action posts FLAT fields; the shared

‎packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ const LEDGERED_PLUGIN_CONFIG = {
4343
deviceAuthorization: true,
4444
};
4545

46+
/** Registered app schemes: mounts the mobile sign-in hand-off's `one-time-token` plugin. */
47+
const LEDGERED_APP_SCHEMES = ['com.example.ledger'];
48+
4649
/**
4750
* `buildPluginList` reads env vars that can flip plugins on top of the config
4851
* above (`OS_SSO_ENABLED`, `OS_SCIM_ENABLED`, …). A developer with any of them
@@ -76,6 +79,10 @@ beforeAll(async () => {
7679
secret: 'route-ledger-conformance-secret-32-chars',
7780
baseUrl: 'http://localhost:9',
7881
plugins: LEDGERED_PLUGIN_CONFIG,
82+
// The one-time-token plugin is switched by a registered app scheme, not
83+
// by a `plugins` flag: one is registered so the maximal surface carries
84+
// its two vendor routes.
85+
trustedAppSchemes: LEDGERED_APP_SCHEMES,
7986
} as never);
8087
// No dataEngine: createDatabaseConfig() falls back to better-auth's in-memory
8188
// adapter. Route registration does not touch the database — only request
@@ -215,6 +222,12 @@ describe('auth route ledger hygiene', () => {
215222
expect(own).toEqual([
216223
'GET /api/v1/auth/bootstrap-status',
217224
'GET /api/v1/auth/config',
225+
// On this pin's own terms: `auth-plugin.ts` mounts it itself (a
226+
// `rawApp.get` on the `${basePath}/one-time-token/handoff`
227+
// template, ahead of the catch-all), and the `live.has(route)` loop
228+
// below holds it to the same proof — the vendor plugin publishes only
229+
// `/one-time-token/generate` and `/one-time-token/verify`.
230+
'GET /api/v1/auth/one-time-token/handoff',
218231
// [#26020] On this pin's own terms: `auth-plugin.ts` mounts it itself (a
219232
// `rawApp.get` on the `${basePath}/organization/invitation-preview`
220233
// template, ahead of the catch-all), and the `live.has(route)` loop below

‎packages/plugins/plugin-auth/src/auth-route-ledger.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,13 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
283283
{ route: 'POST /api/v1/auth/organization/update', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.update', requires: 'organization' },
284284
{ route: 'POST /api/v1/auth/organization/update-member-role', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.updateMemberRole', requires: 'organization' },
285285
{ route: 'POST /api/v1/auth/organization/update-team', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.teams.update', requires: 'organization' },
286+
// The mobile sign-in hand-off (maintainer ruling, option B): better-auth's
287+
// `one-time-token` plugin, mounted only when `trustedAppSchemes` registers
288+
// an app scheme, plus the ObjectStack hand-off that is its only minter.
289+
// `one-time-token-handoff.ts` carries the interception argument.
290+
{ route: 'GET /api/v1/auth/one-time-token/generate', family: 'one-time-token', source: 'better-auth', disposition: 'server-only', requires: 'oneTimeToken', note: 'published by the catch-all and refused to every client request (disableClientRequest: 400 with a session, 401 without); the only caller is the in-process hand-off, which binds the token it mints to the app shell\'s PKCE challenge' },
291+
{ route: 'POST /api/v1/auth/one-time-token/verify', family: 'one-time-token', source: 'better-auth', disposition: 'public', requires: 'oneTimeToken', note: 'no SDK method builds this URL — the mobile app shell (or the Console in its WebView) redeems a hand-off token here with no session: body { token: "T.code_verifier" }, answering the vendor { session, user } plus the session cookie, once, within one minute; a token without the verifier whose challenge started the hand-off (an intercepted callback) answers the vendor 400 and consumes nothing' },
292+
{ route: 'GET /api/v1/auth/one-time-token/handoff', family: 'one-time-token', source: 'objectstack', disposition: 'server-only', requires: 'oneTimeToken', note: 'no SDK method builds this URL — the mobile app shell opens it in the system browser after a sign-in there; session required. Closed query set { redirect_uri, code_challenge, code_challenge_method }: answers 302 to a redirect_uri whose scheme trustedAppSchemes registers, with a single-use one-minute token bound to the S256 code_challenge; an unregistered scheme answers 400 with no redirect. The mount is unconditional; with no registered scheme every target is refused' },
286293
{ route: 'POST /api/v1/auth/two-factor/disable', family: 'two-factor', source: 'better-auth', disposition: 'sdk', client: 'auth.twoFactor.disable', requires: 'twoFactor' },
287294
{ route: 'POST /api/v1/auth/two-factor/enable', family: 'two-factor', source: 'better-auth', disposition: 'sdk', client: 'auth.twoFactor.enable', requires: 'twoFactor' },
288295
{ route: 'POST /api/v1/auth/two-factor/generate-backup-codes', family: 'two-factor', source: 'better-auth', disposition: 'sdk', client: 'auth.twoFactor.generateBackupCodes', requires: 'twoFactor' },
@@ -344,6 +351,7 @@ export const BETTER_AUTH_MOUNTED_SURFACE: readonly string[] = [
344351
'GET /api/v1/auth/oauth2/public-client',
345352
'GET /api/v1/auth/oauth2/userinfo',
346353
'GET /api/v1/auth/ok',
354+
'GET /api/v1/auth/one-time-token/generate',
347355
'GET /api/v1/auth/organization/get-active-member',
348356
'GET /api/v1/auth/organization/get-active-member-role',
349357
'GET /api/v1/auth/organization/get-full-organization',
@@ -389,6 +397,7 @@ export const BETTER_AUTH_MOUNTED_SURFACE: readonly string[] = [
389397
'POST /api/v1/auth/get-session',
390398
'POST /api/v1/auth/link-social',
391399
'POST /api/v1/auth/oauth2/authorize',
400+
'POST /api/v1/auth/one-time-token/verify',
392401
// `private_key_jwt` client key rotation. Added to `@better-auth/oauth-provider`
393402
// after 1.7.3 and published here since the 1.7.12 lift (#25096). The handler
394403
// refuses before it reads anything unless the plugin is given

0 commit comments

Comments
 (0)