@htilabs/platform-common-models 0.29.0 → 0.32.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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The confidential Referrals (magic link) read (pl-iza, 0.32.0) over a stored
3
+ * collection: the in-memory double (`./mongoDouble.ts`, always) and a REAL
4
+ * MongoDB (only when `POC_WRITER_MONGO_URI` names a server, as in
5
+ * `./writer.mongo.test.ts`; CI sets it). The same rows on both, so the
6
+ * filters the reader builds (`$or` rollup keys, array membership on
7
+ * `purposes`, `is_confidential: true` vs `{ $ne: true }`) are checked against
8
+ * the server's own matcher, not only the double's.
9
+ *
10
+ * mongod --dbpath "$(mktemp -d)" --port 27999 --fork --logpath /tmp/mongod.log
11
+ * POC_WRITER_MONGO_URI=mongodb://127.0.0.1:27999 npx vitest run src/pointsOfContact
12
+ */
13
+ import { inspect } from "node:util";
14
+
15
+ import mongoose from "mongoose";
16
+ import type { MongoClient as MongoClientType } from "mongodb";
17
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
18
+
19
+ import {
20
+ POINTS_OF_CONTACT_COLLECTION,
21
+ listReferralContactsForPartner,
22
+ pocIdentityKey,
23
+ resolveMagicLinkRecipients,
24
+ type PocDbLike,
25
+ type PointOfContactDoc,
26
+ type SeatReach,
27
+ } from "../index.js";
28
+ import { mongoDouble } from "./mongoDouble.js";
29
+
30
+ const URI = process.env.POC_WRITER_MONGO_URI;
31
+ const { MongoClient, ObjectId } = mongoose.mongo;
32
+ const REF = "REFERRALS_MAGIC_LINK" as const;
33
+ const ADVOCATE = "auth0|advocate";
34
+
35
+ function row(over: Partial<PointOfContactDoc> & { email?: string | null }): PointOfContactDoc {
36
+ const base: PointOfContactDoc = {
37
+ id: "poc-x",
38
+ subject_type: "agency",
39
+ subject_id: "agency-a",
40
+ agency_id: "agency-a",
41
+ org_id: "org-a",
42
+ user_id: null,
43
+ person_id: null,
44
+ display_name: "Pat Doe",
45
+ emails: [],
46
+ phones: [],
47
+ purposes: [REF],
48
+ urgent_methods: [],
49
+ is_primary: false,
50
+ is_confidential: false,
51
+ active: true,
52
+ notes: null,
53
+ status: "confirmed",
54
+ origin: "admin_hub",
55
+ added_in_app: "platform",
56
+ identity_key: "x",
57
+ confirmed_by: "steward",
58
+ confirmed_at: "2026-10-14T00:00:00.000Z",
59
+ deactivated_by: null,
60
+ deactivated_at: null,
61
+ version: 2,
62
+ createdBy: "u1",
63
+ createdAt: "2026-10-14T00:00:00.000Z",
64
+ updatedBy: "u1",
65
+ updatedAt: "2026-10-14T00:00:00.000Z",
66
+ };
67
+ const { email, ...rest } = over;
68
+ const d: PointOfContactDoc = { ...base, ...rest };
69
+ if (email !== undefined) d.emails = email === null ? [] : [{ value: email, is_preferred: true }];
70
+ return { ...d, identity_key: pocIdentityKey(d) };
71
+ }
72
+
73
+ const conf = (over: Partial<PointOfContactDoc> & { email?: string | null }) =>
74
+ row({ is_confidential: true, display_name: "Hidden", ...over });
75
+
76
+ /** One partner (agency-a / org-a) with every case the confidential read must get right. */
77
+ const ROWS: PointOfContactDoc[] = [
78
+ row({ id: "poc-visible", email: "visible@a.org", display_name: "Visible" }),
79
+ conf({ id: "poc-c-agency", email: "hidden-agency@a.org" }),
80
+ conf({ id: "poc-c-prog", subject_type: "program", subject_id: "prog-1", email: "hidden-prog@a.org" }),
81
+ conf({ id: "poc-c-team", subject_type: "team", subject_id: "intake", email: "hidden-team@a.org" }),
82
+ conf({ id: "poc-c-loc", subject_type: "location", subject_id: "loc-1", email: "hidden-loc@a.org" }),
83
+ conf({ id: "poc-c-svc", subject_type: "service", subject_id: "svc-1", email: "hidden-svc@a.org" }),
84
+ conf({ id: "poc-c-org", subject_type: "org", subject_id: "org-a", agency_id: null, email: "hidden-org@a.org" }),
85
+ conf({ id: "poc-c-seat", user_id: "u-seat", email: null, display_name: null }),
86
+ conf({ id: "poc-c-seat-nomail", user_id: "u-noemail", email: null, display_name: null }),
87
+ // A visible row also reaches it (still counted); a second holder of the same address (deduped).
88
+ conf({ id: "poc-c-visible-dup", email: "visible@a.org" }),
89
+ conf({ id: "poc-c-agency-dup", subject_type: "program", subject_id: "prog-2", email: "hidden-agency@a.org" }),
90
+ // Never counted.
91
+ conf({ id: "poc-c-pending", email: "pending@a.org", status: "pending" }),
92
+ conf({ id: "poc-c-gone", email: "gone@a.org", active: false }),
93
+ conf({ id: "poc-c-untagged", email: "billing@a.org", purposes: ["BILLING"] }),
94
+ conf({ id: "poc-c-other", agency_id: "agency-b", subject_id: "agency-b", org_id: "org-b", email: "b@b.org" }),
95
+ // The advocate's own pending add of a confidential holder's address: listed, never deduped against.
96
+ row({
97
+ id: "poc-mine",
98
+ email: "hidden-prog@a.org",
99
+ display_name: "Mine",
100
+ status: "pending",
101
+ origin: "in_app",
102
+ added_in_app: "thread",
103
+ confirmed_by: null,
104
+ confirmed_at: null,
105
+ createdBy: ADVOCATE,
106
+ }),
107
+ ];
108
+
109
+ /** A stored confidential row that does not match the contract: skipped and counted, never named. */
110
+ const CORRUPT = { ...conf({ id: "poc-c-corrupt", email: "corrupt@a.org" }), origin: "bogus" };
111
+ /** A visible-leg row whose stored flag is malformed: it matches `{ $ne: true }` on the server too. */
112
+ const FLAG = { ...row({ id: "poc-v-flag", email: "flag@a.org" }), is_confidential: "true" };
113
+ const STORED = [...ROWS, CORRUPT, FLAG];
114
+
115
+ const SECRETS = [
116
+ "corrupt@a.org",
117
+ "flag@a.org",
118
+ "hidden-agency@a.org",
119
+ "hidden-prog@a.org",
120
+ "hidden-team@a.org",
121
+ "hidden-loc@a.org",
122
+ "hidden-svc@a.org",
123
+ "hidden-org@a.org",
124
+ "seat@a.org",
125
+ ];
126
+
127
+ const SEATS = new Map<string, SeatReach>([
128
+ ["u-seat", { email: " Seat@A.org ", phone: null, name: "Sam Seat" }],
129
+ ["u-noemail", { email: null, phone: null, name: "No Mail" }],
130
+ ]);
131
+ const resolveSeats = async (ids: readonly string[]) =>
132
+ new Map(ids.filter((i) => SEATS.has(i)).map((i) => [i, SEATS.get(i)!]));
133
+
134
+ function suite(name: string, handle: () => PocDbLike) {
135
+ const partner = { agency_id: "agency-a", org_id: "org-a" };
136
+ const withPending = { resolveSeats, includeOwnPendingFor: ADVOCATE };
137
+
138
+ it(`${name}: counts distinct confirmed confidential holders on every rollup subject`, async () => {
139
+ const r = await listReferralContactsForPartner(handle(), partner, { resolveSeats });
140
+ expect(r.recipients.map((x) => x.id)).toEqual(["poc-visible"]);
141
+ expect(r.confidentialCount).toBe(8);
142
+ // `unreachable` is visible-only; the no-email seat, the corrupt row and the
143
+ // malformed flag are a server-side count on the send list only.
144
+ expect(r.unreachable).toEqual([]);
145
+ expect(r).not.toHaveProperty("confidentialUnreachableCount");
146
+ const send = await resolveMagicLinkRecipients(handle(), partner, { resolveSeats });
147
+ expect(send.confidentialUnreachableCount).toBe(3);
148
+ expect(JSON.stringify(r) + JSON.stringify(send)).not.toMatch(/poc-c-|poc-v-flag/);
149
+ });
150
+
151
+ it(`${name}: an own-pending add of a confidential address is listed and the count does not drop`, async () => {
152
+ const r = await listReferralContactsForPartner(handle(), partner, withPending);
153
+ expect(r.recipients.map((x) => [x.id, x.pending ?? false])).toEqual([
154
+ ["poc-visible", false],
155
+ ["poc-mine", true],
156
+ ]);
157
+ expect(r.confidentialCount).toBe(8);
158
+ });
159
+
160
+ it(`${name}: the send list delivers up to capacity and renders as a count only`, async () => {
161
+ const send = await resolveMagicLinkRecipients(handle(), partner, withPending);
162
+ // hidden-prog@a.org is also the advocate's OWN pending add, so it is theirs to see
163
+ // (as their pick, never as a confidential holder); every other holder stays unseen.
164
+ const unseen = SECRETS.filter((a) => a !== "hidden-prog@a.org");
165
+ for (const text of [JSON.stringify(send), inspect(send, { depth: null, showHidden: true })]) {
166
+ for (const secret of unseen) expect(text).not.toContain(secret);
167
+ }
168
+ const plain = await resolveMagicLinkRecipients(handle(), partner, { resolveSeats });
169
+ for (const text of [JSON.stringify(plain), inspect(plain, { depth: null, showHidden: true })]) {
170
+ for (const secret of SECRETS) expect(text).not.toContain(secret);
171
+ }
172
+ expect(JSON.parse(JSON.stringify(send)).confidential).toEqual({ count: 8 });
173
+ const got: string[] = [];
174
+ const r = await send.confidential.deliver(async (to) => void got.push(to), { capacity: 5 });
175
+ // Reading order, the first five sent (visible@ and hidden-prog@ too, though a visible
176
+ // row and the advocate's own pick also reach them: duplicates they cannot observe),
177
+ // the last three overflowing.
178
+ expect(got).toEqual([
179
+ "seat@a.org",
180
+ "hidden-agency@a.org",
181
+ "visible@a.org",
182
+ "hidden-org@a.org",
183
+ "hidden-prog@a.org",
184
+ ]);
185
+ expect(r).toEqual({ count: 8, delivered: 5, failed: 0, overflow: 3, firstErrorName: null });
186
+ });
187
+ }
188
+
189
+ describe("confidential referral holders over the in-memory double", () => {
190
+ const m = mongoDouble();
191
+ m.store.set(POINTS_OF_CONTACT_COLLECTION, STORED.map((d) => ({ ...d })));
192
+ suite("double", () => m.handle() as unknown as PocDbLike);
193
+ });
194
+
195
+ describe.skipIf(!URI)("confidential referral holders against a real MongoDB", () => {
196
+ let client: MongoClientType;
197
+ let dbName: string;
198
+
199
+ beforeAll(async () => {
200
+ client = await new MongoClient(URI!).connect();
201
+ dbName = `poc_reader_test_${new ObjectId().toHexString()}`;
202
+ const coll = client.db(dbName).collection(POINTS_OF_CONTACT_COLLECTION);
203
+ await coll.insertMany(STORED.map((d) => ({ ...d })));
204
+ });
205
+ afterAll(async () => {
206
+ await client?.db(dbName).dropDatabase();
207
+ await client?.close();
208
+ });
209
+
210
+ suite("mongodb", () => client.db(dbName) as unknown as PocDbLike);
211
+ });
@@ -0,0 +1,190 @@
1
+ /**
2
+ * The shared in-app partner add against a REAL MongoDB: the server's own
3
+ * partial unique indexes and their E11000 errors, a repeated index creation
4
+ * from every process, and ObjectId-keyed `agencies` / `organizations` rows. The package's default suite stays free
5
+ * of a real MongoDB: this runs only when `POC_WRITER_MONGO_URI` names a
6
+ * server, e.g.
7
+ *
8
+ * mongod --dbpath "$(mktemp -d)" --port 27999 --fork --logpath /tmp/mongod.log
9
+ * POC_WRITER_MONGO_URI=mongodb://127.0.0.1:27999 npx vitest run src/pointsOfContact
10
+ *
11
+ * Each run uses a fresh throwaway database and drops it.
12
+ */
13
+ import mongoose from "mongoose";
14
+ import type { Db, MongoClient as MongoClientType } from "mongodb";
15
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
16
+
17
+ import {
18
+ POC_IN_APP_PENDING_CAP_PER_PARTNER,
19
+ POC_IN_APP_PENDING_INDEX,
20
+ POINTS_OF_CONTACT_COLLECTION,
21
+ POINT_OF_CONTACT_INDEXES,
22
+ ensurePocIndexes,
23
+ mintPartnerContact,
24
+ type PartnerContactResult,
25
+ } from "../index.js";
26
+
27
+ const URI = process.env.POC_WRITER_MONGO_URI;
28
+ const { MongoClient, ObjectId } = mongoose.mongo;
29
+ const DRIVER = { ObjectId };
30
+
31
+ const AGENCY_A = new ObjectId();
32
+ const ORG_A = new ObjectId();
33
+ const ORG_C = new ObjectId();
34
+ const ADVOCATE = { id: "auth0|advocate" };
35
+ const NOW = new Date("2026-10-14T15:00:00Z");
36
+
37
+ describe.skipIf(!URI)("mintPartnerContact against a real MongoDB", () => {
38
+ let client: MongoClientType;
39
+ let dbName: string;
40
+ let db: Db;
41
+ const fresh = () => client.db(dbName); // a new handle object each call
42
+ const add = (partner: Record<string, string>, contact: Record<string, unknown>, h: Db = db) =>
43
+ mintPartnerContact(h, { app: "pave", partner, contact: contact as never, actor: ADVOCATE, now: NOW }, DRIVER);
44
+ const idOf = (r: PartnerContactResult) => (r.ok ? r.value.id : "(refused)");
45
+ const rows = () => db.collection(POINTS_OF_CONTACT_COLLECTION).find({}).toArray();
46
+
47
+ beforeAll(async () => {
48
+ client = await new MongoClient(URI!).connect();
49
+ });
50
+ afterAll(async () => {
51
+ await client?.close();
52
+ });
53
+ beforeEach(async () => {
54
+ dbName = `poc_writer_test_${new ObjectId().toHexString()}`;
55
+ db = fresh();
56
+ await db.collection("agencies").insertOne({ _id: AGENCY_A, entity_id: "agency-a", organizationId: ORG_A });
57
+ await db.collection("organizations").insertMany([
58
+ { _id: ORG_A, name: "A", agencyId: AGENCY_A },
59
+ { _id: ORG_C, name: "C (no agency)" },
60
+ ]);
61
+ await ensurePocIndexes(fresh()); // the platform's job, on its own handle
62
+ return async () => {
63
+ await db.dropDatabase();
64
+ };
65
+ });
66
+
67
+ it("creates the full index set; every later process (a new handle) finds it in place", async () => {
68
+ await ensurePocIndexes(db);
69
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
70
+ const before = await coll.indexes();
71
+ const byName = Object.fromEntries(before.map((i) => [i.name, i]));
72
+ expect(byName[POC_IN_APP_PENDING_INDEX]).toMatchObject({
73
+ key: { agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1, createdBy: 1 },
74
+ unique: true,
75
+ partialFilterExpression: { status: "pending", origin: "in_app", active: true },
76
+ });
77
+ for (const name of Object.values(POINT_OF_CONTACT_INDEXES)) {
78
+ expect(byName[name], name).toBeDefined();
79
+ }
80
+ for (let i = 0; i < 2; i++) await ensurePocIndexes(fresh());
81
+ expect(await coll.indexes()).toEqual(before);
82
+ });
83
+
84
+ it("resolves ObjectId-keyed agencies and orgs: an agency by entity_id or hex, an org with a genuine mirror onto its agency", async () => {
85
+ const hex = AGENCY_A.toHexString();
86
+ for (const [i, form] of ["agency-a", hex, hex.toUpperCase()].entries()) {
87
+ expect(await add({ agency_id: form }, { display_name: form, emails: [{ value: `form${i}@a.org` }] }), form).toMatchObject({
88
+ ok: true,
89
+ value: { subject_type: "agency", subject_id: hex, agency_id: hex, org_id: ORG_A.toHexString(), created: true },
90
+ });
91
+ }
92
+ expect(await add({ org_id: ORG_A.toHexString() }, { display_name: "agency-a", emails: [{ value: "form0@a.org" }] })).toMatchObject({
93
+ value: { subject_type: "agency", subject_id: hex, created: false },
94
+ });
95
+ expect(await add({ agency_id: "agency-a", org_id: ORG_C.toHexString() }, { display_name: "X", emails: [{ value: "x@x.org" }] })).toMatchObject({
96
+ reason: "owner_mismatch",
97
+ });
98
+ });
99
+
100
+ it("the server's pending index settles a race of one identity: one row, the loser answers with it; a shared mailbox is not one identity", async () => {
101
+ const org = { org_id: ORG_C.toHexString() };
102
+ const [a, b] = await Promise.all([
103
+ add(org, { display_name: "Desk", emails: [{ value: "desk@c.org" }, { value: "shared@c.org" }] }, fresh()),
104
+ add(org, { display_name: "desk", emails: [{ value: "DESK@c.org" }, { value: "other@c.org" }] }, fresh()),
105
+ ]);
106
+ expect(await rows()).toHaveLength(1);
107
+ expect(idOf(a)).toBe(idOf(b));
108
+ expect([a, b].map((r) => (r.ok ? r.value.created : null)).sort()).toEqual([false, true]);
109
+ // Jane and Dan share the mailbox with Desk: each is their own row, pending side by side.
110
+ for (const name of ["Jane", "Dan"]) {
111
+ const r = await add(org, { display_name: name, emails: [{ value: `${name}@c.org` }, { value: "shared@c.org" }] });
112
+ expect(r, name).toMatchObject({ ok: true, value: { created: true } });
113
+ }
114
+ expect(await rows()).toHaveLength(3);
115
+ });
116
+
117
+ it("the real driver's E11000 on the pending index maps to duplicate_pending_add and is answered with the winner's row", async () => {
118
+ const org = { org_id: ORG_C.toHexString() };
119
+ const first = await add(org, { display_name: "Desk", emails: [{ value: "desk@c.org" }, { value: "shared@c.org" }] });
120
+ // Hide the existing row from the first read only: the add reaches the insert, as the
121
+ // loser of a race does, and meets the server's partial unique index on identity_key.
122
+ let hidden = false;
123
+ const racing = {
124
+ collection: (name: string) => {
125
+ const c = db.collection(name);
126
+ if (name !== POINTS_OF_CONTACT_COLLECTION) return c;
127
+ return Object.assign(Object.create(c) as typeof c, {
128
+ find: (f: Record<string, unknown>, o?: Record<string, unknown>) =>
129
+ hidden ? c.find(f, o) : ((hidden = true), c.find({ id: "(none)" })),
130
+ });
131
+ },
132
+ } as unknown as Db;
133
+ const r = await add(org, { display_name: "DESK", emails: [{ value: "desk@c.org" }] }, racing);
134
+ expect(r).toEqual({ ok: true, value: { ...(first.ok && first.value), created: false } });
135
+ expect(await rows()).toHaveLength(1);
136
+ });
137
+
138
+ it("a parallel burst on the server stays within the cap; every survivor answered ok, every 429 left no row", async () => {
139
+ const org = { org_id: ORG_C.toHexString() };
140
+ for (let round = 0; round < 3; round++) {
141
+ await db.collection(POINTS_OF_CONTACT_COLLECTION).deleteMany({});
142
+ const results = await Promise.all(
143
+ Array.from({ length: 12 }, (_, i) => add(org, { display_name: `Par${round}-${i}`, emails: [{ value: `par${round}-${i}@c.org` }] }, fresh())),
144
+ );
145
+ const kept = await rows();
146
+ expect(kept.length, `round ${round}`).toBeLessThanOrEqual(POC_IN_APP_PENDING_CAP_PER_PARTNER);
147
+ const okIds = results.filter((r) => r.ok).map(idOf).sort();
148
+ expect(okIds).toEqual(kept.map((r) => r.id as string).sort());
149
+ for (const r of results.filter((x) => !x.ok)) expect(r).toMatchObject({ status: 429, reason: "too_many_pending_adds" });
150
+ }
151
+ // Once it settles, sequential adds fill up to the cap and no further.
152
+ for (let i = (await rows()).length; i < POC_IN_APP_PENDING_CAP_PER_PARTNER; i++) {
153
+ expect((await add(org, { display_name: `Seq${i}`, emails: [{ value: `seq${i}@c.org` }] })).ok).toBe(true);
154
+ }
155
+ expect(await add(org, { display_name: "After", emails: [{ value: "after@c.org" }] })).toMatchObject({
156
+ status: 429,
157
+ reason: "too_many_pending_adds",
158
+ });
159
+ });
160
+
161
+ it("fails closed without the indexes: no collection (NamespaceNotFound) or a wrong spec is indexes_missing, and nothing is created", async () => {
162
+ const bareName = `poc_writer_bare_${new ObjectId().toHexString()}`;
163
+ const bare = client.db(bareName);
164
+ try {
165
+ await bare.collection("organizations").insertOne({ _id: ORG_C, name: "C (no agency)" });
166
+ const org = { org_id: ORG_C.toHexString() };
167
+ const desk = { display_name: "Desk", emails: [{ value: "desk@c.org" }] };
168
+ expect(await add(org, desk, bare)).toMatchObject({ ok: false, status: 503, reason: "indexes_missing" });
169
+ const created = await bare.listCollections({ name: POINTS_OF_CONTACT_COLLECTION }).toArray();
170
+ expect(created).toHaveLength(0);
171
+
172
+ // The interim multikey variant under the right name is not the index.
173
+ await bare.collection(POINTS_OF_CONTACT_COLLECTION).createIndex({ id: 1 }, { unique: true, name: "pointsofcontact_id_unique" });
174
+ await bare.collection(POINTS_OF_CONTACT_COLLECTION).createIndex(
175
+ { agency_id: 1, subject_type: 1, subject_id: 1, "emails.value": 1, createdBy: 1 },
176
+ { name: POC_IN_APP_PENDING_INDEX, unique: true, partialFilterExpression: { status: "pending", origin: "in_app", active: true } },
177
+ );
178
+ const h = client.db(bareName);
179
+ expect(await add(org, desk, h)).toMatchObject({ reason: "indexes_missing" });
180
+ expect(await bare.collection(POINTS_OF_CONTACT_COLLECTION).countDocuments({})).toBe(0);
181
+
182
+ // The platform fixes it; the same handle then writes (a refusal is not memoized).
183
+ await bare.collection(POINTS_OF_CONTACT_COLLECTION).dropIndex(POC_IN_APP_PENDING_INDEX);
184
+ await ensurePocIndexes(client.db(bareName));
185
+ expect(await add(org, desk, h)).toMatchObject({ ok: true, value: { created: true } });
186
+ } finally {
187
+ await bare.dropDatabase();
188
+ }
189
+ });
190
+ });