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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ Each layer imports only from the layers below it.
| `kit/pay` | Collect money for an order | New (`pay(order)` from the CineStack plan) | Its own tests only |
| `kit/auth` | Say who is asking | Both apps' `src/session.js` | Its own tests only |
| `kit/staff` | The people who run a business: an owner, the staff they invite, passwords, sessions that can be ended, roles; `kit/staff/pages` for their pages and routes | New: every platform faked it with a "sign in on any device" button | Its own tests, attacks included, and the routes over HTTP; 35 mutations |
| `kit/customers` | A business's customers, with accounts of their own: sign up, sign in with lockout, sessions that end, one-time reset links, turned off by the business | New: every app took a name and email at checkout and forgot them | Its own tests, attacks included |
| `kit/notice` | Show a page's one-line message only if the server wrote it: signs `?problem=` and `?done=` on redirect, drops unsigned ones on read | New: a link could put any words in a real page's alert box | Its own tests; 3 mutations |
| `kit/notify` | Tell a person something | New, interface and an outbox | Its own tests only |
| `kit/files` | Keep a file and return its address | New, interface, memory and disk | Its own tests only |
| `kit/reports` | Count and total records by day, week or month in the business's time zone, break them down by a key, and write CSV a spreadsheet can't run | New | Its own tests, a daylight saving change included |
| `kit/store` | The seam to where documents live (below) | Both apps | Both apps' tests; `syncStore` on `@zubra/sync` 5.8 |

Features, built from the rules:
Expand Down
220 changes: 220 additions & 0 deletions modules/customers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
// customers: a business's customers, with accounts of their own.
//
// `auth` says who a guest is with no account, and `staff` is for the people who run the business.
// This module is for customers who want one: an email, a name, a password, and sessions that end.
// They sign themselves up. Everything lives in the business's own log, in collections no page
// can read or write (`serverOnly` refuses them, reads included):
//
// customers/<id> { email, name, hash, disabled, at }
// customer-sessions/<hash> { customer, until, ended } the session id itself is never stored
// customer-tokens/<hash> { customer, until, used } one-time password reset links
//
// const customers = createCustomers({ store, secure: production });
// await customers.signUp({ email, name, password }) → { ok, customer, cookie } | { error }
// await customers.signIn(email, password, { client }) → { ok, customer, cookie } | { error: 'wrong' | 'locked' }
// customers.session(req) → { customer, name, email } | null
//
// A customer's own records (orders, bookings) stay in the app's collections, keyed by `customer`.
import { createHash, randomBytes } from 'node:crypto';
import { checkPassword, hashPassword } from '../staff/index.js';

export const CUSTOMER_COLLECTIONS = Object.freeze(['customers', 'customer-sessions', 'customer-tokens']);

const sha256 = (text) => createHash('sha256').update(text).digest('hex');
const token = () => randomBytes(32).toString('base64url');
const cleanEmail = (email) => String(email ?? '').trim().toLowerCase();
const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/;

export function createCustomers({
store,
name = 'account',
secure = false,
sessionMs = 30 * 86_400_000,
tokenMs = 3_600_000,
tries = 5,
emailTries = 100,
lockMs = 15 * 60_000,
minPassword = 10,
cost = { N: 2 ** 15, r: 8, p: 1 },
now = Date.now,
} = {}) {
if (!store) throw new TypeError('createCustomers needs a store');
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new TypeError('The cookie name may hold letters, digits, - and _');
const cookieName = secure ? `__Host-${name}` : name;
const decoy = hashPassword(token(), cost);
const failures = new Map();
const byEmailFailures = new Map();
const live = (entry) => (entry && entry.until > now() ? entry : null);
function count(map, key) {
const counted = (live(map.get(key))?.count ?? 0) + 1;
if (map.size >= 10_000) for (const [k, entry] of map) if (entry.until <= now()) map.delete(k);
map.set(key, { count: counted, until: now() + lockMs });
return counted;
}

const all = () => store.under('customers');
const byEmail = (email) => all().find((one) => one.email === email) ?? null;
const view = (one) => (one ? { customer: one.key, name: one.name, email: one.email, disabled: Boolean(one.disabled), at: one.at } : null);

function passwordProblem(password, email) {
if (typeof password !== 'string' || password.length < minPassword) return `Use at least ${minPassword} characters.`;
if (password.length > 200) return 'Use at most 200 characters.';
if (cleanEmail(password) === email) return 'Don’t use your email as your password.';
return '';
}

const cookie = (id, maxAge) => `${cookieName}=${id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`;

async function startSession(customer) {
const id = token();
await store.write('customer-sessions', sha256(id), { customer, until: now() + sessionMs, ended: false, at: now() });
return cookie(id, Math.floor(sessionMs / 1000));
}

function readCookie(input) {
const header = typeof input === 'string' ? input : typeof input?.headers?.get === 'function' ? (input.headers.get('cookie') ?? '') : (input?.headers?.cookie ?? '');
const raw = header
.split(';')
.map((part) => part.trim())
.find((part) => part.startsWith(`${cookieName}=`))
?.slice(cookieName.length + 1);
return raw && /^[A-Za-z0-9_-]{43}$/.test(raw) ? raw : null;
}

async function endSessions(customer) {
let ended = 0;
for (const session of store.under('customer-sessions')) {
if (session.customer === customer && !session.ended && session.until > now()) {
await store.write('customer-sessions', session.key, { ended: true });
ended++;
}
}
return ended;
}

return {
cookieName,

/** The session on a Node request, a fetch Request or a Cookie header: who it is, or null. */
session(input) {
const id = readCookie(input);
if (!id) return null;
const session = store.get('customer-sessions', sha256(id));
if (!session || session.ended || session.until <= now()) return null;
const one = store.get('customers', session.customer);
if (!one || one.disabled) return null;
return view({ key: session.customer, ...one });
},

/** A new account, signed in. One account per email. */
async signUp({ email, name: given, password } = {}) {
email = cleanEmail(email);
const name = String(given ?? '').trim().slice(0, 80);
if (!EMAIL.test(email)) return { error: 'Give your email address.' };
if (!name) return { error: 'Give your name.' };
const problem = passwordProblem(password, email);
if (problem) return { error: problem };
if (byEmail(email)) return { error: 'There’s already an account with that email. Sign in, or reset its password.' };
const hash = await hashPassword(password, cost);
if (byEmail(email)) return { error: 'There’s already an account with that email. Sign in, or reset its password.' };
const customer = `c${now().toString(36)}${randomBytes(6).toString('hex')}`;
await store.write('customers', customer, { email, name, hash, disabled: false, at: now() });
return { ok: true, customer, cookie: await startSession(customer) };
},

/**
* Sign in. A wrong password and an unknown email get the same answer, in about the same time.
* After `tries` failures from one client the email is locked for that client for `lockMs`;
* after `emailTries` from anywhere, for everyone.
*/
async signIn(email, password, { client = '' } = {}) {
email = cleanEmail(email);
const pair = `${email} ${String(client).slice(0, 100)}`;
const mine = live(failures.get(pair));
const every = live(byEmailFailures.get(email));
if ((mine && mine.count >= tries) || (every && every.count >= emailTries)) return { error: 'locked' };
const one = byEmail(email);
const ok = (await checkPassword(String(password ?? ''), one?.hash ?? (await decoy))) && Boolean(one) && !one.disabled;
if (!ok) {
const fromHere = count(failures, pair);
const everywhere = count(byEmailFailures, email);
return fromHere >= tries || everywhere >= emailTries ? { error: 'locked' } : { error: 'wrong' };
}
failures.delete(pair);
return { ok: true, customer: one.key, cookie: await startSession(one.key) };
},

/** End the session a request carries, and the cookie that clears it. */
async signOut(input) {
const id = readCookie(input);
if (id) {
const key = sha256(id);
if (store.get('customer-sessions', key)) await store.write('customer-sessions', key, { ended: true });
}
return { ok: true, cookie: cookie('', 0) };
},

/**
* A one-time token for a password reset link, for the app to email. Null for an unknown or
* turned-off email: the app should answer the same either way.
*/
async resetToken(email) {
const one = byEmail(cleanEmail(email));
if (!one || one.disabled) return null;
const raw = token();
await store.write('customer-tokens', sha256(raw), { customer: one.key, until: now() + tokenMs, used: false, at: now() });
return raw;
},

/** Whether a reset link still works, without using it. */
peek(raw) {
if (typeof raw !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(raw)) return false;
const found = store.get('customer-tokens', sha256(raw));
return Boolean(found && !found.used && found.until > now());
},

/** Use a reset link: a new password, every other session ended, signed in. Works once. */
async reset(raw, password) {
if (typeof raw !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(raw)) return { error: 'That link has expired or been used. Ask for a new one.' };
const key = sha256(raw);
const found = store.get('customer-tokens', key);
const one = found ? store.get('customers', found.customer) : null;
if (!found || found.used || found.until <= now() || !one || one.disabled) return { error: 'That link has expired or been used. Ask for a new one.' };
const problem = passwordProblem(password, one.email);
if (problem) return { error: problem };
const spending = store.write('customer-tokens', key, { used: true, usedAt: now() });
const hash = await hashPassword(password, cost);
await spending;
await store.write('customers', found.customer, { hash, changedAt: now() });
await endSessions(found.customer);
byEmailFailures.delete(one.email);
for (const k of failures.keys()) if (k.startsWith(`${one.email} `)) failures.delete(k);
return { ok: true, customer: found.customer, cookie: await startSession(found.customer) };
},

/** A customer's own name, changed by them. */
async rename(customer, given) {
const name = String(given ?? '').trim().slice(0, 80);
if (!name) return { error: 'Give your name.' };
if (!store.get('customers', customer)) return { error: 'No such customer.' };
await store.write('customers', customer, { name });
return { ok: true };
},

/** One customer, or null. */
get: (customer) => view(store.get('customers', customer) ? { key: customer, ...store.get('customers', customer) } : null),

/** Every customer, newest first, for the business's admin pages. */
list: () => all().map(view).sort((a, b) => b.at - a.at),

/** Turn an account off (or back on). Off ends its sessions; it can't sign in or reset. */
async setDisabled(customer, disabled) {
if (!store.get('customers', customer)) return { error: 'No such customer.' };
await store.write('customers', customer, { disabled: Boolean(disabled) });
if (disabled) await endSessions(customer);
return { ok: true };
},

endSessions,
};
}
126 changes: 126 additions & 0 deletions modules/customers/test/customers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { memoryStore, serverOnly, SECRET } from '../../store/index.js';
import { createCustomers, CUSTOMER_COLLECTIONS } from '../index.js';

const cost = { N: 2 ** 10, r: 8, p: 1 };
const make = (options = {}) => {
const store = memoryStore();
return { store, customers: createCustomers({ store, cost, ...options }) };
};
const header = (cookie) => cookie.split(';')[0];

test('sign up makes an account and signs it in', async () => {
const { customers, store } = make();
const made = await customers.signUp({ email: ' Ann@Example.com ', name: ' Ann Baker ', password: 'correct horse battery' });
assert.ok(made.ok);
assert.match(made.cookie, /^account=[A-Za-z0-9_-]{43}; Path=\/; HttpOnly; SameSite=Lax; Max-Age=\d+$/);
assert.deepEqual(customers.session(header(made.cookie)), { customer: made.customer, name: 'Ann Baker', email: 'ann@example.com', disabled: false, at: store.get('customers', made.customer).at });
const stored = store.get('customers', made.customer);
assert.match(stored.hash, /^scrypt\$/);
assert.ok(!JSON.stringify(store.under('customer-sessions')).includes(header(made.cookie).split('=')[1]), 'the session id itself is never stored');
});

test('sign up refuses a bad email, no name, a short password, the email as password, and a second account', async () => {
const { customers } = make();
assert.match((await customers.signUp({ email: 'nope', name: 'A', password: 'correct horse battery' })).error, /email/);
assert.match((await customers.signUp({ email: 'a@example.com', name: ' ', password: 'correct horse battery' })).error, /name/);
assert.match((await customers.signUp({ email: 'a@example.com', name: 'A', password: 'short' })).error, /at least 10/);
assert.match((await customers.signUp({ email: 'a@example.com', name: 'A', password: 'A@example.com' })).error, /email as your password/);
assert.ok((await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' })).ok);
assert.match((await customers.signUp({ email: 'A@EXAMPLE.COM', name: 'B', password: 'another long password' })).error, /already an account/);
assert.equal(customers.list().length, 1);
});

test('sign in, sign out, and a wrong password or unknown email get the same answer', async () => {
const { customers } = make();
await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
assert.deepEqual(await customers.signIn('a@example.com', 'wrong password!'), { error: 'wrong' });
assert.deepEqual(await customers.signIn('nobody@example.com', 'correct horse battery'), { error: 'wrong' });
const signed = await customers.signIn('A@example.com', 'correct horse battery');
assert.ok(signed.ok);
assert.ok(customers.session(header(signed.cookie)));
const out = await customers.signOut(header(signed.cookie));
assert.equal(out.cookie, 'account=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
assert.equal(customers.session(header(signed.cookie)), null, 'a signed-out session is over');
});

test('five wrong tries from one device lock that device out, even with the right password', async () => {
const { customers } = make();
await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
for (let i = 0; i < 4; i++) assert.deepEqual(await customers.signIn('a@example.com', `guess ${i} wrong`, { client: '1.2.3.4' }), { error: 'wrong' });
assert.deepEqual(await customers.signIn('a@example.com', 'guess 5 wrong', { client: '1.2.3.4' }), { error: 'locked' });
assert.deepEqual(await customers.signIn('a@example.com', 'correct horse battery', { client: '1.2.3.4' }), { error: 'locked' });
assert.ok((await customers.signIn('a@example.com', 'correct horse battery', { client: '5.6.7.8' })).ok, 'another device is not locked');
});

test('a session ends when its time is up', async () => {
let at = 1_000_000;
const { customers } = make({ now: () => at, sessionMs: 1000 });
const made = await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
assert.ok(customers.session(header(made.cookie)));
at += 1001;
assert.equal(customers.session(header(made.cookie)), null);
});

test('a reset link sets a new password once, ends other sessions, and runs out', async () => {
let at = 1_000_000;
const { customers } = make({ now: () => at, tokenMs: 60_000 });
const made = await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
assert.equal(await customers.resetToken('nobody@example.com'), null);
const raw = await customers.resetToken('A@example.com');
assert.match(raw, /^[A-Za-z0-9_-]{43}$/);
assert.equal(customers.peek(raw), true);
assert.match((await customers.reset(raw, 'short')).error, /at least 10/);
const done = await customers.reset(raw, 'a brand new password');
assert.ok(done.ok);
assert.equal(customers.session(header(made.cookie)), null, 'the old session ended');
assert.ok(customers.session(header(done.cookie)));
assert.match((await customers.reset(raw, 'another new password')).error, /expired or been used/);
assert.ok((await customers.signIn('a@example.com', 'a brand new password')).ok);

const late = await customers.resetToken('a@example.com');
at += 60_001;
assert.equal(customers.peek(late), false);
assert.match((await customers.reset(late, 'yet another password')).error, /expired/);
});

test('a turned-off account cannot sign in, keep a session, or reset', async () => {
const { customers } = make();
const made = await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
const raw = await customers.resetToken('a@example.com');
await customers.setDisabled(made.customer, true);
assert.equal(customers.session(header(made.cookie)), null);
assert.deepEqual(await customers.signIn('a@example.com', 'correct horse battery'), { error: 'wrong' });
assert.equal(await customers.resetToken('a@example.com'), null);
assert.match((await customers.reset(raw, 'a brand new password')).error, /expired/);
await customers.setDisabled(made.customer, false);
assert.ok((await customers.signIn('a@example.com', 'correct horse battery')).ok);
});

test('a customer can rename themselves; the list is newest first', async () => {
let at = 1;
const { customers } = make({ now: () => at++ });
const a = await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
await customers.signUp({ email: 'b@example.com', name: 'B', password: 'correct horse battery' });
assert.deepEqual(await customers.rename(a.customer, ' '), { error: 'Give your name.' });
assert.ok((await customers.rename(a.customer, 'Ann')).ok);
assert.deepEqual(customers.list().map((c) => c.name), ['B', 'Ann']);
});

test('a forged or malformed cookie is nobody, and on https the cookie is __Host- and Secure', async () => {
const { customers } = make({ secure: true });
const made = await customers.signUp({ email: 'a@example.com', name: 'A', password: 'correct horse battery' });
assert.match(made.cookie, /^__Host-account=.*; Secure$/);
for (const bad of ['', '__Host-account=abc', `__Host-account=${'A'.repeat(43)}`, 'account=' + header(made.cookie).split('=')[1]]) {
assert.equal(customers.session(bad), null, bad);
}
});

test('pages can never read or write the customer collections', () => {
for (const collection of CUSTOMER_COLLECTIONS) assert.ok(SECRET.includes(collection), collection);
const authorize = serverOnly();
for (const collection of CUSTOMER_COLLECTIONS) {
assert.equal(authorize({ collection, op: 'read' }), false, collection);
}
});
Loading