Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/specs/hosted.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ The relay Worker serves the self-host Relay's HTTP API to many accounts: the pat

| Route | On Hosted |
|---|---|
| `POST /api/setup/begin`, `/finish` | The passkey joins the account owning the token's Burrow, recorded as that Burrow's: `accountId` is its user ID, `existingCredentialIds` its passkeys; 409 at `MAX_PASSKEYS_PER_ACCOUNT`, naming the account page; `finish`'s session counts toward `MAX_SESSIONS_PER_ACCOUNT` as sign-in's does |
| `POST /api/setup/begin`, `/finish` | The passkey joins the account owning the token's Burrow, recorded as that Burrow's: `accountId` is its user ID, `existingCredentialIds` its passkeys, `accountEmail` its email (which names the new passkey, so it reaches whoever holds a live code); 409 at `MAX_PASSKEYS_PER_ACCOUNT`, naming the account page; `finish`'s session counts toward `MAX_SESSIONS_PER_ACCOUNT` as sign-in's does |
| `POST /api/setup/retire` | Spends only a token one of the session's account's Burrows minted |
| `POST /api/signin/finish` | The asserted credential's account; `accountId` is its user ID. 401 `NOT_ENTITLED_ERROR`, and no session, for an account not entitled |
| `POST /api/reauth/begin`, `/finish` | Only the session's account's credentials and nonces |
Expand Down
5 changes: 3 additions & 2 deletions hosted/server/relay-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ export function relayApiRoutes(app: Hono<{ Bindings: RelayEnv }>) {
return database(c, async (db) => {
const {
rows: [minter],
} = await db.query<OwnerRow & { burrowId: string; credentialIds: string[] }>(
`SELECT t."burrowId", b."userId", ${OWNER_COLUMNS},
} = await db.query<OwnerRow & { burrowId: string; credentialIds: string[]; email: string | null }>(
`SELECT t."burrowId", b."userId", u.email, ${OWNER_COLUMNS},
ARRAY(
SELECT p."credentialId" FROM dormouse_relay_passkeys p
WHERE p."userId" = b."userId" ORDER BY p."createdAt", p."credentialId"
Expand All @@ -236,6 +236,7 @@ export function relayApiRoutes(app: Hono<{ Bindings: RelayEnv }>) {
rpId: rpIdOf(c.env),
accountId: minter.userId,
existingCredentialIds: minter.credentialIds,
...(minter.email ? { accountEmail: minter.email } : {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better Auth's user.email is NOT NULL, and this query inner-joins "user", so no Hosted row reaches the empty branch. The field can be unconditional, which also lets the row type above say email: string:

Suggested change
...(minter.email ? { accountEmail: minter.email } : {}),
accountEmail: minter.email,

};
return c.json(res);
});
Expand Down
8 changes: 6 additions & 2 deletions hosted/server/tests/relay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -687,8 +687,12 @@ test("another account's session sees, proves with, and retires none of this acco
await f.entitle(a);
expect((await finish(sessionA.sessionToken)).status).toBe(200);
const begun = await f.call("POST", API_ROUTES.setupBegin, { body: { setupToken: code } });
// Only A's own credentials are excluded, never B's.
expect(begun.json).toMatchObject({ accountId: a, existingCredentialIds: [phoneA.credentialId] });
// Only A's own credentials are excluded, never B's, and the passkey is named by A's email.
expect(begun.json).toMatchObject({
accountId: a,
existingCredentialIds: [phoneA.credentialId],
accountEmail: ADMIN_EMAIL,
});

// B's Burrow mints nothing for an account that is not entitled.
expect(await f.mint(laptopB.token)).toMatchObject({ status: 403, json: { error: NOT_ENTITLED_ERROR } });
Expand Down
23 changes: 23 additions & 0 deletions lib/src/remote/client/pocket-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1540,6 +1540,29 @@ describe('setup + signin', () => {
expect(harness.client.holdsAnyCredential(['someone-else'])).toBe(false);
});

it('names the passkey by the account email the Relay sends, and as before without one', async () => {
const emails: (string | undefined)[] = [];
const webauthn: WebAuthnClient = {
...fakeWebAuthn,
registerPasskey: (...args) => {
emails.push(args[4]);
return fakeWebAuthn.registerPasskey(...args);
},
};
const withEmail = makeClient(
{
...AUTH_ROUTES,
'/api/setup/begin': () => ({
json: { challenge: secret(), rpId: 'relay.test', accountId: ACCOUNT_ID, existingCredentialIds: [], accountEmail: 'a@example.test' },
}),
},
{ webauthn },
);
await withEmail.client.setup({ setupToken: secret() }, 'Phone');
await makeClient({ ...AUTH_ROUTES }, { webauthn }).client.setup({ setupToken: secret() }, 'Phone');
expect(emails).toEqual(['a@example.test', undefined]);
});

/**
* Its own error class, because Pocket has to react rather than report: a
* spent code means "show a new one on the computer", where the shared
Expand Down
1 change: 1 addition & 0 deletions lib/src/remote/client/pocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ export class PocketClient {
begin.rpId,
begin.accountId,
begin.existingCredentialIds,
begin.accountEmail,
);
} catch (err) {
// Translated at this seam, not inside the browser wrapper, so every
Expand Down
19 changes: 19 additions & 0 deletions lib/src/remote/client/webauthn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,25 @@ describe('browserWebAuthn.registerPasskey', () => {
expect(user.displayName).toBe('Dormouse Pocket (relay.dormouse.sh)');
expect(utf8Decode(new Uint8Array(user.id as ArrayBuffer))).toBe('user-123');
});

it('names the passkey by its account email when the Relay sent one', async () => {
const create = vi.fn(async () => ({
id: 'cred',
response: {
getPublicKey: () => new Uint8Array([1, 2, 3]).buffer,
clientDataJSON: new Uint8Array([4]).buffer,
},
}));
vi.stubGlobal('navigator', { credentials: { create } });

await browserWebAuthn.registerPasskey(toBase64Url(new Uint8Array(32)), 'relay.dormouse.sh', 'user-123', [], 'a@example.test');

const { user } = (create.mock.calls[0] as unknown as [{ publicKey: PublicKeyCredentialCreationOptions }])[0]
.publicKey;
expect(user.name).toBe('a@example.test (Dormouse.sh)');
expect(user.displayName).toBe('a@example.test (Dormouse.sh)');
expect(utf8Decode(new Uint8Array(user.id as ArrayBuffer))).toBe('user-123');
});
});

describe('a dismissed or timed-out passkey prompt', () => {
Expand Down
18 changes: 11 additions & 7 deletions lib/src/remote/client/webauthn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,12 @@ export function isPasskeyAlreadyRegistered(err: unknown): boolean {

/**
* The name a registered passkey shows in the platform's passkey manager: the
* app and the Relay it signs in to, never the account id, which is the
* credential's opaque `user.id` alone.
* account's email where the Relay sent one, so one phone's passkeys for two
* accounts read apart, else the app and the Relay it signs in to. Never the
* account id, which is the credential's opaque `user.id` alone.
*/
export function passkeyUserName(rpId: string): string {
return `Dormouse Pocket (${rpId})`;
export function passkeyUserName(rpId: string, accountEmail?: string): string {
return accountEmail ? `${accountEmail} (Dormouse.sh)` : `Dormouse Pocket (${rpId})`;
}

/** The result of a passkey registration, ready for `POST /api/setup/finish`. */
Expand All @@ -79,13 +80,15 @@ export interface WebAuthnClient {
/**
* Create a passkey for `accountId`. Pass `excludeCredentialIds` (base64url,
* from `SetupBeginResponse`) to stop the authenticator minting a duplicate of
* a credential the Relay already holds.
* a credential the Relay already holds, and `accountEmail` (also from it)
* to name the passkey by its account.
*/
registerPasskey(
challenge: string,
rpId: string,
accountId: string,
excludeCredentialIds?: readonly string[],
accountEmail?: string,
): Promise<PasskeyRegistration>;
/**
* Get an assertion bound to `challenge`. Pass `allowCredentials` (base64url
Expand Down Expand Up @@ -132,15 +135,16 @@ async function registerPasskey(
rpId: string,
accountId: string,
excludeCredentialIds: readonly string[] = [],
accountEmail?: string,
): Promise<PasskeyRegistration> {
const credential = (await navigator.credentials.create({
publicKey: {
challenge: toBufferSource(fromBase64Url(challenge)),
rp: { id: rpId, name: 'Dormouse' },
user: {
id: toBufferSource(utf8Encode(accountId)),
name: passkeyUserName(rpId),
displayName: passkeyUserName(rpId),
name: passkeyUserName(rpId, accountEmail),
displayName: passkeyUserName(rpId, accountEmail),
},
pubKeyCredParams: [{ type: 'public-key', alg: -7 }],
excludeCredentials: excludeCredentialIds.map((id) => ({
Expand Down
7 changes: 7 additions & 0 deletions remote-lib-common/src/remote/wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,13 @@ export interface SetupBeginResponse {
* cache is empty on a fresh install and cleared again by a refused `finish`.
*/
existingCredentialIds: string[];
/**
* The account's email, where the Relay keeps one (Hosted does, selfhost does
* not), so a phone holding passkeys for two accounts can tell them apart in
* its passkey manager. Optional both ways: a Pocket that predates it ignores
* it, and one reading a Relay that sends none names the passkey as before.
*/
accountEmail?: string;
}

export type SetupFinishRequest = SetupCredential & {
Expand Down
Loading