@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,967 @@
1
+ /**
2
+ * The in-app partner add, shared (pl-bt1, pl-e98): an advocate in Thread, PAVE
3
+ * or LEADS names a partner on a share and the contact they type lands in
4
+ * platform-db `pointsofcontact` as a PENDING Point of contact tagged Referrals
5
+ * (magic link). Every app runs THIS implementation against its own platform-db
6
+ * handle; there is no HTTP hop. It is the platform's `addPartnerContact`
7
+ * (platform `lib/points-of-contact/repository.ts`, the store behind
8
+ * `POST /api/partner-contacts`) and the internals it uses from
9
+ * `lib/points-of-contact/core.ts` (`resolveOwner` for an agency or org
10
+ * subject, `insertContact`, the index set, the duplicate-key mapping) and
11
+ * `lib/sharing-settings/recipient-id.ts` (`resolveRecipientId`), moved here
12
+ * with the same rules, the same order of checks and the same refusal codes.
13
+ *
14
+ * ## What it does, in order
15
+ *
16
+ * 1. The actor names the advocate (`actor_required`), the app is one of
17
+ * {@link POC_PARTNER_ADD_APPS} (`invalid_app`), the contact is a strict
18
+ * {@link PocInAppSchema} body (`invalid_contact`), always tagged Referrals
19
+ * (magic link) first.
20
+ * 2. The partner is a strict {@link PartnerContactSelectorSchema} selector
21
+ * (`invalid_partner`), resolved to its owner (decision D1): an agency in any
22
+ * accepted form (`entity_id`, `id`, `_id` in either stored shape, a mapped
23
+ * `registry_agencies` row) becomes `String(agencies._id)`; an org is
24
+ * `String(organizations._id)`. An org whose org GENUINELY mirrors an
25
+ * agency puts the contact on that agency (kickoff D1). Unresolved:
26
+ * `owner_not_found`; an agency and org that are not one partner:
27
+ * `owner_mismatch`. A canonical singleton org (`canonical_org`) or a PAVE
28
+ * 2.0-shape org (`foreign_row_shape`) is refused.
29
+ * 3. What already exists answers the add, looking only at rows the caller may
30
+ * know about, matched on the package identity rule ({@link pocIdentityKey}:
31
+ * `writein:<name>|<preferred email>`), never on a shared email: a visible
32
+ * tagged contact, else the caller's own pending add (both `created:
33
+ * false`, no write); the caller's own add that the partner removed is
34
+ * refused (`contact_deactivated`).
35
+ * 4. The caller's outstanding pending adds are capped per partner
36
+ * ({@link POC_IN_APP_PENDING_CAP_PER_PARTNER}) and across the network
37
+ * ({@link POC_IN_APP_PENDING_CAP_PER_ACTOR}): `too_many_pending_adds`.
38
+ * 5. The row is inserted `pending`, `origin: in_app`, `added_in_app: <app>`,
39
+ * version 1, after the whole-contact rules ({@link pocRuleViolations})
40
+ * and the index check ({@link checkPocIndexes}: the writer never creates
41
+ * an index; a missing one is `indexes_missing`, 503). A simultaneous
42
+ * identical add that won the insert (`duplicate_pending_add`) answers with
43
+ * the winner's row; an add that finds a cap exceeded after its insert
44
+ * withdraws itself (429).
45
+ *
46
+ * ## The caller's part
47
+ *
48
+ * The full contract is the package README ("Caller contract"). In short:
49
+ * `actor.id` is the advocate's Auth0 `sub`, taken server-side from the
50
+ * verified token, never from a request body; `app` is the caller's own server
51
+ * constant and the caller checks the advocate's `allowed_apps` for it; the
52
+ * handle is the deployment's own platform-db, long-lived, reading from the
53
+ * primary; `now` is never taken from a request. The platform's own write
54
+ * guard (`read_only_registry`) is not here.
55
+ *
56
+ * ## No driver import, no logging
57
+ *
58
+ * Like the reads, the handle is typed structurally ({@link PocWriteDbLike}):
59
+ * a `mongodb` `Db` or a mongoose connection's `.db` fits. The driver's
60
+ * `ObjectId` class is passed in ({@link PocWriterDriver}): it builds the
61
+ * ObjectId form of a 24-hex id (production `agencies._id` and
62
+ * `organizations._id` are ObjectIds) and mints the `poc-<hex>` id. Nothing is
63
+ * logged: a domain refusal is a returned code, never a throw, and no message
64
+ * carries a stored value (a contact's email, a driver error's duplicate key).
65
+ * A read or write ERROR (an outage, a stored row that does not parse,
66
+ * `PointOfContactShapeError`) propagates.
67
+ */
68
+
69
+ import { z } from "zod";
70
+
71
+ import { isAgencyOwnOrganization } from "../orgDirectory/rules.js";
72
+ import {
73
+ AGENCIES_COLLECTION,
74
+ ORGANIZATIONS_COLLECTION,
75
+ readAgencyOwnOrganization,
76
+ readDirectoryOrganization,
77
+ type OrgDirectoryReadOptions,
78
+ } from "../orgDirectory/read.js";
79
+ import type { PocDbLike } from "./reader.js";
80
+ import { normalizePointOfContact } from "./readRules.js";
81
+ import {
82
+ POC_IDENTITY_INDEX_FILTER,
83
+ POC_IN_APP_PENDING_INDEX_FILTER,
84
+ POC_IN_APP_PENDING_INDEX_KEY,
85
+ POC_PRIMARY_INDEX_FILTER,
86
+ POINTS_OF_CONTACT_COLLECTION,
87
+ POINT_OF_CONTACT_INDEXES,
88
+ PocInAppSchema,
89
+ pocIdentityKey,
90
+ pocRuleViolations,
91
+ type PocInApp,
92
+ type PocInAppInput,
93
+ type PocOwner,
94
+ type PointOfContactDoc,
95
+ } from "./schemas.js";
96
+ import {
97
+ POC_ADDED_IN_APPS,
98
+ REFERRALS_MAGIC_LINK_PURPOSE,
99
+ pocInitialStatus,
100
+ type PocAddedInApp,
101
+ type PocStatus,
102
+ } from "./vocabulary.js";
103
+
104
+ // ─── Handle and driver ───────────────────────────────────────────────
105
+
106
+ /** The slice of a driver cursor the writer uses. */
107
+ export interface PocWriteCursorLike {
108
+ toArray(): Promise<unknown[]>;
109
+ }
110
+
111
+ /** One entry of a driver `indexes()` (`listIndexes`) listing. */
112
+ export interface PocIndexInfoLike {
113
+ name?: unknown;
114
+ key?: unknown;
115
+ unique?: unknown;
116
+ partialFilterExpression?: unknown;
117
+ }
118
+
119
+ /** The options the writer passes to `createIndex`. */
120
+ export interface PocCreateIndexOptions {
121
+ name: string;
122
+ unique?: boolean;
123
+ partialFilterExpression?: Record<string, unknown>;
124
+ }
125
+
126
+ /** The slice of a driver `Collection` the writer uses. */
127
+ export interface PocWriteCollectionLike {
128
+ find(filter: Record<string, unknown>, options?: Record<string, unknown>): PocWriteCursorLike;
129
+ findOne(filter: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;
130
+ countDocuments(filter: Record<string, unknown>): Promise<number>;
131
+ insertOne(doc: Record<string, unknown>): Promise<unknown>;
132
+ deleteOne(filter: Record<string, unknown>): Promise<unknown>;
133
+ /** Used by the platform's {@link ensurePocIndexes} only; the writer never creates an index. */
134
+ createIndex(key: Record<string, 1 | -1>, options: PocCreateIndexOptions): Promise<unknown>;
135
+ indexes(): Promise<PocIndexInfoLike[]>;
136
+ }
137
+
138
+ /** The slice of a driver `Db` the writer uses: a platform-db handle the caller may write. */
139
+ export interface PocWriteDbLike {
140
+ collection(name: string): PocWriteCollectionLike;
141
+ }
142
+
143
+ /** The driver's ObjectId class (`mongodb`'s `ObjectId`, or `mongoose.Types.ObjectId`). */
144
+ export interface PocObjectIdClass {
145
+ new (hex?: string): { toHexString(): string };
146
+ }
147
+
148
+ /** What the writer needs from the caller's driver. */
149
+ export interface PocWriterDriver {
150
+ ObjectId: PocObjectIdClass;
151
+ }
152
+
153
+ // ─── Vocabulary of the in-app add ────────────────────────────────────
154
+
155
+ /** The apps an in-app add may come from: {@link POC_ADDED_IN_APPS} less `platform`. */
156
+ export type PocPartnerAddApp = Exclude<PocAddedInApp, "platform">;
157
+ export const POC_PARTNER_ADD_APPS = POC_ADDED_IN_APPS.filter(
158
+ (a): a is PocPartnerAddApp => a !== "platform",
159
+ ) as readonly PocPartnerAddApp[];
160
+
161
+ const directoryId = z.string().trim().min(1).max(200);
162
+
163
+ /**
164
+ * The partner the advocate picked or created, in the directory id universe
165
+ * (D1): `agency_id` = `String(agencies._id)` or any form that resolves to it,
166
+ * `org_id` = `String(organizations._id)`. One key, or both when they are a
167
+ * genuine mirror pair. The same keys as `listReferralContactsForPartner`, so
168
+ * an app writes and reads one partner the same way. Strict: a subject the
169
+ * body picks is refused.
170
+ */
171
+ export const PartnerContactSelectorSchema = z
172
+ .object({ agency_id: directoryId.optional(), org_id: directoryId.optional() })
173
+ .strict()
174
+ .refine((p) => Boolean(p.agency_id || p.org_id), {
175
+ message: "Name the partner's agency_id or org_id.",
176
+ });
177
+ export type PartnerContactSelector = z.infer<typeof PartnerContactSelectorSchema>;
178
+ export type PartnerContactSelectorInput = z.input<typeof PartnerContactSelectorSchema>;
179
+
180
+ /** Outstanding (pending, active) in-app adds one adder may have across the network. */
181
+ export const POC_IN_APP_PENDING_CAP_PER_ACTOR = 25;
182
+ /** Outstanding (pending, active) in-app adds one adder may have on one partner. */
183
+ export const POC_IN_APP_PENDING_CAP_PER_PARTNER = 5;
184
+
185
+ // ─── Indexes ─────────────────────────────────────────────────────────
186
+
187
+ /**
188
+ * One outstanding in-app add per adder, per subject and identity
189
+ * ({@link POC_IN_APP_PENDING_INDEX_KEY}: the stored `identity_key`, name +
190
+ * preferred email). Two simultaneous identical first adds race to the insert;
191
+ * the loser's E11000 maps to `duplicate_pending_add`, which
192
+ * {@link mintPartnerContact} answers with the winner's row: the index and the
193
+ * matcher ({@link pocRowsWithIdentity}) use the same key, so the re-read always
194
+ * finds the winner.
195
+ *
196
+ * Not keyed on emails: people share mailboxes (`intake@`), and a
197
+ * "shares ANY email" rule (an interim 0.30.0 platform build, multikey on
198
+ * `emails.value`) answered one person's add with another's row and let a
199
+ * removed row block every later add sharing a secondary mailbox.
200
+ */
201
+ export const POC_IN_APP_PENDING_INDEX = POINT_OF_CONTACT_INDEXES.inAppPending;
202
+ /** The steward's review queue, paged oldest first (platform `listPendingContacts`). */
203
+ export const POC_PENDING_QUEUE_INDEX = POINT_OF_CONTACT_INDEXES.pendingQueue;
204
+
205
+ const indexRuns = new WeakMap<object, Promise<void>>();
206
+
207
+ /**
208
+ * FOR THE PLATFORM (its deploy or boot), never an app's writer: Thread and
209
+ * PAVE hold no index privilege, and {@link mintPartnerContact} only checks
210
+ * the indexes ({@link checkPocIndexes}). The platform must deploy and run this
211
+ * before any app writes.
212
+ *
213
+ * Create the `pointsofcontact` indexes, the platform's full set: plain
214
+ * `createIndex` calls, idempotent (memoized per handle, retried after a
215
+ * failure; a failure propagates). No migration: no data or index existed
216
+ * before 0.30.0. The partial unique indexes are the store's uniqueness rules:
217
+ * no twin of one person among a subject's visible rows, at most one visible
218
+ * primary per subject, and one outstanding in-app add per adder, subject and
219
+ * identity ({@link POC_IN_APP_PENDING_INDEX}). Pass a long-lived handle: the
220
+ * memo is keyed on it.
221
+ */
222
+ export function ensurePocIndexes(db: PocWriteDbLike): Promise<void> {
223
+ const memo = indexRuns.get(db);
224
+ if (memo) return memo;
225
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
226
+ const ix = POINT_OF_CONTACT_INDEXES;
227
+ const run = (async () => {
228
+ await coll.createIndex({ id: 1 }, { name: ix.id, unique: true });
229
+ await coll.createIndex({ subject_type: 1, subject_id: 1, active: 1 }, { name: ix.subject });
230
+ await coll.createIndex({ agency_id: 1, purposes: 1, active: 1 }, { name: ix.agencyPurpose });
231
+ await coll.createIndex({ org_id: 1, purposes: 1, active: 1 }, { name: ix.orgPurpose });
232
+ await coll.createIndex({ status: 1 }, { name: ix.status });
233
+ await coll.createIndex(
234
+ { agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1 },
235
+ {
236
+ name: ix.identity,
237
+ unique: true,
238
+ partialFilterExpression: { ...POC_IDENTITY_INDEX_FILTER },
239
+ },
240
+ );
241
+ await coll.createIndex(
242
+ { agency_id: 1, subject_type: 1, subject_id: 1 },
243
+ { name: ix.primary, unique: true, partialFilterExpression: { ...POC_PRIMARY_INDEX_FILTER } },
244
+ );
245
+ await coll.createIndex(
246
+ { ...POC_IN_APP_PENDING_INDEX_KEY },
247
+ {
248
+ name: POC_IN_APP_PENDING_INDEX,
249
+ unique: true,
250
+ partialFilterExpression: { ...POC_IN_APP_PENDING_INDEX_FILTER },
251
+ },
252
+ );
253
+ await coll.createIndex({ status: 1, createdAt: 1, id: 1 }, { name: POC_PENDING_QUEUE_INDEX });
254
+ })().catch((err) => {
255
+ indexRuns.delete(db);
256
+ throw err;
257
+ });
258
+ indexRuns.set(db, run);
259
+ return run;
260
+ }
261
+
262
+ const indexesChecked = new WeakMap<object, true>();
263
+
264
+ const codeOf = (err: unknown) =>
265
+ err && typeof err === "object" ? (err as { code?: unknown }).code : undefined;
266
+ /** NamespaceNotFound: `listIndexes` on a collection that does not exist. */
267
+ const NAMESPACE_NOT_FOUND = 26;
268
+
269
+ const sameKey = (got: unknown, want: Record<string, number>) => {
270
+ if (!got || typeof got !== "object") return false;
271
+ const g = Object.entries(got);
272
+ const w = Object.entries(want);
273
+ return g.length === w.length && w.every(([k, v], i) => g[i][0] === k && Number(g[i][1]) === v);
274
+ };
275
+
276
+ const sameFilter = (got: unknown, want: Record<string, unknown> | undefined) => {
277
+ if (!want) return got === undefined || got === null;
278
+ if (!got || typeof got !== "object") return false;
279
+ const sorted = (o: object) =>
280
+ JSON.stringify(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : 1)));
281
+ return sorted(got) === sorted(want);
282
+ };
283
+
284
+ /** The indexes the writer's guarantees rest on: the `id` and in-app pending unique indexes. */
285
+ const REQUIRED_INDEXES: { key: Record<string, number>; filter?: Record<string, unknown> }[] = [
286
+ { key: { id: 1 } },
287
+ { key: { ...POC_IN_APP_PENDING_INDEX_KEY }, filter: { ...POC_IN_APP_PENDING_INDEX_FILTER } },
288
+ ];
289
+
290
+ /**
291
+ * Whether the indexes the writer relies on exist, read through `listIndexes`
292
+ * (the writer never creates one: least privilege; the platform creates them
293
+ * with {@link ensurePocIndexes}). Each required index must exist with exactly
294
+ * its key (fields, order, direction), `unique: true` and exactly its partial
295
+ * filter (under any name): `id` unique, and {@link POC_IN_APP_PENDING_INDEX}
296
+ * (the race recovery and the dedupe depend on it). A missing collection
297
+ * (NamespaceNotFound) or index refuses the write, `indexes_missing` (503):
298
+ * fail closed. A pass is memoized per handle; a refusal is not, so the next
299
+ * add re-checks. Any other read error propagates.
300
+ */
301
+ export async function checkPocIndexes(db: PocWriteDbLike): Promise<PartnerContactFailure | null> {
302
+ if (indexesChecked.has(db)) return null;
303
+ let listed: PocIndexInfoLike[];
304
+ try {
305
+ listed = await db.collection(POINTS_OF_CONTACT_COLLECTION).indexes();
306
+ } catch (err) {
307
+ if (codeOf(err) === NAMESPACE_NOT_FOUND) return INDEXES_MISSING;
308
+ throw err;
309
+ }
310
+ const present = REQUIRED_INDEXES.every((want) =>
311
+ listed.some(
312
+ (ix) =>
313
+ ix.unique === true &&
314
+ sameKey(ix.key, want.key) &&
315
+ sameFilter(ix.partialFilterExpression, want.filter),
316
+ ),
317
+ );
318
+ if (!present) return INDEXES_MISSING;
319
+ indexesChecked.set(db, true);
320
+ return null;
321
+ }
322
+
323
+ // ─── Results ─────────────────────────────────────────────────────────
324
+
325
+ /** Every refusal {@link mintPartnerContact} can return, as the platform route answers them. */
326
+ export const PARTNER_CONTACT_FAILURE_REASONS = [
327
+ "actor_required",
328
+ "invalid_app",
329
+ "invalid_contact",
330
+ "invalid_partner",
331
+ "owner_not_found",
332
+ "owner_mismatch",
333
+ "canonical_org",
334
+ "foreign_row_shape",
335
+ "contact_deactivated",
336
+ "too_many_pending_adds",
337
+ "duplicate_pending_add",
338
+ "duplicate_contact",
339
+ "primary_exists",
340
+ "duplicate_contact_id",
341
+ "duplicate_key",
342
+ "user_id_xor_person_id",
343
+ "seat_contact_has_own_reach",
344
+ "display_name_required",
345
+ "referral_contact_needs_email",
346
+ "indexes_missing",
347
+ ] as const;
348
+ export type PartnerContactFailureReason = (typeof PARTNER_CONTACT_FAILURE_REASONS)[number];
349
+
350
+ /**
351
+ * A domain refusal: `status` is the HTTP status the platform route answers it
352
+ * with, `reason` its code, `message` a fixed human sentence, or for
353
+ * `invalid_contact` / `invalid_partner` the schema's issue list (paths and
354
+ * rule messages). Never a stored value.
355
+ */
356
+ export interface PartnerContactFailure {
357
+ ok: false;
358
+ status: 400 | 409 | 429 | 503;
359
+ reason: PartnerContactFailureReason;
360
+ message?: string;
361
+ }
362
+
363
+ /** What an in-app add returns to the app: the contact's id and status, never another org's contact details. */
364
+ export interface PartnerContactReceipt {
365
+ id: string;
366
+ status: PocStatus;
367
+ /** False when an equivalent contact already existed and nothing was written. */
368
+ created: boolean;
369
+ /** Where the store put it: the partner's agency when the org has a genuine-mirror agency (kickoff D1), else the org. */
370
+ subject_type: PocOwner["subject_type"];
371
+ subject_id: string;
372
+ agency_id: string | null;
373
+ org_id: string | null;
374
+ }
375
+
376
+ export type PartnerContactResult =
377
+ | { ok: true; value: PartnerContactReceipt }
378
+ | PartnerContactFailure;
379
+
380
+ function fail(
381
+ status: PartnerContactFailure["status"],
382
+ reason: PartnerContactFailureReason,
383
+ message?: string,
384
+ ): PartnerContactFailure {
385
+ return { ok: false, status, reason, ...(message ? { message } : {}) };
386
+ }
387
+
388
+ const INDEXES_MISSING = fail(
389
+ 503,
390
+ "indexes_missing",
391
+ "The points-of-contact indexes are not in place; the platform must create them (ensurePocIndexes) before an app writes.",
392
+ );
393
+
394
+ const isFailure = (v: unknown): v is PartnerContactFailure =>
395
+ !!v && typeof v === "object" && (v as { ok?: unknown }).ok === false;
396
+
397
+ function invalid(
398
+ err: z.ZodError,
399
+ reason: "invalid_contact" | "invalid_partner",
400
+ ): PartnerContactFailure {
401
+ const issues = err.issues.map((i) => `${i.path.map(String).join(".") || "(body)"}: ${i.message}`);
402
+ return fail(400, reason, issues.join("; "));
403
+ }
404
+
405
+ // ─── Ids ─────────────────────────────────────────────────────────────
406
+
407
+ const HEX_24 = /^[0-9a-fA-F]{24}$/;
408
+ /** A 24-hex id in one spelling (lowercase), as `String(ObjectId)` prints it. */
409
+ const canonicalId = (v: string): string => (HEX_24.test(v) ? v.toLowerCase() : v);
410
+ const idOf = (v: unknown): string | null =>
411
+ v === null || v === undefined || v === "" ? null : String(v);
412
+
413
+ interface Ids {
414
+ /** Every stored form of one id: the string, plus its ObjectId when 24-hex. Feed to `$in`. */
415
+ forms(value: string): unknown[];
416
+ /** The org-directory reads' ObjectId factory. */
417
+ read: OrgDirectoryReadOptions;
418
+ /** A fresh `poc-<24 hex>` id. */
419
+ newId(): string;
420
+ }
421
+
422
+ function idsOf(driver: PocWriterDriver): Ids {
423
+ const { ObjectId } = driver;
424
+ return {
425
+ forms: (value) => (HEX_24.test(value) ? [value, new ObjectId(value)] : [value]),
426
+ read: { toObjectId: (hex) => new ObjectId(hex) },
427
+ newId: () => `poc-${new ObjectId().toHexString()}`,
428
+ };
429
+ }
430
+
431
+ // ─── Agency resolution (platform `resolveRecipientId`) ───────────────
432
+
433
+ const REGISTRY_AGENCIES_COLLECTION = "registry_agencies";
434
+ const AGENCY_PROJECTION = { projection: { _id: 1, entity_id: 1, id: 1 } };
435
+
436
+ interface AgencyRowLike {
437
+ _id?: unknown;
438
+ entity_id?: unknown;
439
+ id?: unknown;
440
+ }
441
+
442
+ /** Every string form that names a row: `entity_id`, `id`, `String(_id)`. */
443
+ function formsOf(row: AgencyRowLike): string[] {
444
+ const out: string[] = [];
445
+ if (typeof row.entity_id === "string" && row.entity_id !== "") out.push(row.entity_id);
446
+ if (typeof row.id === "string" && row.id !== "") out.push(row.id);
447
+ if (row._id !== undefined && row._id !== null) out.push(String(row._id));
448
+ return [...new Set(out)];
449
+ }
450
+
451
+ /** The three-id-universe agency match: `entity_id`, `id`, or `_id` in either stored form. */
452
+ const agencyIdFilter = (ids: Ids, agencyId: string): Record<string, unknown> => ({
453
+ $or: [{ entity_id: agencyId }, { id: agencyId }, { _id: { $in: ids.forms(agencyId) } }],
454
+ });
455
+
456
+ /** First an `agencies` row the form names; else a registry row it names, mapped to the `agencies` row carrying one of its forms. */
457
+ function resolveRecipient(
458
+ form: string,
459
+ agencies: readonly AgencyRowLike[],
460
+ registry: readonly AgencyRowLike[],
461
+ ): string | null {
462
+ const direct = agencies.find((a) => formsOf(a).includes(form));
463
+ if (direct) return String(direct._id);
464
+ const reg = registry.find((r) => formsOf(r).includes(form));
465
+ if (!reg) return null;
466
+ const regForms = formsOf(reg);
467
+ const mapped = agencies.find((a) => formsOf(a).some((f) => regForms.includes(f)));
468
+ return mapped ? String(mapped._id) : null;
469
+ }
470
+
471
+ /**
472
+ * `String(_id)` of the platform-db `agencies` row a form names, or null. The
473
+ * registry (`registry_agencies`) is read from the same handle: the platform
474
+ * writes only when its registry handle IS platform-db. Read errors propagate.
475
+ */
476
+ async function resolveAgencyId(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {
477
+ const agencies = db.collection(AGENCIES_COLLECTION);
478
+ const direct = (await agencies
479
+ .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)
480
+ .toArray()) as AgencyRowLike[];
481
+ if (direct.length > 0) return resolveRecipient(form, direct, []);
482
+ const registry = (await db
483
+ .collection(REGISTRY_AGENCIES_COLLECTION)
484
+ .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)
485
+ .toArray()) as AgencyRowLike[];
486
+ if (registry.length === 0) return null;
487
+ const regForms = formsOf(registry[0]);
488
+ const mapped = (await agencies
489
+ .find({ $or: regForms.map((f) => agencyIdFilter(ids, f)) }, AGENCY_PROJECTION)
490
+ .toArray()) as AgencyRowLike[];
491
+ return resolveRecipient(form, mapped, registry);
492
+ }
493
+
494
+ /** The stored agency key of a form, canonical, or null. */
495
+ async function agencyKey(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {
496
+ const id = await resolveAgencyId(db, ids, canonicalId(form));
497
+ return id ? canonicalId(id) : null;
498
+ }
499
+
500
+ // ─── Owner (platform `resolveOwner`, agency and org subjects) ────────
501
+
502
+ const OWNER_NOT_FOUND = fail(
503
+ 400,
504
+ "owner_not_found",
505
+ "The contact's owner does not resolve to a platform agency or organization.",
506
+ );
507
+ const OWNER_MISMATCH = fail(
508
+ 400,
509
+ "owner_mismatch",
510
+ "The agency and organization named are not the same partner.",
511
+ );
512
+
513
+ /** The agency whose OWN organization `org` is (both halves of the pair), or null. */
514
+ async function genuineMirrorAgency(
515
+ db: PocWriteDbLike,
516
+ ids: Ids,
517
+ org: Record<string, unknown>,
518
+ ): Promise<string | null> {
519
+ const declared = idOf(org.agencyId);
520
+ if (!declared) return null;
521
+ const agency = (await db
522
+ .collection(AGENCIES_COLLECTION)
523
+ .findOne(
524
+ { _id: { $in: ids.forms(canonicalId(declared)) } },
525
+ { projection: { _id: 1, organizationId: 1 } },
526
+ )) as { _id?: unknown; organizationId?: unknown } | null;
527
+ if (!agency || !isAgencyOwnOrganization(org, agency)) return null;
528
+ return agencyKey(db, ids, String(agency._id));
529
+ }
530
+
531
+ /**
532
+ * The selector → the stored owner. An agency names the agency subject (an org
533
+ * named with it must be its genuine mirror); an org alone names the org
534
+ * subject, rewritten to its genuine-mirror agency when it has one (kickoff
535
+ * D1). Rows carry the other key only when the pair is a genuine mirror.
536
+ */
537
+ async function resolvePartnerOwner(
538
+ db: PocWriteDbLike,
539
+ ids: Ids,
540
+ p: PartnerContactSelector,
541
+ ): Promise<PocOwner | PartnerContactFailure> {
542
+ let agencyId: string | null = null;
543
+ if (p.agency_id) {
544
+ agencyId = await agencyKey(db, ids, p.agency_id);
545
+ if (!agencyId) return OWNER_NOT_FOUND;
546
+ }
547
+
548
+ let org: Record<string, unknown> | null = null;
549
+ if (p.org_id) {
550
+ org = (await db
551
+ .collection(ORGANIZATIONS_COLLECTION)
552
+ .findOne(
553
+ { _id: { $in: ids.forms(canonicalId(p.org_id)) } },
554
+ { projection: { _id: 1, agencyId: 1 } },
555
+ )) as Record<string, unknown> | null;
556
+ if (!org) return OWNER_NOT_FOUND;
557
+ }
558
+ const orgId = org ? canonicalId(String(org._id)) : null;
559
+
560
+ if (!agencyId) {
561
+ if (!org || !orgId) return OWNER_NOT_FOUND;
562
+ const mirrorAgency = await genuineMirrorAgency(db, ids, org);
563
+ if (mirrorAgency) {
564
+ return {
565
+ subject_type: "agency",
566
+ subject_id: mirrorAgency,
567
+ agency_id: mirrorAgency,
568
+ org_id: orgId,
569
+ };
570
+ }
571
+ return { subject_type: "org", subject_id: orgId, agency_id: null, org_id: orgId };
572
+ }
573
+
574
+ const own = await readAgencyOwnOrganization(db, agencyId, ids.read);
575
+ const mirrorOrg = own ? canonicalId(own.id) : null;
576
+ if (orgId && orgId !== mirrorOrg) return OWNER_MISMATCH;
577
+ return { subject_type: "agency", subject_id: agencyId, agency_id: agencyId, org_id: mirrorOrg };
578
+ }
579
+
580
+ /**
581
+ * The partner's organization row must be one an in-app add may name: never a
582
+ * canonical singleton (Unknown, Anonymous) and never a PAVE 2.0-shape row, the
583
+ * shapes the org directory also refuses (`organizationRowShape`).
584
+ */
585
+ async function refuseForeignPartnerOrg(
586
+ db: PocWriteDbLike,
587
+ ids: Ids,
588
+ orgId: string | null,
589
+ ): Promise<PartnerContactFailure | null> {
590
+ if (!orgId) return null;
591
+ const org = await readDirectoryOrganization(db, orgId, ids.read);
592
+ if (org?.shape === "canonical") {
593
+ return fail(409, "canonical_org", "A canonical singleton organization is not a partner.");
594
+ }
595
+ if (org?.shape === "pave") {
596
+ return fail(
597
+ 409,
598
+ "foreign_row_shape",
599
+ "This organization is a PAVE 2.0-shape row; an in-app contact is not added to it.",
600
+ );
601
+ }
602
+ return null;
603
+ }
604
+
605
+ // ─── Existing rows ───────────────────────────────────────────────────
606
+
607
+ /**
608
+ * The rows on the resolved subject with this identity ({@link pocIdentityKey},
609
+ * as stored in `identity_key`), any status or activity: the same key as
610
+ * {@link POC_IN_APP_PENDING_INDEX}, so a raced add always finds the row that
611
+ * won. The index and this matcher must agree, which is why both live here.
612
+ * A row that does not parse throws.
613
+ */
614
+ export async function pocRowsWithIdentity(
615
+ db: PocDbLike,
616
+ owner: Pick<PocOwner, "agency_id" | "subject_type" | "subject_id">,
617
+ identityKey: string,
618
+ ): Promise<PointOfContactDoc[]> {
619
+ const raw = await db
620
+ .collection(POINTS_OF_CONTACT_COLLECTION)
621
+ .find({
622
+ agency_id: owner.agency_id,
623
+ subject_type: owner.subject_type,
624
+ subject_id: owner.subject_id,
625
+ identity_key: identityKey,
626
+ })
627
+ .toArray();
628
+ return raw
629
+ .map((r) => normalizePointOfContact(r as Record<string, unknown>))
630
+ .filter((d) => d.identity_key === identityKey);
631
+ }
632
+
633
+ /** The add's identity: a write-in, keyed on its name and preferred email. */
634
+ const identityOf = (body: PocInApp) =>
635
+ pocIdentityKey({
636
+ user_id: null,
637
+ person_id: null,
638
+ display_name: body.display_name,
639
+ emails: body.emails,
640
+ });
641
+
642
+ const ownInApp = (d: PointOfContactDoc, actorId: string) =>
643
+ d.origin === "in_app" && d.createdBy === actorId;
644
+
645
+ /**
646
+ * What an in-app add of `body` on the resolved subject already is, looking
647
+ * only at rows the caller may know about (no oracle for the rest):
648
+ * - `visible`: an active, confirmed, not confidential contact with the same
649
+ * identity that already carries every purpose asked for. Preferred.
650
+ * - `own_pending`: the caller's own outstanding in-app add of the identity.
651
+ * - `own_deactivated`: the caller's own in-app add of the identity that the
652
+ * partner (or the steward) has since removed. Re-adding it is refused.
653
+ * Another adder's pending row, a confidential contact, a contact without the
654
+ * purposes and a contact someone else removed never match: such an add lands
655
+ * as a new pending row, the steward's duplicate to resolve.
656
+ */
657
+ function classifyExisting(rows: PointOfContactDoc[], body: PocInApp, actorId: string) {
658
+ const visible = rows.find(
659
+ (d) =>
660
+ d.active &&
661
+ d.status === "confirmed" &&
662
+ !d.is_confidential &&
663
+ body.purposes.every((p) => d.purposes.includes(p)),
664
+ );
665
+ if (visible) return { kind: "visible" as const, doc: visible };
666
+ const pending = rows.find((d) => d.active && d.status === "pending" && ownInApp(d, actorId));
667
+ if (pending) return { kind: "own_pending" as const, doc: pending };
668
+ const removed = rows.find((d) => !d.active && ownInApp(d, actorId));
669
+ if (removed) return { kind: "own_deactivated" as const, doc: removed };
670
+ return null;
671
+ }
672
+
673
+ // ─── Caps ────────────────────────────────────────────────────────────
674
+
675
+ /** The adder's two caps: outstanding pending in-app adds on this partner, and across the network. */
676
+ function pendingCaps(owner: PocOwner, actorId: string) {
677
+ const mine = { createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER };
678
+ return [
679
+ {
680
+ filter: {
681
+ ...mine,
682
+ agency_id: owner.agency_id,
683
+ subject_type: owner.subject_type,
684
+ subject_id: owner.subject_id,
685
+ },
686
+ cap: POC_IN_APP_PENDING_CAP_PER_PARTNER,
687
+ refusal: fail(
688
+ 429,
689
+ "too_many_pending_adds",
690
+ `At most ${POC_IN_APP_PENDING_CAP_PER_PARTNER} contacts you added to one partner can wait for HTI Labs at a time.`,
691
+ ),
692
+ },
693
+ {
694
+ filter: mine,
695
+ cap: POC_IN_APP_PENDING_CAP_PER_ACTOR,
696
+ refusal: fail(
697
+ 429,
698
+ "too_many_pending_adds",
699
+ `At most ${POC_IN_APP_PENDING_CAP_PER_ACTOR} contacts you added can wait for HTI Labs at a time.`,
700
+ ),
701
+ },
702
+ ];
703
+ }
704
+
705
+ /** The early refusal: the adder is already at a cap before inserting. */
706
+ async function checkPendingCaps(
707
+ db: PocWriteDbLike,
708
+ owner: PocOwner,
709
+ actorId: string,
710
+ ): Promise<PartnerContactFailure | null> {
711
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
712
+ for (const c of pendingCaps(owner, actorId)) {
713
+ if ((await coll.countDocuments(c.filter)) >= c.cap) return c.refusal;
714
+ }
715
+ return null;
716
+ }
717
+
718
+ /**
719
+ * The binding check, after the insert: the count above and the insert are
720
+ * not atomic, so parallel adds can all pass it. Each new row counts the
721
+ * adder's pending rows (per partner, then across the network) AFTER its own
722
+ * insert; over the cap, it deletes itself and the add is 429. This bounds
723
+ * the outcome at the cap: every surviving row counted at most `cap` rows, and
724
+ * the survivor that counted last counted every survivor (each was inserted
725
+ * before its own count), so no more than `cap` survive. The price is a
726
+ * spurious 429 under contention (a burst may withdraw rows that would have
727
+ * fit; a retry then lands). It holds only if every count reads the primary
728
+ * (README "Caller contract"). The row was never acknowledged to anyone, so
729
+ * this is not the "deactivate, never delete" removal of a contact.
730
+ */
731
+ async function overCapAfterInsert(
732
+ db: PocWriteDbLike,
733
+ owner: PocOwner,
734
+ actorId: string,
735
+ id: string,
736
+ ): Promise<PartnerContactFailure | null> {
737
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
738
+ for (const c of pendingCaps(owner, actorId)) {
739
+ if ((await coll.countDocuments(c.filter)) > c.cap) {
740
+ await coll.deleteOne({ id, createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER });
741
+ return c.refusal;
742
+ }
743
+ }
744
+ return null;
745
+ }
746
+
747
+ // ─── Insert ──────────────────────────────────────────────────────────
748
+
749
+ /**
750
+ * A duplicate-key error → the refusal for the index it hit, or null when the
751
+ * error is not a duplicate key (the caller rethrows). Mapped per index by
752
+ * name, then by key pattern. The driver's message is never returned: it
753
+ * echoes the duplicate key, i.e. the contact's email.
754
+ */
755
+ export function pocDuplicateKeyFailure(err: unknown): PartnerContactFailure | null {
756
+ if (!err || typeof err !== "object") return null;
757
+ const e = err as { code?: unknown; message?: unknown; keyPattern?: Record<string, unknown> };
758
+ const msg = typeof e.message === "string" ? e.message : "";
759
+ if (e.code !== 11000 && !/E11000/.test(msg)) return null;
760
+ const ix = POINT_OF_CONTACT_INDEXES;
761
+ const keys = Object.keys(e.keyPattern ?? {}).join(",");
762
+ if (msg.includes(POC_IN_APP_PENDING_INDEX) || keys.includes("createdBy")) {
763
+ return fail(
764
+ 409,
765
+ "duplicate_pending_add",
766
+ "This adder already has a pending add of this person on this subject.",
767
+ );
768
+ }
769
+ if (msg.includes(ix.primary) || keys === "agency_id,subject_type,subject_id") {
770
+ return fail(
771
+ 409,
772
+ "primary_exists",
773
+ "The subject already has a primary contact. Use setPrimary to move it.",
774
+ );
775
+ }
776
+ if (msg.includes(ix.identity) || keys.includes("identity_key")) {
777
+ return fail(409, "duplicate_contact", "This person is already an active contact on this subject.");
778
+ }
779
+ if (msg.includes(ix.id) || keys === "id") {
780
+ return fail(409, "duplicate_contact_id", "A contact with this id exists.");
781
+ }
782
+ return fail(409, "duplicate_key", "The contact collides with a unique index.");
783
+ }
784
+
785
+ /**
786
+ * Build, check and insert one in-app contact: `active`, version 1, `pending`
787
+ * (D3: `pocInitialStatus("in_app")`), unstamped, no seat or person link, not
788
+ * primary, not confidential, no notes.
789
+ */
790
+ async function insertInAppContact(
791
+ db: PocWriteDbLike,
792
+ f: {
793
+ id: string;
794
+ owner: PocOwner;
795
+ body: PocInApp;
796
+ app: PocPartnerAddApp;
797
+ actorId: string;
798
+ now: Date;
799
+ },
800
+ ): Promise<{ ok: true; value: PointOfContactDoc } | PartnerContactFailure> {
801
+ const at = f.now.toISOString();
802
+ const base = {
803
+ user_id: null,
804
+ person_id: null,
805
+ display_name: f.body.display_name,
806
+ emails: f.body.emails,
807
+ phones: f.body.phones ?? [],
808
+ };
809
+ const doc: PointOfContactDoc = {
810
+ id: f.id,
811
+ subject_type: f.owner.subject_type,
812
+ subject_id: f.owner.subject_id,
813
+ agency_id: f.owner.agency_id,
814
+ org_id: f.owner.org_id,
815
+ ...base,
816
+ purposes: f.body.purposes,
817
+ urgent_methods: f.body.urgent_methods ?? [],
818
+ is_primary: false,
819
+ is_confidential: false,
820
+ active: true,
821
+ notes: null,
822
+ status: pocInitialStatus("in_app"),
823
+ origin: "in_app",
824
+ added_in_app: f.app,
825
+ identity_key: pocIdentityKey(base),
826
+ confirmed_by: null,
827
+ confirmed_at: null,
828
+ deactivated_by: null,
829
+ deactivated_at: null,
830
+ version: 1,
831
+ createdBy: f.actorId,
832
+ createdAt: at,
833
+ updatedBy: f.actorId,
834
+ updatedAt: at,
835
+ };
836
+
837
+ const [broken] = pocRuleViolations(doc);
838
+ if (broken) return fail(400, broken.reason, broken.message);
839
+
840
+ const noIndexes = await checkPocIndexes(db);
841
+ if (noIndexes) return noIndexes;
842
+ try {
843
+ await db.collection(POINTS_OF_CONTACT_COLLECTION).insertOne({ ...doc });
844
+ } catch (err) {
845
+ const dup = pocDuplicateKeyFailure(err);
846
+ if (dup) return dup;
847
+ throw err;
848
+ }
849
+ return { ok: true, value: doc };
850
+ }
851
+
852
+ // ─── The writer ──────────────────────────────────────────────────────
853
+
854
+ /** Who is adding: the advocate. Never a steward here. */
855
+ export interface PocInAppActor {
856
+ /**
857
+ * The advocate's Auth0 `sub`, taken SERVER-SIDE from the verified token
858
+ * (as the platform route takes `auth0Sub`), never from a request body or a
859
+ * client-supplied header. Stored as `createdBy`; the adder's dedupe, caps and
860
+ * removed-add refusal key on it.
861
+ */
862
+ id: string;
863
+ }
864
+
865
+ export interface MintPartnerContactArgs {
866
+ /** The app the advocate is adding from. */
867
+ app: PocPartnerAddApp;
868
+ /** The partner, by directory id ({@link PartnerContactSelectorSchema}). */
869
+ partner: PartnerContactSelectorInput;
870
+ /** The contact ({@link PocInAppSchema}: a name and at least one email; phones optional). */
871
+ contact: PocInAppInput;
872
+ actor: PocInAppActor;
873
+ /** The mint time (`createdAt`); defaults to now. Server time only, never from a request. */
874
+ now?: Date;
875
+ }
876
+
877
+ /**
878
+ * An in-app add is ALWAYS tagged Referrals (magic link) (Crysta 2026-10-14;
879
+ * kickoff D1): an explicit `[]` or a list without it gets it added in front;
880
+ * any other purposes asked for are kept.
881
+ */
882
+ function withReferralTag(purposes: PocInApp["purposes"]): PocInApp["purposes"] {
883
+ return [
884
+ REFERRALS_MAGIC_LINK_PURPOSE,
885
+ ...purposes.filter((p) => p !== REFERRALS_MAGIC_LINK_PURPOSE),
886
+ ];
887
+ }
888
+
889
+ /**
890
+ * The in-app partner add, written straight to platform-db (module comment).
891
+ * Every argument is validated at run time as well as typed. Returns a
892
+ * {@link PartnerContactReceipt} (`created: true` for a new pending row,
893
+ * `false` when an equivalent contact answered and nothing was written) or a
894
+ * {@link PartnerContactFailure}; never throws a domain refusal.
895
+ */
896
+ export async function mintPartnerContact(
897
+ db: PocWriteDbLike,
898
+ args: MintPartnerContactArgs,
899
+ driver: PocWriterDriver,
900
+ ): Promise<PartnerContactResult> {
901
+ const actor = args.actor as unknown;
902
+ const actorId =
903
+ actor && typeof actor === "object" ? (actor as { id?: unknown }).id : undefined;
904
+ if (typeof actorId !== "string" || actorId.trim().length === 0) {
905
+ return fail(400, "actor_required", "An in-app add names the advocate (their Auth0 sub).");
906
+ }
907
+ if (!(POC_PARTNER_ADD_APPS as readonly unknown[]).includes(args.app)) {
908
+ return fail(400, "invalid_app", `An in-app add names its app: ${POC_PARTNER_ADD_APPS.join(", ")}.`);
909
+ }
910
+ const parsed = PocInAppSchema.safeParse(args.contact);
911
+ if (!parsed.success) return invalid(parsed.error, "invalid_contact");
912
+ const body: PocInApp = { ...parsed.data, purposes: withReferralTag(parsed.data.purposes) };
913
+ const partner = PartnerContactSelectorSchema.safeParse(args.partner);
914
+ if (!partner.success) return invalid(partner.error, "invalid_partner");
915
+
916
+ const ids = idsOf(driver);
917
+ const owner = await resolvePartnerOwner(db, ids, partner.data);
918
+ if (isFailure(owner)) return owner;
919
+ const foreign = await refuseForeignPartnerOrg(db, ids, owner.org_id);
920
+ if (foreign) return foreign;
921
+
922
+ const receipt = (d: PointOfContactDoc, created: boolean): PartnerContactResult => ({
923
+ ok: true,
924
+ value: {
925
+ id: d.id,
926
+ status: d.status,
927
+ created,
928
+ subject_type: owner.subject_type,
929
+ subject_id: owner.subject_id,
930
+ agency_id: owner.agency_id,
931
+ org_id: owner.org_id,
932
+ },
933
+ });
934
+ const existingNow = async () =>
935
+ classifyExisting(await pocRowsWithIdentity(db, owner, identityOf(body)), body, actorId);
936
+
937
+ const existing = await existingNow();
938
+ if (existing?.kind === "own_deactivated") {
939
+ return fail(
940
+ 409,
941
+ "contact_deactivated",
942
+ "You added this contact before and it has since been removed from the partner; it is not added again.",
943
+ );
944
+ }
945
+ if (existing) return receipt(existing.doc, false);
946
+
947
+ const capped = await checkPendingCaps(db, owner, actorId);
948
+ if (capped) return capped;
949
+
950
+ const r = await insertInAppContact(db, {
951
+ id: ids.newId(),
952
+ owner,
953
+ body,
954
+ app: args.app,
955
+ actorId,
956
+ now: args.now ?? new Date(),
957
+ });
958
+ if (!r.ok) {
959
+ if (r.reason !== "duplicate_pending_add") return r;
960
+ // A simultaneous identical add won the insert: answer with its row.
961
+ const raced = await existingNow();
962
+ return raced && raced.kind !== "own_deactivated" ? receipt(raced.doc, false) : r;
963
+ }
964
+ const overCap = await overCapAfterInsert(db, owner, actorId, r.value.id);
965
+ if (overCap) return overCap;
966
+ return receipt(r.value, true);
967
+ }