Skip to content
Merged
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
17 changes: 16 additions & 1 deletion docs/ACCOUNTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ repository into static files, exactly as before.

## What a reader can do

- **Sign in** with Google, GitHub or a link sent by email. Nothing asks for
- **Sign in** with Google, GitHub or a link or code sent by email. Nothing asks for
it until they press "New timeline" or "Sign in".
- **New timeline**: say what it is about and a model writes it (see
"Create with AI" below), or start from a private copy of the view on the
Expand Down Expand Up @@ -244,6 +244,21 @@ is not offered the editor.
3. **Email**: the built-in sender only reaches the project's own team and
a few messages an hour. For links to anyone, add an SMTP sender
(Resend's free plan is enough to start).
4. **Authentication → Email Templates**: by default the email's link goes
to the sign-in service's own address, which some readers (and browser
agents) rightly will not open. Make "Magic Link" and "Confirm signup"
both send a link to codegrave.com and the code itself, for example:

```html
<h2>Sign in to codegrave</h2>
<p><a href="{{ .RedirectTo }}#token_hash={{ .TokenHash }}&type=email">Sign in to codegrave</a></p>
<p>Or type this code on the page: <b>{{ .Token }}</b></p>
```

The page trades the key after `#` for a session (`readAuthHash()` and
`verify()` in `site/account.js`), and the "Check your inbox" dialog
takes the code. Since the key is after `#`, it never reaches a server,
and a mail scanner that fetches the link does not use it up.

## Limits known today

Expand Down
2 changes: 2 additions & 0 deletions site/account.css
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,8 @@ body:not(.sb-open) .rail-only { display: flex; transform: rotate(90deg); }
#sb-foot .big { height: 42px; margin-top: 0; font-size: 14px; }
.dlg input[type="text"], .dlg input[type="email"] { width: 100%; height: 46px; padding: 0 14px; font-size: 15px; color: var(--text); background: var(--bg); border: 1px solid var(--rule2); border-radius: 12px; outline: 0; }
.dlg input:focus { border-color: var(--text); }
.dlg form.code input { text-align: center; font-size: 20px; letter-spacing: .3em; font-variant-numeric: tabular-nums; }
.dlg form.code input::placeholder { font-size: 15px; letter-spacing: 0; }
.fld { display: block; }
.fld span { display: block; margin-bottom: 6px; font-size: 12.5px; font-weight: 500; color: var(--muted); }
.addr { display: flex; align-items: center; height: 46px; padding: 0 12px; font-size: 14px; background: var(--bg); border: 1px solid var(--rule2); border-radius: 12px; }
Expand Down
45 changes: 42 additions & 3 deletions site/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export function readAuthHash(hash) {
if (q.get('access_token') && q.get('refresh_token')) {
return { session: { access_token: q.get('access_token'), refresh_token: q.get('refresh_token'), expires_at: Number(q.get('expires_at')) || Math.floor(Date.now() / 1000) + (Number(q.get('expires_in')) || 3600) } };
}
// A sign-in email whose link opens codegrave.com itself carries a one-time key here, which the page
// trades for a session (`verify()`), so the link never has to point at the sign-in service's address.
if (q.get('token_hash')) return { verify: { token_hash: q.get('token_hash'), type: q.get('type') || 'email' } };
if (q.get('error') || q.get('error_code')) return { error: (q.get('error_description') || q.get('error') || 'Sign-in failed').replace(/\+/g, ' ') };
return null;
}
Expand Down Expand Up @@ -114,6 +117,13 @@ export function createAccount(app) {
function emailLink(email) {
return api('/auth/v1/otp?redirect_to=' + encodeURIComponent(here()), { method: 'POST', body: { email, create_user: true } });
}
// Trades a code typed from the email, or the key in a link to codegrave.com, for a session.
async function verify(body) {
const d = await api('/auth/v1/verify', { method: 'POST', body });
if (!d?.access_token) throw new Error('That code did not work. Ask for a new email.');
session = { access_token: d.access_token, refresh_token: d.refresh_token, expires_at: d.expires_at || Math.floor(Date.now() / 1000) + (d.expires_in || 3600) };
user = null; save();
}
async function signOut() {
try { await api('/auth/v1/logout', { method: 'POST' }); } catch (e) { /* the session is dropped here either way */ }
const mine = app.views().some(isStored);
Expand Down Expand Up @@ -364,11 +374,33 @@ export function createAccount(app) {
busy(d, true);
try {
await emailLink(email);
d.innerHTML = `<button type="button" class="ibtn dlg-x" data-close aria-label="Close">${ICON.x}</button><div class="dlg-logo">${LOGO}</div><h1>Check your inbox</h1><p class="dlg-sub">We sent a sign-in link to <b>${esc(email)}</b>. Open it on this device and you are in.</p>`;
sent(d, email);
} catch (err) { d.querySelector('.dlg-err').textContent = err.status === 429 ? 'Too many emails just now. Try again in a minute.' : err.message; busy(d, false); }
});
}

// After the email is sent: open its link on this device, or type the code it holds here.
function sent(d, email) {
d.innerHTML = `<button type="button" class="ibtn dlg-x" data-close aria-label="Close">${ICON.x}</button><div class="dlg-logo">${LOGO}</div><h1>Check your inbox</h1>
<p class="dlg-sub">We sent a sign-in email to <b>${esc(email)}</b>. Open its link on this device, or type the code from it here.</p>
<form class="code"><input type="text" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6,10}" maxlength="10" placeholder="Code from the email" required aria-label="Code from the email">
<button type="submit" class="big pri">Sign in</button></form>
<p class="dlg-err" role="alert"></p>`;
const input = d.querySelector('input');
input.focus();
input.addEventListener('input', () => { input.value = input.value.replace(/\D/g, ''); });
d.querySelector('form').addEventListener('submit', async (e) => {
e.preventDefault();
busy(d, true);
try {
await verify({ type: 'email', email, token: input.value });
closeLayer();
await afterSignIn();
app.redraw();
} catch (err) { d.querySelector('.dlg-err').textContent = err.status === 403 || err.status === 400 ? 'That code is wrong or has expired. Check the newest email.' : err.message; busy(d, false); }
});
}

async function copyTimeline() {
if (!user) { try { sessionStorage.setItem(INTENT, 'new'); } catch (e) { /* fine */ } return signIn('Sign in to start a timeline of your own.'); }
if (!src) return;
Expand Down Expand Up @@ -1389,13 +1421,14 @@ export function createAccount(app) {
const stored = () => { try { return localStorage.getItem(FOLD); } catch (e) { return null; } };

// Runs before the page reads its address: takes a returning sign-in out of the "#".
let pending = null; // the one-time key of a sign-in link to codegrave.com, traded in start()
function boot() {
load();
const got = readAuthHash(location.hash);
let failed = '';
if (got) {
history.replaceState(null, '', location.pathname + location.search);
if (got.session) { session = got.session; user = null; save(); } else failed = got.error;
if (got.session) { session = got.session; user = null; save(); } else if (got.verify) pending = got.verify; else failed = got.error;
}
setOpen(!phone() && (stored() ? stored() === '1' : innerWidth >= 1100), false);
return failed;
Expand All @@ -1404,7 +1437,13 @@ export function createAccount(app) {
wire();
draw(true);
if (failed) toast(failed);
if (!session) return;
if (pending) {
try { await verify(pending); } catch (e) { toast('That sign-in link has expired or was used already. Ask for a new one.'); }
pending = null;
}
if (session) await afterSignIn();
}
async function afterSignIn() {
try {
if (!user) await whoAmI();
await refreshList();
Expand Down
2 changes: 2 additions & 0 deletions tests/account.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ test('a returning sign-in is read from the link, and nothing else is', () => {
assert.equal(got.session.refresh_token, 'bbb');
assert.ok(got.session.expires_at > Date.now() / 1000);
assert.equal(readAuthHash('#error=access_denied&error_description=Email+link+is+invalid').error, 'Email link is invalid');
assert.deepEqual(readAuthHash('#token_hash=abc123&type=email').verify, { token_hash: 'abc123', type: 'email' });
assert.deepEqual(readAuthHash('#token_hash=abc123').verify, { token_hash: 'abc123', type: 'email' });
assert.equal(readAuthHash('#apollo-11'), null);
assert.equal(readAuthHash(''), null);
});
Expand Down
Loading