Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(home): mail a household invitation and let the sender choose which rooms it opens

nirholasa40bb2b068a5
diff --git a/api/_lib/email.js b/api/_lib/email.js
index 3d059cdd9..5769d2a2c 100644
--- a/api/_lib/email.js
+++ b/api/_lib/email.js
@@ -142,6 +142,48 @@ export function sendReferralCommissionEmail({ to, amount, currency, fromHandle,
return sendEmail({ to, ...renderReferralCommission({ amount, currency, fromHandle, skillName, date }) });
}
+// An invitation to somebody's household: a role in a real building, sent to an
+// email address that may not have a three.ws account behind it yet.
+//
+// Three things this template does deliberately, all of them because of what the
+// link opens:
+//
+// 1. It names the ROLE and what that role can never do, in the email, not only
+// behind the link. Somebody forwarding an invitation should be able to see
+// that they are handing over a guest seat and not the house.
+// 2. It never renders the home's label or the inviter's name as HTML. Both are
+// strings a person typed, and one of them is chosen by whoever set up the
+// home; `esc` is not optional here.
+// 3. It says the link works once and when it stops working, because an invite
+// that quietly expires reads as a broken product rather than a policy.
+//
+// `roleNote` is the sentence that makes a guest seat legible to a person who has
+// never used the product. The guest line is the one that matters: it is the
+// difference between letting somebody water the plants and letting them open the
+// front door.
+const HOUSEHOLD_ROLE_NOTE = {
+ admin: 'You will be able to control everything in the home, approve unlocking a door, and invite other people. You will not be able to disconnect the home.',
+ member: 'You will be able to control everything in the home and approve unlocking a door, the same as anybody who lives there.',
+ guest: 'You will be able to control the things you have been given. You will never be able to approve unlocking a door, opening a garage or disarming an alarm.',
+ viewer: 'You will be able to watch the things you have been given, and change nothing.',
+};
+
+export function renderHouseholdInvite({ homeLabel, role, inviterName, inviteUrl, expiresAt }) {
+ const label = homeLabel || 'a home';
+ const who = inviterName ? `${inviterName} has` : 'Somebody has';
+ const note = HOUSEHOLD_ROLE_NOTE[role] || 'You will be able to reach this home from your three.ws account.';
+ const expiry = expiresAt ? new Date(expiresAt).toUTCString() : null;
+ return {
+ subject: `${who.replace(' has', '')} invited you to ${label} on three.ws`,
+ html: householdInviteHtml({ label, role, who, note, inviteUrl, expiry }),
+ text: householdInviteText({ label, role, who, note, inviteUrl, expiry }),
+ };
+}
+
+export function sendHouseholdInviteEmail({ to, homeLabel, role, inviterName, inviteUrl, expiresAt }) {
+ return sendEmail({ to, ...renderHouseholdInvite({ homeLabel, role, inviterName, inviteUrl, expiresAt }) });
+}
+
// Unattended forge completion: sent only by the server-side finalizer when a
// generation finished after the creator left the page. `creationPath` is the
// site-relative share path (/forge?share=<id>).
@@ -283,6 +325,31 @@ function subscriptionHtml(plan, chain, txId) {
`);
}
+function householdInviteHtml({ label, role, who, note, inviteUrl, expiry }) {
+ return layout(`You have been invited to ${label}`, `
+ <p class="brand">three.ws</p>
+ <h1>You have been invited to ${esc(label)}</h1>
+ <p>${esc(who)} given you access to a home they connected to three.ws, as a <strong>${esc(role)}</strong>.</p>
+ <p>${esc(note)}</p>
+ <a class="btn" href="${esc(inviteUrl)}">See the invitation</a>
+ <p class="muted">The link opens a page that shows exactly what you would be able to do before you accept anything. It works once${expiry ? `, and stops working after ${esc(expiry)}` : ''}.</p>
+ <p class="muted">If you were not expecting this, you can ignore it. Nothing happens to your account unless you open the link and accept.</p>
+ `);
+}
+
+function householdInviteText({ label, role, who, note, inviteUrl, expiry }) {
+ return [
+ `${who} given you access to ${label} on three.ws, as a ${role}.`,
+ '',
+ note,
+ '',
+ `See the invitation: ${inviteUrl}`,
+ '',
+ `The link works once${expiry ? `, and stops working after ${expiry}` : ''}.`,
+ 'If you were not expecting this, you can ignore it.',
+ ].join('\n');
+}
+
function subscriptionText(plan, chain, txId) {
return `Your three.ws ${plan} plan is now active on ${chain}.\n${txId ? `Transaction: ${txId}\n` : ''}Open dashboard: ${APP_URL}/dashboard/`;
}
diff --git a/api/home/[id]/members.js b/api/home/[id]/members.js
index a58ce3c03..bc009861a 100644
--- a/api/home/[id]/members.js
+++ b/api/home/[id]/members.js
@@ -13,6 +13,8 @@
// only one of them is safe to disclose.
import { logAudit } from '../../_lib/audit.js';
+import { sendHouseholdInviteEmail } from '../../_lib/email.js';
+import { getConnection } from '../../_lib/home/store.js';
import { getSessionUser } from '../../_lib/auth.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { assertMemberCapacity, HomeQuotaError } from '../../_lib/home/entitlements.js';
@@ -75,6 +77,12 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const gate = await requireMembership(homeId, user.id, 'read');
if (!gate.ok) return error(res, gate.status, gate.code, gate.reason);
+
+ // Metered on the same bucket as every other read on this surface, so a
+ // panel that polls the roster competes with the rest of a person's reads
+ // rather than sitting outside the ceiling everything else is held to.
+ const rl = await limits.homeRead(user.id).catch(() => ({ success: true }));
+ if (rl && rl.success === false) return rateLimited(res, rl, 'too many home reads, slow down');
const [members, invites] = await Promise.all([listMembers(homeId), listInvites(homeId)]);
return json(res, 200, {
role: gate.role,
@@ -139,6 +147,11 @@ export default wrap(async (req, res) => {
});
}
+ // The home's own label, for the email. Read through the membership-resolved
+ // store rather than trusted from the request, so an invitation can never
+ // name a house the sender is not actually in.
+ const home = await getConnection(homeId, user.id);
+
const invite = await createInvite({
homeId,
email,
@@ -147,12 +160,46 @@ export default wrap(async (req, res) => {
invitedBy: user.id,
});
- logAudit({ userId: user.id, action: 'household.invite', resourceId: homeId, meta: { email, role, scope: invite.scope }, req });
+ const url = inviteUrl(req, invite.token);
+
+ // Mail it, and say honestly whether that worked.
+ //
+ // The link is still returned either way, because the send is the
+ // convenience and the link is the invitation. A platform that mails the
+ // only copy of a one-use credential and then fails to deliver it has
+ // destroyed something the inviter cannot recreate without starting over,
+ // so `emailed` reports what actually happened and the UI shows the link
+ // beside it rather than promising a message that may never land.
+ //
+ // Awaited, unlike most sends here, for exactly that reason: `emailed:
+ // true` is a claim about the world and a fire-and-forget send cannot make
+ // it. `sendEmail` answers `{skipped:true}` with no RESEND_API_KEY, which is
+ // the ordinary state on a preview deploy and is reported as not emailed
+ // rather than as a failure.
+ let emailed = false;
+ try {
+ const sent = await sendHouseholdInviteEmail({
+ to: email,
+ homeLabel: home?.label || null,
+ role,
+ inviterName: user.display_name || user.username || null,
+ inviteUrl: url,
+ expiresAt: invite.expiresAt,
+ });
+ emailed = !sent?.skipped;
+ } catch (err) {
+ // A dead mail provider must not cost somebody their invitation: the row
+ // is already written and the link in this response still works.
+ console.warn('[home-members] invite email failed', { home: homeId, error: err?.message });
+ }
+
+ logAudit({ userId: user.id, action: 'household.invite', resourceId: homeId, meta: { email, role, scope: invite.scope, emailed }, req });
// The plaintext token exists in this response and nowhere else, ever.
return json(res, 201, {
invite: { id: invite.id, email: invite.email, role: invite.role, scope: invite.scope, expires_at: invite.expiresAt },
- invite_url: inviteUrl(req, invite.token),
+ invite_url: url,
+ emailed,
});
}
diff --git a/docs/home-households.md b/docs/home-households.md
index 127087f77..555d05f0a 100644
--- a/docs/home-households.md
+++ b/docs/home-households.md
@@ -169,8 +169,15 @@ An invite is an email address plus a link: single use, expiring (7 days by defau
one home and one role.
- **The plaintext token leaves the server exactly once**, in the `invite_url` of the creating
- response. What is stored is `sha256` of it. An invite is a bearer credential for a role in a
- building, so a leaked database must not be a set of working keys.
+ response, and in the email that response also sends. What is stored is `sha256` of it. An invite
+ is a bearer credential for a role in a building, so a leaked database must not be a set of
+ working keys.
+- **The email is awaited, not fired and forgotten**, which is the exception on this platform. The
+ response's `emailed` flag is a claim about the world and a fire-and-forget send cannot make one.
+ With no `RESEND_API_KEY` (the ordinary state on a preview deploy) `sendEmail` answers
+ `{skipped: true}` and this reports `emailed: false`, which is a fact rather than a failure. A
+ dead mail provider never costs anybody their invitation: the row is already written and the link
+ in the response still works.
- **Single use is enforced in the redeeming UPDATE's own WHERE clause**, not by a read followed by
a write, so two people opening the same link at the same moment cannot both become members.
- **Accepting requires an account, and this endpoint does not create one.** Registration and
@@ -201,9 +208,22 @@ whether you may administer that person, so a button that would be refused is nev
A member with no roster authority still sees the household. Hiding the fact that other people hold
keys to the house you are in would be the wrong secret to keep.
-Sending an invitation shows the link once, at that moment, with a copy button. There is no way to
-see it again: the server keeps only a hash, so "check the invitations list for the link" would be a
-promise this system cannot keep, and the UI says so rather than letting somebody discover it.
+When the role being invited is `guest` or `viewer`, the form offers **How much of the house they
+get**: the whole house, or only rooms you tick. The room list comes from the house's own graph, so
+you are choosing between rooms you can see rather than typing area ids nobody can verify. A room
+is the unit the picker works in on purpose: a house with 67 devices makes a flat checkbox list
+unusable, and a room is the unit people actually think in. Individual entity grants set through
+the API survive an edit made in the UI. The same picker sits on a scoped member's row behind
+**What they can see**, and it sends only `scope`, so changing what somebody can see is never
+silently a change to what they can do.
+
+Sending an invitation mails it. The email names the role and, for a guest, states in the body that
+they will never be able to approve unlocking a door, so somebody forwarding an invitation can see
+they are handing over a guest seat and not the house. The link is shown in the UI either way, and
+the response says whether the mail actually went out (`emailed`) rather than assuming: a platform
+that mails the only copy of a one-use credential and then fails to deliver it has destroyed
+something the inviter cannot recreate. There is no way to see the link again afterwards, because
+the server keeps only a hash.
The link opens [/smart-home/join](https://three.ws/smart-home/join). That page inspects the
invitation without spending it, so it can say which home, which role, what that role will let the
@@ -341,6 +361,7 @@ automatic today: an IdP deactivating a user stops them signing in and does not b
| The household panel | `src/home/members.js`, mounted by `src/home/manage.js` |
| The join page | `pages/smart-home-join.html`, `src/home/join.js` |
| The browser half of the API | `src/home/api.js` |
+| The invitation email | `renderHouseholdInvite` / `sendHouseholdInviteEmail` in `api/_lib/email.js` |
| The matrix as an executable test | `tests/home-roles.test.js` |
The owner row is created by a database trigger on `home_connections`, not by the application. "A
diff --git a/src/home/members.js b/src/home/members.js
index b3b79a397..f5fe5d215 100644
--- a/src/home/members.js
+++ b/src/home/members.js
@@ -15,7 +15,7 @@
* chooses one, rather than in documentation nobody opens.
*/
-import { listHousehold, inviteToHousehold, removeFromHousehold, revokeHouseholdInvite, setHouseholdRole } from './api.js';
+import { getHome, listHousehold, inviteToHousehold, removeFromHousehold, revokeHouseholdInvite, setHouseholdRole } from './api.js';
import { clear, el, noticeEl } from './connect.js';
/**
@@ -199,6 +199,17 @@ function memberRow(home, member, { assignable, rerender }) {
}
});
+ // The scope editor, offered only where scope means anything. A member's row
+ // has no button for it because a member is whole-house by definition, and a
+ // control that silently does nothing is worse than no control.
+ if (member.scoped) {
+ const narrow = el('button', 'hm-btn hm-btn-ghost', 'What they can see');
+ narrow.type = 'button';
+ narrow.setAttribute('aria-expanded', 'false');
+ narrow.addEventListener('click', () => editScope(li, main, home, member, rerender, narrow));
+ actions.append(narrow);
+ }
+
const remove = el('button', 'hm-btn hm-btn-danger', 'Remove');
remove.type = 'button';
remove.addEventListener('click', () => confirmRemove(li, main, home, member, rerender));
@@ -208,6 +219,60 @@ function memberRow(home, member, { assignable, rerender }) {
return li;
}
+/**
+ * Narrow or widen what one scoped member can reach, in place on their row.
+ *
+ * Sends only `scope`, leaving `role` untouched, so changing what somebody can
+ * see is not silently a change to what they can do.
+ */
+function editScope(li, main, home, member, rerender, trigger) {
+ const existing = li.querySelector('.hm-scope-edit');
+ if (existing) {
+ existing.remove();
+ trigger.setAttribute('aria-expanded', 'false');
+ return;
+ }
+ trigger.setAttribute('aria-expanded', 'true');
+
+ const box = el('div', 'hm-scope-edit');
+ box.style.marginTop = 'var(--space-sm)';
+ box.style.width = '100%';
+ const picker = scopePicker(home, member.scope);
+ picker.setRole(member.role);
+ box.append(picker.node);
+
+ const actions = el('div', 'hm-card-actions');
+ const save = el('button', 'hm-btn hm-btn-primary', 'Save');
+ save.type = 'button';
+ const cancel = el('button', 'hm-btn hm-btn-ghost', 'Cancel');
+ cancel.type = 'button';
+ cancel.addEventListener('click', () => {
+ box.remove();
+ trigger.setAttribute('aria-expanded', 'false');
+ trigger.focus();
+ });
+ save.addEventListener('click', async () => {
+ save.disabled = true;
+ cancel.disabled = true;
+ save.textContent = 'Saving';
+ try {
+ // `scope: null` from the picker means the whole house; send an explicit
+ // {mode:'all'} rather than omitting the field, because omitting it means
+ // "leave it as it was" to the endpoint and this press meant a change.
+ await setHouseholdRole(home.id, { userId: member.user_id, role: member.role, scope: picker.read() ?? { mode: 'all' } });
+ rerender();
+ } catch (err) {
+ save.disabled = false;
+ cancel.disabled = false;
+ save.textContent = 'Try again';
+ main.append(el('p', 'hm-row-meta', err?.message || 'That change did not go through.'));
+ }
+ });
+ actions.append(save, cancel);
+ box.append(actions);
+ li.append(box);
+}
+
/**
* Removing somebody is not undoable and it revokes their standing allowances
* with them, so the panel says exactly that before it happens rather than after.
@@ -283,6 +348,149 @@ function inviteRow(home, invite, { canAdminister, rerender }) {
return li;
}
+/**
+ * The rooms and devices a scoped role may reach.
+ *
+ * Built from the house's OWN room graph, fetched once and cached for the panel:
+ * a scope written by typing area ids into a box would be a scope nobody can
+ * verify, and an area id that does not exist silently grants nothing while
+ * looking like it granted something.
+ *
+ * Two states, and the default is the safe one only where it is honest. Inviting
+ * somebody is a deliberate act of sharing, so "the whole house" stays the
+ * default for a role that lives there and "only what I choose" is offered
+ * plainly for a role that is visiting. Nothing is inferred: whichever is
+ * selected is what gets sent, and the server normalizes a non-scoped role back
+ * to the whole house regardless of what this control says.
+ *
+ * @param {object} home
+ * @param {object} [initial] an existing scope to start from
+ * @returns {{ node: HTMLElement, read: () => object|null, setRole: (role: string) => void }}
+ */
+function scopePicker(home, initial) {
+ const wrap = el('fieldset', 'hm-field');
+ wrap.style.border = '0';
+ wrap.style.padding = '0';
+ wrap.style.margin = 'var(--space-sm) 0 0';
+ const legend = el('legend', 'hm-label', 'How much of the house they get');
+ wrap.append(legend);
+
+ const name = `scope-mode-${Math.random().toString(36).slice(2, 9)}`;
+ const modes = el('div', 'hm-actions');
+ const all = radio(name, 'all', 'The whole house');
+ const some = radio(name, 'allow', 'Only what I choose');
+ modes.append(all.label, some.label);
+ wrap.append(modes);
+
+ const detail = el('div');
+ detail.style.marginTop = 'var(--space-sm)';
+ detail.hidden = true;
+ wrap.append(detail);
+
+ const checks = new Map();
+ let loaded = false;
+ let unavailable = false;
+
+ async function loadRooms() {
+ if (loaded) return;
+ loaded = true;
+ const skeleton = el('div', 'hm-skeleton');
+ skeleton.style.height = '2.6rem';
+ detail.append(skeleton);
+ try {
+ const body = await getHome(home.id);
+ clear(detail);
+ const rooms = body?.graph?.rooms || [];
+ if (!rooms.length) {
+ unavailable = true;
+ // A house that is not answering cannot be divided up honestly, so the
+ // control says so instead of offering an empty list that would send an
+ // empty allowlist and share nothing.
+ detail.append(el('p', 'hm-row-meta', body?.connected === false
+ ? 'This home is not answering right now, so its rooms cannot be listed. You can invite them to the whole house now and narrow it once the home reconnects.'
+ : 'This home has no rooms assigned yet. Assign areas in Home Assistant and they will appear here.'));
+ return;
+ }
+ detail.append(el('p', 'hm-row-meta', 'Everything you do not tick stays hidden from them completely, not just hidden on screen.'));
+ const list = el('div');
+ list.style.display = 'grid';
+ list.style.gap = '0.35rem';
+ list.style.marginTop = '0.5rem';
+ for (const room of rooms) {
+ const box = el('input');
+ box.type = 'checkbox';
+ box.value = room.id;
+ box.id = `${name}-${room.id}`;
+ if (initial?.areas?.includes(room.id)) box.checked = true;
+ const label = el('label', 'hm-row-meta');
+ label.style.display = 'flex';
+ label.style.gap = '0.5rem';
+ label.style.alignItems = 'center';
+ label.htmlFor = box.id;
+ label.append(box);
+ // A room name is whatever its owner called it in Home Assistant.
+ label.append(document.createTextNode(`${room.name} (${room.entities.length} ${room.entities.length === 1 ? 'device' : 'devices'})`));
+ checks.set(room.id, box);
+ list.append(label);
+ }
+ detail.append(list);
+ } catch (err) {
+ clear(detail);
+ unavailable = true;
+ detail.append(el('p', 'hm-row-meta', err?.message || 'We could not list this home\'s rooms. You can still invite them to the whole house.'));
+ }
+ }
+
+ const sync = () => {
+ detail.hidden = !some.input.checked;
+ if (some.input.checked) loadRooms();
+ };
+ all.input.addEventListener('change', sync);
+ some.input.addEventListener('change', sync);
+
+ if (initial?.mode === 'allow') {
+ some.input.checked = true;
+ sync();
+ } else {
+ all.input.checked = true;
+ }
+
+ return {
+ node: wrap,
+ /** null means "do not send a scope at all", which the server reads as the whole house. */
+ read() {
+ if (!some.input.checked || unavailable) return null;
+ const areas = [...checks.entries()].filter(([, box]) => box.checked).map(([id]) => id);
+ // Individual entities are carried through from an existing scope rather
+ // than picked here: a house with 67 devices makes a flat checkbox list
+ // unusable, and a room is the unit people actually think in. An entity
+ // grant set through the API survives an edit made here.
+ const entities = Array.isArray(initial?.entities) ? initial.entities : [];
+ return { mode: 'allow', areas, entities };
+ },
+ /** Scope only means anything for a scoped role; hide it entirely for the rest. */
+ setRole(role) {
+ const scoped = role === 'guest' || role === 'viewer';
+ wrap.hidden = !scoped;
+ if (!scoped) all.input.checked = true;
+ sync();
+ },
+ };
+}
+
+function radio(name, value, text) {
+ const input = el('input');
+ input.type = 'radio';
+ input.name = name;
+ input.value = value;
+ const label = el('label', 'hm-row-meta');
+ label.style.display = 'flex';
+ label.style.gap = '0.45rem';
+ label.style.alignItems = 'center';
+ label.append(input, document.createTextNode(text));
+ return { input, label };
+}
+
function inviteForm(home, { assignable, rerender }) {
const form = el('form', 'hm-panel');
form.style.marginTop = 'var(--space-sm)';
@@ -315,8 +523,14 @@ function inviteForm(home, { assignable, rerender }) {
const explain = el('p', 'hm-row-meta', ROLE_COPY[role.value] || '');
form.append(explain);
+
+ const scope = scopePicker(home);
+ form.append(scope.node);
+ scope.setRole(role.value);
+
role.addEventListener('change', () => {
explain.textContent = ROLE_COPY[role.value] || '';
+ scope.setRole(role.value);
});
const submit = el('button', 'hm-btn hm-btn-primary', 'Send invitation');
@@ -334,12 +548,14 @@ function inviteForm(home, { assignable, rerender }) {
submit.disabled = true;
submit.textContent = 'Sending';
try {
- const result = await inviteToHousehold(home.id, { email: email.value.trim(), role: role.value });
+ const result = await inviteToHousehold(home.id, { email: email.value.trim(), role: role.value, scope: scope.read() });
+ const sentTo = email.value.trim();
email.value = '';
// The link is shown once, here, because the server keeps only a hash of
// it. Telling somebody to "check the invitations list for the link"
- // would be a promise this system cannot keep.
- outcome.append(inviteLinkBlock(result?.invite_url));
+ // would be a promise this system cannot keep, and it is shown whether or
+ // not the email went out for exactly that reason.
+ outcome.append(inviteLinkBlock(result?.invite_url, { emailed: result?.emailed === true, to: sentTo }));
rerender();
} catch (err) {
outcome.append(noticeEl({
@@ -356,12 +572,17 @@ function inviteForm(home, { assignable, rerender }) {
return form;
}
-function inviteLinkBlock(url) {
+function inviteLinkBlock(url, { emailed = false, to = '' } = {}) {
const wrap = el('div', 'hm-notice hm-notice-ok');
wrap.setAttribute('role', 'status');
const inner = el('div');
- inner.append(el('p', 'hm-row-title', 'Send them this link'));
- inner.append(el('p', 'hm-row-meta', 'It works once and then stops. We only keep a fingerprint of it, so this is the only time it can be shown.'));
+ inner.append(el('p', 'hm-row-title', emailed ? `Invitation sent to ${to}` : 'Send them this link'));
+ // The link is shown either way. When the email went out it is the copy the
+ // inviter can paste into a message themselves, which is what people actually
+ // do; when it did not, it is the invitation.
+ inner.append(el('p', 'hm-row-meta', emailed
+ ? 'Here is the same link, in case you would rather send it yourself. It works once and then stops, and this is the only time we can show it.'
+ : 'We could not email it, so this link is the invitation. It works once and then stops. We only keep a fingerprint of it, so this is the only time it can be shown.'));
const field = el('div', 'hm-card-actions');
const box = el('input', 'hm-input');
diff --git a/tests/home-roles.test.js b/tests/home-roles.test.js
index 268f072aa..6ac3952ba 100644
--- a/tests/home-roles.test.js
+++ b/tests/home-roles.test.js
@@ -573,6 +573,79 @@ d('invitations are single use and they expire', () => {
});
});
+d('the invitation email says what the seat is, and never renders a name as markup', () => {
+ it('names the role and the thing that role can never do', async () => {
+ const { renderHouseholdInvite } = await import('../api/_lib/email.js');
+ const mail = renderHouseholdInvite({
+ homeLabel: 'The office',
+ role: 'guest',
+ inviterName: 'Sam',
+ inviteUrl: 'https://three.ws/smart-home/join?invite=token',
+ expiresAt: '2026-09-10T03:31:52.462Z',
+ });
+ expect(mail.subject).toContain('The office');
+ // The guest line is the one that matters: somebody forwarding this should
+ // be able to see they are handing over a guest seat and not the house.
+ expect(mail.text).toContain('never be able to approve unlocking a door');
+ expect(mail.html).toContain('never be able to approve unlocking a door');
+ expect(mail.text).toContain('works once');
+ });
+
+ it('escapes a home label and an inviter name, both of which a person typed', async () => {
+ const { renderHouseholdInvite } = await import('../api/_lib/email.js');
+ const mail = renderHouseholdInvite({
+ homeLabel: '<img src=x onerror=alert(1)>',
+ role: 'viewer',
+ inviterName: '<b>nobody</b>',
+ inviteUrl: 'https://three.ws/smart-home/join?invite=token',
+ });
+ expect(mail.html).not.toContain('<img src=x');
+ expect(mail.html).not.toContain('<b>nobody</b>');
+ expect(mail.html).toContain('&lt;img');
+ });
+
+ it('carries a different sentence for every assignable role', async () => {
+ const { renderHouseholdInvite } = await import('../api/_lib/email.js');
+ const lines = new Set();
+ for (const role of members.ASSIGNABLE_ROLES) {
+ const mail = renderHouseholdInvite({ homeLabel: 'Home', role, inviteUrl: 'https://three.ws/x' });
+ lines.add(mail.text);
+ }
+ expect(lines.size).toBe(members.ASSIGNABLE_ROLES.length);
+ });
+});
+
+d('a scope survives a round trip through the store', () => {
+ it('keeps the rooms an editor sent, and drops nothing on the way back', async () => {
+ const sent = { mode: 'allow', areas: ['kitchen', 'hall'], entities: ['light.hall_lamp'] };
+ const saved = await members.setMemberRole({ homeId, userId: users.viewer, role: 'viewer', scope: sent });
+ expect(saved.scope).toEqual(sent);
+
+ const read = await members.resolveMembership(homeId, users.viewer);
+ expect(read.scope).toEqual(sent);
+
+ // Widening back to the whole house is an explicit {mode:'all'}, not an
+ // omission: the editor's Save means "this is the scope now".
+ const widened = await members.setMemberRole({ homeId, userId: users.viewer, role: 'viewer', scope: { mode: 'all' } });
+ expect(widened.scope).toEqual({ mode: 'all' });
+
+ await members.setMemberRole({ homeId, userId: users.viewer, role: 'viewer', scope: { mode: 'allow', areas: ['kitchen'], entities: ['light.hall_lamp'] } });
+ });
+
+ it('refuses a scope the schema cannot describe', async () => {
+ await expect(
+ sql`UPDATE home_members SET entity_scope = ${'{"mode":"everything"}'}::jsonb WHERE home_id = ${homeId} AND user_id = ${users.viewer}`,
+ ).rejects.toMatchObject({ code: '23514' });
+ });
+
+ it('de-duplicates and trims what an editor sends, and caps how much it can send', () => {
+ const messy = { mode: 'allow', areas: [' kitchen ', 'kitchen', '', null, 'hall'], entities: Array.from({ length: 900 }, (_, i) => `light.l${i}`) };
+ const clean = members.normalizeScope(messy, 'guest');
+ expect(clean.areas).toEqual(['kitchen', 'hall']);
+ expect(clean.entities).toHaveLength(500);
+ });
+});
+
d('the action log attributes every action to the member who acted', () => {
it('records two members acting on one home under their own ids', async () => {
for (const who of ['admin', 'member']) {