dwelldelta-mcp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -20,7 +20,8 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
22
 
23
- The data files in vendor/ (rents-index.json, indicators.json) are not covered by
24
- this licence. Each figure keeps its source's own licence and attribution, which
25
- the data files and every answer state (for example, ABS data: CC BY 4.0, "Based
26
- on Australian Bureau of Statistics data").
23
+ The data files in vendor/ (rents-index.json, indicators.json, nsw-suburbs.json, vic-rents.json) are
24
+ not covered by this licence. Each figure keeps its source's own licence and
25
+ attribution, which the data files and every answer state (for example, ABS data:
26
+ CC BY 4.0, "Based on Australian Bureau of Statistics data"; the NSW suburb list:
27
+ CC BY 3.0 AU, NSW Spatial Services; Victorian rents: CC BY 4.0, Homes Victoria).
package/README.md CHANGED
@@ -4,18 +4,31 @@ An MCP server that lets an AI assistant check a weekly rent against the ABS rent
4
4
  Australian property and lending indicators. From [DwellDelta](https://dwelldelta.com.au/), a service of
5
5
  Xcelerent Pty Ltd, built on public data.
6
6
 
7
- Three read-only tools:
7
+ Three read-only tools, and one that adds the user's own rent when they ask:
8
8
 
9
9
  | Tool | What it answers |
10
10
  |---|---|
11
11
  | `rent_check` | a weekly rent, and any proposed new rent, against the ABS rents index for the capital city since the lease began (the same arithmetic as the rent check at tools.dwelldelta.com.au) |
12
12
  | `market_indicators` | the latest RBA cash rate, unemployment, wage growth, rents for all eight capitals, NSW lending, lending standards and arrears, approvals and completions - each with period, source, licence and limits; filter by `geography` |
13
+ | `vic_rents` | Victorian rents by suburb group from Homes Victoria's Rental Report: the median weekly rent of new leases, the lease count and the change on a year before, for 146 suburb groups and 13 regions; filter by `suburb_group` or `region` (from 0.5.0) |
13
14
  | `data_sources` | the sources, their licences, and what DwellDelta cannot answer |
15
+ | `contribute_rent` | adds the user's own rent, anonymously, to DwellDelta's suburb benchmarks - only when the user asks, and only after they have read and agreed to the consent wording (from 0.5.0) |
14
16
 
15
- It runs on your own machine over stdio and records nothing. At start it fetches the week's indicators from
16
- tools.dwelldelta.com.au - one request for one public file; nothing about you or your questions is sent - and
17
- otherwise uses the copy it ships with. Set `DWELLDELTA_OFFLINE=1` and it makes no request at all. Nothing it says is
18
- a forecast, a valuation or advice.
17
+ It runs on your own machine over stdio. It records nothing and sends nothing about you unless you choose to add
18
+ your rent. At start it fetches the week's indicators from tools.dwelldelta.com.au - one request for one public
19
+ file; nothing about you or your questions is sent - and otherwise uses the copy it ships with. Set
20
+ `DWELLDELTA_OFFLINE=1` and that fetch is not made. Nothing it says is a forecast, a valuation or advice.
21
+
22
+ ## Adding a rent (from 0.5.0)
23
+
24
+ `contribute_rent` is the one tool that can send anything, and it takes two calls. The first stores and sends
25
+ nothing: it returns the consent wording, the [Contributor Terms](https://tools.dwelldelta.com.au/terms/) and
26
+ [Privacy Notice](https://tools.dwelldelta.com.au/privacy/), and a token. Only when the assistant has shown you
27
+ that wording and you have said yes does it call again, with the token. What is then stored, in AWS Sydney, is the
28
+ suburb, home type, bedrooms, rent, lease month and lease kind, and whether it is a rent you pay or the rent of a
29
+ property you own - never an address, name or email. You get a deletion code; email it to lingtao@xcelerent.com
30
+ and the record is deleted. Only your own rent may be added: an assistant must not add a figure it read on a
31
+ website or a listing.
19
32
 
20
33
  ## Use it
21
34
 
@@ -61,5 +74,6 @@ answer states - for example ABS data is CC BY 4.0, "Based on Australian Bureau o
61
74
 
62
75
  ## Development
63
76
 
64
- `npm test` here starts the server and calls all three tools over MCP; the repository's root `npm test` holds the
77
+ `npm test` here starts the server and calls the three read-only tools, and the first (consent) call of
78
+ `contribute_rent`, over MCP; the repository's root `npm test` holds the
65
79
  tool answers themselves and checks that `vendor/` matches its sources. `npm pack` runs `scripts/vendor.mjs` first.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * contribute_rent: the AI-assistant route into the rent contributions the rent check page collects (2026-09-30,
3
+ * control advisory 2026-09-30-ai-agents-contribute-data.md). Same fields, same checks, same endpoint, same terms,
4
+ * same deletion code as the page - vendored from rent/contribute.mjs so the two cannot disagree.
5
+ *
6
+ * CONNECTED since 2026-10-03, on the owner's word (terms in force on the owner's approval; legal/status.json says
7
+ * so). TERMS_URL and PRIVACY_URL name the pages rendered from legal/. With no endpoint - set
8
+ * CONTRIBUTION_ENDPOINT back to null - every call says contributions are not being collected and nothing is
9
+ * stored or sent.
10
+ *
11
+ * Consent takes two calls, because an assistant cannot agree to terms; its user must:
12
+ * 1. Without a consent_token, nothing is stored or sent. The answer is the consent text, the terms' addresses
13
+ * and a one-use token, valid for TOKEN_MINUTES and bound to exactly these details.
14
+ * 2. The assistant shows the text to its user. Only if the user says yes does it call again with the same
15
+ * details, the token and user_agreed: true. The answer carries the deletion code for the user.
16
+ * The server cannot see the conversation, so this proves the text was fetched, not that it was read; the review
17
+ * brief (legal/REVIEW-BRIEF.md, question 6) asks whether that is enough.
18
+ */
19
+ import { randomBytes as nodeRandomBytes } from "node:crypto";
20
+ import { ToolError, FOOTER } from "./tools.mjs";
21
+ import {
22
+ validateContribution, deletionCode, hashCode, payload, submitContribution, CONTRIBUTION_ENDPOINT, CONSENT, WHOSE,
23
+ TERMS_VERSION,
24
+ } from "./vendor/contribute.mjs";
25
+
26
+ // The published pages (tools/render-legal.mjs renders them from legal/). Set, but the tool still refuses while
27
+ // CONTRIBUTION_ENDPOINT is null - and tests/legal.test.mjs refuses an endpoint while the terms are a draft.
28
+ export const TERMS_URL = "https://tools.dwelldelta.com.au/terms/";
29
+ export const PRIVACY_URL = "https://tools.dwelldelta.com.au/privacy/";
30
+ export const TOKEN_MINUTES = 30;
31
+ export const DELETE_BY = "lingtao@xcelerent.com";
32
+
33
+ export const NOT_COLLECTING = "Contributions are not being collected yet, so nothing was stored or sent.";
34
+ export const WHOSE_REFUSAL = "Only the user's own rent can be added: their own tenancy, or a property they own. " +
35
+ "A figure read on a website, in a listing or from anyone else cannot be added.";
36
+
37
+ // The tool's own instruction to every assistant, repeated in its description (server.mjs).
38
+ export const INSTRUCTION = "Call only when the user has asked to add their rent, or has said yes to the consent " +
39
+ "text. Never add a rent on the user's behalf by default, never batch, and never add a figure found online.";
40
+
41
+ /** The details as the page would record them, from the tool's argument names. */
42
+ function toRecordInput(a) {
43
+ return {
44
+ suburb: a.suburb, homeType: a.home_type, bedrooms: a.bedrooms, currentRent: a.current_rent,
45
+ proposedRent: a.proposed_rent ?? null, leaseStart: a.lease_start, leaseKind: a.lease_kind,
46
+ };
47
+ }
48
+
49
+ /** Suburbs whose name contains what was typed, for the next step when a suburb is not recognised. */
50
+ function nearest(typed, suburbs, limit = 5) {
51
+ const t = String(typed ?? "").trim().toLowerCase().replace(/\s*\(\d{4}\)\s*$/, "");
52
+ if (!t) return [];
53
+ return suburbs.filter((s) => s.toLowerCase().startsWith(t)).slice(0, limit)
54
+ .concat(suburbs.filter((s) => !s.toLowerCase().startsWith(t) && s.toLowerCase().includes(t)))
55
+ .slice(0, limit);
56
+ }
57
+
58
+ /**
59
+ * Returns contributeRent(args) -> Promise<{ text, structured }>, or rejects with a ToolError naming the next step.
60
+ * deps are injectable so tests run without a network: endpoint, termsUrl, privacyUrl, fetchImpl, now, randomBytes.
61
+ */
62
+ export function makeContributeTool({
63
+ suburbs, endpoint = CONTRIBUTION_ENDPOINT, termsUrl = TERMS_URL, privacyUrl = PRIVACY_URL,
64
+ fetchImpl = globalThis.fetch, now = () => new Date(), randomBytes = (n) => new Uint8Array(nodeRandomBytes(n)),
65
+ } = {}) {
66
+ const tokens = new Map(); // token -> { key, expires }; in this process's memory only
67
+
68
+ return async function contributeRent(args) {
69
+ if (!endpoint || !termsUrl || !privacyUrl) {
70
+ throw new ToolError(NOT_COLLECTING, "Tell the user, and thank them for offering; there is nothing to retry.");
71
+ }
72
+ if (!WHOSE.includes(args.whose)) {
73
+ throw new ToolError(WHOSE_REFUSAL, `Use whose = ${WHOSE.join(" or ")} only when that is true; otherwise do not add it.`);
74
+ }
75
+ const t = now();
76
+ let record;
77
+ try {
78
+ record = validateContribution(toRecordInput(args), suburbs, t.toISOString().slice(0, 7));
79
+ } catch (err) {
80
+ const near = /suburb/.test(err.message) ? nearest(args.suburb, suburbs) : [];
81
+ throw new ToolError(`Not added: ${err.message}.`, near.length
82
+ ? `Ask the user which suburb, then call again with its exact name, e.g. ${near.map((s) => `"${s}"`).join(", ")}.`
83
+ : "Ask the user for the missing or corrected detail, then call again. Nothing was stored.");
84
+ }
85
+ const key = JSON.stringify({ record, whose: args.whose });
86
+
87
+ if (!args.consent_token) {
88
+ for (const [k, v] of tokens) if (v.expires <= t.getTime()) tokens.delete(k);
89
+ const token = [...randomBytes(16)].map((b) => b.toString(16).padStart(2, "0")).join("");
90
+ tokens.set(token, { key, expires: t.getTime() + TOKEN_MINUTES * 60000 });
91
+ const consent = `${CONSENT.heading} ${CONSENT.body} By adding it you agree to the Contributor Terms ` +
92
+ `(${termsUrl}) and Privacy Notice (${privacyUrl}), version ${TERMS_VERSION}.`;
93
+ const text = [
94
+ "NOTHING HAS BEEN STORED OR SENT. Show the user this text, word for word, and ask whether to add their rent:",
95
+ "",
96
+ consent,
97
+ "",
98
+ `Only if they say yes, call contribute_rent again with the same details, consent_token "${token}" and ` +
99
+ `user_agreed: true, within ${TOKEN_MINUTES} minutes. If they say no, do nothing further.`,
100
+ "",
101
+ FOOTER,
102
+ ].join("\n");
103
+ return { text, structured: { stored: false, consent_text: consent, terms_url: termsUrl, privacy_url: privacyUrl,
104
+ terms_version: TERMS_VERSION,
105
+ consent_token: token, expires_in_minutes: TOKEN_MINUTES } };
106
+ }
107
+
108
+ const entry = tokens.get(args.consent_token);
109
+ const again = "Call contribute_rent without a consent_token to get the consent text, and show it to the user.";
110
+ if (!entry || entry.expires <= t.getTime()) {
111
+ tokens.delete(args.consent_token);
112
+ throw new ToolError("Not added: that consent token is unknown, used or expired.", again);
113
+ }
114
+ if (entry.key !== key) {
115
+ throw new ToolError("Not added: the details differ from the ones the consent was shown for.", again);
116
+ }
117
+ if (args.user_agreed !== true) {
118
+ throw new ToolError("Not added: user_agreed is not true.",
119
+ "Set user_agreed: true only if the user said yes to the consent text; if they did not, do nothing further.");
120
+ }
121
+ tokens.delete(args.consent_token); // one use, whatever happens next
122
+
123
+ const code = deletionCode(randomBytes(12));
124
+ const body = { ...payload(record, await hashCode(code), t.toISOString().slice(0, 10)), whose: args.whose };
125
+ try {
126
+ await submitContribution(body, { endpoint, fetchImpl });
127
+ } catch (err) {
128
+ throw new ToolError(`Not added: ${err.message}.`, "Tell the user it was not added. Do not retry automatically.");
129
+ }
130
+ const text = [
131
+ `Added. The user's deletion code is ${code} - give it to them now; it is shown once and cannot be recovered.`,
132
+ `To have this rent deleted, they email the code to ${DELETE_BY}.`,
133
+ "DwellDelta publishes only medians built from 10 or more rents, so no one rent can be picked out.",
134
+ "",
135
+ FOOTER,
136
+ ].join("\n");
137
+ return { text, structured: { stored: true, deletion_code: code, delete_by_emailing: DELETE_BY } };
138
+ };
139
+ }
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "dwelldelta-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Is an Australian rent fair? A rent check on the ABS rents index, plus sourced property and lending indicators, for AI agents.",
5
5
  "mcpName": "au.com.dwelldelta/dwelldelta",
6
6
  "license": "MIT",
7
7
  "homepage": "https://dwelldelta.com.au/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/xcelerent/dwelldelta-tools.git",
11
+ "directory": "mcp"
12
+ },
8
13
  "author": "DwellDelta, a service of Xcelerent Pty Ltd",
9
14
  "type": "module",
10
15
  "engines": {
@@ -16,6 +21,8 @@
16
21
  "files": [
17
22
  "server.mjs",
18
23
  "tools.mjs",
24
+ "contribute-tool.mjs",
25
+ "vic-rents-tool.mjs",
19
26
  "vendor/",
20
27
  "LICENSE",
21
28
  "README.md"
package/server.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // DwellDelta MCP server: Australian property market data for AI agents. Runs on the user's machine over stdio and
3
- // records nothing. From 0.4.0 it fetches the week's indicators once at start from tools.dwelldelta.com.au - one
3
+ // records nothing unless the user chooses to add their rent. From 0.4.0 it fetches the week's indicators once at start from tools.dwelldelta.com.au - one
4
4
  // public file; nothing about the user or their questions is sent - and falls back to its bundled copy
5
- // (DWELLDELTA_OFFLINE=1 never fetches). Three read-only tools; the logic lives in tools.mjs.
5
+ // (DWELLDELTA_OFFLINE=1 never fetches). Four read-only tools; the logic lives in tools.mjs, and vic_rents
6
+ // (Victorian rents by suburb group, 0.5.0) in vic-rents-tool.mjs, loaded the same way. A fourth,
7
+ // contribute_rent (contribute-tool.mjs), is connected from 0.5.0 (2026-10-03): it sends a rent only on a second call carrying the user's agreement.
6
8
  //
7
9
  // Every result carries text to quote and a structured result (the figures plus where they come from, under which
8
10
  // licence, how current, and whether stale). Every failure is isError with the next step to take, so an agent
@@ -15,10 +17,17 @@ import {
15
17
  rentCheckResult, marketIndicatorsResult, dataSourcesResult, loadJson, loadSnapshot, ToolError,
16
18
  RENTS_PATH, INDICATORS_PATH, SERVER_VERSION,
17
19
  } from "./tools.mjs";
20
+ import { makeContributeTool, INSTRUCTION } from "./contribute-tool.mjs";
21
+ import { loadVicRents, vicRentsResult } from "./vic-rents-tool.mjs";
22
+ import { HOME_TYPES, BEDROOMS, LEASE_KINDS, WHOSE } from "./vendor/contribute.mjs";
18
23
 
19
24
  const rents = await loadJson(RENTS_PATH);
25
+ const { suburbs } = await loadJson(new URL("./vendor/nsw-suburbs.json", import.meta.url));
26
+ const contributeRent = makeContributeTool({ suburbs });
20
27
  const loaded = await loadSnapshot();
21
28
  const snapshot = loaded.snapshot ? { ...loaded.snapshot, origin: loaded.origin } : null;
29
+ const vicLoaded = await loadVicRents();
30
+ const vic = vicLoaded.feed ? { ...vicLoaded.feed, origin: vicLoaded.origin } : null;
22
31
  const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false, destructiveHint: false };
23
32
 
24
33
  const ok = ({ text, structured }) => ({ content: [{ type: "text", text }], structuredContent: structured });
@@ -28,7 +37,7 @@ const fail = (err) => ({
28
37
  });
29
38
  const guard = (fn) => async (args) => {
30
39
  try {
31
- return ok(fn(args));
40
+ return ok(await fn(args));
32
41
  } catch (err) {
33
42
  return fail(err instanceof ToolError ? err : new ToolError(err.message, "Report this to lingtao@xcelerent.com."));
34
43
  }
@@ -70,9 +79,50 @@ server.registerTool("market_indicators", {
70
79
  server.registerTool("data_sources", {
71
80
  title: "What DwellDelta covers",
72
81
  description: "The sources behind DwellDelta's figures, their licences, and what it cannot answer (individual " +
73
- "sale prices, suburb rents, advice).",
82
+ "sale prices, suburb rents outside Victoria, advice).",
74
83
  inputSchema: {},
75
84
  annotations: readOnly,
76
85
  }, guard(() => dataSourcesResult(needSnapshot())));
77
86
 
87
+ server.registerTool("vic_rents", {
88
+ title: "Victorian rents by suburb group",
89
+ description: "Victorian rents from Homes Victoria's Rental Report (CC BY 4.0): the median weekly rent of new " +
90
+ "leases in the latest quarter, how many leases it rests on, and the change on a year before, for 146 suburb " +
91
+ "groups and 13 regions. Filter by suburb_group (part of a name works, e.g. \"Brighton\") or region. New-lease " +
92
+ "medians, not advertised rents; quote the quarter and the limits.",
93
+ inputSchema: {
94
+ suburb_group: z.string().optional().describe("A Homes Victoria suburb group, or part of a suburb name"),
95
+ region: z.string().optional().describe("A region, e.g. Inner Melbourne, Geelong, Ballarat"),
96
+ },
97
+ annotations: readOnly,
98
+ }, guard((args) => {
99
+ if (!vic) {
100
+ throw new ToolError("The Victorian rents feed is not on this machine.",
101
+ "Point DWELLDELTA_VIC_RENTS at a copy of https://tools.dwelldelta.com.au/market/vic-rents.json.");
102
+ }
103
+ return vicRentsResult(args, vic);
104
+ }));
105
+
106
+ server.registerTool("contribute_rent", {
107
+ title: "Add the user's own rent (NSW), with their consent",
108
+ description: "Add the user's own weekly rent, anonymously, to DwellDelta's NSW suburb rents - suburb, home type, " +
109
+ "bedrooms, rent and lease month; never an address, name or email. Two calls: the first stores nothing and " +
110
+ "returns consent text and a token; show the text to the user, and only if they say yes call again with the " +
111
+ `token and user_agreed: true. ${INSTRUCTION}`,
112
+ inputSchema: {
113
+ suburb: z.string().describe('NSW suburb with its postcode, as "Newtown (2042)"'),
114
+ home_type: z.enum(HOME_TYPES),
115
+ bedrooms: z.enum(BEDROOMS),
116
+ current_rent: z.number().positive().describe("Current weekly rent in Australian dollars"),
117
+ proposed_rent: z.number().positive().optional().describe("Proposed new weekly rent, if there is one"),
118
+ lease_start: z.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/).describe("Month the lease began, YYYY-MM"),
119
+ lease_kind: z.enum(LEASE_KINDS),
120
+ whose: z.enum(WHOSE).describe("my_own_tenancy (the user rents it) or my_own_property (the user owns it). " +
121
+ "There is no value for a figure found online: never add one."),
122
+ consent_token: z.string().optional().describe("From the first call; omit it to get the consent text"),
123
+ user_agreed: z.boolean().optional().describe("true only if the user said yes to the consent text"),
124
+ },
125
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
126
+ }, guard(contributeRent));
127
+
78
128
  await server.connect(new StdioServerTransport());
package/tools.mjs CHANGED
@@ -62,7 +62,7 @@ export async function loadSnapshot({ env = process.env, fetchImpl = globalThis.f
62
62
  }
63
63
 
64
64
  export const FOOTER = "Information, not advice. From DwellDelta (dwelldelta.com.au), built on public data.";
65
- export const SERVER_VERSION = "0.4.0";
65
+ export const SERVER_VERSION = "0.5.0";
66
66
  // The indicators snapshot is rebuilt every Monday. Older than this and the answer says so, in words and in the
67
67
  // structured result, rather than serving a stale figure as current.
68
68
  export const STALE_DAYS = 10;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * "Add my rent" - the opt-in contribution step, kept apart from the page so it can be tested.
3
+ *
4
+ * CONNECTED since 2026-10-03 (owner decision: in force on the owner's approval, before the legal review
5
+ * reports). CONTRIBUTION_ENDPOINT is the Lambda function URL in AWS Sydney; the rent page's CSP admits exactly
6
+ * that origin. To switch it off, set CONTRIBUTION_ENDPOINT back to null: submitContribution then refuses before
7
+ * any request is made. Design: dwelldelta-control/project_team/advisory/2026-09-25-share-your-rent-design.md.
8
+ *
9
+ * What a contribution holds is exactly FIELDS plus the hash of a deletion code and the date: no address,
10
+ * name, email or network address. The deletion code itself is shown to the person once and never sent.
11
+ */
12
+
13
+ export const CONTRIBUTION_ENDPOINT = "https://wzggu4sypmmgth5tsno62olhly0xthts.lambda-url.ap-southeast-2.on.aws/";
14
+
15
+ // The version of the Contributor Terms and Privacy Notice a contributor agrees to, sent with every contribution
16
+ // and stored beside it. tests/legal.test.mjs holds it equal to legal/status.json, which stamps the pages.
17
+ export const TERMS_VERSION = "2026-10-03";
18
+
19
+ export const FIELDS = ["suburb", "homeType", "bedrooms", "currentRent", "proposedRent", "leaseStart", "leaseKind"];
20
+ export const HOME_TYPES = ["house", "unit", "townhouse"];
21
+ export const BEDROOMS = ["1", "2", "3", "4", "5+"];
22
+ export const LEASE_KINDS = ["new lease", "renewal"];
23
+ // The AI-assistant route must say whose rent it is. There is deliberately no value for a figure found online:
24
+ // only the person's own tenancy, or the rent of a property they own, may be added (Contributor Terms section 2).
25
+ export const WHOSE = ["my_own_tenancy", "my_own_property"];
26
+ export const RENT_MIN = 50;
27
+ export const RENT_MAX = 5000;
28
+
29
+ // Wording from the design memo, section 2. Tests hold the promises in it.
30
+ export const CONSENT = {
31
+ heading: "Help build fair rents for your suburb?",
32
+ body: "Add your rent anonymously. We keep your suburb, home type, bedrooms, rent and lease month - never " +
33
+ "your address, name or email. We publish only medians built from 10 or more rents, so no one rent " +
34
+ "can be picked out.",
35
+ agree: "I agree to the Contributor Terms and Privacy Notice - add my rent",
36
+ button: "Add my rent",
37
+ notConnected: "Contributions are not being collected yet, so nothing was sent. Thank you for offering.",
38
+ };
39
+
40
+ /** Checks what the person entered and returns the record to send, or throws with a plain reason. */
41
+ export function validateContribution(input, suburbs, thisMonth) {
42
+ const r = {
43
+ suburb: String(input.suburb ?? "").trim(),
44
+ homeType: input.homeType,
45
+ bedrooms: input.bedrooms,
46
+ currentRent: Number(input.currentRent),
47
+ proposedRent: input.proposedRent === null || input.proposedRent === "" || input.proposedRent === undefined
48
+ ? null : Number(input.proposedRent),
49
+ leaseStart: input.leaseStart,
50
+ leaseKind: input.leaseKind,
51
+ };
52
+ if (!suburbs.includes(r.suburb)) throw new Error("choose your suburb from the list");
53
+ if (!HOME_TYPES.includes(r.homeType)) throw new Error("choose a home type");
54
+ if (!BEDROOMS.includes(r.bedrooms)) throw new Error("choose the number of bedrooms");
55
+ if (!LEASE_KINDS.includes(r.leaseKind)) throw new Error("say whether this is a new lease or a renewal");
56
+ if (!(r.currentRent >= RENT_MIN && r.currentRent <= RENT_MAX)) {
57
+ throw new Error(`the weekly rent must be between $${RENT_MIN} and $${RENT_MAX}`);
58
+ }
59
+ if (r.proposedRent !== null) {
60
+ if (!(r.proposedRent >= RENT_MIN && r.proposedRent <= RENT_MAX)) {
61
+ throw new Error(`the proposed rent must be between $${RENT_MIN} and $${RENT_MAX}`);
62
+ }
63
+ if (r.proposedRent > 2 * r.currentRent) throw new Error("the proposed rent is more than double the current one");
64
+ }
65
+ if (typeof r.leaseStart !== "string" || !/^\d{4}-(0[1-9]|1[0-2])$/.test(r.leaseStart)) {
66
+ throw new Error("the lease start must be a month");
67
+ }
68
+ if (r.leaseStart > thisMonth) throw new Error("the lease start cannot be in the future");
69
+ return r;
70
+ }
71
+
72
+ // Crockford's base32: no I, L, O or U, so a code read aloud or copied by hand cannot be misread.
73
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
74
+
75
+ /** A 12-character deletion code in three groups, from 12 random bytes the caller supplies. */
76
+ export function deletionCode(bytes) {
77
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 12) throw new Error("need 12 random bytes");
78
+ const chars = [...bytes].map((b) => ALPHABET[b % 32]).join("");
79
+ return `${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}`;
80
+ }
81
+
82
+ /** SHA-256 of the code, hex. Only this is stored, so a request to delete can be matched and nothing else. */
83
+ export async function hashCode(code, subtle = globalThis.crypto.subtle) {
84
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(code));
85
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
86
+ }
87
+
88
+ /** The exact body that would be sent: the record, the code's hash, the date and the terms version agreed. */
89
+ export function payload(record, codeHash, today) {
90
+ const body = {};
91
+ for (const f of FIELDS) body[f] = record[f];
92
+ body.deletionCodeSha256 = codeHash;
93
+ body.contributedOn = today;
94
+ body.termsVersion = TERMS_VERSION;
95
+ return body;
96
+ }
97
+
98
+ /** Sends a contribution. While CONTRIBUTION_ENDPOINT is null it refuses before any request is made. */
99
+ export async function submitContribution(body, { endpoint = CONTRIBUTION_ENDPOINT, fetchImpl = globalThis.fetch } = {}) {
100
+ if (!endpoint) throw new Error("not connected");
101
+ const res = await fetchImpl(endpoint, {
102
+ method: "POST",
103
+ headers: { "content-type": "application/json" },
104
+ body: JSON.stringify(body),
105
+ credentials: "omit",
106
+ referrerPolicy: "no-referrer",
107
+ });
108
+ if (!res.ok) throw new Error(`the contribution was not saved (HTTP ${res.status})`);
109
+ }