Compare commits

...
Author SHA1 Message Date
Jose Olarte III 6c50975d3c Merge branch 'master' into api-notification-digest 2026-10-26 10:47:48 -04:00
trentlarson f5f1ae4128 update FCM push notifications to behave like SMS (see recent changes) 2026-10-25 15:32:05 -06:00
trentlarson f6dce1003d restrict the send-multiple-SMS-per-day to authorized users 2026-10-25 13:57:21 -06:00
trentlarson 1b4b14ca19 allow sending of SMS notification if they turn off-and-on, even if they have already been checked or sent one today 2026-10-25 13:38:50 -06:00
trentlarson 7d4b6f3db8 bump version and add "-beta" 2026-10-25 13:28:29 -06:00
trentlarson a1e62dd2dc bump to version 0.2.6 2026-10-24 22:10:55 -06:00
trentlarson 5d3f589b5d add an SMS-watch utility 2026-10-24 22:07:30 -06:00
Jose Olarte III daeb7248e0 Merge branch 'master' into api-notification-digest 2026-10-21 16:39:07 -04:00
Jose Olarte III fc3cbd2bc0 Add a local command that sends one alert_search FCM to a chosen device so a notification tap can be tested without a daily run. 2026-10-20 11:35:27 -04:00
trentlarson 3f3736e81b bump version and add "-beta" 2026-10-19 11:21:26 -06:00
Jose Olarte III 0709c4f5c1 Put the AlertSearch update count in the FCM title so the body lists only the category lines. 2026-10-19 11:36:14 -04:00
trentlarson 3d2e3ae8aa bump to version 0.2.5 2026-10-18 15:36:31 -06:00
trentlarson e14a65d210 fix and finish the alertSearch query & results 2026-10-16 09:14:44 -06:00
trentlarson 0c67bfbc9b add /deep-link/new-activity on the end of the URL in SMS texts 2026-10-15 19:49:58 -06:00
trentlarson cdd84643db rename to "MESSAGE_ENV_LABEL" for both push & SMS 2026-10-15 19:44:00 -06:00
trentlarson ce6111d72b add to SMS text on certain environments 2026-10-15 19:29:31 -06:00
Jose Olarte III e60f6a7c83 Announce the same deduped AlertSearch total in FCM and SMS, and drop the claims category the query never returns. 2026-10-14 12:38:44 -04:00
Jose Olarte III 1781910504 Break the daily AlertSearch push down by update type so a give, an offer, and a nearby or similar match are not all reported as a bare total. 2026-10-14 12:20:39 -04:00
trentlarson a8d20f9f12 bump to version 0.2.4 2026-10-13 19:50:05 -06:00
trentlarson 19c1291ab5 send only new cursors to alertSearch; drop the ID-path handoff 2026-10-13 13:05:36 -06:00
trentlarson 84c4163e31 change after & before from jwtIds to new cursors 2026-10-13 12:37:23 -06:00
trentlarson f9f9774c12 doc: small tweaks to SMS plan 2026-10-05 21:34:32 -06:00
trentlarson 4db216a034 bump to version 0.2.3 2026-10-05 21:33:12 -06:00
Jose Olarte III 45dede8dfe Merge branch 'retire-legacy-notification' 2026-09-28 16:17:42 +08:00
trentlarson 32efcdf656 bump version and add '-beta' 2026-09-27 16:24:27 -06:00
Jose Olarte III 84b11e1fc8 Drop retired /notifications/refresh from the auth docs. 2026-09-25 15:10:57 +08:00
Jose Olarte III 2d2aeb2c3a Remove legacy /notifications/refresh and WAKEUP_PING producer. 2026-09-22 20:46:01 +08:00
Jose Olarte III 51b2c57e7d Stop starting the legacy WAKEUP_PING FCM scheduler. 2026-09-22 18:01:03 +08:00
55 changed files with 4560 additions and 5593 deletions
+14
View File
@@ -26,6 +26,11 @@
# Leave off in production; the routes expose per-device state to any accepted JWT.
# DEBUG_ENDPOINT=false
# Appended as " (<label>)" to every SMS and push body, so a recipient can tell
# which server sent it. NODE_ENV cannot do this: the Docker image sets it to
# "production" everywhere. Unset or blank appends nothing.
# MESSAGE_ENV_LABEL=test
# --- SMS notifications (/notify-sms) ---
# Master switch. While false, every /notify-sms route returns 503 SMS_DISABLED
@@ -75,3 +80,12 @@
# sms_blocked_numbers table that the STOP webhook writes to. Normalized before
# comparison, so formatting does not defeat them.
# SMS_BLOCKED_NUMBERS=+15555550123,+15555550124
# DIDs that may get more than one alert push in a UTC day, after a reset that
# sends rerunToday (for testing). Every other DID gets at most one a day.
# PUSH_SAME_DAY_RESEND_DIDS=did:ethr:0x0000000000000000000000000000000000000000
# Numbers that may get more than one alert text in a UTC day, after a reset
# that sends rerunToday (for testing). Every other number gets at most one a
# day. Normalized before comparison.
# SMS_SAME_DAY_RESEND_NUMBERS=+15555550123
+44 -2
View File
@@ -7,12 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Changed
- If someone turns off and on their notification in the same day and changes their time to the future, it will send at that time (even though it's already checked and maybe sent one today).
### Changed in DB or environment
- SMS_SAME_DAY_RESEND_NUMBERS to allow multiple notification messages in a day
## [0.2.6] - 2026.10.24
### Added
- `sms_alert_search_runs` records every SMS daily run: outcomes, counts, the full records found, and whether a text went out.
- `src/tools/smsWatch.ts` (`pnpm run sms:watch`, or `node dist/tools/smsWatch.js` in the image): a live terminal view of recent SMS runs, upcoming runs with their phones, and the phone log, with a preview that runs a user's next query without consuming anything.
### Changed in DB or environment
- New table `sms_alert_search_runs`, created on startup and pruned to 30 days.
## [0.2.5] - 2026.10.18
### Added
- The SMS link and the push data carry `c`, the cursors the run counted from.
- Both alert-authorization routes accept optional `endorserAfterCursor`, `partnerAfterCursor`, `planHandleIds` and `location`; the cursors replace the channel's stored cursors, and the other two are sent to alertSearch on every run.
- `profilesSimilar` and `plansSimilar` count in the digest.
- Optional `MESSAGE_ENV_LABEL` appends ` (<label>)` to every SMS and push body, so a recipient can tell which server sent it; unset or blank appends nothing. `NODE_ENV` cannot serve, since the Docker image sets it to `production` on every server.
### Changed
- The SMS digest links to `https://giftopia.me/deep-link/new-activity` instead of the bare `https://giftopia.me`.
- A first run (no stored cursor) only stores the cursor and reports nothing, instead of reporting the server's most recent rows.
### Fixed
- The daily run sent no starred plans or area, so the tracked-plan and nearby lists were always empty.
- When one source completed and the other failed, the completed source's cursor moved anyway, and its rows were never counted on the retry; both cursors now move together or not at all.
- A batch uploaded after today's run installed an unused JWT for today, so the run (and the push) could repeat the same day; days with a consumed JWT are skipped.
### Changed in DB or environment
- `alert_search_cursors` and `sms_alert_search_cursors` gain `plan_handle_ids` and `location` columns, added on startup.
- `MESSAGE_ENV_LABEL` (see above) on test environment
## [0.2.4] - 2026.10.13
### Changed
- The alertSearch cursors are the servers' `nextAfterCursor` values, sent back as `afterCursor`, so no item is missed or repeated. Requires endorser-ch 4.4.7 or later on both endpoints: a response without `nextAfterCursor` is an error, and nothing is notified.
### Changed in DB or environment
- Deploy after endorser-ch 4.4.7. On startup, `alert_search_cursors` and `sms_alert_search_cursors` from 0.2.3 and earlier (columns `endorser_after_id`, `partner_after_at`) are dropped and created again with `endorser_after_cursor` and `partner_after_cursor`; each user's next run is a first run, which reports the server's most recent rows.
- A 400 from alertSearch counts as an authorization failure only when its error says so; its error text is in the log message.
## [0.2.3] - 2026.09.28
### Changed
- `POST /notifications/alert-authorization` and `POST /notify-sms/alert-authorization` replace `PUT` for installing a delegated JWT batch; path and payload are unchanged
- Digest FCM and SMS bodies use singular “update” when the count is one
## [0.2.2] - 2026.09.22
### Changed
- `POST /notifications/alert-authorization` and `POST /notify-sms/alert-authorization` replace `PUT` for installing a delegated JWT batch; path and payload are unchanged
- Digest FCM and SMS bodies use singular “update” when the count is one
- `SMS_ENABLED`, `SMS_REQUIRE_ACTION_CLAIM`, and `SMS_DEV_ECHO_CODE` parse like `DEBUG_ENDPOINT`: trimmed, case-insensitive, accepting `true`/`1`/`yes`/`on` and `false`/`0`/`no`/`off`. (A trailing space from `docker run --env-file` no longer silently turns SMS off, and an unrecognized `SMS_REQUIRE_ACTION_CLAIM` keeps the claim required instead of disabling it.)
+23 -7
View File
@@ -6,12 +6,25 @@ a real handset.
## Goal
Deliver the daily alertSearch digest by SMS as well as by FCM. A user registers
Deliver the daily alertSearch digest by SMS. A user registers
a phone number, proves possession of it with a 6-digit code, authorizes a batch
of delegated alertSearch JWTs for the SMS channel, and receives at most one text
per local day when that day's retrieval finds updates — at an hour of their
per local day when that day's retrieval finds updates — at a time of their
choosing, and only until they revoke the authorization.
The Endorser & Partner server checks that it attempts are:
- claims issued by someone else that name the user as either `toEntity` or
`fromEntity` (`claims`);
- `GiveAction` and `Offer` claims associated with a plan the user owns or
represents as its agent (`personalPlanContributions`);
- changes to plans the user tracks (`trackedPlanUpdates`);
- `GiveAction` and `Offer` claims that reference plans the user tracks
(`trackedPlanClaims`);
- plans created or changed inside the user's selected geographic area
(`plansNearby`); and
- profiles created or changed inside that area (`profilesNearby`).
Every phone action is authorized by a JWT that names the action and the phone
number it applies to, and every phone action is recorded.
@@ -24,7 +37,7 @@ next to the FCM one. Plus one FCM-side addition: `DELETE
user turning alerts off means both channels and only one of them had a way to
say so.
Out of scope: changing how the FCM channel searches or delivers, changing
Out of scope: changing current FCM channel searches or delivers,
`WAKEUP_PING`, MMS, inbound conversational SMS beyond opt-out keywords, and
international sender registration beyond US A2P 10DLC. The notification hour is
an SMS-channel setting; the FCM scheduler does not read it.
@@ -493,7 +506,7 @@ carries its purpose as a SQL comment, which SQLite preserves verbatim in
### `sms_alert_search_cursors`
`user_id` PK, `endorser_after_id`, `partner_after_at`, `created_at`,
`user_id` PK, `endorser_after_cursor`, `partner_after_cursor`, `created_at`,
`updated_at`. Same shape as `alert_search_cursors`.
This table is not optional decoration. `alert_search_cursors` holds one row per
@@ -528,10 +541,11 @@ everywhere, so no existing call site or test changes.
"already texted today" flag is needed.
- Recipients: `sms_registrations` rows for the DID with `verified = 1`,
deduplicated by number.
- Body: `Gift Economies: you have N new updates. https://giftopia.me` plus
- Body: `Gift Economies: you have N new updates. https://giftopia.me/deep-link/new-activity` plus
`Reply STOP to end.` Kept inside 160 GSM-7 characters — a second segment is a
second charge for the privilege of a longer sentence. The link is
`https://giftopia.me`; `https://giftopia.tech` is the claim `@context`
the app's `https://giftopia.me/deep-link/new-activity` deep link;
`https://giftopia.tech` is the claim `@context`
namespace and never appears in a message.
- Each send writes `alert-sent` or `alert-send-failed` to `sms_phone_log` with
the provider message id. Send failures are logged and do not roll back cursor
@@ -885,7 +899,9 @@ sends a real message.
- **Single replica.** The SMS scheduler's in-flight guard is process-local,
exactly like the other two. A second replica double-texts.
## Rejected
## History
### Rejected
**One shared JWT inventory across channels.** `/notify-sms/alert-authorization`
would write into `alert_authorization_*`, one daily retrieval per user would
+89 -13
View File
@@ -32,11 +32,17 @@ On first use, the service creates `NOTIFY_DATA_DIR` (default `./data`) and the S
### Authentication
`POST /notifications/register` and `POST /notifications/refresh` require a Bearer JWT. After local JWT verification, the service checks the token with Endorser. Registration and refresh continue only if Endorser accepts the JWT.
`POST /notifications/register` requires a Bearer JWT. After local JWT verification, the service checks the token with Endorser. Registration continues only if Endorser accepts the JWT.
Every Bearer JWT, on these routes and the SMS ones, must carry a numeric `exp` no more than an hour away (`AUTH_JWT_MAX_REMAINING_SEC`); the app signs a fresh one per request that expires in a minute. Without that rule, any JWT the DID ever signed without `exp`, such as a claim published on Endorser, would authenticate as that DID.
`POST /notifications/alert-authorization` uses the same current-user Bearer JWT + Endorser check. It does **not** accept the `testMode` local bypass. The 100 delegated JWTs in the body are stored credentials, not the request authenticator.
**Local notification test bypass:** send `testMode: true` in the JSON body and omit the `Authorization` header. The request skips JWT and Endorser checks and uses a synthetic local test user, same as before. This applies to register/refresh only.
`DELETE /notifications/register` removes every device registration for the DID, for someone who chose on-device notifications. Like the alert-authorization delete, it needs only the verified Bearer JWT.
`DELETE /notifications/alert-authorization` needs only the verified Bearer JWT, without the Endorser check, so an identity whose Endorser registration was removed can still turn its alerts off.
**Local notification test bypass:** send `testMode: true` in the JSON body and omit the `Authorization` header. The request skips JWT and Endorser checks and uses a synthetic local test user, same as before. This applies to register only.
Set `NODE_ENV=test-local` in `.env` to bypass ethr JWT *expiry* verification during local development (this is separate from the `testMode` bypass above).
@@ -70,7 +76,22 @@ Authorization: Bearer <current-user-JWT>
`notifyHourUtc` and `notifyMinuteUtc` are **required** and `timezone` is optional; all three behave exactly as on [the SMS twin](#endpoints). Both channels gate on the stored hour ([Notification hour](#notification-hour)).
A successful call replaces that user's previous **unused** JWTs atomically. Passkey (`did:peer`) identities cannot mint this batch and receive `DELEGATED_JWT_UNSUPPORTED_IDENTITY`.
A successful call replaces that user's previous **unused** JWTs atomically. JWTs for a UTC day that already holds a consumed JWT are skipped, so a re-upload after today's run does not run (and notify) again today; `storedCount` reports what was inserted. `"rerunToday": true` stores those JWTs anyway, so a deliberate reset (turning a channel on, a new time) can run today; the app leaves it out of the automatic re-upload after a New Activity visit. Each route honors it only while today's alert can still go out. On the SMS route that means one of the identity's numbers has had no alert text since UTC midnight or is on `SMS_SAME_DAY_RESEND_NUMBERS`; on the push route, the identity has had no alert push since UTC midnight or is on `PUSH_SAME_DAY_RESEND_DIDS`. Otherwise it is ignored and logged, so the reset cannot spend today's run on an alert the daily cap would withhold. Passkey (`did:peer`) identities cannot mint this batch and receive `DELEGATED_JWT_UNSUPPORTED_IDENTITY`.
The body may also carry the channel's alertSearch state, on both alert-authorization routes:
```json
{
"endorserAfterCursor": "48213",
"partnerAfterCursor": "912-48213",
"planHandleIds": ["https://endorser.ch/entity/01H..."],
"location": { "minLocLat": 40.1, "maxLocLat": 40.9, "minLocLon": -112.2, "maxLocLon": -111.4 }
}
```
- The cursors replace the channel's stored cursors, so the next run counts changes after them. The app sends the latest cursors when notifications are turned on and when the person opens New Activity. A cursor is at most 64 letters, digits, `_`, `:` or `-`.
- `planHandleIds` (at most 200) and `location` are sent to alertSearch on every run, for the starred-project and nearby lists. `null` clears either one.
- An absent field keeps what is stored. Any invalid field rejects the whole upload, and nothing is stored.
### Removing an authorization
@@ -86,13 +107,13 @@ The daily scheduler runs `retrieveAlertSearch` against:
- `{ENDORSER_URL}/api/v2/report/alertSearch`
- `{PARTNER_URL}/api/partner/alertSearch`
The **delegated** JWT is sent as `Authorization: Bearer`. Pass independent `endorserAfterId` / `partnerAfterDate` (or omit them on first run). Nearby search uses the alertSearch bbox (`minLocLat`, `maxLocLat`, `minLocLon`, `maxLocLon`).
The **delegated** JWT is sent as `Authorization: Bearer`. Each source takes its own cursor, `endorserAfterCursor` / `partnerAfterCursor`: an opaque string the server returned as `nextAfterCursor` and receives back as `afterCursor` (endorser-ch CHANGE/PLAN-accurate-cursors.md). With a cursor, a source pages while `hasMore` (up to 20 pages; the rest comes on the next run). Without one (a user's first run), it makes one request without a cursor and keeps only the returned cursor: the rows predate the notifications, so a first run reports nothing (`seeded: true`, outcome `empty`). A response without `nextAfterCursor` (endorser-ch through 4.4.6) is `malformed`. Nearby search uses the stored `location` bbox (`minLocLat`, `maxLocLat`, `minLocLon`, `maxLocLon`), and the tracked-plan lists use the stored `planHandleIds`; without them those lists are empty.
`loadAlertSearchCursors` / `retrieveAlertSearch` / `advanceAlertSearchCursors` (or `runAlertSearchCycle`) persist those bounds per user DID in SQLite. Cursors advance only after a complete `success` retrieval (not `empty`, `pagination`, or errors). A Partner page of 50 rows that share the oldest `updatedAt` is `pagination` because exclusive `beforeDate` cannot drain timestamp ties.
`loadAlertSearchCursors` / `retrieveAlertSearch` / `advanceAlertSearchCursors` (or `runAlertSearchCycle`) persist those cursors per user DID in SQLite. Both cursors move to their last `nextAfterCursor` only when both sources had a `success` or `empty` run. After `pagination` (the server's userMessage says a list timed out) or an error on either side, both stay, so the retry searches the whole window again rather than skipping what the completed side found. Because the cursors move after every complete run, sent or not, each notification counts only changes after the previous run.
`runDailyAlertSearch(userId, now?)` picks the unused delegated JWT for the current **UTC** day, runs `runAlertSearchCycle` with that JWT, and marks that specific JWT consumed only when both Endorser and Partner complete (`success` or `empty`, including both empty). Pagination or source failures leave the JWT unused so the same day can be retried. The result reports the day it used as `utcDay`. After a retrieve, the result includes `digest` from `buildAlertSearchDigest` (six bucket records and counts). `digest` is `null` when there is no batch or no unused JWT for today. Consumption does not depend on `digest.hasUpdates`.
`runDailyAlertSearch(userId, now?)` picks the unused delegated JWT for the current **UTC** day, runs `runAlertSearchCycle` with that JWT, and marks that specific JWT consumed only when both Endorser and Partner complete (`success` or `empty`, including both empty). Pagination or source failures leave the JWT unused so the same day can be retried. The result reports the day it used as `utcDay`. After a retrieve, the result includes `digest` from `buildAlertSearchDigest` (eight bucket records and counts: the five endorser lists plus `profilesNearby`, `profilesSimilar` and `plansSimilar`), and `startCursors`, the cursors the run counted from (absent on a first run). `digest` is `null` when there is no batch or no unused JWT for today. Consumption does not depend on `digest.hasUpdates`.
`startAlertSearchScheduler()` (started from `src/index.ts` next to the FCM scheduler) is a **separate** user-level job. One query per pass asks for the users who hold an unused JWT for the current UTC day, flagged by whether their `notify_hour_min_utc` has arrived ([Scheduler selection](#scheduler-selection)); it calls `runDailyAlertSearch` on the due ones, up to `ALERT_SEARCH_USER_CONCURRENCY` at a time. After each run, if the digest is complete with updates **and** today's JWT was consumed, it sends a user-visible FCM message (`title: TimeSafari`, body `You have N new updates.`, data `type: alert_search`) to that user's registered tokens. It does not call `sendPushToDevice` or change `WAKEUP_PING`. Subsequent ticks the same UTC day see no unused JWT (`digest: null`) and do not resend. FCM send failures are logged and do not roll back cursors or JWT consumption. A process-local in-flight flag skips a tick if a pass is still running.
`startAlertSearchScheduler()` (started from `src/index.ts` next to the FCM scheduler) is a **separate** user-level job. One query per pass asks for the users who hold an unused JWT for the current UTC day, flagged by whether their `notify_hour_min_utc` has arrived ([Scheduler selection](#scheduler-selection)); it calls `runDailyAlertSearch` on the due ones, up to `ALERT_SEARCH_USER_CONCURRENCY` at a time. After each run, if the digest is complete with updates **and** today's JWT was consumed, it sends a user-visible FCM message (`title: TimeSafari`, body `You have N new updates.`, data `type: alert_search` and `c`, the start cursors joined by `.`) to that user's registered tokens. It does not call `sendPushToDevice` or change `WAKEUP_PING`. Subsequent ticks the same UTC day see no unused JWT (`digest: null`) and do not resend. Underneath that, an `alert_push_sends` count caps alert pushes at one per identity per UTC day, to all its devices at once; for a DID on `PUSH_SAME_DAY_RESEND_DIDS` it counts only pushes since the current batch was stored, so a `rerunToday` reset can push again. A push that reached no device is not counted. FCM send failures are logged and do not roll back cursors or JWT consumption. A process-local in-flight flag skips a tick if a pass is still running.
`buildAlertSearchDigest` maps a retrieve result into structured payload data: per-bucket record arrays, counts, `totalCount`, `hasUpdates`, and Endorser/Partner completion status. It does not invent a notification string; FCM uses only `totalCount` for the short body. Incomplete outcomes (`pagination`, auth, network, etc.) yield `completed: false` and `hasUpdates: false`. Empty successful retrieves are complete with `hasUpdates: false` and do not send FCM.
@@ -213,7 +234,9 @@ link that appears in messages and is never the claim namespace.
The middleware chain is `requireAuth` (Bearer JWT, signature verified against
the issuer DID), `requireEndorserAuth` (Endorser accepts the same token), then
`requireSmsActionJwt(action)`, then the handler. The handler performs no
`requireSmsActionJwt(action)`, then the handler. `DELETE /notify-sms/alert-authorization`
and `DELETE /notify-sms/phone` skip `requireEndorserAuth`, so an identity whose
Endorser registration was removed can still stop its texts. The handler performs no
authorization checks of its own. There is no `testMode` bypass: no local-test
path sends real texts to real handsets.
@@ -405,10 +428,13 @@ second replica double-texts.
Eligibility is the same predicate the FCM path uses: the run consumed today's
JWT and the digest is complete with updates. Consumption is what makes later
ticks on the same UTC day no-ops. The message is
`Gift Economies: you have N new updates. https://giftopia.me Reply STOP to end.`,
`Gift Economies: you have N new updates. https://giftopia.me/deep-link/new-activity?c=<start cursors> Reply STOP to end.`,
kept inside one 160-character GSM-7 segment, since a second segment is a second
charge. Underneath the JWT rule, an `sms_phone_log` count caps sends at one per
handset per identity per UTC calendar day. Send failures are logged and do not roll back
charge. `c` is the endorser and partner cursors the run counted from, joined by
`.`; the app compares it with its own to tell whether it shows the same window. Underneath the JWT rule, an `sms_phone_log` count caps sends at one per
handset per identity per UTC calendar day. For a number on
`SMS_SAME_DAY_RESEND_NUMBERS` it counts only sends since the current batch was
stored, so a `rerunToday` reset can text it again. Send failures are logged and do not roll back
cursor advancement or JWT consumption.
The SMS channel keeps its own JWT inventory and its own cursor table. A user on
@@ -646,8 +672,8 @@ Unique on `(batch_pk, sequence)` and on `(user_id, day)` for unused rows. Indexe
Table `alert_search_cursors` holds one row per user DID:
- `endorser_after_id` — last complete Endorser ULID (`afterId`), or null
- `partner_after_at` — last complete Partner `updatedAt` bound (`afterDate`), or null
- `endorser_after_cursor` — Endorser `nextAfterCursor` of the last complete run, or null before the first
- `partner_after_cursor` — Partner `nextAfterCursor` of the last complete run, or null before the first
- `created_at`, `updated_at`
Table `sms_registrations` holds one row per `(DID, phone)` pair:
@@ -691,6 +717,20 @@ Tables `sms_alert_authorization_batches` / `sms_alert_authorization_jwts` and
`sms_alert_search_cursors` are column-for-column mirrors of their FCM
counterparts, holding the SMS channel's independent JWT inventory and cursor.
Table `alert_push_sends` holds one row per alert push that reached at least
one device (`user_id`, `batch_id`, `sent_at`), for the push daily cap. Each
identity's rows older than 30 days are deleted when it gets a new one.
Table `sms_alert_search_runs` holds one row per SMS daily run the scheduler
attempted, texted or not: `user_id`, `utc_day`, `ran_at`, `elapsed_ms`,
`completed`, `consumed`, each source's outcome, the start cursors, `total_count`,
the digest's `counts` and full `records` (JSON), and the SMS result
(`sms_eligible`, `sms_sent`, `sms_failed`, `sms_blocked`), or `error` when the
run threw. Its `records` hold other identities' claims and profiles exactly as
the servers returned them. Rows older than 30 days are pruned on each SMS
scheduler pass. Nothing in the service reads it; it exists for
[Watching the SMS channel](#watching-the-sms-channel).
The schema is created automatically on startup if the database or tables do not already exist. New tables are added with `CREATE TABLE IF NOT EXISTS`; existing `fcm_registrations` rows are not migrated or altered.
### Backup
@@ -738,6 +778,7 @@ Set `NOTIFY_DATA_DIR` to a durable directory, or keep the Docker default `/app/d
| `FIREBASE_SERVICE_ACCOUNT_JSON` **or** working ADC | **Required** for FCM (wakeup and AlertSearch) | ADC if JSON unset |
| `NOTIFY_DATA_DIR` | **Durable** path (or volume on `/app/data`) | `./data` (cwd-relative; in Docker that is `/app/data`) |
| `NODE_ENV` | Must **not** be `test-local` (that bypasses ethr JWT expiry) | Docker image sets `production` |
| `MESSAGE_ENV_LABEL` | Optional; appended as ` (<label>)` to every SMS and push body. Leave unset in production, set it (e.g. `test`) elsewhere | Unset (nothing appended) |
| `SMS_ENABLED` | Optional; `/notify-sms` returns `503 SMS_DISABLED` while off | `false` |
| `SMS_CODE_SECRET` | **Required** when `SMS_ENABLED` (startup fails without it) | None |
| `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | **Required** to send; absent means `SMS_NOT_CONFIGURED` per send | None |
@@ -751,6 +792,8 @@ Set `NOTIFY_DATA_DIR` to a durable directory, or keep the Docker default `/app/d
| `SMS_REQUIRE_ACTION_CLAIM` | Must **not** be a false value in production | `true` |
| `SMS_ALLOWED_RECIPIENT_DIDS` | Leave **unset** in production; on a test server, set it to the DIDs that server may text | Unset (no restriction) |
| `SMS_BLOCKED_NUMBERS` | Optional; numbers blocked by configuration, on top of the `sms_blocked_numbers` table | Empty |
| `PUSH_SAME_DAY_RESEND_DIDS` | Optional, comma-separated; DIDs a `rerunToday` reset may push again the same UTC day (testing). Every other DID gets at most one alert push a day | Empty |
| `SMS_SAME_DAY_RESEND_NUMBERS` | Optional, comma-separated; numbers a `rerunToday` reset may text again the same UTC day (testing). Every other number gets at most one alert text a day | Empty |
| `SMS_DEV_ECHO_CODE` | Must be unset or `false`; honored only under `NODE_ENV=test-local` | `false` |
| Replicas | **One** process | Not enforced in code |
| Persistent volume | **Required** for Docker so SQLite survives replace | None unless you pass `-v` |
@@ -787,3 +830,36 @@ Every line this service prints is prefixed with an ISO-8601 UTC timestamp
5. **SMS activity in logs (when `SMS_ENABLED`):** look for `[SmsAlertSearchScheduler] Pass started` / `Pass completed in`. Route activity logs under `[NotifySms]`, and rejected authorizations under `[SmsActionJwt] Rejected`.
6. **SQLite location:** after the process has handled a request or a scheduler pass that opens the DB, confirm `{NOTIFY_DATA_DIR}/notify.sqlite` exists (Docker default: `/app/data/notify.sqlite` on the volume). WAL sidecars may appear while the process is running.
### Watching the SMS channel
`src/tools/smsWatch.ts` is a `top`-style terminal view of the SMS channel,
read from `notify.sqlite` alone. It opens the database read-only, so it is safe
beside the running service, and it reads the service's own environment, so it
needs no configuration of its own:
```
docker exec -it <container> node dist/tools/smsWatch.js
pkgx pnpm run sms:watch -- --db path/to/notify.sqlite # a local copy
```
It has three views, refreshed every 2 seconds (`--refresh <sec>` changes that):
1. **Recent runs** — from `sms_alert_search_runs`: when, the outcome (`SENT n`,
`no updates`, `SEEDED`, `INCOMPLETE`, `WITHHELD`, `ERROR`, …), the update
count, the user's verified phones, the per-bucket counts, and a one-line
summary of the records. Enter shows the whole run, records included.
2. **Scheduled** — every user with an SMS batch or a verified phone, ordered by
their next run: the time, phones, unused JWTs left, cursors, search inputs,
and flags for the conditions that silence a text (`NO-PHONE`, `BLOCKED`,
`NOT-ALLOWED`, `SEED-NEXT`). Enter shows the exact query URLs the next run
sends. `p` runs that query against Endorser and Partner with today's JWT and
shows what it would find; it consumes nothing and moves no cursor, so the
real run later sees the same window. The first `p` in a session asks for
`y`/`n` first: once Endorser rejects replayed JWTs, a preview spends the
user's JWT for today and the real run finds nothing.
3. **Phone log** — `sms_phone_log`, newest first.
Keys: `1`/`2`/`3` or Tab switch views, `j`/`k` or the arrows move, Space/`b`
page, Enter expands, Esc or `q` goes back, and `q` quits. With `--once`, or
when output is not a terminal, it prints one snapshot of all three and exits.
-3795
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "notification-wakeup-service",
"version": "0.2.2",
"version": "0.2.7-beta",
"private": true,
"type": "module",
"packageManager": "pnpm@11.4.0",
@@ -13,7 +13,9 @@
"sms:send": "tsx scripts/sms-send.ts",
"sms:smoke": "tsx scripts/sms-smoke.ts",
"twilio:whoami": "tsx scripts/twilio-whoami.ts",
"sms:blocks": "tsx scripts/sms-blocks.ts"
"sms:blocks": "tsx scripts/sms-blocks.ts",
"alert-search:tap": "tsx scripts/alert-search-tap.ts",
"sms:watch": "tsx src/tools/smsWatch.ts"
},
"dependencies": {
"@peculiar/asn1-ecc": "^2.7.0",
+83
View File
@@ -0,0 +1,83 @@
/**
* Send one visible AlertSearch FCM notification to one registered device.
* Does not start the server, run the daily scheduler, consume a JWT, or
* advance a cursor.
*
* pnpm alert-search:tap
* pnpm alert-search:tap -- --device-id <deviceId>
*
* Uses FIREBASE_SERVICE_ACCOUNT_JSON (or ADC) and the local notification
* database (NOTIFY_DATA_DIR, default ./data). Omitting --device-id lists
* registrations and sends nothing.
*/
import "../src/env.js";
import { db } from "../src/db/fcmTokensSqlite.js";
import { sendAlertSearchPushToDevice } from "../src/services/pushService.js";
import { maskToken } from "../src/util/maskToken.js";
const TITLE = "AlertSearch tap test";
const BODY = "Tap this notification.";
function deviceIdArg(argv: string[]): string | undefined {
const inline = argv.find((arg) => arg.startsWith("--device-id="));
if (inline !== undefined) {
const value = inline.slice("--device-id=".length).trim();
return value.length > 0 ? value : undefined;
}
const index = argv.indexOf("--device-id");
if (index === -1) return undefined;
const value = argv[index + 1]?.trim();
return value !== undefined && value.length > 0 ? value : undefined;
}
function maskUserId(userId: string): string {
if (userId.length <= 16) return "…";
return userId.slice(0, 12) + "…" + userId.slice(-4);
}
const rows = await db.getAll();
const deviceId = deviceIdArg(process.argv.slice(2));
if (deviceId === undefined) {
console.log("Pass --device-id to send one notification. Registered devices:");
if (rows.length === 0) {
console.log("(none)");
}
for (const row of rows) {
console.log(
[
row.platform,
row.deviceId,
"token …" + maskToken(row.fcmToken),
maskUserId(row.userId),
].join(" ")
);
}
process.exit(rows.length === 0 ? 1 : 0);
}
const matches = rows.filter((row) => row.deviceId === deviceId);
if (matches.length !== 1) {
console.error(
`Expected one registration for device ${deviceId}, found ${matches.length}.`
);
process.exit(1);
}
const row = matches[0];
const status = await sendAlertSearchPushToDevice(row.fcmToken, {
title: TITLE,
body: BODY,
});
console.log(
JSON.stringify({
status,
deviceId: row.deviceId,
platform: row.platform,
tokenSuffix: maskToken(row.fcmToken),
title: TITLE,
body: BODY,
dataType: "alert_search",
})
);
process.exit(status === "sent" ? 0 : 1);
+318
View File
@@ -0,0 +1,318 @@
import type {
AlertSearchClaimRecord,
AlertSearchJwtWithClaimRecord,
AlertSearchPlanRecord,
AlertSearchProfileRecord,
CombinedAlertSearchData,
} from "./types.js";
/**
* Claim `@type` values Endorser stores on a jwt row (`claim.service.js`).
* `fromEntity` / `toEntity` are written only for GiveAction and Offer, and the
* plan-contribution queries filter to those two types. Any other claimType is
* kept as a broader category rather than called an offer or a give.
*/
export const GIVE_CLAIM_TYPE = "GiveAction";
export const OFFER_CLAIM_TYPE = "Offer";
export const ENDORSER_CLAIM_TYPES = [
"AgreeAction",
"Confirmation",
"Emoji",
"GiveAction",
"JoinAction",
"Offer",
"Organization",
"PlanAction",
"Project",
"RegisterAction",
"Tenure",
"VoteAction",
] as const;
export type ClaimUpdateKind = "give" | "offer" | "other";
/**
* Notification lines, most specific relationship first. A record that the APIs
* place in more than one list is counted only in the first category that
* claims it (see `countAlertSearchUpdates`).
*/
export const ALERT_SEARCH_UPDATE_CATEGORIES = [
"offerToOwnedProject",
"giveToOwnedProject",
"otherContributionToOwnedProject",
"offerToStarredProject",
"giveToStarredProject",
"otherClaimOnStarredProject",
"starredProjectUpdate",
"offerToYou",
"giveToYou",
"otherClaimToYou",
"offerFromYou",
"giveFromYou",
"otherClaimFromYou",
"projectNearby",
"profileNearby",
"projectSimilar",
"profileSimilar",
] as const;
export type AlertSearchUpdateCategory =
(typeof ALERT_SEARCH_UPDATE_CATEGORIES)[number];
export type AlertSearchUpdateCounts = {
[K in AlertSearchUpdateCategory]: number;
};
export function claimUpdateKind(claimType: unknown): ClaimUpdateKind {
if (claimType === GIVE_CLAIM_TYPE) return "give";
if (claimType === OFFER_CLAIM_TYPE) return "offer";
return "other";
}
function emptyCounts(): AlertSearchUpdateCounts {
return {
offerToOwnedProject: 0,
giveToOwnedProject: 0,
otherContributionToOwnedProject: 0,
offerToStarredProject: 0,
giveToStarredProject: 0,
otherClaimOnStarredProject: 0,
starredProjectUpdate: 0,
offerToYou: 0,
giveToYou: 0,
otherClaimToYou: 0,
offerFromYou: 0,
giveFromYou: 0,
otherClaimFromYou: 0,
projectNearby: 0,
profileNearby: 0,
projectSimilar: 0,
profileSimilar: 0,
};
}
function idPart(value: unknown): string | undefined {
if (typeof value === "string" && value.length > 0) return value;
if (typeof value === "number" && Number.isFinite(value)) return String(value);
return undefined;
}
function ownedProjectCategory(kind: ClaimUpdateKind): AlertSearchUpdateCategory {
if (kind === "offer") return "offerToOwnedProject";
if (kind === "give") return "giveToOwnedProject";
return "otherContributionToOwnedProject";
}
function starredClaimCategory(kind: ClaimUpdateKind): AlertSearchUpdateCategory {
if (kind === "offer") return "offerToStarredProject";
if (kind === "give") return "giveToStarredProject";
return "otherClaimOnStarredProject";
}
function claimSideCategory(
kind: ClaimUpdateKind,
side: "to" | "from"
): AlertSearchUpdateCategory {
if (side === "to") {
if (kind === "offer") return "offerToYou";
if (kind === "give") return "giveToYou";
return "otherClaimToYou";
}
if (kind === "offer") return "offerFromYou";
if (kind === "give") return "giveFromYou";
return "otherClaimFromYou";
}
/**
* `jwtsWithDidAfterId` returns a row only when `toEntity` or `fromEntity` is
* the requester and the issuer is not. `toEntity` is the recipient; `fromEntity`
* is the giver or offerer. There is no third side.
*/
function claimAboutYouCategory(
row: AlertSearchClaimRecord,
userId: string | undefined
): AlertSearchUpdateCategory {
const kind = claimUpdateKind(row.claimType);
if (userId !== undefined && row.toEntity === userId) {
return claimSideCategory(kind, "to");
}
return claimSideCategory(kind, "from");
}
function planKeys(plan: AlertSearchPlanRecord): string[] {
const keys: string[] = [];
const handleId = idPart(plan.handleId);
const jwtId = idPart(plan.jwtId);
if (handleId !== undefined) keys.push(`plan:${handleId}`);
if (jwtId !== undefined) keys.push(`planJwt:${jwtId}`);
return keys;
}
function profileKeys(profile: AlertSearchProfileRecord): string[] {
const keys: string[] = [];
const rowId = idPart(profile.rowId);
const issuerDid = idPart(profile.issuerDid);
if (rowId !== undefined) keys.push(`profile:${rowId}`);
if (issuerDid !== undefined) keys.push(`profileDid:${issuerDid}`);
return keys;
}
function jwtKey(row: AlertSearchClaimRecord): string | undefined {
const id = idPart(row.id);
return id === undefined ? undefined : `jwt:${id}`;
}
/**
* Counts each underlying record once. The same jwt id can be returned in
* `personalPlanContributions` and `trackedPlanClaims` when the recipient owns
* and also tracks that project, and the same plan or profile can sit in a
* tracked/nearby list and a semantic-match list. Ownership beats tracking,
* tracking beats a personal claim, a tracked project update beats nearby, and
* nearby beats a semantic match.
*/
export function countAlertSearchUpdates(
records: CombinedAlertSearchData,
userId?: string
): AlertSearchUpdateCounts {
const counts = emptyCounts();
const seenKeys = new Set<string>();
const seenObjects = new WeakSet<object>();
const take = (
row: object,
keys: string[],
category: AlertSearchUpdateCategory
): void => {
if (seenObjects.has(row)) return;
if (keys.some((key) => seenKeys.has(key))) return;
seenObjects.add(row);
for (const key of keys) seenKeys.add(key);
counts[category] += 1;
};
const takeClaim = (
row: AlertSearchJwtWithClaimRecord | AlertSearchClaimRecord,
category: AlertSearchUpdateCategory
): void => {
const key = jwtKey(row);
take(row, key === undefined ? [] : [key], category);
};
for (const row of records.personalPlanContributions) {
takeClaim(row, ownedProjectCategory(claimUpdateKind(row.claimType)));
}
for (const row of records.trackedPlanClaims) {
takeClaim(row, starredClaimCategory(claimUpdateKind(row.claimType)));
}
for (const row of records.claims) {
takeClaim(row, claimAboutYouCategory(row, userId));
}
for (const row of records.trackedPlanUpdates) {
take(row, planKeys(row), "starredProjectUpdate");
}
for (const row of records.plansNearby) {
take(row, planKeys(row), "projectNearby");
}
for (const row of records.plansSimilar) {
take(row.plan, planKeys(row.plan), "projectSimilar");
}
for (const row of records.profilesNearby) {
take(row, profileKeys(row), "profileNearby");
}
for (const row of records.profilesSimilar) {
take(row.profile, profileKeys(row.profile), "profileSimilar");
}
return counts;
}
export function totalAlertSearchUpdates(counts: AlertSearchUpdateCounts): number {
return ALERT_SEARCH_UPDATE_CATEGORIES.reduce(
(sum, category) => sum + counts[category],
0
);
}
function line(count: number, singular: string, plural: string): string {
return `${count} ${count === 1 ? singular : plural}`;
}
/** One category fragment, without the "You have" prefix. */
export function formatAlertSearchUpdateLine(
category: AlertSearchUpdateCategory,
count: number
): string {
switch (category) {
case "offerToOwnedProject":
return line(
count,
"new offer to a project you own",
"new offers to projects you own"
);
case "giveToOwnedProject":
return line(
count,
"new give to a project you own",
"new gives to projects you own"
);
case "otherContributionToOwnedProject":
return line(
count,
"new contribution to a project you own",
"new contributions to projects you own"
);
case "offerToStarredProject":
return line(
count,
"new offer to a starred project",
"new offers to your starred projects"
);
case "giveToStarredProject":
return line(
count,
"new give to a starred project",
"new gives to your starred projects"
);
case "otherClaimOnStarredProject":
return line(
count,
"new claim on a starred project",
"new claims on your starred projects"
);
case "starredProjectUpdate":
return line(
count,
"new project update to a starred project",
"new project updates to your starred projects"
);
case "offerToYou":
return line(count, "new offer to you", "new offers to you");
case "giveToYou":
return line(count, "new give to you", "new gives to you");
case "otherClaimToYou":
return line(count, "new claim to you", "new claims to you");
case "offerFromYou":
return line(count, "new offer from you", "new offers from you");
case "giveFromYou":
return line(count, "new give from you", "new gives from you");
case "otherClaimFromYou":
return line(count, "new claim from you", "new claims from you");
case "projectNearby":
return line(count, "new project near you", "new projects near you");
case "profileNearby":
return line(count, "new profile near you", "new profiles near you");
case "projectSimilar":
return line(
count,
"new project similar to your profile",
"new projects similar to your profile"
);
case "profileSimilar":
return line(
count,
"new profile similar to yours",
"new profiles similar to yours"
);
}
}
+100 -111
View File
@@ -6,9 +6,10 @@ import {
type AlertSearchQueryInput,
} from "./params.js";
import {
ALERT_SEARCH_PAGE_SIZE,
type AlertSearchFailureReason,
type AlertSearchSource,
type AlertSearchSimilarPlan,
type AlertSearchSimilarProfile,
type EndorserAlertSearchData,
type EndorserAlertSearchResponse,
type PartnerAlertSearchData,
@@ -56,14 +57,43 @@ export function emptyEndorserData(): EndorserAlertSearchData {
}
export function emptyPartnerData(): PartnerAlertSearchData {
return { profilesNearby: [] };
return { profilesNearby: [], profilesSimilar: [], plansSimilar: [] };
}
function classifyHttpStatus(status: number): AlertSearchFailureReason {
if (status === 400 || status === 401 || status === 403) return "auth";
/** The `error` text of an error response body, when it has one. */
function bodyErrorText(body: unknown): string | undefined {
if (body === null || typeof body !== "object") return undefined;
const error = (body as { error?: unknown }).error;
if (typeof error === "string") return error;
if (error !== null && typeof error === "object") {
const userMessage = (error as { userMessage?: unknown }).userMessage;
if (typeof userMessage === "string") return userMessage;
}
return undefined;
}
/**
* The servers answer a missing or bad Authorization JWT with 400, which they
* also use for bad parameters (eg. a malformed cursor), so a 400 counts as an
* authorization failure only when its error says so.
*/
function classifyHttpStatus(
status: number,
errorText: string | undefined
): AlertSearchFailureReason {
if (status === 401 || status === 403) return "auth";
if (status === 400) {
return errorText === undefined || /authoriz|jwt/i.test(errorText)
? "auth"
: "http";
}
return "http";
}
function httpErrorMessage(status: number, errorText: string | undefined): string {
return errorText === undefined ? `HTTP ${status}` : `HTTP ${status}: ${errorText}`;
}
function isAbortError(err: unknown): boolean {
if (err instanceof Error) {
if (err.name === "AbortError" || err.name === "TimeoutError") return true;
@@ -112,11 +142,11 @@ async function getJson(
parsed = await response.json();
} catch (err) {
if (!response.ok) {
const reason = classifyHttpStatus(response.status);
const reason = classifyHttpStatus(response.status, undefined);
return {
ok: false,
reason,
message: `HTTP ${response.status}`,
message: httpErrorMessage(response.status, undefined),
status: response.status,
url,
};
@@ -131,11 +161,12 @@ async function getJson(
}
if (!response.ok) {
const reason = classifyHttpStatus(response.status);
const errorText = bodyErrorText(parsed);
const reason = classifyHttpStatus(response.status, errorText);
return {
ok: false,
reason,
message: `HTTP ${response.status}`,
message: httpErrorMessage(response.status, errorText),
status: response.status,
url,
};
@@ -192,10 +223,56 @@ export function parseEndorserAlertSearchResponse(
plansNearby as EndorserAlertSearchResponse["data"]["plansNearby"],
},
};
copyCursorFields(body, parsed);
return parsed;
}
/** Copies userMessage, nextAfterCursor, nextBeforeCursor, and hasMore when the server sent them. */
function copyCursorFields(
body: Record<string, unknown>,
parsed: EndorserAlertSearchResponse | PartnerAlertSearchResponse
): void {
if (typeof body.userMessage === "string") {
parsed.userMessage = body.userMessage;
}
return parsed;
if (typeof body.nextAfterCursor === "string" && body.nextAfterCursor.length > 0) {
parsed.nextAfterCursor = body.nextAfterCursor;
}
if (typeof body.nextBeforeCursor === "string" && body.nextBeforeCursor.length > 0) {
parsed.nextBeforeCursor = body.nextBeforeCursor;
}
if (typeof body.hasMore === "boolean") {
parsed.hasMore = body.hasMore;
}
}
/**
* Missing similar lists are an older partner response and mean none.
* A present value that is not an array, or an element without its nested
* record, is malformed so those matches are not dropped.
*/
function parseSimilarProfiles(
value: unknown
): AlertSearchSimilarProfile[] | undefined {
if (value === undefined) return [];
const items = asObjectArray(value);
if (items === undefined) return undefined;
for (const item of items) {
if (!isRecord(item.profile)) return undefined;
}
return items as AlertSearchSimilarProfile[];
}
function parseSimilarPlans(
value: unknown
): AlertSearchSimilarPlan[] | undefined {
if (value === undefined) return [];
const items = asObjectArray(value);
if (items === undefined) return undefined;
for (const item of items) {
if (!isRecord(item.plan)) return undefined;
}
return items as AlertSearchSimilarPlan[];
}
export function parsePartnerAlertSearchResponse(
@@ -203,16 +280,24 @@ export function parsePartnerAlertSearchResponse(
): PartnerAlertSearchResponse | undefined {
if (!isRecord(body) || !isRecord(body.data)) return undefined;
const profilesNearby = asObjectArray(body.data.profilesNearby);
if (profilesNearby === undefined) return undefined;
const profilesSimilar = parseSimilarProfiles(body.data.profilesSimilar);
const plansSimilar = parseSimilarPlans(body.data.plansSimilar);
if (
profilesNearby === undefined ||
profilesSimilar === undefined ||
plansSimilar === undefined
) {
return undefined;
}
const parsed: PartnerAlertSearchResponse = {
data: {
profilesNearby:
profilesNearby as PartnerAlertSearchResponse["data"]["profilesNearby"],
profilesSimilar,
plansSimilar,
},
};
if (typeof body.userMessage === "string") {
parsed.userMessage = body.userMessage;
}
copyCursorFields(body, parsed);
return parsed;
}
@@ -260,107 +345,11 @@ export async function fetchPartnerAlertSearchPage(input: {
return {
ok: false,
reason: "malformed",
message: "Partner alertSearch response is missing profilesNearby.",
message:
"Partner alertSearch response is missing profilesNearby or has invalid profilesSimilar or plansSimilar.",
status: raw.status,
url,
};
}
return { ok: true, status: raw.status, body: parsed, url };
}
export function endorserBucketHitPageLimit(
data: EndorserAlertSearchData
): boolean {
return (
data.claims.length >= ALERT_SEARCH_PAGE_SIZE ||
data.personalPlanContributions.length >= ALERT_SEARCH_PAGE_SIZE ||
data.trackedPlanUpdates.length >= ALERT_SEARCH_PAGE_SIZE ||
data.trackedPlanClaims.length >= ALERT_SEARCH_PAGE_SIZE ||
data.plansNearby.length >= ALERT_SEARCH_PAGE_SIZE
);
}
export function partnerBucketHitPageLimit(
data: PartnerAlertSearchData
): boolean {
return data.profilesNearby.length >= ALERT_SEARCH_PAGE_SIZE;
}
function minUlid(ids: unknown[]): string | undefined {
const values = ids.filter(
(id): id is string => typeof id === "string" && id.length > 0
);
if (values.length === 0) return undefined;
values.sort();
return values[0];
}
/**
* Next shared Endorser beforeId: MAX of the per-bucket minima for buckets
* that hit LIMIT 50. A global min would skip remaining rows in higher-ID
* truncated buckets.
*/
export function nextEndorserBeforeId(
data: EndorserAlertSearchData
): string | undefined {
const truncatedMins: string[] = [];
const truncatedBuckets: unknown[][] = [];
if (data.claims.length >= ALERT_SEARCH_PAGE_SIZE) {
truncatedBuckets.push(data.claims.map((r) => r.id));
}
if (data.personalPlanContributions.length >= ALERT_SEARCH_PAGE_SIZE) {
truncatedBuckets.push(data.personalPlanContributions.map((r) => r.id));
}
if (data.trackedPlanClaims.length >= ALERT_SEARCH_PAGE_SIZE) {
truncatedBuckets.push(data.trackedPlanClaims.map((r) => r.id));
}
if (data.trackedPlanUpdates.length >= ALERT_SEARCH_PAGE_SIZE) {
truncatedBuckets.push(data.trackedPlanUpdates.map((r) => r.jwtId));
}
if (data.plansNearby.length >= ALERT_SEARCH_PAGE_SIZE) {
truncatedBuckets.push(data.plansNearby.map((r) => r.jwtId));
}
for (const ids of truncatedBuckets) {
const min = minUlid(ids);
if (min !== undefined) truncatedMins.push(min);
}
if (truncatedMins.length === 0) return undefined;
truncatedMins.sort();
return truncatedMins[truncatedMins.length - 1];
}
export function plansNearbyHitPageLimit(
data: EndorserAlertSearchData
): boolean {
return data.plansNearby.length >= ALERT_SEARCH_PAGE_SIZE;
}
export function minPartnerBeforeDate(
data: PartnerAlertSearchData
): string | undefined {
if (data.profilesNearby.length < ALERT_SEARCH_PAGE_SIZE) return undefined;
const dates = data.profilesNearby
.map((p) => p.updatedAt)
.filter((d): d is string => typeof d === "string" && d.length > 0);
if (dates.length === 0) return undefined;
dates.sort();
return dates[0];
}
/**
* A LIMIT-50 page whose oldest updatedAt appears more than once cannot be
* drained with exclusive beforeDate: remaining rows at that timestamp are
* skipped. Detectable from the page without a rowid API.
*/
export function partnerPageHasTiedBeforeDate(
data: PartnerAlertSearchData
): boolean {
if (data.profilesNearby.length < ALERT_SEARCH_PAGE_SIZE) return false;
const min = minPartnerBeforeDate(data);
if (min === undefined) return false;
let count = 0;
for (const row of data.profilesNearby) {
if (row.updatedAt === min) count += 1;
}
return count > 1;
}
+66 -97
View File
@@ -3,27 +3,32 @@ import {
smsAlertSearchCursorsDb,
type AlertSearchCursorsStore,
} from "../db/alertSearchCursorsSqlite.js";
import { isAlertSearchCursorUlid } from "./params.js";
import type {
AlertSearchSourceResult,
RetrieveAlertSearchResult,
} from "./retrieve.js";
import type {
AlertSearchChannel,
EndorserAlertSearchData,
PartnerAlertSearchData,
} from "./types.js";
import type { AlertSearchChannel, AlertSearchLocationBBox } from "./types.js";
/**
* `endorserAfterCursor` / `partnerAfterCursor` are the servers' opaque cursors;
* a missing one means that source has never completed a run.
*/
export type StoredAlertSearchCursors = {
endorserAfterId?: string;
partnerAfterDate?: string;
endorserAfterCursor?: string;
partnerAfterCursor?: string;
};
export type CursorAdvanceResult = {
endorserAdvanced: boolean;
partnerAdvanced: boolean;
endorserAfterId: string | null;
partnerAfterAt: string | null;
endorserAfterCursor: string | null;
partnerAfterCursor: string | null;
};
/** The search inputs an upload stored for a channel. Omits missing values. */
export type StoredAlertSearchInputs = {
planHandleIds?: string[];
location?: AlertSearchLocationBBox;
};
const CURSOR_STORES: Record<AlertSearchChannel, AlertSearchCursorsStore> = {
@@ -31,93 +36,64 @@ const CURSOR_STORES: Record<AlertSearchChannel, AlertSearchCursorsStore> = {
sms: smsAlertSearchCursorsDb,
};
const COMPLETE_OUTCOMES = new Set(["success"]);
function isCompleteOutcome(outcome: string): boolean {
return COMPLETE_OUTCOMES.has(outcome);
}
/** MAX ULID across Endorser alertSearch identifier fields. */
export function maxEndorserAlertSearchUlid(
data: EndorserAlertSearchData
): string | undefined {
const ids: string[] = [];
for (const row of data.claims) {
if (isAlertSearchCursorUlid(row.id)) ids.push(row.id);
}
for (const row of data.personalPlanContributions) {
if (isAlertSearchCursorUlid(row.id)) ids.push(row.id);
}
for (const row of data.trackedPlanClaims) {
if (isAlertSearchCursorUlid(row.id)) ids.push(row.id);
}
for (const row of data.trackedPlanUpdates) {
if (isAlertSearchCursorUlid(row.jwtId)) ids.push(row.jwtId);
}
for (const row of data.plansNearby) {
if (isAlertSearchCursorUlid(row.jwtId)) ids.push(row.jwtId);
}
if (ids.length === 0) return undefined;
ids.sort();
return ids[ids.length - 1];
}
/** MAX profilesNearby.updatedAt (ISO). Not rowId. */
export function maxPartnerUpdatedAt(
data: PartnerAlertSearchData
): string | undefined {
let best: string | undefined;
let bestMs = Number.NEGATIVE_INFINITY;
for (const row of data.profilesNearby) {
if (typeof row.updatedAt !== "string" || row.updatedAt.length === 0) {
continue;
}
const ms = Date.parse(row.updatedAt);
if (Number.isNaN(ms)) continue;
if (ms > bestMs) {
bestMs = ms;
best = row.updatedAt;
}
}
return best;
}
export function nextEndorserCursorFromResult(
endorser: AlertSearchSourceResult<EndorserAlertSearchData>
): string | undefined {
if (!isCompleteOutcome(endorser.outcome)) return undefined;
return maxEndorserAlertSearchUlid(endorser.data);
}
export function nextPartnerCursorFromResult(
partner: AlertSearchSourceResult<PartnerAlertSearchData>
): string | undefined {
if (!isCompleteOutcome(partner.outcome)) return undefined;
return maxPartnerUpdatedAt(partner.data);
/** The cursor and search-input store for a channel. */
export function alertSearchCursorsStore(
channel: AlertSearchChannel
): AlertSearchCursorsStore {
return CURSOR_STORES[channel];
}
/**
* Load stored cursors for a retrieval query.
* Omits missing values so first run sends no afterId / afterDate / "0".
* The cursor to store after a run, or undefined when it stays. It also moves
* on an empty run: it covers everything the server had, so holding it back
* would only widen the next window.
*/
export function nextCursorFromResult(
result: AlertSearchSourceResult<unknown>
): string | undefined {
return result.outcome === "success" || result.outcome === "empty"
? result.nextAfterCursor
: undefined;
}
/** Load stored cursors for a retrieval query. Omits missing values. */
export async function loadAlertSearchCursors(
userId: string,
channel: AlertSearchChannel = "fcm"
): Promise<StoredAlertSearchCursors> {
const row = await CURSOR_STORES[channel].get(userId);
const out: StoredAlertSearchCursors = {};
if (row?.endorserAfterId && isAlertSearchCursorUlid(row.endorserAfterId)) {
out.endorserAfterId = row.endorserAfterId;
if (row?.endorserAfterCursor) {
out.endorserAfterCursor = row.endorserAfterCursor;
}
if (row?.partnerAfterAt && row.partnerAfterAt.length > 0) {
out.partnerAfterDate = row.partnerAfterAt;
if (row?.partnerAfterCursor) {
out.partnerAfterCursor = row.partnerAfterCursor;
}
return out;
}
/** Load the starred handle IDs and area stored for a channel. */
export async function loadAlertSearchInputs(
userId: string,
channel: AlertSearchChannel = "fcm"
): Promise<StoredAlertSearchInputs> {
const row = await CURSOR_STORES[channel].get(userId);
const out: StoredAlertSearchInputs = {};
if (row?.planHandleIds && row.planHandleIds.length > 0) {
out.planHandleIds = row.planHandleIds;
}
if (row?.location) {
out.location = row.location;
}
return out;
}
/**
* Advance each cursor independently after retrieveAlertSearch.
* Does not persist on empty, pagination, or error outcomes.
* Advance both cursors after retrieveAlertSearch, to each server's
* nextAfterCursor, only when both sources had a success or empty run. A
* failure on either side leaves both in place: the run sends nothing and does
* not consume its JWT, so the retry must search the whole window again, and a
* cursor that had moved would skip the rows it covered.
*/
export async function advanceAlertSearchCursors(
userId: string,
@@ -125,26 +101,19 @@ export async function advanceAlertSearchCursors(
channel: AlertSearchChannel = "fcm"
): Promise<CursorAdvanceResult> {
const store = CURSOR_STORES[channel];
let endorserAdvanced = false;
let partnerAdvanced = false;
const nextEndorser = nextEndorserCursorFromResult(result.endorser);
if (nextEndorser !== undefined) {
await store.setEndorserAfterId(userId, nextEndorser);
endorserAdvanced = true;
}
const nextPartner = nextPartnerCursorFromResult(result.partner);
if (nextPartner !== undefined) {
await store.setPartnerAfterAt(userId, nextPartner);
partnerAdvanced = true;
const nextEndorser = nextCursorFromResult(result.endorser);
const nextPartner = nextCursorFromResult(result.partner);
const advance = nextEndorser !== undefined && nextPartner !== undefined;
if (advance) {
await store.setAfterCursors(userId, nextEndorser, nextPartner);
}
const stored = await store.get(userId);
return {
endorserAdvanced,
partnerAdvanced,
endorserAfterId: stored?.endorserAfterId ?? null,
partnerAfterAt: stored?.partnerAfterAt ?? null,
endorserAdvanced: advance,
partnerAdvanced: advance,
endorserAfterCursor: stored?.endorserAfterCursor ?? null,
partnerAfterCursor: stored?.partnerAfterCursor ?? null,
};
}
+10 -5
View File
@@ -1,6 +1,7 @@
import {
advanceAlertSearchCursors,
loadAlertSearchCursors,
loadAlertSearchInputs,
type CursorAdvanceResult,
} from "./cursors.js";
import type { AlertSearchChannel } from "./types.js";
@@ -12,7 +13,7 @@ import {
export type AlertSearchCycleInput = Omit<
RetrieveAlertSearchInput,
"endorserAfterId" | "partnerAfterId" | "partnerAfterDate"
"endorserAfterCursor" | "partnerAfterCursor"
>;
export type AlertSearchCycleResult = {
@@ -22,8 +23,10 @@ export type AlertSearchCycleResult = {
};
/**
* Load stored cursors, retrieve Endorser+Partner alertSearch, then advance
* only complete source cursors. Not invoked by FCM, register, or startup.
* Load stored cursors and search inputs, retrieve Endorser+Partner
* alertSearch, then advance the cursors when both sources completed. A
* location or planHandleIds in the input replaces the stored one. Not invoked
* by FCM, register, or startup.
*/
export async function runAlertSearchCycle(
userId: string,
@@ -31,10 +34,12 @@ export async function runAlertSearchCycle(
channel: AlertSearchChannel = "fcm"
): Promise<AlertSearchCycleResult> {
const loaded = await loadAlertSearchCursors(userId, channel);
const inputs = await loadAlertSearchInputs(userId, channel);
const retrieved = await retrieveAlertSearch({
...inputs,
...input,
endorserAfterId: loaded.endorserAfterId,
partnerAfterDate: loaded.partnerAfterDate,
endorserAfterCursor: loaded.endorserAfterCursor,
partnerAfterCursor: loaded.partnerAfterCursor,
});
const advanced = await advanceAlertSearchCursors(userId, retrieved, channel);
return { loaded, retrieved, advanced };
+32
View File
@@ -37,8 +37,18 @@ export type DailyAlertSearchResult = {
partnerOutcome: AlertSearchQueryOutcome | null;
completed: boolean;
consumed: boolean;
/**
* When the JWT this run used was stored, which is when its batch was
* uploaded; absent when no JWT was selected.
*/
authorizedAt?: string;
/** Phase 6A digest after a retrieve; null when no batch/JWT was used. */
digest: AlertSearchDigest | null;
/**
* The cursors this run counted from, for the notification link; absent when
* no run happened or a source had never run before.
*/
startCursors?: { endorser: string; partner: string };
};
function noJwtResult(
@@ -59,6 +69,18 @@ function noJwtResult(
};
}
/**
* The `c` query value for a notification link: the start cursors joined by
* ".", which appears in neither server's cursor format.
*/
export function alertSearchLinkCursorParam(
startCursors: DailyAlertSearchResult["startCursors"]
): string | undefined {
return startCursors === undefined
? undefined
: `${startCursors.endorser}.${startCursors.partner}`;
}
/**
* Select today's unused delegated JWT by UTC day, run the existing alertSearch
* cycle, and consume that JWT only when both required sources completed
@@ -107,10 +129,20 @@ export async function runDailyAlertSearch(
utcDay,
batchId: selected.batchId,
jwtSequence: selected.sequence,
authorizedAt: selected.createdAt,
endorserOutcome,
partnerOutcome,
completed,
consumed,
digest,
...(cycle.loaded.endorserAfterCursor !== undefined &&
cycle.loaded.partnerAfterCursor !== undefined
? {
startCursors: {
endorser: cycle.loaded.endorserAfterCursor,
partner: cycle.loaded.partnerAfterCursor,
},
}
: {}),
};
}
+23 -3
View File
@@ -1,3 +1,7 @@
import {
countAlertSearchUpdates,
totalAlertSearchUpdates,
} from "./categories.js";
import type {
AlertSearchSourceResult,
RetrieveAlertSearchResult,
@@ -24,6 +28,8 @@ export const ALERT_SEARCH_DIGEST_BUCKETS = [
"trackedPlanClaims",
"plansNearby",
"profilesNearby",
"profilesSimilar",
"plansSimilar",
] as const;
export type AlertSearchDigestBucket =
@@ -47,6 +53,10 @@ export type AlertSearchDigestSourceStatus = {
export type AlertSearchDigest = {
completed: boolean;
hasUpdates: boolean;
/**
* Records counted once across lists. FCM's heading and the SMS sentence both
* use this number. `counts` stays the raw length of each API list.
*/
totalCount: number;
counts: AlertSearchDigestCounts;
records: CombinedAlertSearchData;
@@ -68,8 +78,15 @@ function copyEndorserRecords(
function copyPartnerRecords(
data: PartnerAlertSearchData
): Pick<CombinedAlertSearchData, "profilesNearby"> {
return { profilesNearby: [...data.profilesNearby] };
): Pick<
CombinedAlertSearchData,
"profilesNearby" | "profilesSimilar" | "plansSimilar"
> {
return {
profilesNearby: [...data.profilesNearby],
profilesSimilar: [...data.profilesSimilar],
plansSimilar: [...data.plansSimilar],
};
}
function sourceStatus(
@@ -95,9 +112,12 @@ export function countAlertSearchDigestRecords(
trackedPlanClaims: records.trackedPlanClaims.length,
plansNearby: records.plansNearby.length,
profilesNearby: records.profilesNearby.length,
profilesSimilar: records.profilesSimilar.length,
plansSimilar: records.plansSimilar.length,
};
}
/** Sum of raw list lengths. Not the number announced in FCM or SMS. */
export function totalAlertSearchDigestCount(counts: AlertSearchDigestCounts): number {
return ALERT_SEARCH_DIGEST_BUCKETS.reduce(
(sum, bucket) => sum + counts[bucket],
@@ -121,7 +141,7 @@ export function buildAlertSearchDigest(
...copyPartnerRecords(retrieved.partner.data),
};
const counts = countAlertSearchDigestRecords(records);
const totalCount = totalAlertSearchDigestCount(counts);
const totalCount = totalAlertSearchUpdates(countAlertSearchUpdates(records));
const hasUpdates = completed && totalCount > 0;
return {
+7 -6
View File
@@ -4,10 +4,13 @@ export {
PARTNER_ALERT_SEARCH_PATH,
} from "./types.js";
export type {
AlertSearchCursor,
AlertSearchCursorUlid,
AlertSearchFailureReason,
AlertSearchLocationBBox,
AlertSearchQueryOutcome,
AlertSearchSimilarPlan,
AlertSearchSimilarProfile,
CombinedAlertSearchData,
EndorserAlertSearchData,
EndorserAlertSearchResponse,
@@ -17,24 +20,22 @@ export type {
export {
alertSearchUrl,
buildAlertSearchQuery,
isAlertSearchCursorUlid,
isCompleteLocationBBox,
} from "./params.js";
export {
fetchEndorserAlertSearchPage,
fetchPartnerAlertSearchPage,
nextEndorserBeforeId,
parseEndorserAlertSearchResponse,
parsePartnerAlertSearchResponse,
partnerPageHasTiedBeforeDate,
} from "./client.js";
export { retrieveAlertSearch } from "./retrieve.js";
export type { RetrieveAlertSearchInput, RetrieveAlertSearchResult } from "./retrieve.js";
export {
advanceAlertSearchCursors,
alertSearchCursorsStore,
loadAlertSearchCursors,
maxEndorserAlertSearchUlid,
maxPartnerUpdatedAt,
loadAlertSearchInputs,
nextCursorFromResult,
} from "./cursors.js";
export type { CursorAdvanceResult, StoredAlertSearchCursors } from "./cursors.js";
export { runAlertSearchCycle } from "./cycle.js";
@@ -59,8 +60,8 @@ export type {
} from "./scheduler.js";
export {
ALERT_SEARCH_FCM_TYPE,
ALERT_SEARCH_NOTIFICATION_TITLE,
alertSearchNotificationBody,
alertSearchNotificationTitle,
buildAlertSearchNotificationContent,
deliverAlertSearchNotification,
isAlertSearchNotificationEligible,
+124 -9
View File
@@ -1,15 +1,29 @@
import { alertPushSendsDb } from "../db/alertPushSendsSqlite.js";
import { db } from "../db/fcmTokensSqlite.js";
import { pushSameDayResendDids } from "../env.js";
import { utcCalendarDay } from "../services/alertAuthorization.js";
import { errorMessage } from "../util/formatElapsed.js";
import type { DailyAlertSearchResult } from "./daily.js";
import {
ALERT_SEARCH_UPDATE_CATEGORIES,
countAlertSearchUpdates,
formatAlertSearchUpdateLine,
totalAlertSearchUpdates,
} from "./categories.js";
import {
alertSearchLinkCursorParam,
type DailyAlertSearchResult,
} from "./daily.js";
import type { CombinedAlertSearchData } from "./types.js";
import { log } from "../util/log.js";
export const ALERT_SEARCH_NOTIFICATION_TITLE = "TimeSafari";
export const ALERT_SEARCH_FCM_TYPE = "alert_search";
export type AlertSearchNotificationContent = {
title: string;
body: string;
type: typeof ALERT_SEARCH_FCM_TYPE;
/** The run's start cursors, as the `c` query value of the app link. */
cursorParam?: string;
};
export type AlertSearchTokenSender = (
@@ -20,26 +34,97 @@ export type AlertSearchTokenSender = (
export type AlertSearchNotifyDeps = {
listTokens?: (userId: string) => Promise<string[]>;
send?: AlertSearchTokenSender;
/** Cap window uses this instant's UTC day. Tests pass a fixed clock. */
now?: Date;
};
export type AlertSearchNotifyResult = {
eligible: boolean;
sent: number;
failed: number;
/** True when the daily cap withheld an eligible digest. */
capped?: boolean;
};
export function alertSearchNotificationBody(totalCount: number): string {
const noun = totalCount === 1 ? "update" : "updates";
return `You have ${totalCount} new ${noun}.`;
/** Deduplicated total. Singular only when that total is exactly 1. */
export function alertSearchNotificationTitle(total: number): string {
const noun = total === 1 ? "update" : "updates";
return `You have ${total} new ${noun}`;
}
function alertSearchUpdateLines(
records: CombinedAlertSearchData,
userId?: string
): string[] {
const counts = countAlertSearchUpdates(records, userId);
return ALERT_SEARCH_UPDATE_CATEGORIES.flatMap((category) => {
const count = counts[category];
if (count <= 0) return [];
return [formatAlertSearchUpdateLine(category, count)];
});
}
/**
* One `- ` line per nonzero category, in display order. The title carries the
* total. An empty string means nothing to show; eligibility still refuses to
* send that digest.
*/
export function alertSearchNotificationBody(
records: CombinedAlertSearchData,
userId?: string
): string {
return alertSearchUpdateLines(records, userId)
.map((line) => `- ${line}`)
.join("\n");
}
/**
* Backstop on top of JWT consumption: at most one alert push per identity per
* UTC calendar day, to all of its devices at once. A DID on
* `PUSH_SAME_DAY_RESEND_DIDS` gets one per uploaded batch instead, so a
* `rerunToday` reset can push it again the same day.
*/
export const ALERT_PUSHES_PER_DAY = 1;
/** Midnight UTC at the start of `now`'s day, in the send log's ISO format. */
function utcDayStartIso(now: Date): string {
return utcCalendarDay(Math.floor(now.getTime() / 1000)) + "T00:00:00.000Z";
}
/** Whether `PUSH_SAME_DAY_RESEND_DIDS` lets this DID get a second push in a day. */
export function canPushAgainSameDay(userId: string): boolean {
return pushSameDayResendDids().includes(userId.trim().toLowerCase());
}
/**
* Whether a `rerunToday` reset may re-arm today: the identity has had no
* alert push since UTC midnight, or may get another the same day. Otherwise
* the run would push nothing and only move the cursors past what the next
* push should report.
*/
export async function sameDayPushRerunAllowed(
userId: string,
now: Date = new Date()
): Promise<boolean> {
if (canPushAgainSameDay(userId)) return true;
const pushedToday = await alertPushSendsDb.countSince(
userId,
utcDayStartIso(now)
);
return pushedToday < ALERT_PUSHES_PER_DAY;
}
export function buildAlertSearchNotificationContent(
totalCount: number
records: CombinedAlertSearchData,
userId?: string,
cursorParam?: string
): AlertSearchNotificationContent {
const total = totalAlertSearchUpdates(countAlertSearchUpdates(records, userId));
return {
title: ALERT_SEARCH_NOTIFICATION_TITLE,
body: alertSearchNotificationBody(totalCount),
title: alertSearchNotificationTitle(total),
body: alertSearchNotificationBody(records, userId),
type: ALERT_SEARCH_FCM_TYPE,
...(cursorParam !== undefined ? { cursorParam } : {}),
};
}
@@ -82,6 +167,7 @@ async function defaultSend(
return sendAlertSearchPushToDevice(fcmToken, {
title: content.title,
body: content.body,
cursorParam: content.cursorParam,
});
}
@@ -98,7 +184,29 @@ export async function deliverAlertSearchNotification(
return { eligible: false, sent: 0, failed: 0 };
}
const content = buildAlertSearchNotificationContent(digest.totalCount);
const content = buildAlertSearchNotificationContent(
digest.records,
result.userId,
alertSearchLinkCursorParam(result.startCursors)
);
const now = deps.now ?? new Date();
const dayStartIso = utcDayStartIso(now);
// ISO-8601 UTC strings compare chronologically as text.
const capWindowStartIso =
canPushAgainSameDay(result.userId) &&
result.authorizedAt !== undefined &&
result.authorizedAt > dayStartIso
? result.authorizedAt
: dayStartIso;
const alreadyPushed = await alertPushSendsDb.countSince(
result.userId,
capWindowStartIso
);
if (alreadyPushed >= ALERT_PUSHES_PER_DAY) {
log.info("[AlertSearchNotify] Daily cap already met for", result.userId);
return { eligible: true, sent: 0, failed: 0, capped: true };
}
const listTokens = deps.listTokens ?? defaultListTokens;
const send = deps.send ?? defaultSend;
const tokens = await listTokens(result.userId);
@@ -116,5 +224,12 @@ export async function deliverAlertSearchNotification(
}
}
if (sent > 0) {
await alertPushSendsDb.append({
userId: result.userId,
batchId: result.batchId,
sentAt: now.toISOString(),
});
}
return { eligible: true, sent, failed };
}
+4 -27
View File
@@ -1,13 +1,4 @@
import type { AlertSearchCursorUlid, AlertSearchLocationBBox } from "./types.js";
/** Crockford ULID, same regex as endorser-ch alert-search.service.js */
const ULID_REGEX = /^[0-9A-HJKMNP-TV-Z]{26}$/;
export function isAlertSearchCursorUlid(
value: unknown
): value is AlertSearchCursorUlid {
return typeof value === "string" && ULID_REGEX.test(value);
}
import type { AlertSearchCursor, AlertSearchLocationBBox } from "./types.js";
/**
* Only a complete bbox is sent. Partial boxes are omitted rather than guessing.
@@ -32,17 +23,14 @@ export function isCompleteLocationBBox(
}
export type AlertSearchQueryInput = {
afterId?: string;
beforeId?: string;
afterDate?: string;
beforeDate?: string;
/** Changes after this cursor. Omitted on a first run: the server returns its most recent rows. */
afterCursor?: AlertSearchCursor;
location?: AlertSearchLocationBBox;
planHandleIds?: string[];
};
/**
* GET query params for alertSearch.
* Omits afterId/beforeId unless they are valid ULIDs (never sends "0").
* Location is flattened to minLocLat/maxLocLat/minLocLon/maxLocLon for GET.
*/
export function buildAlertSearchQuery(
@@ -50,18 +38,7 @@ export function buildAlertSearchQuery(
): URLSearchParams {
const params = new URLSearchParams();
if (isAlertSearchCursorUlid(input.afterId)) {
params.set("afterId", input.afterId);
}
if (isAlertSearchCursorUlid(input.beforeId)) {
params.set("beforeId", input.beforeId);
}
if (typeof input.afterDate === "string" && input.afterDate.length > 0) {
params.set("afterDate", input.afterDate);
}
if (typeof input.beforeDate === "string" && input.beforeDate.length > 0) {
params.set("beforeDate", input.beforeDate);
}
if (input.afterCursor) params.set("afterCursor", input.afterCursor);
if (input.location !== undefined && isCompleteLocationBBox(input.location)) {
params.set("minLocLat", String(input.location.minLocLat));
params.set("maxLocLat", String(input.location.maxLocLat));
+180 -155
View File
@@ -7,21 +7,20 @@ import {
import {
emptyEndorserData,
emptyPartnerData,
endorserBucketHitPageLimit,
fetchEndorserAlertSearchPage,
fetchPartnerAlertSearchPage,
minPartnerBeforeDate,
nextEndorserBeforeId,
partnerBucketHitPageLimit,
partnerPageHasTiedBeforeDate,
plansNearbyHitPageLimit,
type AlertSearchHttpConfig,
type AlertSearchHttpResult,
} from "./client.js";
import type { AlertSearchQueryInput } from "./params.js";
import type {
AlertSearchCursor,
AlertSearchFailureReason,
AlertSearchLocationBBox,
AlertSearchPlanRecord,
AlertSearchProfileRecord,
AlertSearchQueryOutcome,
AlertSearchSimilarPlan,
AlertSearchSimilarProfile,
CombinedAlertSearchData,
EndorserAlertSearchData,
PartnerAlertSearchData,
@@ -31,12 +30,6 @@ const DEFAULT_MAX_PAGES = 20;
const TRUNCATION_HINT = "Some data was not available in this search";
const PLANS_NEARBY_INCOMPLETE_MESSAGE =
"plansNearby reached the server row limit. The alertSearch API orders that bucket by rowid while filtering jwtId, so remaining nearby plans cannot be proven complete.";
const PARTNER_TIMESTAMP_TIE_MESSAGE =
"Partner alertSearch page hit the row limit with multiple profiles sharing the oldest updatedAt. Exclusive beforeDate pagination cannot retrieve remaining rows at that timestamp.";
export type AlertSearchSourceResult<TData> = {
outcome: AlertSearchQueryOutcome;
reason?: AlertSearchFailureReason;
@@ -44,17 +37,19 @@ export type AlertSearchSourceResult<TData> = {
userMessage?: string;
pageCount: number;
data: TData;
/** Cursor to store: the last page's nextAfterCursor. Absent on failure. */
nextAfterCursor?: AlertSearchCursor;
/** A first run: the rows were discarded and only the cursor is kept. */
seeded?: boolean;
};
export type RetrieveAlertSearchInput = {
/** Delegated notification JWT for this scheduled day. Not the setup session JWT. */
jwt: string;
/** Endorser cursor from a previous successful daily run. Omit on first run. */
endorserAfterId?: string;
/** Partner afterId ULID (decoded to a timestamp by the server). Prefer partnerAfterDate. */
partnerAfterId?: string;
/** Partner exclusive lower bound: updatedAt > this ISO time. Omit on first run. */
partnerAfterDate?: string;
/** Endorser cursor (nextAfterCursor) from a previous run. Omit on first run. */
endorserAfterCursor?: AlertSearchCursor;
/** Partner cursor (nextAfterCursor) from a previous run. Omit on first run. */
partnerAfterCursor?: AlertSearchCursor;
/** User-selected nearby-search bbox (alertSearch minLoc* / maxLoc* shape). */
location?: AlertSearchLocationBBox;
planHandleIds?: string[];
@@ -120,6 +115,44 @@ function mergeEndorser(
};
}
function mergeBy<T>(
existing: T[],
incoming: T[],
keyOf: (row: T) => string | undefined
): T[] {
const seen = new Set<string>();
const out: T[] = [];
for (const row of [...existing, ...incoming]) {
const key = keyOf(row);
if (key !== undefined) {
if (seen.has(key)) continue;
seen.add(key);
}
out.push(row);
}
return out;
}
function profileMergeKey(profile: AlertSearchProfileRecord): string | undefined {
if (typeof profile.rowId === "number" || typeof profile.rowId === "string") {
return `rowId:${profile.rowId}`;
}
if (typeof profile.issuerDid === "string" && profile.issuerDid.length > 0) {
return `issuerDid:${profile.issuerDid}`;
}
return undefined;
}
function planMergeKey(plan: AlertSearchPlanRecord): string | undefined {
if (typeof plan.handleId === "string" && plan.handleId.length > 0) {
return `handleId:${plan.handleId}`;
}
if (typeof plan.jwtId === "string" && plan.jwtId.length > 0) {
return `jwtId:${plan.jwtId}`;
}
return undefined;
}
function mergePartner(
acc: PartnerAlertSearchData,
page: PartnerAlertSearchData
@@ -130,6 +163,17 @@ function mergePartner(
"issuerDid",
"updatedAt",
]),
profilesSimilar: mergeBy(
acc.profilesSimilar,
page.profilesSimilar,
(row: AlertSearchSimilarProfile) => profileMergeKey(row.profile)
),
// plansSimilar is the whole main-DB window on every forward page.
plansSimilar: mergeBy(
acc.plansSimilar,
page.plansSimilar,
(row: AlertSearchSimilarPlan) => planMergeKey(row.plan)
),
};
}
@@ -144,37 +188,48 @@ function endorserEmpty(data: EndorserAlertSearchData): boolean {
}
function partnerEmpty(data: PartnerAlertSearchData): boolean {
return data.profilesNearby.length === 0;
return (
data.profilesNearby.length === 0 &&
data.profilesSimilar.length === 0 &&
data.plansSimilar.length === 0
);
}
async function retrieveEndorserPages(input: {
jwt: string;
afterId?: string;
location?: AlertSearchLocationBBox;
planHandleIds?: string[];
baseUrl: string;
type PageResponse<TData> = {
data: TData;
userMessage?: string;
nextAfterCursor?: AlertSearchCursor;
hasMore?: boolean;
};
/**
* Pages with afterCursor = the previous nextAfterCursor while hasMore. Each page
* is complete up to its nextAfterCursor, so stopping at maxPages still yields a
* usable cursor; the rest comes on the next run.
*
* Without afterCursor (a first run), the server returns its most recent rows
* and the cursor at which they were read. That one page is the whole run, and
* its rows are dropped: they happened before notifications were turned on, so
* a first run only seeds the cursor.
*/
async function retrieveCursorPages<TData>(input: {
afterCursor?: AlertSearchCursor;
maxPages: number;
config?: AlertSearchHttpConfig;
}): Promise<AlertSearchSourceResult<EndorserAlertSearchData>> {
let data = emptyEndorserData();
let beforeId: string | undefined;
source: string;
empty: TData;
merge: (acc: TData, page: TData) => TData;
isEmpty: (data: TData) => boolean;
fetchPage: (
afterCursor: AlertSearchCursor | undefined
) => Promise<AlertSearchHttpResult<PageResponse<TData>>>;
}): Promise<AlertSearchSourceResult<TData>> {
let data = input.empty;
let afterCursor = input.afterCursor;
let userMessage: string | undefined;
let pageCount = 0;
let plansNearbyTruncated = false;
for (let page = 0; page < input.maxPages; page++) {
const query: AlertSearchQueryInput = {
afterId: input.afterId,
beforeId,
location: input.location,
planHandleIds: input.planHandleIds,
};
const result = await fetchEndorserAlertSearchPage({
baseUrl: input.baseUrl,
jwt: input.jwt,
query,
config: input.config,
});
const result = await input.fetchPage(afterCursor);
pageCount += 1;
if (!result.ok) {
return {
@@ -191,8 +246,8 @@ async function retrieveEndorserPages(input: {
? `${userMessage} ${result.body.userMessage}`
: result.body.userMessage;
}
data = input.merge(data, result.body.data);
if (result.body.userMessage?.includes(TRUNCATION_HINT)) {
data = mergeEndorser(data, result.body.data);
return {
outcome: "pagination",
reason: "pagination",
@@ -202,147 +257,118 @@ async function retrieveEndorserPages(input: {
data,
};
}
data = mergeEndorser(data, result.body.data);
if (plansNearbyHitPageLimit(result.body.data)) {
plansNearbyTruncated = true;
}
if (!endorserBucketHitPageLimit(result.body.data)) {
if (plansNearbyTruncated) {
return {
outcome: "pagination",
reason: "pagination",
message: PLANS_NEARBY_INCOMPLETE_MESSAGE,
userMessage,
pageCount,
data,
};
}
const nextAfterCursor = result.body.nextAfterCursor;
if (nextAfterCursor === undefined) {
// a server that predates cursors (and ignores 'afterCursor')
return {
outcome: endorserEmpty(data) ? "empty" : "success",
outcome: "malformed",
reason: "malformed",
message: `${input.source} alertSearch returned no nextAfterCursor.`,
userMessage,
pageCount,
data,
};
}
const nextBefore = nextEndorserBeforeId(result.body.data);
if (nextBefore === undefined) {
if (afterCursor === undefined) {
return {
outcome: "empty",
userMessage,
pageCount,
data: input.empty,
nextAfterCursor,
seeded: true,
};
}
if (result.body.hasMore !== true) {
return {
outcome: input.isEmpty(data) ? "empty" : "success",
userMessage,
pageCount,
data,
nextAfterCursor,
};
}
if (nextAfterCursor === afterCursor) {
return {
outcome: "pagination",
reason: "pagination",
message:
"Endorser page was at the server row limit but no beforeId ULID could be derived.",
message: `${input.source} alertSearch reported more rows without moving nextAfterCursor.`,
userMessage,
pageCount,
data,
};
}
beforeId = nextBefore;
afterCursor = nextAfterCursor;
}
return {
outcome: "pagination",
reason: "pagination",
message: plansNearbyTruncated
? PLANS_NEARBY_INCOMPLETE_MESSAGE
: `Endorser alertSearch stopped after ${input.maxPages} pages.`,
outcome: input.isEmpty(data) ? "empty" : "success",
message: `${input.source} alertSearch stopped after ${input.maxPages} pages; the rest comes on the next run.`,
userMessage,
pageCount,
data,
nextAfterCursor: afterCursor,
};
}
async function retrievePartnerPages(input: {
function retrieveEndorserPages(input: {
jwt: string;
afterId?: string;
afterDate?: string;
afterCursor?: AlertSearchCursor;
location?: AlertSearchLocationBBox;
planHandleIds?: string[];
baseUrl: string;
maxPages: number;
config?: AlertSearchHttpConfig;
}): Promise<AlertSearchSourceResult<EndorserAlertSearchData>> {
return retrieveCursorPages({
afterCursor: input.afterCursor,
maxPages: input.maxPages,
source: "Endorser",
empty: emptyEndorserData(),
merge: mergeEndorser,
isEmpty: endorserEmpty,
fetchPage: (afterCursor) =>
fetchEndorserAlertSearchPage({
baseUrl: input.baseUrl,
jwt: input.jwt,
query: {
afterCursor,
location: input.location,
planHandleIds: input.planHandleIds,
},
config: input.config,
}),
});
}
function retrievePartnerPages(input: {
jwt: string;
afterCursor?: AlertSearchCursor;
location?: AlertSearchLocationBBox;
baseUrl: string;
maxPages: number;
config?: AlertSearchHttpConfig;
}): Promise<AlertSearchSourceResult<PartnerAlertSearchData>> {
let data = emptyPartnerData();
let beforeDate: string | undefined;
let userMessage: string | undefined;
let pageCount = 0;
for (let page = 0; page < input.maxPages; page++) {
const query: AlertSearchQueryInput = {
afterId: input.afterId,
afterDate: input.afterDate,
beforeDate,
location: input.location,
};
const result = await fetchPartnerAlertSearchPage({
baseUrl: input.baseUrl,
jwt: input.jwt,
query,
config: input.config,
});
pageCount += 1;
if (!result.ok) {
return {
outcome: result.reason,
reason: result.reason,
message: result.message,
userMessage,
pageCount,
data,
};
}
if (result.body.userMessage) {
userMessage = userMessage
? `${userMessage} ${result.body.userMessage}`
: result.body.userMessage;
}
data = mergePartner(data, result.body.data);
if (partnerBucketHitPageLimit(result.body.data)) {
if (partnerPageHasTiedBeforeDate(result.body.data)) {
return {
outcome: "pagination",
reason: "pagination",
message: PARTNER_TIMESTAMP_TIE_MESSAGE,
userMessage,
pageCount,
data,
};
}
}
if (!partnerBucketHitPageLimit(result.body.data)) {
return {
outcome: partnerEmpty(data) ? "empty" : "success",
userMessage,
pageCount,
data,
};
}
const nextBefore = minPartnerBeforeDate(result.body.data);
if (nextBefore === undefined) {
return {
outcome: "pagination",
reason: "pagination",
message:
"Partner page was at the server row limit but no beforeDate could be derived.",
userMessage,
pageCount,
data,
};
}
beforeDate = nextBefore;
}
return {
outcome: "pagination",
reason: "pagination",
message: `Partner alertSearch stopped after ${input.maxPages} pages.`,
userMessage,
pageCount,
data,
};
return retrieveCursorPages({
afterCursor: input.afterCursor,
maxPages: input.maxPages,
source: "Partner",
empty: emptyPartnerData(),
merge: mergePartner,
isEmpty: partnerEmpty,
fetchPage: (afterCursor) =>
fetchPartnerAlertSearchPage({
baseUrl: input.baseUrl,
jwt: input.jwt,
query: { afterCursor, location: input.location },
config: input.config,
}),
});
}
/**
* Query Endorser and Partner alertSearch independently with the same delegated JWT.
* Does not persist cursors; the caller supplies afterId values.
* Does not persist cursors; the caller supplies them.
*/
export async function retrieveAlertSearch(
input: RetrieveAlertSearchInput
@@ -356,7 +382,7 @@ export async function retrieveAlertSearch(
const [endorser, partner] = await Promise.all([
retrieveEndorserPages({
jwt: input.jwt,
afterId: input.endorserAfterId,
afterCursor: input.endorserAfterCursor,
location: input.location,
planHandleIds: input.planHandleIds,
baseUrl: endorserBaseUrl,
@@ -365,8 +391,7 @@ export async function retrieveAlertSearch(
}),
retrievePartnerPages({
jwt: input.jwt,
afterId: input.partnerAfterId,
afterDate: input.partnerAfterDate,
afterCursor: input.partnerAfterCursor,
location: input.location,
baseUrl: partnerBaseUrl,
maxPages,
+77 -11
View File
@@ -11,13 +11,22 @@ import {
} from "../services/smsService.js";
import { smsBlockedNumbersDb } from "../db/smsBlockedNumbersSqlite.js";
import { errorMessage } from "../util/formatElapsed.js";
import { maskPhoneNumber } from "../util/smsPhoneNumber.js";
import {
maskPhoneNumber,
normalizePhoneNumber,
} from "../util/smsPhoneNumber.js";
import { hashPhoneNumber } from "../util/smsVerificationCode.js";
import type { DailyAlertSearchResult } from "./daily.js";
import {
alertSearchLinkCursorParam,
type DailyAlertSearchResult,
} from "./daily.js";
import { log } from "../util/log.js";
/** The app link. giftopia.tech is the claim namespace and never appears in a message. */
export const ALERT_SEARCH_SMS_LINK = "https://giftopia.me";
/**
* The app's new-activity deep link. giftopia.tech is the claim namespace and
* never appears in a message.
*/
export const ALERT_SEARCH_SMS_LINK = "https://giftopia.me/deep-link/new-activity";
/** One GSM-7 segment. A second segment is a second charge for a longer sentence. */
export const SMS_SINGLE_SEGMENT_LIMIT = 160;
@@ -26,10 +35,48 @@ export const SMS_SINGLE_SEGMENT_LIMIT = 160;
* Backstop on top of JWT consumption: at most one digest per handset per
* identity per UTC calendar day. Scoped to the pair rather than the identity
* alone, because a DID with two verified handsets legitimately receives two
* texts.
* texts. A number on `SMS_SAME_DAY_RESEND_NUMBERS` gets one per uploaded batch
* instead, so a `rerunToday` reset can text it again the same day.
*/
export const ALERT_SENDS_PER_PHONE_PER_DAY = 1;
/** Midnight UTC at the start of `now`'s day, in the log's ISO format. */
function utcDayStartIso(now: Date): string {
return utcCalendarDay(Math.floor(now.getTime() / 1000)) + "T00:00:00.000Z";
}
/** Whether `SMS_SAME_DAY_RESEND_NUMBERS` lets this number get a second text in a day. */
export function canResendSameDay(phoneE164: string): boolean {
return smsConfig().sameDayResendNumbers.some(
(entry) => normalizePhoneNumber(entry) === phoneE164
);
}
/**
* Whether a `rerunToday` reset may re-arm today: some number of this identity
* can still get a text today, because it has had none since UTC midnight or
* may resend the same day. Otherwise the run would text nobody and only move
* the cursors past what the next text should report.
*/
export async function sameDayRerunAllowed(
userId: string,
phones: string[],
secret: string,
now: Date = new Date()
): Promise<boolean> {
for (const phoneE164 of phones) {
if (canResendSameDay(phoneE164)) return true;
const textedToday = await smsPhoneLogDb.countByUserAndPhoneHashSince(
userId,
hashPhoneNumber(phoneE164, secret),
["alert-sent"],
utcDayStartIso(now)
);
if (textedToday < ALERT_SENDS_PER_PHONE_PER_DAY) return true;
}
return false;
}
export type AlertSearchSmsNotifyDeps = {
listPhones?: (userId: string) => Promise<string[]>;
send?: SmsSender;
@@ -45,11 +92,23 @@ export type AlertSearchSmsNotifyResult = {
blocked: number;
};
export function alertSearchSmsBody(totalCount: number): string {
/**
* @param totalCount `digest.totalCount`: the same deduped total the FCM heading uses
* @param cursorParam the run's start cursors (`alertSearchLinkCursorParam`),
* so the app can tell whether it shows the window this text counted
*/
export function alertSearchSmsBody(
totalCount: number,
cursorParam?: string
): string {
const noun = totalCount === 1 ? "update" : "updates";
const link =
cursorParam === undefined
? ALERT_SEARCH_SMS_LINK
: `${ALERT_SEARCH_SMS_LINK}?c=${encodeURIComponent(cursorParam)}`;
return (
`Gift Economies: you have ${totalCount} new ${noun}. ` +
`${ALERT_SEARCH_SMS_LINK} Reply STOP to end.`
`${link} Reply STOP to end.`
);
}
@@ -130,12 +189,19 @@ export async function deliverAlertSearchSms(
return { eligible: false, sent: 0, failed: 0, blocked: 0 };
}
const body = alertSearchSmsBody(digest.totalCount);
const body = alertSearchSmsBody(
digest.totalCount,
alertSearchLinkCursorParam(result.startCursors)
);
const listPhones = deps.listPhones ?? defaultListPhones;
const send = deps.send ?? sendSms;
const now = deps.now ?? new Date();
const utcDayStartIso =
utcCalendarDay(Math.floor(now.getTime() / 1000)) + "T00:00:00.000Z";
const dayStartIso = utcDayStartIso(now);
// ISO-8601 UTC strings compare chronologically as text.
const batchWindowStartIso =
result.authorizedAt !== undefined && result.authorizedAt > dayStartIso
? result.authorizedAt
: dayStartIso;
const phones = await listPhones(result.userId);
// The digest was worth sending; this instance is simply not allowed to send
@@ -190,7 +256,7 @@ export async function deliverAlertSearchSms(
result.userId,
phoneHash,
["alert-sent"],
utcDayStartIso
canResendSameDay(phoneE164) ? batchWindowStartIso : dayStartIso
);
if (alreadySent >= ALERT_SENDS_PER_PHONE_PER_DAY) {
log.info(
+103 -3
View File
@@ -1,4 +1,9 @@
import { smsActionJwtUseDb } from "../db/smsActionJwtUseSqlite.js";
import {
SMS_ALERT_SEARCH_RUN_RETENTION_DAYS,
smsAlertSearchRunsDb,
type SmsAlertSearchRunInput,
} from "../db/smsAlertSearchRunsSqlite.js";
import type { PendingDayUser } from "../db/alertAuthorizationSqlite.js";
import { smsAlertAuthorizationDb } from "../db/smsAlertAuthorizationSqlite.js";
import { smsConfig } from "../env.js";
@@ -15,7 +20,10 @@ import {
runDailyAlertSearch,
type DailyAlertSearchResult,
} from "./daily.js";
import { deliverAlertSearchSms } from "./smsNotify.js";
import {
deliverAlertSearchSms,
type AlertSearchSmsNotifyResult,
} from "./smsNotify.js";
import { log } from "../util/log.js";
/** Keeps the SMS pass off the same instant as the FCM pass at Endorser. */
@@ -32,6 +40,8 @@ export type SmsAlertSearchSchedulerPassInput = {
runDaily?: (userId: string) => Promise<DailyAlertSearchResult>;
notify?: (result: DailyAlertSearchResult) => Promise<unknown>;
prune?: () => Promise<unknown>;
/** Stores what one user's run found. Failures are logged, never fatal. */
recordRun?: (run: SmsAlertSearchRunInput) => Promise<unknown>;
/** The instant this pass represents. Defaults to now. */
now?: Date;
/** Users worked on at once. Set to 1 for a deterministic order in tests. */
@@ -64,6 +74,60 @@ async function defaultPrune(): Promise<void> {
1000
).toISOString();
await smsActionJwtUseDb.pruneOlderThan(cutoff);
await smsAlertSearchRunsDb.pruneOlderThan(
new Date(
Date.now() - SMS_ALERT_SEARCH_RUN_RETENTION_DAYS * 24 * 60 * 60 * 1000
).toISOString()
);
}
/** The counts deliverAlertSearchSms returns, when the notifier returned them. */
function smsNotifyCounts(
value: unknown
): Pick<
SmsAlertSearchRunInput,
"smsEligible" | "smsSent" | "smsFailed" | "smsBlocked"
> {
if (value === null || typeof value !== "object") return {};
const v = value as Partial<AlertSearchSmsNotifyResult>;
return typeof v.eligible === "boolean"
? {
smsEligible: v.eligible,
smsSent: v.sent,
smsFailed: v.failed,
smsBlocked: v.blocked,
}
: {};
}
/** The run row for a daily result; the digest's records go in whole. */
export function smsAlertSearchRunRow(
daily: DailyAlertSearchResult,
notified: unknown,
ranAt: string,
elapsedMs: number
): SmsAlertSearchRunInput {
const digest = daily.digest;
return {
userId: daily.userId,
utcDay: daily.utcDay,
ranAt,
elapsedMs,
completed: daily.completed,
consumed: daily.consumed,
endorserOutcome: daily.endorserOutcome,
partnerOutcome: daily.partnerOutcome,
endorserStartCursor: daily.startCursors?.endorser,
partnerStartCursor: daily.startCursors?.partner,
totalCount: digest?.totalCount,
counts: digest?.counts,
records: digest?.records,
sourceMessages:
digest === null
? undefined
: { endorser: digest.endorser.message, partner: digest.partner.message },
...smsNotifyCounts(notified),
};
}
/**
@@ -90,6 +154,20 @@ export async function runSmsAlertSearchSchedulerPass(
((userId: string) => runDailyAlertSearch(userId, now, {}, "sms"));
const notify = input.notify ?? deliverAlertSearchSms;
const prune = input.prune ?? defaultPrune;
const recordRun =
input.recordRun ??
((run: SmsAlertSearchRunInput) => smsAlertSearchRunsDb.append(run));
const record = async (run: SmsAlertSearchRunInput): Promise<void> => {
try {
await recordRun(run);
} catch (err) {
log.error(
"[SmsAlertSearchScheduler] Run record failed",
run.userId + ":",
errorMessage(err)
);
}
};
const listPending =
input.listPending ??
((query: { day: string; hourMinute: string }) =>
@@ -117,17 +195,33 @@ export async function runSmsAlertSearchSchedulerPass(
userIds,
input.concurrency ?? ALERT_SEARCH_USER_CONCURRENCY,
async (userId) => {
const ranAt = new Date().toISOString();
const userStarted = Date.now();
try {
const daily = await runDaily(userId);
let notified: unknown;
let notifyError: string | undefined;
try {
await notify(daily);
notified = await notify(daily);
} catch (err) {
notifyError = errorMessage(err);
log.error(
"[SmsAlertSearchScheduler] Notification failed",
userId + ":",
errorMessage(err)
notifyError
);
}
await record({
...smsAlertSearchRunRow(
daily,
notified,
ranAt,
Date.now() - userStarted
),
...(notifyError === undefined
? {}
: { error: "notify: " + notifyError }),
});
} catch (err) {
failed += 1;
log.error(
@@ -135,6 +229,12 @@ export async function runSmsAlertSearchSchedulerPass(
userId + ":",
errorMessage(err)
);
await record({
userId,
ranAt,
elapsedMs: Date.now() - userStarted,
error: errorMessage(err),
});
}
}
);
+45
View File
@@ -12,6 +12,13 @@ export type AlertSearchChannel = "fcm" | "sms";
/** Server-issued ULID on a stored JWT/plan record. Not an auth or delegated JWT. */
export type AlertSearchCursorUlid = string;
/**
* Opaque cursor returned by alertSearch as `nextAfterCursor` and sent back as
* `afterCursor`. Stored as text and never parsed (see endorser-ch
* CHANGE/PLAN-accurate-cursors.md).
*/
export type AlertSearchCursor = string;
export type AlertSearchLocationBBox = {
minLocLat: number;
maxLocLat: number;
@@ -21,6 +28,7 @@ export type AlertSearchLocationBBox = {
export type AlertSearchClaimRecord = {
id: AlertSearchCursorUlid;
changeSeq?: number;
issuedAt: string;
issuer: string;
subject?: string;
@@ -38,6 +46,7 @@ export type AlertSearchJwtWithClaimRecord = AlertSearchClaimRecord & {
export type AlertSearchPlanRecord = {
handleId: string;
jwtId: AlertSearchCursorUlid;
changeSeq?: number;
issuerDid?: string;
agentDid?: string;
fulfillsLinkConfirmed?: boolean | number;
@@ -58,6 +67,7 @@ export type AlertSearchPlanRecord = {
export type AlertSearchProfileRecord = {
rowId?: number;
changeSeq?: number;
issuerDid: string;
updatedAt?: string;
description: string;
@@ -68,6 +78,26 @@ export type AlertSearchProfileRecord = {
[key: string]: unknown;
};
/**
* Partner `profilesSimilar` element: a profile whose embedding was stamped in
* the cursor window and is at least `alertMinimumSimilarity` from the
* requester's profile. Best first; not paged on its own.
*/
export type AlertSearchSimilarProfile = {
similarity?: number;
profile: AlertSearchProfileRecord;
};
/**
* Partner `plansSimilar` element: a plan whose embedding was stamped in the
* cursor window and is close to the requester's profile. Best first. On a
* forward cursor the whole plan window is repeated on every profiles page.
*/
export type AlertSearchSimilarPlan = {
similarity?: number;
plan: AlertSearchPlanRecord;
};
export type EndorserAlertSearchData = {
claims: AlertSearchClaimRecord[];
personalPlanContributions: AlertSearchJwtWithClaimRecord[];
@@ -76,21 +106,36 @@ export type EndorserAlertSearchData = {
plansNearby: AlertSearchPlanRecord[];
};
/** The similar lists are empty from partner servers that predate them. */
export type PartnerAlertSearchData = {
profilesNearby: AlertSearchProfileRecord[];
profilesSimilar: AlertSearchSimilarProfile[];
plansSimilar: AlertSearchSimilarPlan[];
};
export type CombinedAlertSearchData = EndorserAlertSearchData &
PartnerAlertSearchData;
/**
* `nextAfterCursor` and `hasMore` are absent from servers that predate cursors
* (endorser-ch through 4.4.6); this service treats such a response as malformed.
*/
export type EndorserAlertSearchResponse = {
data: EndorserAlertSearchData;
userMessage?: string;
nextAfterCursor?: AlertSearchCursor;
/** For paging backwards (newest first); not used by this service. */
nextBeforeCursor?: AlertSearchCursor;
hasMore?: boolean;
};
export type PartnerAlertSearchResponse = {
data: PartnerAlertSearchData;
userMessage?: string;
nextAfterCursor?: AlertSearchCursor;
/** For paging backwards (newest first); not used by this service. */
nextBeforeCursor?: AlertSearchCursor;
hasMore?: boolean;
};
export const ENDORSER_ALERT_SEARCH_PATH = "/api/v2/report/alertSearch";
+22 -2
View File
@@ -163,7 +163,9 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
return {
/**
* Atomically drop this user's unused JWTs (and empty batch rows), then install
* a new batch. Consumed JWTs from prior batches are left in place.
* a new batch. Consumed JWTs from prior batches are left in place, and the
* new batch's JWTs for those days are skipped: a day that already ran must
* not run (and notify) again because the app uploaded after it.
*/
async replaceUnusedBatch(input: {
userId: string;
@@ -172,6 +174,8 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
notifyMinuteUtc?: number;
timezone?: string;
jwts: AlertAuthorizationJwtInput[];
/** Also store JWTs for days that already hold a consumed one. */
rerunToday?: boolean;
}): Promise<{
batch: AlertAuthorizationBatchRecord;
storedCount: number;
@@ -181,6 +185,7 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
const now = new Date().toISOString();
const batchPk = randomUUID();
let insertedCount = 0;
const run = connection.transaction(() => {
connection
.prepare(
@@ -191,6 +196,19 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
)
.run(input.userId, ALERT_JWT_STATUS_UNUSED);
const consumedDays = new Set(
(
connection
.prepare(
`
SELECT DISTINCT day FROM ${tables.jwts}
WHERE user_id = ? AND status = ?
`
)
.all(input.userId, ALERT_JWT_STATUS_CONSUMED) as { day: string }[]
).map((row) => row.day)
);
connection
.prepare(
`
@@ -234,6 +252,8 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
);
for (const item of input.jwts) {
if (!input.rerunToday && consumedDays.has(item.day)) continue;
insertedCount += 1;
insertJwt.run({
id: randomUUID(),
batch_pk: batchPk,
@@ -264,7 +284,7 @@ export function createAlertAuthorizationStore(tables: AlertAuthorizationTables)
timezone: input.timezone,
createdAt: now,
},
storedCount: input.jwts.length,
storedCount: insertedCount,
unusedCount,
};
},
+41
View File
@@ -0,0 +1,41 @@
import { randomUUID } from "node:crypto";
import { getDatabase } from "./sqlite.js";
/** How long send rows are kept. The cap reads only the current UTC day. */
export const ALERT_PUSH_SEND_RETENTION_DAYS = 30;
/** Push-channel alerts sent, per identity: the push twin of SMS `alert-sent` rows. */
export const alertPushSendsDb = {
/** Record a send, and drop this identity's rows past the retention window. */
async append(input: {
userId: string;
batchId?: string | null;
sentAt?: string;
}): Promise<void> {
const sentAt = input.sentAt ?? new Date().toISOString();
const cutoff = new Date(
Date.parse(sentAt) - ALERT_PUSH_SEND_RETENTION_DAYS * 24 * 60 * 60 * 1000
).toISOString();
const db = getDatabase();
db.transaction(() => {
db.prepare(
`INSERT INTO alert_push_sends (id, user_id, batch_id, sent_at)
VALUES (?, ?, ?, ?)`
).run(randomUUID(), input.userId, input.batchId ?? null, sentAt);
db.prepare(
`DELETE FROM alert_push_sends WHERE user_id = ? AND sent_at < ?`
).run(input.userId, cutoff);
})();
},
/** Sends to this identity at or after `sinceIso`. */
async countSince(userId: string, sinceIso: string): Promise<number> {
const row = getDatabase()
.prepare(
`SELECT COUNT(*) AS n FROM alert_push_sends
WHERE user_id = ? AND sent_at >= ?`
)
.get(userId, sinceIso) as { n: number };
return row.n;
},
};
+101 -41
View File
@@ -1,26 +1,58 @@
import type { AlertSearchLocationBBox } from "../alertSearch/types.js";
import { getDatabase } from "./sqlite.js";
export type AlertSearchCursorRecord = {
userId: string;
endorserAfterId: string | null;
partnerAfterAt: string | null;
/** Opaque Endorser cursor (alertSearch nextAfterCursor). */
endorserAfterCursor: string | null;
/** Opaque Partner cursor (alertSearch nextAfterCursor). */
partnerAfterCursor: string | null;
/** Starred plan handle IDs to track; null when none were uploaded. */
planHandleIds: string[] | null;
/** Area for the nearby lists; null when none was uploaded. */
location: AlertSearchLocationBBox | null;
createdAt: string;
updatedAt: string;
};
/**
* What an upload sets. A field left undefined keeps its stored value; null
* clears planHandleIds or location.
*/
export type AlertSearchStateUpdate = {
endorserAfterCursor?: string;
partnerAfterCursor?: string;
planHandleIds?: string[] | null;
location?: AlertSearchLocationBBox | null;
};
type CursorDbRow = {
user_id: string;
endorser_after_id: string | null;
partner_after_at: string | null;
endorser_after_cursor: string | null;
partner_after_cursor: string | null;
plan_handle_ids: string | null;
location: string | null;
created_at: string;
updated_at: string;
};
/** A stored JSON column, or null when it is empty or unreadable. */
function parseJsonColumn<T>(value: string | null): T | null {
if (value === null) return null;
try {
return JSON.parse(value) as T;
} catch {
return null;
}
}
function toRecord(row: CursorDbRow): AlertSearchCursorRecord {
return {
userId: row.user_id,
endorserAfterId: row.endorser_after_id,
partnerAfterAt: row.partner_after_at,
endorserAfterCursor: row.endorser_after_cursor,
partnerAfterCursor: row.partner_after_cursor,
planHandleIds: parseJsonColumn<string[]>(row.plan_handle_ids),
location: parseJsonColumn<AlertSearchLocationBBox>(row.location),
createdAt: row.created_at,
updatedAt: row.updated_at,
};
@@ -37,9 +69,8 @@ function ensureRow(table: string, userId: string, now: string): void {
getDatabase()
.prepare(
`
INSERT INTO ${table} (
user_id, endorser_after_id, partner_after_at, created_at, updated_at
) VALUES (?, NULL, NULL, ?, ?)
INSERT INTO ${table} (user_id, created_at, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(user_id) DO NOTHING
`
)
@@ -52,6 +83,27 @@ function ensureRow(table: string, userId: string, now: string): void {
* delta and leave the other reporting nothing.
*/
export function createAlertSearchCursorsStore(table: string) {
/** Column name to value; names come only from this module. */
function setColumns(userId: string, values: Record<string, string | null>): void {
const names = Object.keys(values);
if (names.length === 0) return;
const now = new Date().toISOString();
const connection = getDatabase();
const run = connection.transaction(() => {
ensureRow(table, userId, now);
connection
.prepare(
`
UPDATE ${table}
SET ${names.map((name) => `${name} = ?`).join(", ")}, updated_at = ?
WHERE user_id = ?
`
)
.run(...names.map((name) => values[name]), now, userId);
});
run();
}
return {
async get(
userId: string
@@ -59,7 +111,8 @@ export function createAlertSearchCursorsStore(table: string) {
const row = getDatabase()
.prepare(
`
SELECT user_id, endorser_after_id, partner_after_at, created_at, updated_at
SELECT user_id, endorser_after_cursor, partner_after_cursor,
plan_handle_ids, location, created_at, updated_at
FROM ${table}
WHERE user_id = ?
`
@@ -68,40 +121,47 @@ export function createAlertSearchCursorsStore(table: string) {
return row === undefined ? undefined : toRecord(row);
},
async setEndorserAfterId(userId: string, afterId: string): Promise<void> {
const now = new Date().toISOString();
const connection = getDatabase();
const run = connection.transaction(() => {
ensureRow(table, userId, now);
connection
.prepare(
`
UPDATE ${table}
SET endorser_after_id = ?, updated_at = ?
WHERE user_id = ?
`
)
.run(afterId, now, userId);
});
run();
async setEndorserAfterCursor(userId: string, after: string): Promise<void> {
setColumns(userId, { endorser_after_cursor: after });
},
async setPartnerAfterAt(userId: string, afterAt: string): Promise<void> {
const now = new Date().toISOString();
const connection = getDatabase();
const run = connection.transaction(() => {
ensureRow(table, userId, now);
connection
.prepare(
`
UPDATE ${table}
SET partner_after_at = ?, updated_at = ?
WHERE user_id = ?
`
)
.run(afterAt, now, userId);
async setPartnerAfterCursor(userId: string, after: string): Promise<void> {
setColumns(userId, { partner_after_cursor: after });
},
/** Both cursors in one write, so neither moves without the other. */
async setAfterCursors(
userId: string,
endorserAfter: string,
partnerAfter: string
): Promise<void> {
setColumns(userId, {
endorser_after_cursor: endorserAfter,
partner_after_cursor: partnerAfter,
});
run();
},
/** Apply what an alert-authorization upload sent, in one write. */
async setSearchState(
userId: string,
update: AlertSearchStateUpdate
): Promise<void> {
const values: Record<string, string | null> = {};
if (update.endorserAfterCursor !== undefined) {
values.endorser_after_cursor = update.endorserAfterCursor;
}
if (update.partnerAfterCursor !== undefined) {
values.partner_after_cursor = update.partnerAfterCursor;
}
if (update.planHandleIds !== undefined) {
values.plan_handle_ids =
update.planHandleIds === null ? null : JSON.stringify(update.planHandleIds);
}
if (update.location !== undefined) {
values.location =
update.location === null ? null : JSON.stringify(update.location);
}
setColumns(userId, values);
},
};
}
+7 -18
View File
@@ -116,16 +116,6 @@ export const db = {
return rows.map(toStoredRow);
},
/** Scheduler iteration; excludes `__legacy__` rows. */
async getAllForScheduler(): Promise<StoredRow[]> {
const rows = getDatabase()
.prepare(
`SELECT ${ROW_COLUMNS} FROM fcm_registrations WHERE user_id != '__legacy__'`
)
.all() as DbRow[];
return rows.map(toStoredRow);
},
/**
* Resolve a device owned by userId via deviceId and/or fcmToken.
* When both are given, they must refer to the same row.
@@ -157,6 +147,13 @@ export const db = {
return undefined;
},
/** Remove every device registration for this DID; returns how many. */
async deleteByUserId(userId: string): Promise<number> {
return getDatabase()
.prepare(`DELETE FROM fcm_registrations WHERE user_id = ?`)
.run(userId).changes;
},
async getByUserId(userId: string): Promise<StoredRow[]> {
const rows = getDatabase()
.prepare(
@@ -208,12 +205,4 @@ export const db = {
.get(userId, fcmToken) as DbRow | undefined;
return row === undefined ? undefined : toStoredRow(row);
},
async update(id: string, patch: { lastNotifiedAt: number }): Promise<void> {
getDatabase()
.prepare(
`UPDATE fcm_registrations SET last_notified_at = ? WHERE id = ?`
)
.run(patch.lastNotifiedAt, id);
},
};
+88
View File
@@ -0,0 +1,88 @@
import { randomUUID } from "node:crypto";
import { getDatabase } from "./sqlite.js";
/** How long run rows are kept. They exist for diagnosis, not for history. */
export const SMS_ALERT_SEARCH_RUN_RETENTION_DAYS = 30;
export type SmsAlertSearchRunInput = {
userId: string;
utcDay?: string | null;
ranAt: string;
elapsedMs: number;
completed?: boolean;
consumed?: boolean;
endorserOutcome?: string | null;
partnerOutcome?: string | null;
endorserStartCursor?: string;
partnerStartCursor?: string;
totalCount?: number;
counts?: unknown;
records?: unknown;
sourceMessages?: unknown;
smsEligible?: boolean;
smsSent?: number;
smsFailed?: number;
smsBlocked?: number;
error?: string;
};
function boolColumn(value: boolean | undefined): number | null {
return value === undefined ? null : value ? 1 : 0;
}
function jsonColumn(value: unknown): string | null {
return value === undefined ? null : JSON.stringify(value);
}
/** Append-only record of what each SMS daily run found and did. */
export const smsAlertSearchRunsDb = {
async append(input: SmsAlertSearchRunInput): Promise<string> {
const id = randomUUID();
getDatabase()
.prepare(
`
INSERT INTO sms_alert_search_runs (
id, user_id, utc_day, ran_at, elapsed_ms, completed, consumed,
endorser_outcome, partner_outcome, endorser_start_cursor,
partner_start_cursor, total_count, counts, records, source_messages,
sms_eligible, sms_sent, sms_failed, sms_blocked, error
) VALUES (
@id, @user_id, @utc_day, @ran_at, @elapsed_ms, @completed, @consumed,
@endorser_outcome, @partner_outcome, @endorser_start_cursor,
@partner_start_cursor, @total_count, @counts, @records, @source_messages,
@sms_eligible, @sms_sent, @sms_failed, @sms_blocked, @error
)
`
)
.run({
id,
user_id: input.userId,
utc_day: input.utcDay ?? null,
ran_at: input.ranAt,
elapsed_ms: input.elapsedMs,
completed: boolColumn(input.completed),
consumed: boolColumn(input.consumed),
endorser_outcome: input.endorserOutcome ?? null,
partner_outcome: input.partnerOutcome ?? null,
endorser_start_cursor: input.endorserStartCursor ?? null,
partner_start_cursor: input.partnerStartCursor ?? null,
total_count: input.totalCount ?? null,
counts: jsonColumn(input.counts),
records: jsonColumn(input.records),
source_messages: jsonColumn(input.sourceMessages),
sms_eligible: boolColumn(input.smsEligible),
sms_sent: input.smsSent ?? null,
sms_failed: input.smsFailed ?? null,
sms_blocked: input.smsBlocked ?? null,
error: input.error ?? null,
});
return id;
},
async pruneOlderThan(cutoffIso: string): Promise<number> {
const result = getDatabase()
.prepare(`DELETE FROM sms_alert_search_runs WHERE ran_at < ?`)
.run(cutoffIso);
return result.changes;
},
};
+104 -4
View File
@@ -100,8 +100,16 @@ CREATE INDEX IF NOT EXISTS idx_alert_auth_jwts_batch_pk
CREATE TABLE IF NOT EXISTS alert_search_cursors (
user_id TEXT PRIMARY KEY NOT NULL,
endorser_after_id TEXT,
partner_after_at TEXT,
endorser_after_cursor TEXT,
partner_after_cursor TEXT,
-- JSON array of the starred plan handle IDs to track, or NULL for none.
plan_handle_ids TEXT,
-- JSON {minLocLat, maxLocLat, minLocLon, maxLocLon} for the nearby lists,
-- or NULL for no area.
location TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
@@ -257,17 +265,109 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_sms_blocked_numbers_hash
CREATE TABLE IF NOT EXISTS sms_alert_search_cursors (
user_id TEXT PRIMARY KEY NOT NULL,
endorser_after_id TEXT,
partner_after_at TEXT,
endorser_after_cursor TEXT,
partner_after_cursor TEXT,
plan_handle_ids TEXT,
location TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
-- One row per SMS-channel daily run the scheduler attempted, whether or not it
-- texted anyone, so an operator can see what each run found. Read by
-- src/tools/smsWatch.ts; pruned with the scheduler's other housekeeping.
CREATE TABLE IF NOT EXISTS sms_alert_search_runs (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
utc_day TEXT,
ran_at TEXT NOT NULL,
elapsed_ms INTEGER NOT NULL,
-- NULL when the run threw before producing a result; see error.
completed INTEGER,
consumed INTEGER,
endorser_outcome TEXT,
partner_outcome TEXT,
-- The cursors the run counted from, NULL on a first (seeding) run.
endorser_start_cursor TEXT,
partner_start_cursor TEXT,
total_count INTEGER,
-- JSON: the digest's per-bucket counts, its records, and each source's
-- outcome message.
counts TEXT,
records TEXT,
source_messages TEXT,
-- From deliverAlertSearchSms: whether the digest qualified for a text, and
-- how many numbers were sent, failed, or withheld.
sms_eligible INTEGER,
sms_sent INTEGER,
sms_failed INTEGER,
sms_blocked INTEGER,
error TEXT
);
CREATE INDEX IF NOT EXISTS idx_sms_alert_search_runs_ran_at
ON sms_alert_search_runs (ran_at);
-- One row per push-channel alert that reached at least one device, for the
-- daily cap in src/alertSearch/notify.ts (SMS counts sms_phone_log instead).
CREATE TABLE IF NOT EXISTS alert_push_sends (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
batch_id TEXT,
sent_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_alert_push_sends_user_sent
ON alert_push_sends (user_id, sent_at);
`;
let database: Database.Database | null = null;
/**
* Cursor tables from 0.2.3 and earlier hold ULID / date cursors (columns
* endorser_after_id, partner_after_at), which this version cannot use. They
* are dropped so SCHEMA_SQL creates them again; each user's next run is then
* a first run.
*/
const CURSOR_TABLES = ["alert_search_cursors", "sms_alert_search_cursors"];
function dropIdPathCursorTables(connection: Database.Database): void {
for (const table of CURSOR_TABLES) {
const columns = connection
.prepare(`PRAGMA table_info(${table})`)
.all() as Array<{ name: string }>;
if (columns.some((c) => c.name === "endorser_after_id")) {
connection.exec(`DROP TABLE ${table}`);
}
}
}
/** Search-input columns added to the cursor tables after 0.2.5. */
const CURSOR_TABLE_ADDED_COLUMNS = ["plan_handle_ids", "location"];
function addCursorSearchInputColumns(connection: Database.Database): void {
for (const table of CURSOR_TABLES) {
const columns = connection
.prepare(`PRAGMA table_info(${table})`)
.all() as Array<{ name: string }>;
for (const column of CURSOR_TABLE_ADDED_COLUMNS) {
if (!columns.some((c) => c.name === column)) {
connection.exec(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`);
}
}
}
}
function ensureSchema(connection: Database.Database): void {
dropIdPathCursorTables(connection);
connection.exec(SCHEMA_SQL);
addCursorSearchInputColumns(connection);
}
/**
+29
View File
@@ -61,11 +61,30 @@ function didListEnv(name: string): string[] | undefined {
.filter((did) => did.length > 0);
}
/**
* DIDs whose push alert may fire again the same UTC day after a reset
* (`rerunToday`). Every other DID gets at most one alert push a day. Read on
* each call, like {@link smsConfig}. Absent or empty: no DID.
*/
export function pushSameDayResendDids(): string[] {
return didListEnv("PUSH_SAME_DAY_RESEND_DIDS") ?? [];
}
function stringEnv(name: string): string | undefined {
const raw = process.env[name];
return raw !== undefined && raw.length > 0 ? raw : undefined;
}
/**
* Appends " (<MESSAGE_ENV_LABEL>)" to user-visible text, so a recipient can tell
* which deployment sent it. NODE_ENV cannot serve: the Docker image fixes it to
* "production" on every server. Read per call, like smsConfig.
*/
export function withEnvLabel(text: string): string {
const label = process.env.MESSAGE_ENV_LABEL?.trim();
return label ? `${text} (${label})` : text;
}
export type SmsConfig = {
enabled: boolean;
codeSecret?: string;
@@ -93,6 +112,12 @@ export type SmsConfig = {
* Normalized at read time so the comparison matches stored E.164.
*/
blockedNumbers: string[];
/**
* Numbers that may receive more than one alert text per UTC day, after a
* reset (`rerunToday`). Every other number gets at most one a day.
* Normalized at read time, like `blockedNumbers`.
*/
sameDayResendNumbers: string[];
};
/**
@@ -123,6 +148,10 @@ export function smsConfig(): SmsConfig {
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
sameDayResendNumbers: (process.env.SMS_SAME_DAY_RESEND_NUMBERS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
};
}
-2
View File
@@ -8,7 +8,6 @@ import { notificationsRouter } from "./routes/notifications.js";
import { notifySmsRouter } from "./routes/notifySms.js";
import { startAlertSearchScheduler } from "./alertSearch/scheduler.js";
import { startSmsAlertSearchScheduler } from "./alertSearch/smsScheduler.js";
import { startScheduler } from "./scheduler.js";
import { log } from "./util/log.js";
const app = express();
@@ -40,7 +39,6 @@ if (DEBUG_ENDPOINT) {
assertSmsConfigured();
startScheduler();
startAlertSearchScheduler();
if (smsConfig().enabled) {
startSmsAlertSearchScheduler();
+29
View File
@@ -21,6 +21,28 @@ type ClientErrorBody = {
};
};
/**
* Longest an authenticating JWT may have left. The app signs a fresh one per
* request, expiring in a minute; a token with no `exp`, or a long one, is
* likely something else the DID signed, such as a published claim.
*/
export const AUTH_JWT_MAX_REMAINING_SEC = 60 * 60;
/** Why `payload` is not a usable request token, or undefined when it is. */
export function authJwtLifetimeProblem(
payload: Record<string, unknown>,
nowSec: number = Math.floor(Date.now() / 1000)
): string | undefined {
const exp = payload.exp;
if (typeof exp !== "number") {
return 'The Bearer JWT must carry a numeric "exp".';
}
if (exp - nowSec > AUTH_JWT_MAX_REMAINING_SEC) {
return `The Bearer JWT must expire within ${AUTH_JWT_MAX_REMAINING_SEC} seconds.`;
}
return undefined;
}
/** Synthetic userId for unauthenticated local debug registrations (testMode). */
const LOCAL_TEST_USER_ID = "__notification_local_test__";
@@ -86,6 +108,13 @@ export async function requireAuth(
return;
}
const lifetimeProblem = authJwtLifetimeProblem(verified.payload);
if (lifetimeProblem !== undefined) {
log.info("[Auth] Authentication failed:", lifetimeProblem);
res.status(401).json({ success: false, message: lifetimeProblem });
return;
}
const did = verified.issuer;
req.did = did;
req.jwt = token;
+1 -82
View File
@@ -1,13 +1,6 @@
import express, { Router } from "express";
import { db } from "../db/fcmTokensSqlite.js";
import {
requireAuth,
requireAuthOrNotificationLocalTest,
} from "../middleware/auth.js";
import {
computeNextEligibleAt,
sendPushToDevice,
} from "../services/pushService.js";
import { requireAuth } from "../middleware/auth.js";
import { formatElapsedMs } from "../util/formatElapsed.js";
import { maskToken } from "../util/maskToken.js";
import { log } from "../util/log.js";
@@ -21,7 +14,6 @@ function deviceDebugPayload(row: {
testMode?: boolean;
createdAt: string;
updatedAt: string;
lastNotifiedAt?: number;
fcmToken: string;
}) {
return {
@@ -31,22 +23,10 @@ function deviceDebugPayload(row: {
testMode: row.testMode ?? false,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
lastNotifiedAt: row.lastNotifiedAt,
nextEligibleAt: computeNextEligibleAt(row),
fcmTokenSuffix: maskToken(row.fcmToken),
};
}
function sendWakeupFailureReason(
result: "sent" | "skipped" | "failed"
): string | undefined {
if (result === "sent") return undefined;
if (result === "skipped") {
return "Device was notified within the eligibility threshold";
}
return "FCM send failed";
}
debugRouter.get("/device/:token", requireAuth, async (req, res) => {
const started = Date.now();
const userId = req.did;
@@ -82,64 +62,3 @@ debugRouter.get("/device/:token", requireAuth, async (req, res) => {
suffix
);
});
debugRouter.post("/send-wakeup", requireAuthOrNotificationLocalTest, async (req, res) => {
const started = Date.now();
const userId = req.did;
if (userId === undefined) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}
const { fcmToken } = req.body as { fcmToken?: unknown };
if (typeof fcmToken !== "string" || fcmToken.length === 0) {
log.info(
"[DebugEndpoint] Send-wakeup rejected in",
formatElapsedMs(Date.now() - started) + ":",
"fcmToken is required"
);
res.status(400).json({
success: false,
failureReason: "fcmToken is required",
});
return;
}
const suffix = maskToken(fcmToken);
log.info("[DebugEndpoint] Send-wakeup request, token suffix:", suffix);
const row = await db.resolveOwnedDevice(userId, { fcmToken });
if (row === undefined) {
log.info(
"[DebugEndpoint] Send-wakeup rejected in",
formatElapsedMs(Date.now() - started) + ",",
"token suffix:",
suffix + ",",
"reason: Device not found"
);
res.status(404).json({
success: false,
failureReason: "Device not found",
fcmTokenSuffix: suffix,
});
return;
}
const result = await sendPushToDevice(fcmToken);
const success = result === "sent";
const failureReason = sendWakeupFailureReason(result);
res.json({
success,
...(failureReason !== undefined ? { failureReason } : {}),
fcmTokenSuffix: suffix,
});
log.info(
"[DebugEndpoint] Send-wakeup completed in",
formatElapsedMs(Date.now() - started) + ",",
success ? "success" : result + ",",
"token suffix:",
suffix
);
});
+45 -77
View File
@@ -1,5 +1,6 @@
import express, { Router } from "express";
import { alertAuthorizationDb } from "../db/alertAuthorizationSqlite.js";
import { alertSearchCursorsDb } from "../db/alertSearchCursorsSqlite.js";
import { db } from "../db/fcmTokensSqlite.js";
import {
requireAuth,
@@ -13,6 +14,7 @@ import {
validateAlertAuthorizationBatch,
} from "../services/alertAuthorization.js";
import { identitySupportsDelegatedJwtBatch } from "../vc/index.js";
import { sameDayPushRerunAllowed } from "../alertSearch/notify.js";
import { errorMessage, formatElapsedMs } from "../util/formatElapsed.js";
import { maskToken } from "../util/maskToken.js";
import { log } from "../util/log.js";
@@ -23,81 +25,6 @@ notificationsRouter.get("/", (_req, res) => {
res.json({ ok: true, resource: "notifications" });
});
notificationsRouter.post(
"/refresh",
requireAuthOrNotificationLocalTest,
requireEndorserAuth,
async (req, res) => {
const started = Date.now();
const userId = req.did;
if (userId === undefined) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}
const { deviceId, fcmToken } = req.body as {
deviceId?: unknown;
fcmToken?: unknown;
};
const canonicalDeviceId =
typeof deviceId === "string" ? deviceId.trim() : undefined;
const token =
typeof fcmToken === "string" && fcmToken.length > 0
? fcmToken
: undefined;
log.info(
"[Refresh] Request received",
canonicalDeviceId !== undefined ? `deviceId=${canonicalDeviceId}` : "",
token !== undefined ? `token suffix=${maskToken(token)}` : ""
);
if (
(canonicalDeviceId === undefined || canonicalDeviceId.length === 0) &&
token === undefined
) {
log.info(
"[Refresh] Rejected in",
formatElapsedMs(Date.now() - started) + ":",
"deviceId or fcmToken is required"
);
res.status(400).json({ error: "deviceId or fcmToken is required" });
return;
}
const device = await db.resolveOwnedDevice(userId, {
deviceId: canonicalDeviceId,
fcmToken: token,
});
if (device === undefined) {
log.info(
"[Refresh] Device not found in",
formatElapsedMs(Date.now() - started),
canonicalDeviceId !== undefined
? `deviceId=${canonicalDeviceId}`
: "",
token !== undefined ? `token suffix=${maskToken(token)}` : ""
);
res.status(404).json({ error: "Device not found" });
return;
}
const now = Date.now();
res.json({
shouldNotify: true,
nextNotifications: [{ timestamp: now + 600000 }],
});
log.info(
"[Refresh] Completed in",
formatElapsedMs(Date.now() - started) + ",",
"deviceId=" + device.deviceId + ",",
"token suffix=" + maskToken(device.fcmToken)
);
}
);
notificationsRouter.post(
"/alert-authorization",
requireAuth,
@@ -147,6 +74,13 @@ notificationsRouter.post(
}
try {
const rerunToday =
validated.rerunToday && (await sameDayPushRerunAllowed(userId));
if (validated.rerunToday && !rerunToday) {
log.info(
"[AlertAuthorization] rerunToday ignored: already pushed today"
);
}
const stored = await alertAuthorizationDb.replaceUnusedBatch({
userId,
batchId: validated.batchId,
@@ -154,7 +88,9 @@ notificationsRouter.post(
notifyMinuteUtc: validated.notifyMinuteUtc,
timezone: validated.timezone,
jwts: validated.jwts,
rerunToday,
});
await alertSearchCursorsDb.setSearchState(userId, validated.searchState);
res.status(200).json({
success: true,
batchId: stored.batch.batchId,
@@ -188,12 +124,11 @@ notificationsRouter.post(
/**
* Turn the push channel off: every batch and every JWT for this DID, used or
* not, so the alertSearch scheduler stops listing the identity. Device
* registrations are untouched; WAKEUP_PING is a separate mechanism.
* registrations are untouched.
*/
notificationsRouter.delete(
"/alert-authorization",
requireAuth,
requireEndorserAuth,
async (req, res) => {
const started = Date.now();
const userId = req.did;
@@ -229,6 +164,39 @@ notificationsRouter.delete(
}
);
/**
* Forget every device this DID registered, for a person who chose on-device
* notifications: the service then holds no way to reach them. Like the other
* removals, it needs only the DID's signature, not Endorser registration.
*/
notificationsRouter.delete("/register", requireAuth, async (req, res) => {
const started = Date.now();
const userId = req.did;
if (userId === undefined) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}
try {
const deleted = await db.deleteByUserId(userId);
res.status(200).json({ success: true, deleted });
log.info(
"[Register] Deleted in",
formatElapsedMs(Date.now() - started) + ",",
"devices=" + deleted
);
} catch (err) {
log.error(
"[Register] Delete failed in",
formatElapsedMs(Date.now() - started) + ":",
errorMessage(err)
);
res.status(500).json({
success: false,
message: "Failed to remove the device registrations.",
});
}
});
notificationsRouter.post(
"/register",
requireAuthOrNotificationLocalTest,
+26 -2
View File
@@ -1,5 +1,6 @@
import express, { Router, type RequestHandler } from "express";
import { smsAlertAuthorizationDb } from "../db/smsAlertAuthorizationSqlite.js";
import { smsAlertSearchCursorsDb } from "../db/alertSearchCursorsSqlite.js";
import { smsPhoneLogDb } from "../db/smsPhoneLogSqlite.js";
import { smsRegistrationsDb } from "../db/smsRegistrationsSqlite.js";
import { smsConfig } from "../env.js";
@@ -39,6 +40,7 @@ import {
verificationCodeMatches,
} from "../util/smsVerificationCode.js";
import { identitySupportsDelegatedJwtBatch } from "../vc/index.js";
import { sameDayRerunAllowed } from "../alertSearch/smsNotify.js";
import { log } from "../util/log.js";
/** Code sends allowed per handset per hour, counted across every DID. */
@@ -194,6 +196,10 @@ export function createNotifySmsRouter(deps: NotifySmsDeps = {}): express.Router
const router = Router();
const send = deps.sender ?? sendSms;
const authStages = deps.authStages ?? [requireAuth, requireEndorserAuth];
// Turning texts off and forgetting a number skip the Endorser check: a
// signature from the DID is enough to stop its own texts, and Endorser can
// drop a registration after texts were turned on.
const revokeStages = deps.authStages ?? [requireAuth];
router.use(requireSmsEnabled);
@@ -626,7 +632,7 @@ export function createNotifySmsRouter(deps: NotifySmsDeps = {}): express.Router
router.delete(
"/phone",
...authStages,
...revokeStages,
requireSmsActionJwt("delete-phone"),
async (req, res) => {
const userId = req.did as string;
@@ -707,6 +713,19 @@ export function createNotifySmsRouter(deps: NotifySmsDeps = {}): express.Router
return;
}
const rerunToday =
validated.rerunToday &&
(await sameDayRerunAllowed(
userId,
verified.map((row) => row.phoneE164),
secret
));
if (validated.rerunToday && !rerunToday) {
log.info(
"[NotifySmsAlertAuthorization] rerunToday ignored: already texted today"
);
}
try {
const stored = await smsAlertAuthorizationDb.replaceUnusedBatch({
userId,
@@ -715,7 +734,12 @@ export function createNotifySmsRouter(deps: NotifySmsDeps = {}): express.Router
notifyMinuteUtc: validated.notifyMinuteUtc,
timezone: validated.timezone,
jwts: validated.jwts,
rerunToday,
});
await smsAlertSearchCursorsDb.setSearchState(
userId,
validated.searchState
);
await recordPhoneAction({
userId,
phoneE164: verified[0].phoneE164,
@@ -946,7 +970,7 @@ export function createNotifySmsRouter(deps: NotifySmsDeps = {}): express.Router
router.delete(
"/alert-authorization",
...authStages,
...revokeStages,
requireSmsActionJwt("revoke-alert-search"),
deleteAlertAuthorization
);
-67
View File
@@ -1,67 +0,0 @@
import { db } from "./db/fcmTokensSqlite.js";
import { sendPushToDevice } from "./services/pushService.js";
import { errorMessage, formatElapsedMs } from "./util/formatElapsed.js";
import { log } from "./util/log.js";
let intervalId: ReturnType<typeof setInterval> | undefined;
export function startScheduler(): void {
if (intervalId !== undefined) return;
intervalId = setInterval(async () => {
const passStarted = Date.now();
log.info("[Scheduler] Pass started");
try {
const devices = await db.getAllForScheduler();
const seenTokens = new Set<string>();
let checked = 0;
let sent = 0;
let skipped = 0;
let failed = 0;
let duplicates = 0;
for (const d of devices) {
if (seenTokens.has(d.fcmToken)) {
duplicates++;
continue;
}
seenTokens.add(d.fcmToken);
checked++;
const result = await sendPushToDevice(d.fcmToken);
if (result === "sent") sent++;
else if (result === "skipped") skipped++;
else failed++;
}
const summaryParts = [
`Checked ${checked} devices`,
`sent ${sent} pushes`,
`skipped ${skipped}`,
];
if (failed > 0) summaryParts.push(`failed ${failed}`);
if (duplicates > 0) {
summaryParts.push(`${duplicates} duplicates ignored`);
}
log.info("[Scheduler]", summaryParts.join(", "));
log.info(
"[Scheduler] Pass completed in",
formatElapsedMs(Date.now() - passStarted)
);
} catch (err) {
log.error(
"[Scheduler] Pass failed in",
formatElapsedMs(Date.now() - passStarted) + ":",
errorMessage(err)
);
}
}, 5 * 60 * 1000);
}
export function stopScheduler(): void {
if (intervalId !== undefined) {
clearInterval(intervalId);
intervalId = undefined;
}
}
+120
View File
@@ -1,4 +1,5 @@
import { EXPECTED_ALERT_JWT_BATCH_SIZE } from "../db/alertAuthorizationSqlite.js";
import type { AlertSearchStateUpdate } from "../db/alertSearchCursorsSqlite.js";
import {
DELEGATED_JWT_UNSUPPORTED_IDENTITY_CODE,
decodeAndVerifyDelegatedJwt,
@@ -16,8 +17,31 @@ export type AlertAuthorizationRequestBody = {
notifyMinuteUtc?: unknown;
timezone?: unknown;
jwts?: unknown;
/**
* Optional alertSearch state. Cursors replace the channel's stored cursors,
* so the next run counts from them; planHandleIds and location replace the
* stored search inputs, and null clears them. Absent keeps what is stored.
*/
endorserAfterCursor?: unknown;
partnerAfterCursor?: unknown;
planHandleIds?: unknown;
location?: unknown;
/**
* Optional; true stores the batch's JWT for a day that already ran, so a
* reset fires again today. Absent or false skips such days.
*/
rerunToday?: unknown;
};
/**
* Cursors are opaque, but they travel in a URL query and are joined with "."
* in notification links, so only these characters are accepted.
*/
const CURSOR_RE = /^[0-9A-Za-z_:-]{1,64}$/;
/** The daily GET sends these as JSON in the query string. */
const MAX_PLAN_HANDLE_IDS = 200;
const MAX_PLAN_HANDLE_ID_LENGTH = 200;
export type ValidatedAlertJwt = {
sequence: number;
day: string;
@@ -39,6 +63,10 @@ export type BatchValidationSuccess = {
*/
timezone: string | undefined;
jwts: ValidatedAlertJwt[];
/** Apply with the channel's cursor store after the batch is stored. */
searchState: AlertSearchStateUpdate;
/** Store JWTs for days that already ran; false when the field was absent. */
rerunToday: boolean;
};
export type BatchValidationFailure = {
@@ -222,6 +250,18 @@ export async function validateAlertAuthorizationBatch(
}
}
const searchState = validateAlertSearchState(body, details);
let rerunToday = false;
if (body.rerunToday !== undefined && body.rerunToday !== null) {
if (typeof body.rerunToday !== "boolean") {
details.push(
"rerunToday must be a boolean, got " + JSON.stringify(body.rerunToday)
);
} else {
rerunToday = body.rerunToday;
}
}
if (!Array.isArray(body.jwts)) {
details.push("jwts must be an array of 100 delegated JWT entries");
return fail(details);
@@ -384,9 +424,89 @@ export async function validateAlertAuthorizationBatch(
notifyMinuteUtc,
timezone,
jwts: validated,
searchState,
rerunToday,
};
}
function isLatitude(value: unknown): boolean {
return typeof value === "number" && Number.isFinite(value) && value >= -90 && value <= 90;
}
function isLongitude(value: unknown): boolean {
return typeof value === "number" && Number.isFinite(value) && value >= -180 && value <= 180;
}
/** The optional alertSearch fields of an upload; problems go into details. */
function validateAlertSearchState(
body: AlertAuthorizationRequestBody,
details: string[]
): AlertSearchStateUpdate {
const state: AlertSearchStateUpdate = {};
for (const field of ["endorserAfterCursor", "partnerAfterCursor"] as const) {
const value = body[field];
if (value === undefined || value === null) continue;
if (typeof value !== "string" || !CURSOR_RE.test(value)) {
details.push(
`${field} must be a cursor from an alertSearch response (letters, digits, '_', ':', '-'; at most 64)`
);
} else {
state[field] = value;
}
}
if (body.planHandleIds === null) {
state.planHandleIds = null;
} else if (body.planHandleIds !== undefined) {
const ids = body.planHandleIds;
if (
!Array.isArray(ids) ||
ids.length > MAX_PLAN_HANDLE_IDS ||
!ids.every(
(id) =>
typeof id === "string" &&
id.length > 0 &&
id.length <= MAX_PLAN_HANDLE_ID_LENGTH
)
) {
details.push(
`planHandleIds must be an array of at most ${MAX_PLAN_HANDLE_IDS} non-empty strings`
);
} else {
state.planHandleIds = ids as string[];
}
}
if (body.location === null) {
state.location = null;
} else if (body.location !== undefined) {
const box = body.location as Record<string, unknown>;
if (
typeof box !== "object" ||
Array.isArray(box) ||
!isLatitude(box.minLocLat) ||
!isLatitude(box.maxLocLat) ||
!isLongitude(box.minLocLon) ||
!isLongitude(box.maxLocLon) ||
(box.minLocLat as number) > (box.maxLocLat as number)
) {
details.push(
"location must be { minLocLat, maxLocLat, minLocLon, maxLocLon } with valid coordinates"
);
} else {
state.location = {
minLocLat: box.minLocLat as number,
maxLocLat: box.maxLocLat as number,
minLocLon: box.minLocLon as number,
maxLocLon: box.maxLocLon as number,
};
}
}
return state;
}
function fail(details: string[]): BatchValidationFailure {
const reported = details.slice(0, MAX_REPORTED_ERRORS);
if (details.length > MAX_REPORTED_ERRORS) {
+30
View File
@@ -0,0 +1,30 @@
import { withEnvLabel } from "../env.js";
export const ALERT_SEARCH_FCM_TYPE = "alert_search";
export type AlertSearchFcmMessage = {
token: string;
notification: { title: string; body: string };
data: { type: typeof ALERT_SEARCH_FCM_TYPE; c?: string };
};
/** The FCM message a tap on the daily New Activity notification carries. */
export function buildAlertSearchFcmMessage(
fcmToken: string,
content: { title: string; body: string; cursorParam?: string }
): AlertSearchFcmMessage {
return {
token: fcmToken,
notification: {
title: content.title,
body: withEnvLabel(content.body),
},
data: {
type: ALERT_SEARCH_FCM_TYPE,
// the app opens /new-activity?c=<this> on a tap
...(content.cursorParam !== undefined
? { c: content.cursorParam }
: {}),
},
};
}
+8 -119
View File
@@ -1,138 +1,27 @@
import { db, type StoredRow } from "../db/fcmTokensSqlite.js";
import { errorMessage, formatElapsedMs } from "../util/formatElapsed.js";
import { maskToken } from "../util/maskToken.js";
import {
ALERT_SEARCH_FCM_TYPE,
buildAlertSearchFcmMessage,
} from "./alertSearchFcmPayload.js";
import { messaging } from "./firebase.js";
import { log } from "../util/log.js";
const MS_PRODUCTION = 23 * 60 * 60 * 1000;
const MS_TEST = 10 * 60 * 1000;
export function notifyThresholdMs(testMode?: boolean): number {
return testMode === true ? MS_TEST : MS_PRODUCTION;
}
/** Epoch ms when the device may receive another push (diagnostics only). */
export function computeNextEligibleAt(row: {
lastNotifiedAt?: number;
testMode?: boolean;
}): number {
const threshold = notifyThresholdMs(row.testMode);
if (row.lastNotifiedAt === undefined) {
return Date.now();
}
return row.lastNotifiedAt + threshold;
}
function lastNotifiedMs(row: StoredRow | undefined): number | undefined {
const v = row?.lastNotifiedAt;
if (v === undefined) return undefined;
if (typeof v === "number") return Number.isNaN(v) ? undefined : v;
return undefined;
}
function stringifyData(
payload: Record<string, unknown>
): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(payload)) {
out[k] = v === undefined || v === null ? "" : String(v);
}
return out;
}
export { ALERT_SEARCH_FCM_TYPE };
/**
* Sends an FCM data message if the token is outside the dedupe window
* (23h production, 10m test).
*/
export async function sendPushToDevice(
fcmToken: string,
payload: Record<string, unknown> = {}
): Promise<"sent" | "skipped" | "failed"> {
const suffix = maskToken(fcmToken);
const row = await db.getByFcmToken(fcmToken);
const now = Date.now();
const last = lastNotifiedMs(row);
if (
last !== undefined &&
now - last < notifyThresholdMs(row?.testMode)
) {
return "skipped";
}
const sendStarted = Date.now();
log.info("[Push] Send attempt, token suffix:", suffix);
try {
const data: Record<string, string> = {
...stringifyData(payload),
type: "WAKEUP_PING",
};
await messaging.send({
token: fcmToken,
apns: {
headers: {
"apns-push-type": "background",
"apns-priority": "5",
},
payload: {
aps: {
contentAvailable: true,
},
},
},
data,
});
const persisted = await db.getByFcmToken(fcmToken);
if (persisted !== undefined) {
await db.update(persisted.id, { lastNotifiedAt: Date.now() });
}
log.info(
"[Push] Send completed in",
formatElapsedMs(Date.now() - sendStarted) + ",",
"token suffix:",
suffix
);
return "sent";
} catch (err) {
log.error(
"[Push] Send failed in",
formatElapsedMs(Date.now() - sendStarted) + ",",
"token suffix:",
suffix + ":",
errorMessage(err)
);
return "failed";
}
}
export const ALERT_SEARCH_FCM_TYPE = "alert_search";
/**
* User-visible AlertSearch digest push. Does not apply the WAKEUP_PING
* last_notified_at window and does not write last_notified_at.
* User-visible AlertSearch digest push.
*/
export async function sendAlertSearchPushToDevice(
fcmToken: string,
content: { title: string; body: string }
content: { title: string; body: string; cursorParam?: string }
): Promise<"sent" | "failed"> {
const suffix = maskToken(fcmToken);
const sendStarted = Date.now();
log.info("[AlertSearchPush] Send attempt, token suffix:", suffix);
try {
await messaging.send({
token: fcmToken,
notification: {
title: content.title,
body: content.body,
},
data: {
type: ALERT_SEARCH_FCM_TYPE,
},
});
await messaging.send(buildAlertSearchFcmMessage(fcmToken, content));
log.info(
"[AlertSearchPush] Send completed in",
formatElapsedMs(Date.now() - sendStarted) + ",",
+3 -2
View File
@@ -1,4 +1,4 @@
import { smsConfig, type SmsConfig } from "../env.js";
import { smsConfig, withEnvLabel, type SmsConfig } from "../env.js";
import { errorMessage } from "../util/formatElapsed.js";
import { maskPhoneNumber } from "../util/smsPhoneNumber.js";
import { log } from "../util/log.js";
@@ -147,7 +147,8 @@ let warnedNotConfigured = false;
* The configured sender, resolved per call. Missing credentials fail the send
* rather than the process: a texting outage should not take push down with it.
*/
export const sendSms: SmsSender = async (to, body) => {
export const sendSms: SmsSender = async (to, rawBody) => {
const body = withEnvLabel(rawBody);
const config = smsConfig();
const credentials = twilioCredentials(config);
+743
View File
@@ -0,0 +1,743 @@
/**
* A `top`-style view of the SMS channel, read straight from notify.sqlite:
* recent daily runs (what each query found and whether it texted), the next
* scheduled run per user, and the raw sms_phone_log. A scheduled row can be
* previewed: its query runs against Endorser and Partner with that user's
* stored cursors and today's JWT, without consuming the JWT or moving a cursor.
*
* docker exec -it <container> node dist/tools/smsWatch.js
* pkgx pnpm run sms:watch [-- --db path/to/notify.sqlite] [--once]
*
* The database is opened read-only, so running this beside the service never
* writes to it. The service's environment (NOTIFY_DATA_DIR, ENDORSER_URL,
* PARTNER_URL, SMS_*) is read the same way the service reads it.
*
* Keys: 1/2/3 or Tab switch view, j/k or arrows move, Enter expands, p
* previews the selected scheduled run (asking y/n about replays the first
* time), Esc/q goes back, q quits.
*/
import path from "node:path";
import Database from "better-sqlite3";
import { alertSearchDigestDebugSummary, buildAlertSearchDigest } from "../alertSearch/digest.js";
import { alertSearchUrl, buildAlertSearchQuery } from "../alertSearch/params.js";
import { retrieveAlertSearch } from "../alertSearch/retrieve.js";
import {
ENDORSER_ALERT_SEARCH_PATH,
PARTNER_ALERT_SEARCH_PATH,
type AlertSearchLocationBBox,
} from "../alertSearch/types.js";
import { ENDORSER_URL, PARTNER_URL, smsConfig } from "../env.js";
import { utcCalendarDay, utcHourMinute } from "../services/alertAuthorization.js";
import { isSmsRecipientAllowed } from "../services/smsService.js";
import { normalizePhoneNumber } from "../util/smsPhoneNumber.js";
import { hashPhoneNumber } from "../util/smsVerificationCode.js";
// ---- arguments and database ----
function argValue(name: string): string | undefined {
const i = process.argv.indexOf(name);
return i >= 0 ? process.argv[i + 1] : undefined;
}
const ONCE = process.argv.includes("--once") || !process.stdout.isTTY;
const REFRESH_SEC = Number(argValue("--refresh") ?? "2") || 2;
const DB_PATH =
argValue("--db") ??
path.join(process.env.NOTIFY_DATA_DIR ?? path.join(process.cwd(), "data"), "notify.sqlite");
const db = new Database(DB_PATH, { readonly: true, fileMustExist: true });
function hasTable(name: string): boolean {
return (
db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).get(name) !==
undefined
);
}
// Read-only, so the schema cannot be created here; only the service creates it.
const REQUIRED_TABLES = [
"sms_registrations",
"sms_phone_log",
"sms_blocked_numbers",
"sms_alert_authorization_batches",
"sms_alert_authorization_jwts",
"sms_alert_search_cursors",
];
const missingTables = REQUIRED_TABLES.filter((table) => !hasTable(table));
if (missingTables.length > 0) {
console.error(
`${DB_PATH} has no SMS tables (missing: ${missingTables.join(", ")}).\n` +
"Start the service against it once to create them, or pass --db <path> to another notify.sqlite."
);
process.exit(1);
}
// ---- data ----
type RunRow = {
user_id: string;
utc_day: string | null;
ran_at: string;
elapsed_ms: number;
completed: number | null;
consumed: number | null;
endorser_outcome: string | null;
partner_outcome: string | null;
endorser_start_cursor: string | null;
partner_start_cursor: string | null;
total_count: number | null;
counts: string | null;
records: string | null;
source_messages: string | null;
sms_eligible: number | null;
sms_sent: number | null;
sms_failed: number | null;
sms_blocked: number | null;
error: string | null;
};
type ScheduledUser = {
userId: string;
phones: string[];
unverifiedPhones: string[];
notifyHourMin?: string;
timezone?: string;
batchCreatedAt?: string;
/** Status of the JWT for today's UTC day, when one exists. */
todayStatus?: string;
/** Today's JWT when it is inside its nbf/exp window: usable for a preview. */
previewJwt?: string;
nextUnusedDay?: string;
lastUnusedDay?: string;
unusedLeft: number;
endorserCursor?: string;
partnerCursor?: string;
planHandleIds?: string[];
location?: AlertSearchLocationBBox;
lastRunAt?: string;
blockedPhones: string[];
allowed: boolean;
/** Sort key: the next run's "YYYY-MM-DD HH:MM", or "~" to sort last. */
sortKey: string;
nextLabel: string;
};
type PhoneLogRow = {
created_at: string;
user_id: string;
phone_e164: string | null;
action: string;
result: string;
detail: string | null;
provider_message_id: string | null;
};
function verifiedPhonesByUser(): Map<string, { verified: string[]; unverified: string[] }> {
const out = new Map<string, { verified: string[]; unverified: string[] }>();
const rows = db
.prepare(`SELECT user_id, phone_e164, verified FROM sms_registrations ORDER BY created_at`)
.all() as { user_id: string; phone_e164: string; verified: number }[];
for (const row of rows) {
const entry = out.get(row.user_id) ?? { verified: [], unverified: [] };
(row.verified === 1 ? entry.verified : entry.unverified).push(row.phone_e164);
out.set(row.user_id, entry);
}
return out;
}
function phonesFor(userId: string, phones: ReturnType<typeof verifiedPhonesByUser>): string {
const list = phones.get(userId)?.verified ?? [];
return list.length === 0 ? "(no verified phone)" : list.join(",");
}
function loadRuns(limit = 200): RunRow[] {
if (!hasTable("sms_alert_search_runs")) return [];
return db
.prepare(`SELECT * FROM sms_alert_search_runs ORDER BY ran_at DESC LIMIT ?`)
.all(limit) as RunRow[];
}
function loadPhoneLog(limit = 200): PhoneLogRow[] {
return db
.prepare(
`SELECT created_at, user_id, phone_e164, action, result, detail, provider_message_id
FROM sms_phone_log ORDER BY created_at DESC LIMIT ?`
)
.all(limit) as PhoneLogRow[];
}
function blockedPhones(phones: string[]): string[] {
const config = smsConfig();
const configured = new Set(
config.blockedNumbers.map((n) => normalizePhoneNumber(n)).filter((n) => n !== undefined)
);
const byNumber = db.prepare(
`SELECT 1 FROM sms_blocked_numbers WHERE phone_e164 = ? OR phone_hash = ?`
);
return phones.filter((phone) => {
if (configured.has(phone)) return true;
const hash = config.codeSecret === undefined ? "" : hashPhoneNumber(phone, config.codeSecret);
return byNumber.get(phone, hash) !== undefined;
});
}
function parseJson<T>(text: string | null | undefined): T | undefined {
if (text === null || text === undefined) return undefined;
try {
return JSON.parse(text) as T;
} catch {
return undefined;
}
}
function loadScheduled(now: Date): ScheduledUser[] {
const nowSec = Math.floor(now.getTime() / 1000);
const today = utcCalendarDay(nowSec);
const nowHourMin = utcHourMinute(nowSec);
const phones = verifiedPhonesByUser();
const hasRuns = hasTable("sms_alert_search_runs");
const userIds = (
db
.prepare(
`SELECT user_id FROM sms_alert_authorization_batches
UNION SELECT user_id FROM sms_registrations WHERE verified = 1`
)
.all() as { user_id: string }[]
).map((r) => r.user_id);
const latestBatch = db.prepare(
`SELECT notify_hour_min_utc, timezone, created_at FROM sms_alert_authorization_batches
WHERE user_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1`
);
const todayJwt = db.prepare(
`SELECT jwt, nbf, exp, status FROM sms_alert_authorization_jwts
WHERE user_id = ? AND day = ? ORDER BY status = 'unused' DESC, created_at DESC LIMIT 1`
);
const inventory = db.prepare(
`SELECT MIN(day) AS next_day, MAX(day) AS last_day, COUNT(*) AS n
FROM sms_alert_authorization_jwts
WHERE user_id = ? AND status = 'unused' AND day >= ?`
);
const cursors = db.prepare(`SELECT * FROM sms_alert_search_cursors WHERE user_id = ?`);
const lastRun = hasRuns
? db.prepare(`SELECT MAX(ran_at) AS ran_at FROM sms_alert_search_runs WHERE user_id = ?`)
: undefined;
return userIds
.map((userId): ScheduledUser => {
const batch = latestBatch.get(userId) as
| { notify_hour_min_utc: string | null; timezone: string | null; created_at: string }
| undefined;
const jwt = todayJwt.get(userId, today) as
| { jwt: string; nbf: number; exp: number; status: string }
| undefined;
const inv = inventory.get(userId, today) as {
next_day: string | null;
last_day: string | null;
n: number;
};
const cur = cursors.get(userId) as
| {
endorser_after_cursor: string | null;
partner_after_cursor: string | null;
plan_handle_ids: string | null;
location: string | null;
}
| undefined;
const userPhones = phones.get(userId) ?? { verified: [], unverified: [] };
const hm = batch?.notify_hour_min_utc ?? "00:00";
let sortKey = "~";
let nextLabel: string;
if (batch === undefined) {
nextLabel = "NEVER: no SMS authorization batch";
} else if (jwt?.status === "unused") {
sortKey = `${today} ${hm}`;
nextLabel = hm <= nowHourMin ? `DUE now (${hm}Z)` : `today ${hm}Z`;
} else if (inv.next_day !== null) {
sortKey = `${inv.next_day} ${hm}`;
nextLabel = `${inv.next_day === today ? "today" : inv.next_day} ${hm}Z`;
} else {
nextLabel = "NEVER: no unused JWT left";
}
return {
userId,
phones: userPhones.verified,
unverifiedPhones: userPhones.unverified,
notifyHourMin: batch?.notify_hour_min_utc ?? undefined,
timezone: batch?.timezone ?? undefined,
batchCreatedAt: batch?.created_at,
todayStatus: jwt?.status,
previewJwt:
jwt !== undefined && jwt.nbf <= nowSec && nowSec < jwt.exp ? jwt.jwt : undefined,
nextUnusedDay: inv.next_day ?? undefined,
lastUnusedDay: inv.last_day ?? undefined,
unusedLeft: inv.n,
endorserCursor: cur?.endorser_after_cursor ?? undefined,
partnerCursor: cur?.partner_after_cursor ?? undefined,
planHandleIds: parseJson<string[]>(cur?.plan_handle_ids),
location: parseJson<AlertSearchLocationBBox>(cur?.location),
lastRunAt:
(lastRun?.get(userId) as { ran_at: string | null } | undefined)?.ran_at ?? undefined,
blockedPhones: blockedPhones(userPhones.verified),
allowed: isSmsRecipientAllowed(userId),
sortKey,
nextLabel,
};
})
.sort((a, b) => a.sortKey.localeCompare(b.sortKey) || a.userId.localeCompare(b.userId));
}
// ---- describing rows ----
function shortDid(did: string): string {
return did.length <= 24 ? did : `${did.slice(0, 14)}…${did.slice(-6)}`;
}
function shortCursor(cursor: string | null | undefined): string {
if (cursor === null || cursor === undefined) return "-";
return cursor.length <= 12 ? cursor : `${cursor.slice(0, 5)}…${cursor.slice(-5)}`;
}
function stamp(iso: string): string {
// "2026-10-22T15:04:05.123Z" -> "10-22 15:04:05"
return `${iso.slice(5, 10)} ${iso.slice(11, 19)}`;
}
function runStatus(run: RunRow): string {
if (run.error !== null && run.completed === null) return "ERROR";
if (run.completed === 0) return `INCOMPLETE e=${run.endorser_outcome} p=${run.partner_outcome}`;
if (run.endorser_start_cursor === null && run.partner_start_cursor === null && run.consumed === 1) {
return "SEEDED (first run)";
}
if ((run.total_count ?? 0) === 0) return "no updates";
if (run.sms_sent !== null && run.sms_sent > 0) return `SENT ${run.sms_sent}`;
if (run.sms_eligible === 0) return "NOT ELIGIBLE";
if ((run.sms_blocked ?? 0) > 0) return `WITHHELD ${run.sms_blocked}`;
if ((run.sms_failed ?? 0) > 0) return `SEND FAILED ${run.sms_failed}`;
return "NOT SENT (cap or no phone)";
}
function nonZeroCounts(counts: Record<string, number> | undefined): string {
if (counts === undefined) return "";
return Object.entries(counts)
.filter(([, n]) => n > 0)
.map(([bucket, n]) => `${bucket}=${n}`)
.join(" ");
}
/** One short phrase per record, for the one-line view. */
function recordHeadlines(records: Record<string, unknown[]> | undefined): string {
if (records === undefined) return "";
const out: string[] = [];
for (const [bucket, rows] of Object.entries(records)) {
for (const row of rows) {
const r = row as Record<string, unknown>;
const inner = (r.plan ?? r.profile ?? r) as Record<string, unknown>;
const text =
inner.name ?? inner.claimType ?? inner.description ?? inner.handleId ?? inner.id ?? "?";
out.push(`${bucket}:${String(text).replace(/\s+/g, " ").slice(0, 40)}`);
}
}
return out.join("; ");
}
function runLine(run: RunRow, phones: ReturnType<typeof verifiedPhonesByUser>): string {
const counts = parseJson<Record<string, number>>(run.counts);
const records = parseJson<Record<string, unknown[]>>(run.records);
return [
stamp(run.ran_at),
runStatus(run).padEnd(18),
`n=${run.total_count ?? "-"}`.padEnd(6),
phonesFor(run.user_id, phones),
shortDid(run.user_id),
nonZeroCounts(counts),
recordHeadlines(records) || (run.error ?? ""),
].join(" │ ");
}
function scheduledLine(user: ScheduledUser): string {
const flags: string[] = [];
if (!user.allowed) flags.push("NOT-ALLOWED");
if (user.blockedPhones.length > 0) flags.push(`BLOCKED ${user.blockedPhones.join(",")}`);
if (user.phones.length === 0) flags.push("NO-PHONE");
if (user.endorserCursor === undefined || user.partnerCursor === undefined) flags.push("SEED-NEXT");
return [
user.nextLabel.padEnd(18),
user.phones.join(",") || "(no verified phone)",
shortDid(user.userId),
`jwts=${user.unusedLeft}`,
`E:${shortCursor(user.endorserCursor)} P:${shortCursor(user.partnerCursor)}`,
`plans=${user.planHandleIds?.length ?? 0} loc=${user.location === undefined ? "no" : "yes"}`,
flags.join(" "),
].join(" │ ");
}
function phoneLogLine(row: PhoneLogRow): string {
return [
stamp(row.created_at),
row.action.padEnd(28),
row.result.padEnd(8),
row.phone_e164 ?? "(scrubbed)",
shortDid(row.user_id),
row.detail ?? row.provider_message_id ?? "",
].join(" │ ");
}
function queryUrls(user: ScheduledUser): { endorser: string; partner: string } {
const endorser = alertSearchUrl(
ENDORSER_URL,
ENDORSER_ALERT_SEARCH_PATH,
buildAlertSearchQuery({
afterCursor: user.endorserCursor,
location: user.location,
planHandleIds: user.planHandleIds,
})
);
const partner = alertSearchUrl(
PARTNER_URL,
PARTNER_ALERT_SEARCH_PATH,
buildAlertSearchQuery({ afterCursor: user.partnerCursor, location: user.location })
);
return { endorser, partner };
}
function localNotifyTime(user: ScheduledUser): string {
if (user.notifyHourMin === undefined || user.timezone === undefined) return "";
const [h, m] = user.notifyHourMin.split(":").map(Number);
const at = new Date(Date.UTC(2000, 0, 1, h, m));
try {
return (
" = " +
at.toLocaleTimeString("en-US", { timeZone: user.timezone, hour: "2-digit", minute: "2-digit" }) +
` ${user.timezone} (at today's offset)`
);
} catch {
return "";
}
}
function pretty(value: unknown): string[] {
return JSON.stringify(value, null, 2).split("\n");
}
function runDetail(run: RunRow, phones: ReturnType<typeof verifiedPhonesByUser>): string[] {
return [
`Run at ${run.ran_at} (${run.elapsed_ms}ms) for UTC day ${run.utc_day ?? "-"}`,
`Status: ${runStatus(run)}`,
`User: ${run.user_id}`,
`Verified phones now: ${phonesFor(run.user_id, phones)}`,
`Completed: ${run.completed} consumed: ${run.consumed} endorser: ${run.endorser_outcome} partner: ${run.partner_outcome}`,
`Start cursors: endorser ${run.endorser_start_cursor ?? "-"} partner ${run.partner_start_cursor ?? "-"}`,
`SMS: eligible ${run.sms_eligible} sent ${run.sms_sent} failed ${run.sms_failed} withheld ${run.sms_blocked}`,
...(run.error === null ? [] : [`Error: ${run.error}`]),
`Source messages: ${run.source_messages ?? "-"}`,
"",
`Counts: ${nonZeroCounts(parseJson(run.counts)) || "(none)"}`,
"",
"Records:",
...pretty(parseJson(run.records) ?? null),
];
}
function scheduledDetail(user: ScheduledUser): string[] {
const urls = queryUrls(user);
return [
`User: ${user.userId}`,
`Next run: ${user.nextLabel}`,
`Notify time: ${user.notifyHourMin ?? "-"} UTC${localNotifyTime(user)}`,
`Verified phones: ${user.phones.join(", ") || "(none: the run happens, the text has nowhere to go)"}`,
`Unverified phones: ${user.unverifiedPhones.join(", ") || "-"}`,
`Blocked phones: ${user.blockedPhones.join(", ") || "-"}`,
`Allowed by SMS_ALLOWED_RECIPIENT_DIDS: ${user.allowed}`,
`Latest batch uploaded: ${user.batchCreatedAt ?? "-"}`,
`Today's JWT: ${user.todayStatus ?? "none"}${user.previewJwt === undefined ? "" : " (valid now: preview available, press p)"}`,
`Unused JWTs from today: ${user.unusedLeft} (${user.nextUnusedDay ?? "-"} .. ${user.lastUnusedDay ?? "-"})`,
`Last run recorded: ${user.lastRunAt ?? "-"}`,
`Endorser cursor: ${user.endorserCursor ?? "(none: next run only seeds it)"}`,
`Partner cursor: ${user.partnerCursor ?? "(none: next run only seeds it)"}`,
`Plan handle IDs: ${user.planHandleIds?.join(", ") ?? "-"}`,
`Location: ${user.location === undefined ? "-" : JSON.stringify(user.location)}`,
"",
"Queries the next run will send (first page):",
` ${urls.endorser}`,
` ${urls.partner}`,
];
}
// ---- preview ----
async function preview(user: ScheduledUser): Promise<string[]> {
if (user.previewJwt === undefined) {
return [
`No JWT for today is inside its validity window for ${user.userId},`,
"so the servers would reject the query. Nothing was sent.",
];
}
// retrieve logs failures through console; keep them in the preview instead.
const captured: string[] = [];
const saved = { log: console.log, error: console.error, warn: console.warn };
const capture = (...args: unknown[]) => captured.push(args.map(String).join(" "));
console.log = console.error = console.warn = capture;
const started = Date.now();
try {
const retrieved = await retrieveAlertSearch({
jwt: user.previewJwt,
endorserAfterCursor: user.endorserCursor,
partnerAfterCursor: user.partnerCursor,
location: user.location,
planHandleIds: user.planHandleIds,
});
const digest = buildAlertSearchDigest(retrieved);
const seeding = user.endorserCursor === undefined || user.partnerCursor === undefined;
return [
`PREVIEW for ${user.userId} in ${Date.now() - started}ms (nothing consumed, no cursor moved)`,
`Phones: ${user.phones.join(", ") || "(none)"}`,
...(seeding ? ["A cursor is missing: the real run would seed it and report nothing."] : []),
alertSearchDigestDebugSummary(digest),
`Endorser: ${retrieved.endorser.pageCount} page(s), next cursor ${retrieved.endorser.nextAfterCursor ?? "-"}${retrieved.endorser.message ? ", " + retrieved.endorser.message : ""}`,
`Partner: ${retrieved.partner.pageCount} page(s), next cursor ${retrieved.partner.nextAfterCursor ?? "-"}${retrieved.partner.message ? ", " + retrieved.partner.message : ""}`,
`Would text: ${digest.hasUpdates && !seeding ? `yes, ${digest.totalCount} update(s)` : "no"}`,
...captured.map((line) => `log: ${line}`),
"",
"Records:",
...pretty(digest.records),
];
} catch (err) {
return [`Preview failed: ${err instanceof Error ? err.message : String(err)}`, ...captured];
} finally {
Object.assign(console, saved);
}
}
// ---- once mode ----
type Snapshot = {
runs: RunRow[];
scheduled: ScheduledUser[];
phoneLog: PhoneLogRow[];
phones: ReturnType<typeof verifiedPhonesByUser>;
runsTable: boolean;
};
function snapshot(): Snapshot {
return {
runs: loadRuns(),
scheduled: loadScheduled(new Date()),
phoneLog: loadPhoneLog(),
phones: verifiedPhonesByUser(),
runsTable: hasTable("sms_alert_search_runs"),
};
}
const NO_RUNS_TABLE =
"(no sms_alert_search_runs table: the service predates run recording; upgrade it)";
if (ONCE) {
const snap = snapshot();
const width = 200;
const cut = (s: string) => (s.length > width ? s.slice(0, width - 1) + "…" : s);
console.log(`DB ${DB_PATH} now ${new Date().toISOString()}`);
console.log("\n== Recent runs ==");
if (!snap.runsTable) console.log(NO_RUNS_TABLE);
for (const run of snap.runs.slice(0, 30)) console.log(cut(runLine(run, snap.phones)));
console.log("\n== Scheduled ==");
for (const user of snap.scheduled) console.log(cut(scheduledLine(user)));
console.log("\n== Phone log ==");
for (const row of snap.phoneLog.slice(0, 30)) console.log(cut(phoneLogLine(row)));
process.exit(0);
}
// ---- interactive mode ----
type View = "runs" | "scheduled" | "log";
const VIEWS: View[] = ["runs", "scheduled", "log"];
const VIEW_TITLES: Record<View, string> = {
runs: "1 Recent runs",
scheduled: "2 Scheduled",
log: "3 Phone log",
};
const state = {
view: "runs" as View,
selected: { runs: 0, scheduled: 0, log: 0 } as Record<View, number>,
top: { runs: 0, scheduled: 0, log: 0 } as Record<View, number>,
/** When set, a detail page is showing instead of a list. */
detail: undefined as string[] | undefined,
detailTop: 0,
status: "",
/** Set once the replay warning has been accepted in this session. */
previewConfirmed: false,
/** True while the replay warning waits for y or n. */
confirmingPreview: false,
snap: snapshot(),
};
const ESC = "\x1b[";
const out = (s: string) => process.stdout.write(s);
function fit(text: string, width: number): string {
const flat = text.replace(/[\r\n\t]+/g, " ");
return flat.length > width ? flat.slice(0, width - 1) + "…" : flat.padEnd(width);
}
function wrap(lines: string[], width: number): string[] {
const wrapped: string[] = [];
for (const line of lines) {
if (line.length <= width) wrapped.push(line);
else for (let i = 0; i < line.length; i += width) wrapped.push(line.slice(i, i + width));
}
return wrapped;
}
function listLines(): string[] {
const { snap } = state;
if (state.view === "runs") return snap.runs.map((run) => runLine(run, snap.phones));
if (state.view === "scheduled") return snap.scheduled.map(scheduledLine);
return snap.phoneLog.map(phoneLogLine);
}
function render(): void {
const width = process.stdout.columns || 120;
const height = process.stdout.rows || 40;
const now = new Date();
const tabs = VIEWS.map((v) => (v === state.view ? `${ESC}7m ${VIEW_TITLES[v]} ${ESC}0m` : ` ${VIEW_TITLES[v]} `)).join("");
const header = `SMS watch ${now.toISOString().slice(0, 19)}Z `;
let screen = `${ESC}H${ESC}2J${header}${tabs}\n`;
const bodyHeight = height - 3;
if (state.detail !== undefined) {
const lines = wrap(state.detail, width);
state.detailTop = Math.max(0, Math.min(state.detailTop, lines.length - bodyHeight));
for (const line of lines.slice(state.detailTop, state.detailTop + bodyHeight)) {
screen += line + "\n";
}
screen += `${ESC}${height};1H${ESC}7m${fit(
`${state.detailTop + 1}-${Math.min(lines.length, state.detailTop + bodyHeight)}/${lines.length} j/k space/b g/G scroll Esc back ${state.status}`,
width
)}${ESC}0m`;
out(screen);
return;
}
const lines = listLines();
const view = state.view;
state.selected[view] = Math.max(0, Math.min(state.selected[view], lines.length - 1));
if (state.selected[view] < state.top[view]) state.top[view] = state.selected[view];
if (state.selected[view] >= state.top[view] + bodyHeight) {
state.top[view] = state.selected[view] - bodyHeight + 1;
}
if (view === "runs" && !state.snap.runsTable) screen += NO_RUNS_TABLE + "\n";
else if (lines.length === 0) screen += "(nothing yet)\n";
lines.slice(state.top[view], state.top[view] + bodyHeight).forEach((line, i) => {
const selected = state.top[view] + i === state.selected[view];
screen += (selected ? `${ESC}7m` : "") + fit(line, width) + (selected ? `${ESC}0m` : "") + "\n";
});
const help = view === "scheduled" ? "Enter details p preview" : "Enter details";
screen += `${ESC}${height};1H${ESC}7m${fit(
`${lines.length} rows 1/2/3 Tab view j/k move ${help} q quit ${state.status}`,
width
)}${ESC}0m`;
out(screen);
}
function refresh(): void {
try {
state.snap = snapshot();
} catch (err) {
state.status = `read failed: ${err instanceof Error ? err.message : String(err)}`;
}
if (state.detail === undefined) render();
}
function quit(): void {
out(`${ESC}?25h${ESC}?1049l`);
process.exit(0);
}
function openDetail(): void {
const i = state.selected[state.view];
const { snap } = state;
if (state.view === "runs" && snap.runs[i]) state.detail = runDetail(snap.runs[i], snap.phones);
if (state.view === "scheduled" && snap.scheduled[i]) state.detail = scheduledDetail(snap.scheduled[i]);
if (state.view === "log" && snap.phoneLog[i]) state.detail = pretty(snap.phoneLog[i]);
state.detailTop = 0;
}
const REPLAY_WARNING = [
"Endorser will eventually protect against replays, meaning the real user would",
"not see anything for today because you're running the query.",
"",
"Are you sure you want to continue? (y/n)",
];
async function runPreview(): Promise<void> {
if (state.view !== "scheduled") return;
const user = state.snap.scheduled[state.selected.scheduled];
if (user === undefined) return;
if (!state.previewConfirmed) {
state.confirmingPreview = true;
state.detail = REPLAY_WARNING;
state.detailTop = 0;
render();
return;
}
state.detail = [`Querying Endorser and Partner for ${user.userId}…`];
state.detailTop = 0;
render();
state.detail = await preview(user);
render();
}
function onKey(key: string): void {
const height = (process.stdout.rows || 40) - 3;
if (key === "\x03") quit();
if (state.confirmingPreview) {
if (key !== "y" && key !== "Y" && key !== "n" && key !== "N" && key !== "\x1b") return;
state.confirmingPreview = false;
state.detail = undefined;
if (key === "y" || key === "Y") {
state.previewConfirmed = true;
void runPreview();
} else {
render();
}
return;
}
if (state.detail !== undefined) {
if (key === "\x1b" || key === "q" || key === "\x7f") state.detail = undefined;
else if (key === "j" || key === `${ESC}B`) state.detailTop += 1;
else if (key === "k" || key === `${ESC}A`) state.detailTop = Math.max(0, state.detailTop - 1);
else if (key === " " || key === `${ESC}6~`) state.detailTop += height;
else if (key === "b" || key === `${ESC}5~`) state.detailTop = Math.max(0, state.detailTop - height);
else if (key === "g") state.detailTop = 0;
else if (key === "G") state.detailTop = Number.MAX_SAFE_INTEGER;
render();
return;
}
const view = state.view;
if (key === "q") quit();
else if (key === "1" || key === "2" || key === "3") state.view = VIEWS[Number(key) - 1];
else if (key === "\t") state.view = VIEWS[(VIEWS.indexOf(view) + 1) % VIEWS.length];
else if (key === "j" || key === `${ESC}B`) state.selected[view] += 1;
else if (key === "k" || key === `${ESC}A`) state.selected[view] = Math.max(0, state.selected[view] - 1);
else if (key === " " || key === `${ESC}6~`) state.selected[view] += height;
else if (key === "b" || key === `${ESC}5~`) state.selected[view] = Math.max(0, state.selected[view] - height);
else if (key === "\r") openDetail();
else if (key === "p") {
void runPreview();
return;
}
render();
}
out(`${ESC}?1049h${ESC}?25l`);
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.on("data", (data: string) => onKey(data));
process.stdout.on("resize", render);
process.on("SIGTERM", quit);
setInterval(refresh, REFRESH_SEC * 1000);
render();
+419
View File
@@ -0,0 +1,419 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { emptyEndorserData, emptyPartnerData } from "../../src/alertSearch/client.js";
import {
ALERT_SEARCH_UPDATE_CATEGORIES,
ENDORSER_CLAIM_TYPES,
claimUpdateKind,
countAlertSearchUpdates,
formatAlertSearchUpdateLine,
totalAlertSearchUpdates,
} from "../../src/alertSearch/categories.js";
import {
ALERT_SEARCH_FCM_TYPE,
alertSearchNotificationBody,
alertSearchNotificationTitle,
buildAlertSearchNotificationContent,
isAlertSearchNotificationEligible,
} from "../../src/alertSearch/notify.js";
import type { AlertSearchDigest } from "../../src/alertSearch/digest.js";
import type { DailyAlertSearchResult } from "../../src/alertSearch/daily.js";
import type {
AlertSearchClaimRecord,
AlertSearchPlanRecord,
AlertSearchProfileRecord,
CombinedAlertSearchData,
} from "../../src/alertSearch/types.js";
const USER = "did:ethr:0xuser";
const OTHER = "did:ethr:0xother";
function records(
partial: Partial<CombinedAlertSearchData> = {}
): CombinedAlertSearchData {
return {
...emptyEndorserData(),
...emptyPartnerData(),
...partial,
};
}
function jwt(
id: string,
claimType?: string,
extra: Partial<AlertSearchClaimRecord> = {}
): AlertSearchClaimRecord {
return {
id,
issuedAt: "2026-01-01T00:00:00Z",
issuer: OTHER,
...extra,
...(claimType === undefined ? {} : { claimType }),
};
}
function plan(handleId: string): AlertSearchPlanRecord {
return { handleId, jwtId: `jwt-${handleId}`, name: handleId };
}
function profile(rowId: number, issuerDid = `did:ethr:0xp${rowId}`): AlertSearchProfileRecord {
return { rowId, issuerDid, description: `profile-${rowId}` };
}
function onlyCategory(
data: CombinedAlertSearchData,
userId?: string
): string {
const counts = countAlertSearchUpdates(data, userId);
const nonzero = ALERT_SEARCH_UPDATE_CATEGORIES.filter(
(category) => counts[category] > 0
);
assert.equal(nonzero.length, 1, nonzero.join(","));
return nonzero[0];
}
function bulletNumbers(body: string): number[] {
return body
.split("\n")
.map((line) => {
const match = /^- (\d+) /.exec(line);
assert.ok(match, line);
return Number(match[1]);
});
}
describe("alertSearch update classification", () => {
it("classifies every Endorser claim type from claimType, not from other fields", () => {
const extras = ["TradeAction", "DonateAction", "OrganizationRole", "giveaction", "Offer "];
for (const claimType of [...ENDORSER_CLAIM_TYPES, ...extras]) {
const kind = claimUpdateKind(claimType);
if (claimType === "GiveAction") assert.equal(kind, "give");
else if (claimType === "Offer") assert.equal(kind, "offer");
else assert.equal(kind, "other", claimType);
const owned = onlyCategory(
records({
personalPlanContributions: [
{
...jwt("owned", claimType),
claim: JSON.stringify({ "@type": "Offer" }),
offer: true,
},
],
}),
USER
);
const starred = onlyCategory(
records({
trackedPlanClaims: [jwt("starred", claimType, { fromEntity: "offer" })],
}),
USER
);
const toYou = onlyCategory(
records({
claims: [jwt("to-you", claimType, { toEntity: USER, fromEntity: OTHER })],
}),
USER
);
if (claimType === "GiveAction") {
assert.equal(owned, "giveToOwnedProject");
assert.equal(starred, "giveToStarredProject");
assert.equal(toYou, "giveToYou");
} else if (claimType === "Offer") {
assert.equal(owned, "offerToOwnedProject");
assert.equal(starred, "offerToStarredProject");
assert.equal(toYou, "offerToYou");
} else {
assert.equal(owned, "otherContributionToOwnedProject", claimType);
assert.equal(starred, "otherClaimOnStarredProject", claimType);
assert.equal(toYou, "otherClaimToYou", claimType);
}
}
});
it("uses fromEntity when the claims row is not addressed to the requester", () => {
assert.equal(
onlyCategory(
records({
claims: [jwt("from-give", "GiveAction", { fromEntity: USER, toEntity: "plan-1" })],
}),
USER
),
"giveFromYou"
);
assert.equal(
onlyCategory(
records({
claims: [jwt("from-offer", "Offer", { fromEntity: USER })],
}),
USER
),
"offerFromYou"
);
assert.equal(
onlyCategory(
records({
claims: [jwt("from-other", "PlanAction", { fromEntity: USER })],
}),
USER
),
"otherClaimFromYou"
);
assert.equal(
onlyCategory(
records({
claims: [jwt("both", "GiveAction", { toEntity: USER, fromEntity: USER })],
}),
USER
),
"giveToYou"
);
});
it("classifies a claims row as to the requester or from the requester", () => {
const names = new Set<string>(ALERT_SEARCH_UPDATE_CATEGORIES);
assert.equal(names.has("offerInvolvingYou"), false);
assert.equal(names.has("giveInvolvingYou"), false);
assert.equal(names.has("otherClaimInvolvingYou"), false);
assert.equal(
onlyCategory(
records({
claims: [jwt("to-offer", "Offer", { toEntity: USER, fromEntity: OTHER })],
}),
USER
),
"offerToYou"
);
assert.equal(
onlyCategory(
records({
claims: [jwt("from-give", "GiveAction", { fromEntity: USER, toEntity: "plan-1" })],
}),
USER
),
"giveFromYou"
);
});
it("counts one record once when the APIs return it in more than one list", () => {
const sharedGive = jwt("same-jwt", "GiveAction", { toEntity: USER });
const starredCopy = jwt("same-jwt", "Offer", { toEntity: "plan-star" });
const nearbyPlan = plan("shared-plan");
const similarPlan = { ...plan("shared-plan"), description: "same project" };
const nearbyProfile = profile(7, "did:ethr:0xshared");
const data = records({
personalPlanContributions: [sharedGive],
trackedPlanClaims: [starredCopy],
claims: [jwt("same-jwt", "GiveAction", { toEntity: USER })],
trackedPlanUpdates: [nearbyPlan],
plansNearby: [{ ...nearbyPlan, locLat: 1 }],
plansSimilar: [{ similarity: 0.8, plan: similarPlan }],
profilesNearby: [nearbyProfile],
profilesSimilar: [
{ similarity: 0.4, profile: { ...profile(7, "did:ethr:0xshared"), description: "again" } },
],
});
const counts = countAlertSearchUpdates(data, USER);
assert.equal(counts.giveToOwnedProject, 1);
assert.equal(counts.offerToStarredProject, 0);
assert.equal(counts.giveToYou, 0);
assert.equal(counts.starredProjectUpdate, 1);
assert.equal(counts.projectNearby, 0);
assert.equal(counts.projectSimilar, 0);
assert.equal(counts.profileNearby, 1);
assert.equal(counts.profileSimilar, 0);
assert.equal(totalAlertSearchUpdates(counts), 3);
const content = buildAlertSearchNotificationContent(data, USER);
assert.equal(content.title, "You have 3 new updates");
assert.equal(
content.body,
[
"- 1 new give to a project you own",
"- 1 new project update to a starred project",
"- 1 new profile near you",
].join("\n")
);
assert.equal(content.body.includes("You have"), false);
assert.equal(
bulletNumbers(content.body).reduce((sum, n) => sum + n, 0),
3
);
});
});
describe("alertSearch notification body", () => {
it("puts a total of 1 in the title and the single category in the body", () => {
const data = records({
personalPlanContributions: [jwt("g1", "GiveAction")],
});
const content = buildAlertSearchNotificationContent(data, USER);
assert.equal(content.title, "You have 1 new update");
assert.equal(content.title, alertSearchNotificationTitle(1));
assert.equal(content.body, "- 1 new give to a project you own");
assert.equal(content.body.includes("You have"), false);
});
it("uses updates in the title when the only category is plural", () => {
const content = buildAlertSearchNotificationContent(
records({
trackedPlanClaims: [jwt("o1", "Offer"), jwt("o2", "Offer")],
}),
USER
);
assert.equal(content.title, "You have 2 new updates");
assert.equal(content.body, "- 2 new offers to your starred projects");
assert.equal(content.body.includes("\n"), false);
});
it("lists each nonzero category once, with the title total equal to the lines", () => {
const content = buildAlertSearchNotificationContent(
records({
personalPlanContributions: [jwt("g1", "GiveAction")],
trackedPlanClaims: [jwt("o1", "Offer"), jwt("o2", "Offer")],
trackedPlanUpdates: [plan("star-1"), plan("star-2")],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
}),
USER
);
assert.equal(content.title, "You have 5 new updates");
assert.equal(
content.body,
[
"- 1 new give to a project you own",
"- 2 new offers to your starred projects",
"- 2 new project updates to your starred projects",
].join("\n")
);
const stated = Number(/You have (\d+) /.exec(content.title)?.[1]);
assert.equal(
stated,
bulletNumbers(content.body).reduce((sum, n) => sum + n, 0)
);
assert.equal(content.body.includes("You have"), false);
assert.equal(content.body.includes("profile"), false);
assert.equal(content.body.includes("near you"), false);
});
it("phrases every category in the singular and the plural and omits zeros", () => {
const plural: Record<(typeof ALERT_SEARCH_UPDATE_CATEGORIES)[number], string> = {
offerToOwnedProject: "2 new offers to projects you own",
giveToOwnedProject: "2 new gives to projects you own",
otherContributionToOwnedProject: "2 new contributions to projects you own",
offerToStarredProject: "2 new offers to your starred projects",
giveToStarredProject: "2 new gives to your starred projects",
otherClaimOnStarredProject: "2 new claims on your starred projects",
starredProjectUpdate: "2 new project updates to your starred projects",
offerToYou: "2 new offers to you",
giveToYou: "2 new gives to you",
otherClaimToYou: "2 new claims to you",
offerFromYou: "2 new offers from you",
giveFromYou: "2 new gives from you",
otherClaimFromYou: "2 new claims from you",
projectNearby: "2 new projects near you",
profileNearby: "2 new profiles near you",
projectSimilar: "2 new projects similar to your profile",
profileSimilar: "2 new profiles similar to yours",
};
const data = records({
personalPlanContributions: [
jwt("own-offer", "Offer"),
jwt("own-give", "GiveAction"),
jwt("own-other", "PlanAction"),
],
trackedPlanClaims: [
jwt("star-offer", "Offer"),
jwt("star-give", "GiveAction"),
jwt("star-other", "AgreeAction"),
],
trackedPlanUpdates: [plan("starred")],
claims: [
jwt("to-offer", "Offer", { toEntity: USER }),
jwt("to-give", "GiveAction", { toEntity: USER }),
jwt("to-other", "JoinAction", { toEntity: USER }),
jwt("from-offer", "Offer", { fromEntity: USER, toEntity: "plan-9" }),
jwt("from-give", "GiveAction", { fromEntity: USER, toEntity: "plan-9" }),
jwt("from-other", "Project", { fromEntity: USER }),
],
plansNearby: [plan("nearby")],
plansSimilar: [{ similarity: 0.7, plan: plan("similar-plan") }],
profilesNearby: [profile(1)],
profilesSimilar: [{ similarity: 0.7, profile: profile(2) }],
});
const counts = countAlertSearchUpdates(data, USER);
const content = buildAlertSearchNotificationContent(data, USER);
const body = content.body;
const lines = body.split("\n");
assert.equal(lines.length, ALERT_SEARCH_UPDATE_CATEGORIES.length);
ALERT_SEARCH_UPDATE_CATEGORIES.forEach((category, index) => {
assert.equal(counts[category], 1, category);
assert.equal(lines[index], `- ${formatAlertSearchUpdateLine(category, 1)}`);
assert.equal(formatAlertSearchUpdateLine(category, 2), plural[category]);
assert.notEqual(
formatAlertSearchUpdateLine(category, 1),
formatAlertSearchUpdateLine(category, 2)
);
});
const stated = Number(/You have (\d+) /.exec(content.title)?.[1]);
assert.equal(stated, totalAlertSearchUpdates(counts));
assert.equal(stated, lines.length);
assert.equal(content.title, alertSearchNotificationTitle(stated));
assert.equal(content.type, ALERT_SEARCH_FCM_TYPE);
assert.equal(content.type, "alert_search");
assert.equal(content.body, body);
assert.equal(content.body.includes(USER), false);
assert.equal(content.body.includes("\n- 0 "), false);
});
it("builds an empty body when there are no records, and that digest is not sent", () => {
const content = buildAlertSearchNotificationContent(records(), USER);
assert.equal(content.title, "You have 0 new updates");
assert.equal(content.body, "");
const digest: AlertSearchDigest = {
completed: true,
hasUpdates: false,
totalCount: 0,
counts: {
claims: 0,
personalPlanContributions: 0,
trackedPlanUpdates: 0,
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
},
records: records(),
endorser: { outcome: "empty", completed: true },
partner: { outcome: "empty", completed: true },
};
const daily: DailyAlertSearchResult = {
userId: USER,
utcDay: "2026-08-14",
batchId: "batch-1",
jwtSequence: 1,
endorserOutcome: "empty",
partnerOutcome: "empty",
completed: true,
consumed: true,
digest,
};
assert.equal(isAlertSearchNotificationEligible(daily), false);
const incomplete: DailyAlertSearchResult = {
...daily,
completed: false,
consumed: false,
digest: {
...digest,
completed: false,
hasUpdates: false,
totalCount: 1,
partner: { outcome: "auth", completed: false, reason: "auth" },
},
};
assert.equal(isAlertSearchNotificationEligible(incomplete), false);
});
});
+101 -215
View File
@@ -4,25 +4,20 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, it } from "node:test";
import { alertSearchCursorsDb } from "../../src/db/alertSearchCursorsSqlite.js";
import { closeDatabase } from "../../src/db/sqlite.js";
import Database from "better-sqlite3";
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
import {
advanceAlertSearchCursors,
loadAlertSearchCursors,
maxEndorserAlertSearchUlid,
} from "../../src/alertSearch/cursors.js";
import { retrieveAlertSearch } from "../../src/alertSearch/retrieve.js";
import type { AlertSearchSourceResult, RetrieveAlertSearchResult } from "../../src/alertSearch/retrieve.js";
import { ALERT_SEARCH_PAGE_SIZE } from "../../src/alertSearch/types.js";
import type { EndorserAlertSearchData, PartnerAlertSearchData } from "../../src/alertSearch/types.js";
const USER = "did:ethr:0xcursoruser";
const OTHER_USER = "did:ethr:0xother";
const JWT = "delegated.jwt.token";
function ulid(n: number): string {
return `01H${String(n).padStart(23, "0")}`;
}
function emptyEndorser(): EndorserAlertSearchData {
return {
claims: [],
@@ -34,21 +29,21 @@ function emptyEndorser(): EndorserAlertSearchData {
}
function emptyPartner(): PartnerAlertSearchData {
return { profilesNearby: [] };
return { profilesNearby: [], profilesSimilar: [], plansSimilar: [] };
}
function endorserResult(
outcome: AlertSearchSourceResult<EndorserAlertSearchData>["outcome"],
data: EndorserAlertSearchData = emptyEndorser()
nextAfterCursor?: string
): AlertSearchSourceResult<EndorserAlertSearchData> {
return { outcome, pageCount: 1, data };
return { outcome, pageCount: 1, data: emptyEndorser(), nextAfterCursor };
}
function partnerResult(
outcome: AlertSearchSourceResult<PartnerAlertSearchData>["outcome"],
data: PartnerAlertSearchData = emptyPartner()
nextAfterCursor?: string
): AlertSearchSourceResult<PartnerAlertSearchData> {
return { outcome, pageCount: 1, data };
return { outcome, pageCount: 1, data: emptyPartner(), nextAfterCursor };
}
function combined(
@@ -107,10 +102,9 @@ describe("alertSearch cursor persistence", () => {
await rm(dir, { recursive: true, force: true });
});
it("no existing cursor → retrieval receives no afterId or afterDate", async () => {
it("no existing cursor → one request per source without 'afterCursor', returning the server's cursor", async () => {
const loaded = await loadAlertSearchCursors(USER);
assert.equal(loaded.endorserAfterId, undefined);
assert.equal(loaded.partnerAfterDate, undefined);
assert.deepEqual(loaded, {});
const urls: string[] = [];
const result = await retrieveAlertSearch({
@@ -121,241 +115,101 @@ describe("alertSearch cursor persistence", () => {
config: {
fetch: async (url) => {
urls.push(url);
// hasMore on a first run means older rows, which are not news
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "4-20", hasMore: true });
}
return jsonResponse(emptyEndorserBody());
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "20", hasMore: true });
},
},
});
assert.equal(result.endorser.outcome, "empty");
assert.equal(urls.length, 2);
for (const url of urls) {
assert.equal(url.includes("afterId="), false);
assert.equal(url.includes("afterDate="), false);
assert.equal(new URL(url).searchParams.has("afterCursor"), false);
}
assert.equal(result.endorser.outcome, "empty");
assert.equal(result.endorser.nextAfterCursor, "20");
assert.equal(result.partner.nextAfterCursor, "4-20");
});
it("complete Endorser retrieval → cursor becomes maximum returned ULID", async () => {
const data = emptyEndorser();
data.claims = [
{ id: ulid(10), issuedAt: "t", issuer: "did:ethr:0x1" },
{ id: ulid(30), issuedAt: "t", issuer: "did:ethr:0x1" },
];
data.plansNearby = [{ handleId: "p", jwtId: ulid(20) }];
assert.equal(maxEndorserAlertSearchUlid(data), ulid(30));
it("success → both cursors move to nextAfterCursor", async () => {
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("success", data), partnerResult("empty"))
combined(endorserResult("success", "48213"), partnerResult("success", "912-48213"))
);
assert.equal(advanced.endorserAdvanced, true);
assert.equal(advanced.endorserAfterId, ulid(30));
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAdvanced, true);
assert.equal(advanced.endorserAfterCursor, "48213");
assert.equal(advanced.partnerAfterCursor, "912-48213");
});
it("Endorser empty retrieval → existing cursor unchanged", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(99));
it("empty run → cursors advance", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "10");
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("empty"), partnerResult("empty"))
combined(endorserResult("empty", "25"), partnerResult("empty", "2-25"))
);
assert.equal(advanced.endorserAdvanced, false);
assert.equal(advanced.endorserAfterId, ulid(99));
assert.equal(advanced.endorserAdvanced, true);
assert.equal(advanced.endorserAfterCursor, "25");
assert.equal(advanced.partnerAdvanced, true);
assert.equal(advanced.partnerAfterCursor, "2-25");
});
it("Endorser pagination → cursor unchanged", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(5));
const data = emptyEndorser();
data.claims = Array.from({ length: ALERT_SEARCH_PAGE_SIZE }, (_, i) => ({
id: ulid(100 + i),
issuedAt: "t",
issuer: "did:ethr:0x1",
}));
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("pagination", data), partnerResult("empty"))
);
assert.equal(advanced.endorserAdvanced, false);
assert.equal(advanced.endorserAfterId, ulid(5));
});
it("Endorser error → cursor unchanged", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(5));
for (const outcome of ["auth", "timeout", "network", "malformed", "http"] as const) {
it("pagination or error → cursor unchanged", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "10");
await alertSearchCursorsDb.setPartnerAfterCursor(USER, "3-10");
for (const outcome of ["pagination", "auth", "timeout", "network", "malformed", "http"] as const) {
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult(outcome), partnerResult("empty"))
combined(endorserResult(outcome, "99"), partnerResult(outcome, "9-99"))
);
assert.equal(advanced.endorserAdvanced, false, outcome);
assert.equal(advanced.endorserAfterId, ulid(5), outcome);
assert.equal(advanced.partnerAdvanced, false, outcome);
assert.equal(advanced.endorserAfterCursor, "10", outcome);
assert.equal(advanced.partnerAfterCursor, "3-10", outcome);
}
});
it("complete Partner retrieval → cursor becomes maximum returned updatedAt", async () => {
const data = emptyPartner();
data.profilesNearby = [
{
issuerDid: "did:ethr:0x1",
description: "a",
updatedAt: "2026-01-01T00:00:00.000Z",
},
{
issuerDid: "did:ethr:0x2",
description: "b",
updatedAt: "2026-03-01T12:00:00.000Z",
},
];
// the retry must search the same window, or the rows the completed source
// found would never be counted
it("Endorser success + Partner failure → neither advances", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "30");
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("empty"), partnerResult("success", data))
);
assert.equal(advanced.partnerAdvanced, true);
assert.equal(advanced.partnerAfterAt, "2026-03-01T12:00:00.000Z");
});
it("Partner empty retrieval → existing cursor unchanged", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-02-01T00:00:00.000Z");
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("empty"), partnerResult("empty"))
);
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAfterAt, "2026-02-01T00:00:00.000Z");
});
it("Partner pagination → cursor unchanged", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-02-01T00:00:00.000Z");
const data = emptyPartner();
data.profilesNearby = Array.from({ length: ALERT_SEARCH_PAGE_SIZE }, (_, i) => ({
issuerDid: `did:ethr:0x${i}`,
description: "p",
updatedAt: "2026-04-01T00:00:00.000Z",
}));
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("empty"), partnerResult("pagination", data))
);
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAfterAt, "2026-02-01T00:00:00.000Z");
});
it("Partner error → cursor unchanged", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-02-01T00:00:00.000Z");
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("empty"), partnerResult("network"))
);
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAfterAt, "2026-02-01T00:00:00.000Z");
});
it("Endorser success + Partner failure → only Endorser advances", async () => {
const endorserData = emptyEndorser();
endorserData.claims = [
{ id: ulid(40), issuedAt: "t", issuer: "did:ethr:0x1" },
];
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("success", endorserData), partnerResult("auth"))
);
assert.equal(advanced.endorserAdvanced, true);
assert.equal(advanced.endorserAfterId, ulid(40));
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAfterAt, null);
});
it("Endorser failure + Partner success → only Partner advances", async () => {
const partnerData = emptyPartner();
partnerData.profilesNearby = [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-05-01T00:00:00.000Z",
},
];
const advanced = await advanceAlertSearchCursors(
USER,
combined(endorserResult("timeout"), partnerResult("success", partnerData))
combined(endorserResult("success", "40"), partnerResult("auth"))
);
assert.equal(advanced.endorserAdvanced, false);
assert.equal(advanced.endorserAfterId, null);
assert.equal(advanced.partnerAdvanced, true);
assert.equal(advanced.partnerAfterAt, "2026-05-01T00:00:00.000Z");
assert.equal(advanced.endorserAfterCursor, "30");
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.partnerAfterCursor, null);
});
it("both successful → both advance", async () => {
const endorserData = emptyEndorser();
endorserData.trackedPlanClaims = [
{ id: ulid(7), issuedAt: "t", issuer: "did:ethr:0x1" },
];
const partnerData = emptyPartner();
partnerData.profilesNearby = [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-06-01T00:00:00.000Z",
},
];
it("Endorser failure + Partner success → neither advances", async () => {
const advanced = await advanceAlertSearchCursors(
USER,
combined(
endorserResult("success", endorserData),
partnerResult("success", partnerData)
)
);
assert.equal(advanced.endorserAdvanced, true);
assert.equal(advanced.partnerAdvanced, true);
assert.equal(advanced.endorserAfterId, ulid(7));
assert.equal(advanced.partnerAfterAt, "2026-06-01T00:00:00.000Z");
});
it("no usable returned cursor → existing cursor unchanged", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(8));
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-01-01T00:00:00.000Z");
const endorserData = emptyEndorser();
endorserData.claims = [
{ id: "not-a-ulid", issuedAt: "t", issuer: "did:ethr:0x1" },
];
const partnerData = emptyPartner();
partnerData.profilesNearby = [
{ issuerDid: "did:ethr:0x1", description: "p" },
];
const advanced = await advanceAlertSearchCursors(
USER,
combined(
endorserResult("success", endorserData),
partnerResult("success", partnerData)
)
combined(endorserResult("timeout"), partnerResult("success", "5-41"))
);
assert.equal(advanced.endorserAdvanced, false);
assert.equal(advanced.endorserAfterCursor, null);
assert.equal(advanced.partnerAdvanced, false);
assert.equal(advanced.endorserAfterId, ulid(8));
assert.equal(advanced.partnerAfterAt, "2026-01-01T00:00:00.000Z");
assert.equal(advanced.partnerAfterCursor, null);
});
it("survives close and reopen of the SQLite connection", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(11));
await alertSearchCursorsDb.setPartnerAfterAt(
USER,
"2026-07-01T00:00:00.000Z"
);
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "11");
await alertSearchCursorsDb.setPartnerAfterCursor(USER, "2-11");
closeDatabase();
const loaded = await loadAlertSearchCursors(USER);
assert.equal(loaded.endorserAfterId, ulid(11));
assert.equal(loaded.partnerAfterDate, "2026-07-01T00:00:00.000Z");
const other = await loadAlertSearchCursors(OTHER_USER);
assert.equal(other.endorserAfterId, undefined);
assert.equal(other.partnerAfterDate, undefined);
assert.deepEqual(await loadAlertSearchCursors(USER), {
endorserAfterCursor: "11",
partnerAfterCursor: "2-11",
});
assert.deepEqual(await loadAlertSearchCursors(OTHER_USER), {});
});
it("loaded Partner cursor is sent as afterDate, not afterId 0", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(
USER,
"2026-08-01T00:00:00.000Z"
);
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(12));
it("stored cursors are sent as 'afterCursor'", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "300");
await alertSearchCursorsDb.setPartnerAfterCursor(USER, "7-300");
const loaded = await loadAlertSearchCursors(USER);
const urls: string[] = [];
await retrieveAlertSearch({
@@ -367,19 +221,51 @@ describe("alertSearch cursor persistence", () => {
fetch: async (url) => {
urls.push(url);
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "7-300", hasMore: false });
}
return jsonResponse(emptyEndorserBody());
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "300", hasMore: false });
},
},
});
const endorserUrl = urls.find((u) => u.includes("/api/v2/report/")) ?? "";
const partnerUrl = urls.find((u) => u.includes("/api/partner/")) ?? "";
assert.equal(endorserUrl.includes(ulid(12)), true);
assert.equal(partnerUrl.includes("afterId=0"), false);
assert.equal(
decodeURIComponent(partnerUrl).includes("afterDate=2026-08-01T00:00:00.000Z"),
true
);
const endorserUrl = new URL(urls.find((u) => u.includes("/api/v2/report/")) ?? "");
const partnerUrl = new URL(urls.find((u) => u.includes("/api/partner/")) ?? "");
assert.equal(endorserUrl.searchParams.get("afterCursor"), "300");
assert.equal(partnerUrl.searchParams.get("afterCursor"), "7-300");
});
it("replaces cursor tables from 0.2.3 and earlier, dropping their rows", async () => {
closeDatabase();
const old = new Database(path.join(dir, "notify.sqlite"));
for (const table of ["alert_search_cursors", "sms_alert_search_cursors"]) {
old.exec(`
CREATE TABLE ${table} (
user_id TEXT PRIMARY KEY NOT NULL,
endorser_after_id TEXT,
partner_after_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`);
}
old
.prepare("INSERT INTO alert_search_cursors VALUES (?, ?, ?, 't', 't')")
.run(USER, "01H00000000000000000000077", "2026-09-01T00:00:00.000Z");
old.close();
for (const table of ["alert_search_cursors", "sms_alert_search_cursors"]) {
const columns = (
getDatabase().prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
).map((c) => c.name);
assert.deepEqual(
columns,
["user_id", "endorser_after_cursor", "partner_after_cursor", "plan_handle_ids", "location", "created_at", "updated_at"],
table
);
}
assert.deepEqual(await loadAlertSearchCursors(USER), {});
// a second open keeps the replaced tables and their rows
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "5");
closeDatabase();
assert.deepEqual(await loadAlertSearchCursors(USER), { endorserAfterCursor: "5" });
});
});
+115 -371
View File
@@ -5,12 +5,8 @@ import path from "node:path";
import { afterEach, beforeEach, describe, it } from "node:test";
import { alertSearchCursorsDb } from "../../src/db/alertSearchCursorsSqlite.js";
import { closeDatabase } from "../../src/db/sqlite.js";
import {
partnerPageHasTiedBeforeDate,
type FetchLike,
} from "../../src/alertSearch/client.js";
import type { FetchLike } from "../../src/alertSearch/client.js";
import { runAlertSearchCycle } from "../../src/alertSearch/cycle.js";
import { ALERT_SEARCH_PAGE_SIZE } from "../../src/alertSearch/types.js";
const USER = "did:ethr:0xcycleuser";
const JWT = "delegated.jwt.token";
@@ -28,8 +24,14 @@ function jsonResponse(body: unknown, status = 200): Response {
});
}
function emptyEndorserBody(overrides?: Record<string, unknown>) {
function endorserBody(
nextAfterCursor: string | undefined,
overrides?: Record<string, unknown>,
hasMore = false
) {
return {
nextAfterCursor,
hasMore,
data: {
claims: [],
personalPlanContributions: [],
@@ -41,10 +43,18 @@ function emptyEndorserBody(overrides?: Record<string, unknown>) {
};
}
function emptyPartnerBody(overrides?: Record<string, unknown>) {
return { data: { profilesNearby: [], ...overrides } };
function partnerBody(
nextAfterCursor: string | undefined,
overrides?: Record<string, unknown>,
hasMore = false
) {
return { nextAfterCursor, hasMore, data: { profilesNearby: [], ...overrides } };
}
const ONE_PROFILE = {
profilesNearby: [{ issuerDid: "did:ethr:0x1", description: "p", rowId: 1 }],
};
function claimRows(from: number, count: number) {
return Array.from({ length: count }, (_, i) => ({
id: ulid(from + i),
@@ -53,80 +63,27 @@ function claimRows(from: number, count: number) {
}));
}
function planRows(from: number, count: number) {
return Array.from({ length: count }, (_, i) => ({
handleId: `plan-${from + i}`,
jwtId: ulid(from + i),
}));
}
function profileRows(
count: number,
updatedAt: (index: number) => string
) {
return Array.from({ length: count }, (_, i) => ({
issuerDid: `did:ethr:0x${i}`,
description: "p",
updatedAt: updatedAt(i),
rowId: i + 1,
}));
}
function captureFetch(
handler: (url: string) => Response | Promise<Response>
handler: (url: string, params: URLSearchParams) => Response | Promise<Response>
): { fetch: FetchLike; urls: string[] } {
const urls: string[] = [];
return {
urls,
fetch: async (url) => {
urls.push(url);
return handler(url);
return handler(url, new URL(url).searchParams);
},
};
}
const isPartner = (url: string) => url.includes("/api/partner/");
const cycleOpts = {
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
};
describe("partnerPageHasTiedBeforeDate", () => {
it("is false when the page is under the server limit", () => {
assert.equal(
partnerPageHasTiedBeforeDate({
profilesNearby: profileRows(10, () => "2026-01-01T00:00:00.000Z"),
}),
false
);
});
it("is true when a full page shares the oldest updatedAt", () => {
const tied = "2026-01-01T12:00:00.000Z";
assert.equal(
partnerPageHasTiedBeforeDate({
profilesNearby: profileRows(ALERT_SEARCH_PAGE_SIZE, () => tied),
}),
true
);
});
it("is true when two or more rows share the page minimum", () => {
const rows = profileRows(ALERT_SEARCH_PAGE_SIZE, (i) =>
i < 2 ? "2026-01-01T00:00:00.000Z" : `2026-02-01T00:${String(i).padStart(2, "0")}:00.000Z`
);
assert.equal(partnerPageHasTiedBeforeDate({ profilesNearby: rows }), true);
});
it("is false when the full page has a unique oldest timestamp", () => {
const rows = profileRows(
ALERT_SEARCH_PAGE_SIZE,
(i) => `2026-01-01T00:${String(i).padStart(2, "0")}:00.000Z`
);
assert.equal(partnerPageHasTiedBeforeDate({ profilesNearby: rows }), false);
});
});
describe("alertSearch cycle integration", () => {
let dir: string;
let previousDataDir: string | undefined;
@@ -148,72 +105,49 @@ describe("alertSearch cycle integration", () => {
await rm(dir, { recursive: true, force: true });
});
it("first run omits cursors and persists after a complete non-empty retrieve", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
profilesNearby: [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-03-01T00:00:00.000Z",
rowId: 1,
},
],
})
);
}
return jsonResponse(
emptyEndorserBody({
claims: claimRows(10, 1),
trackedPlanUpdates: planRows(15, 1),
})
);
it("first run sends no cursor, drops the rows, and stores the server's cursor", async () => {
const cap = captureFetch((url, params) => {
assert.equal(params.has("afterCursor"), false);
if (isPartner(url)) return jsonResponse(partnerBody("3-15", ONE_PROFILE));
return jsonResponse(endorserBody("15", { claims: claimRows(10, 1) }));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.loaded.endorserAfterId, undefined);
assert.equal(cycle.loaded.partnerAfterDate, undefined);
for (const url of cap.urls) {
assert.equal(url.includes("afterId="), false);
assert.equal(url.includes("afterDate="), false);
}
assert.equal(cycle.retrieved.endorser.outcome, "success");
assert.equal(cycle.retrieved.partner.outcome, "success");
assert.equal(cycle.advanced.endorserAdvanced, true);
assert.equal(cycle.advanced.partnerAdvanced, true);
assert.equal(cycle.advanced.endorserAfterId, ulid(15));
assert.equal(cycle.advanced.partnerAfterAt, "2026-03-01T00:00:00.000Z");
assert.deepEqual(cycle.loaded, {});
assert.equal(cycle.retrieved.endorser.outcome, "empty");
assert.equal(cycle.retrieved.endorser.seeded, true);
assert.equal(cycle.retrieved.partner.outcome, "empty");
assert.equal(cycle.retrieved.data.claims.length, 0);
assert.equal(cycle.retrieved.data.profilesNearby.length, 0);
assert.equal(cycle.advanced.endorserAfterCursor, "15");
assert.equal(cycle.advanced.partnerAfterCursor, "3-15");
});
it("loads Endorser afterId, paginates with MAX per-bucket minima, then advances to max ULID", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(1));
let endorserPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
it("first run with nothing found still stores the cursors", async () => {
const cap = captureFetch((url) =>
jsonResponse(isPartner(url) ? partnerBody("0-0") : endorserBody("0"))
);
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "empty");
assert.equal(cycle.advanced.endorserAfterCursor, "0");
assert.equal(cycle.advanced.partnerAfterCursor, "0-0");
});
it("pages while hasMore and stores the last page's cursor", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "100");
await alertSearchCursorsDb.setPartnerAfterCursor(USER, "1-100");
const cap = captureFetch((url, params) => {
if (isPartner(url)) return jsonResponse(partnerBody("1-100"));
if (params.get("afterCursor") === "100") {
return jsonResponse(endorserBody("150", { claims: claimRows(100, 50) }, true));
}
endorserPages += 1;
if (endorserPages === 1) {
assert.equal(url.includes(ulid(1)), true);
assert.equal(url.includes("beforeId="), false);
return jsonResponse(
emptyEndorserBody({
claims: claimRows(200, ALERT_SEARCH_PAGE_SIZE),
personalPlanContributions: claimRows(50, ALERT_SEARCH_PAGE_SIZE),
})
);
}
assert.equal(url.includes(`beforeId=${ulid(200)}`), true);
assert.equal(url.includes(`beforeId=${ulid(50)}`), false);
return jsonResponse(
emptyEndorserBody({
claims: claimRows(180, 3),
})
);
assert.equal(params.get("afterCursor"), "150");
return jsonResponse(endorserBody("160", { claims: claimRows(150, 3) }));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
@@ -221,218 +155,69 @@ describe("alertSearch cycle integration", () => {
});
assert.equal(cycle.retrieved.endorser.outcome, "success");
assert.equal(cycle.retrieved.endorser.pageCount, 2);
assert.equal(cycle.advanced.endorserAdvanced, true);
assert.equal(cycle.advanced.endorserAfterId, ulid(249));
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.retrieved.data.claims.length, 53);
assert.equal(cycle.advanced.endorserAfterCursor, "160");
assert.equal(cycle.advanced.partnerAfterCursor, "1-100");
});
it("does not advance Endorser on empty retrieve", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(9));
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse(emptyEndorserBody());
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "empty");
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(9));
});
it("does not advance Endorser when plansNearby hits 50", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(4));
let endorserPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
endorserPages += 1;
if (endorserPages === 1) {
return jsonResponse(
emptyEndorserBody({
plansNearby: planRows(300, ALERT_SEARCH_PAGE_SIZE),
})
);
}
return jsonResponse(
emptyEndorserBody({ plansNearby: planRows(250, 2) })
);
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "pagination");
assert.equal(cycle.retrieved.data.plansNearby.length, ALERT_SEARCH_PAGE_SIZE + 2);
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(4));
});
it("does not advance Endorser on HTTP auth failure", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(4));
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse({ error: "Unauthorized" }, 401);
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "auth");
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(4));
});
it("loads Partner afterDate, paginates with beforeDate, advances max updatedAt", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(
USER,
"2026-01-01T00:00:00.000Z"
it("a server without cursors is an error and stores nothing", async () => {
const cap = captureFetch((url) =>
jsonResponse(
isPartner(url)
? partnerBody(undefined, ONE_PROFILE)
: endorserBody(undefined, { claims: claimRows(10, 1) })
)
);
const page1 = profileRows(
ALERT_SEARCH_PAGE_SIZE,
(i) => `2026-02-01T00:${String(i).padStart(2, "0")}:00.000Z`
);
const minTime = [...page1.map((p) => p.updatedAt)].sort()[0];
let partnerPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/v2/report/")) {
return jsonResponse(emptyEndorserBody());
}
partnerPages += 1;
if (partnerPages === 1) {
assert.equal(
decodeURIComponent(url).includes("afterDate=2026-01-01T00:00:00.000Z"),
true
);
return jsonResponse(emptyPartnerBody({ profilesNearby: page1 }));
}
assert.equal(decodeURIComponent(url).includes(`beforeDate=${minTime}`), true);
return jsonResponse(
emptyPartnerBody({
profilesNearby: [
{
issuerDid: "did:ethr:0x99",
description: "p",
updatedAt: "2026-01-15T00:00:00.000Z",
rowId: 99,
},
],
})
);
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.partner.outcome, "success");
assert.equal(cycle.retrieved.partner.pageCount, 2);
assert.equal(cycle.advanced.partnerAdvanced, true);
assert.equal(cycle.advanced.partnerAfterAt, page1.map((p) => p.updatedAt).sort()[page1.length - 1]);
});
it("does not advance Partner on empty retrieve", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-01-01T00:00:00.000Z");
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse(emptyEndorserBody());
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.partner.outcome, "empty");
assert.equal(cycle.retrieved.endorser.outcome, "malformed");
assert.equal(cycle.retrieved.partner.outcome, "malformed");
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.advanced.partnerAfterAt, "2026-01-01T00:00:00.000Z");
assert.equal(cycle.advanced.endorserAfterCursor, null);
});
it("does not advance Partner when a full page has tied oldest updatedAt", async () => {
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-01-01T00:00:00.000Z");
const tied = "2026-04-01T00:00:00.000Z";
it("does not advance either source when one server timed out a list", async () => {
await alertSearchCursorsDb.setAfterCursors(USER, "100", "1-100");
const cap = captureFetch((url) => {
if (url.includes("/api/v2/report/")) {
return jsonResponse(emptyEndorserBody());
if (isPartner(url)) {
return jsonResponse({
...partnerBody("1-120", ONE_PROFILE),
userMessage: "Some data was not available in this search.",
});
}
return jsonResponse(
emptyPartnerBody({
profilesNearby: profileRows(ALERT_SEARCH_PAGE_SIZE, () => tied),
})
);
return jsonResponse(endorserBody("120"));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.partner.outcome, "pagination");
assert.match(cycle.retrieved.partner.message ?? "", /updatedAt/);
assert.equal(
cycle.retrieved.data.profilesNearby.length,
ALERT_SEARCH_PAGE_SIZE
);
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.advanced.partnerAfterAt, "2026-01-01T00:00:00.000Z");
assert.equal(cycle.advanced.partnerAfterCursor, "1-100");
assert.equal(cycle.advanced.endorserAfterCursor, "100");
});
it("A: both success → both advance", async () => {
it("Endorser success + Partner failure → neither advances", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
profilesNearby: [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-05-01T00:00:00.000Z",
},
],
})
);
}
return jsonResponse(emptyEndorserBody({ claims: claimRows(20, 1) }));
if (isPartner(url)) return jsonResponse({ error: "Unauthorized" }, 401);
return jsonResponse(endorserBody("21", { claims: claimRows(21, 1) }));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.advanced.endorserAdvanced, true);
assert.equal(cycle.advanced.partnerAdvanced, true);
assert.equal(cycle.advanced.endorserAfterId, ulid(20));
assert.equal(cycle.advanced.partnerAfterAt, "2026-05-01T00:00:00.000Z");
});
it("B: Endorser success + Partner failure → Endorser only", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ error: "Unauthorized" }, 401);
}
return jsonResponse(emptyEndorserBody({ claims: claimRows(21, 1) }));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "success");
assert.equal(cycle.retrieved.partner.outcome, "auth");
assert.equal(cycle.advanced.endorserAdvanced, true);
assert.equal(cycle.advanced.endorserAfterCursor, null);
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(21));
assert.equal(cycle.advanced.partnerAfterAt, null);
assert.equal(cycle.advanced.partnerAfterCursor, null);
});
it("C: Endorser failure + Partner success → Partner only", async () => {
it("Endorser failure + Partner success → neither advances", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
profilesNearby: [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-06-01T00:00:00.000Z",
},
],
})
);
}
if (isPartner(url)) return jsonResponse(partnerBody("6-30", ONE_PROFILE));
return jsonResponse({ error: "fail" }, 500);
});
const cycle = await runAlertSearchCycle(USER, {
@@ -440,16 +225,14 @@ describe("alertSearch cycle integration", () => {
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "http");
assert.equal(cycle.retrieved.partner.outcome, "success");
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.partnerAdvanced, true);
assert.equal(cycle.advanced.endorserAfterId, null);
assert.equal(cycle.advanced.partnerAfterAt, "2026-06-01T00:00:00.000Z");
assert.equal(cycle.advanced.endorserAfterCursor, null);
assert.equal(cycle.advanced.partnerAfterCursor, null);
});
it("D: both fail → neither advances", async () => {
await alertSearchCursorsDb.setEndorserAfterId(USER, ulid(3));
await alertSearchCursorsDb.setPartnerAfterAt(USER, "2026-01-01T00:00:00.000Z");
it("both fail → neither advances", async () => {
await alertSearchCursorsDb.setEndorserAfterCursor(USER, "3");
await alertSearchCursorsDb.setPartnerAfterCursor(USER, "1-3");
const cap = captureFetch(() => jsonResponse({ error: "down" }, 503));
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
@@ -457,74 +240,35 @@ describe("alertSearch cycle integration", () => {
});
assert.equal(cycle.advanced.endorserAdvanced, false);
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(3));
assert.equal(cycle.advanced.partnerAfterAt, "2026-01-01T00:00:00.000Z");
assert.equal(cycle.advanced.endorserAfterCursor, "3");
assert.equal(cycle.advanced.partnerAfterCursor, "1-3");
});
it("E: Partner incomplete + Endorser success → Endorser only", async () => {
const tied = "2026-07-01T00:00:00.000Z";
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
profilesNearby: profileRows(ALERT_SEARCH_PAGE_SIZE, () => tied),
})
);
}
return jsonResponse(emptyEndorserBody({ claims: claimRows(22, 1) }));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: cap.fetch },
});
assert.equal(cycle.retrieved.endorser.outcome, "success");
assert.equal(cycle.retrieved.partner.outcome, "pagination");
assert.equal(cycle.advanced.endorserAdvanced, true);
assert.equal(cycle.advanced.partnerAdvanced, false);
assert.equal(cycle.advanced.endorserAfterId, ulid(22));
});
it("persists cursors across close/reopen and sends them on the next retrieve", async () => {
const first = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
profilesNearby: [
{
issuerDid: "did:ethr:0x1",
description: "p",
updatedAt: "2026-08-01T00:00:00.000Z",
},
],
})
);
}
return jsonResponse(emptyEndorserBody({ claims: claimRows(30, 1) }));
});
await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: first.fetch },
});
it("persists cursors across close/reopen and sends them on the next run", async () => {
const first = captureFetch((url) =>
jsonResponse(isPartner(url) ? partnerBody("4-500", ONE_PROFILE) : endorserBody("500"))
);
await runAlertSearchCycle(USER, { ...cycleOpts, config: { fetch: first.fetch } });
closeDatabase();
const second = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse(emptyEndorserBody());
const next = captureFetch((url, params) => {
if (isPartner(url)) {
assert.equal(params.get("afterCursor"), "4-500");
return jsonResponse(partnerBody("4-510"));
}
assert.equal(params.get("afterCursor"), "500");
return jsonResponse(endorserBody("510"));
});
const cycle = await runAlertSearchCycle(USER, {
...cycleOpts,
config: { fetch: second.fetch },
config: { fetch: next.fetch },
});
assert.equal(cycle.loaded.endorserAfterId, ulid(30));
assert.equal(cycle.loaded.partnerAfterDate, "2026-08-01T00:00:00.000Z");
const endorserUrl =
second.urls.find((u) => u.includes("/api/v2/report/")) ?? "";
const partnerUrl = second.urls.find((u) => u.includes("/api/partner/")) ?? "";
assert.equal(endorserUrl.includes(ulid(30)), true);
assert.equal(
decodeURIComponent(partnerUrl).includes("afterDate=2026-08-01T00:00:00.000Z"),
true
);
assert.equal(partnerUrl.includes("afterId=0"), false);
assert.deepEqual(cycle.loaded, {
endorserAfterCursor: "500",
partnerAfterCursor: "4-500",
});
assert.equal(next.urls.length, 2);
assert.equal(cycle.advanced.endorserAfterCursor, "510");
assert.equal(cycle.advanced.partnerAfterCursor, "4-510");
});
});
+64 -16
View File
@@ -13,7 +13,6 @@ import { alertSearchCursorsDb } from "../../src/db/alertSearchCursorsSqlite.js";
import { closeDatabase } from "../../src/db/sqlite.js";
import type { FetchLike } from "../../src/alertSearch/client.js";
import { runDailyAlertSearch } from "../../src/alertSearch/daily.js";
import { ALERT_SEARCH_PAGE_SIZE } from "../../src/alertSearch/types.js";
const USER = "did:ethr:0xdailyuser";
const ENDORSER_BASE = "https://api.endorser.ch";
@@ -37,8 +36,12 @@ function jsonResponse(body: unknown, status = 200): Response {
});
}
const ENDORSER_CURSOR = "10";
const PARTNER_CURSOR = "2-10";
function emptyEndorserBody(overrides?: Record<string, unknown>) {
return {
nextAfterCursor: ENDORSER_CURSOR,
data: {
claims: [],
personalPlanContributions: [],
@@ -51,7 +54,7 @@ function emptyEndorserBody(overrides?: Record<string, unknown>) {
}
function emptyPartnerBody(overrides?: Record<string, unknown>) {
return { data: { profilesNearby: [], ...overrides } };
return { nextAfterCursor: PARTNER_CURSOR, data: { profilesNearby: [], ...overrides } };
}
function claimRows(from: number, count: number) {
@@ -151,6 +154,8 @@ describe("runDailyAlertSearch", () => {
dir = await mkdtemp(path.join(tmpdir(), "alert-search-daily-"));
process.env.NOTIFY_DATA_DIR = dir;
closeDatabase();
// a run with no stored cursor only seeds it, so start from one
await alertSearchCursorsDb.setAfterCursors(USER, "1", "1-1");
});
afterEach(async () => {
@@ -260,6 +265,7 @@ describe("runDailyAlertSearch", () => {
assert.ok(result.digest);
assert.equal(result.digest.hasUpdates, true);
assert.equal(result.jwtSequence, 1);
assert.deepEqual(result.startCursors, { endorser: "1", partner: "1-1" });
});
it("consumes today's JWT when both sources succeed", async () => {
@@ -323,9 +329,10 @@ describe("runDailyAlertSearch", () => {
assert.equal(result.digest.records.claims[0].id, ulid(10));
const unused = await alertAuthorizationDb.getUnusedForDay(USER, DAY_UTC);
assert.equal(unused?.jwt, JWT_DAY_UTC);
// the retry searches the same window, so the claim is not lost
const stored = await alertSearchCursorsDb.get(USER);
assert.equal(stored?.endorserAfterId, ulid(10));
assert.equal(stored?.partnerAfterAt, null);
assert.equal(stored?.endorserAfterCursor, "1");
assert.equal(stored?.partnerAfterCursor, "1-1");
});
it("does not consume when Partner succeeds and Endorser fails", async () => {
@@ -359,8 +366,8 @@ describe("runDailyAlertSearch", () => {
const unused = await alertAuthorizationDb.getUnusedForDay(USER, DAY_UTC);
assert.equal(unused?.status, ALERT_JWT_STATUS_UNUSED);
const stored = await alertSearchCursorsDb.get(USER);
assert.equal(stored?.endorserAfterId, null);
assert.equal(stored?.partnerAfterAt, "2026-03-01T00:00:00.000Z");
assert.equal(stored?.endorserAfterCursor, "1");
assert.equal(stored?.partnerAfterCursor, "1-1");
});
it("does not consume on Endorser pagination", async () => {
@@ -388,12 +395,10 @@ describe("runDailyAlertSearch", () => {
await seedBatch([jwtInput(1, DAY_UTC, JWT_DAY_UTC)]);
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
const tied = "2026-01-01T12:00:00.000Z";
return jsonResponse(
emptyPartnerBody({
profilesNearby: profileRows(ALERT_SEARCH_PAGE_SIZE, () => tied),
})
);
return jsonResponse({
...emptyPartnerBody({ profilesNearby: profileRows(3, () => "2026-01-01T12:00:00.000Z") }),
userMessage: "Some data was not available in this search.",
});
}
return jsonResponse(emptyEndorserBody());
});
@@ -507,7 +512,49 @@ describe("runDailyAlertSearch", () => {
assert.equal(await alertAuthorizationDb.countUnused(USER), 0);
});
it("does not alter Phase 4B cursor rules: empty does not advance; success does", async () => {
it("a first run seeds the cursors, counts nothing, and has no start cursors", async () => {
closeDatabase();
await rm(dir, { recursive: true, force: true });
dir = await mkdtemp(path.join(tmpdir(), "alert-search-daily-"));
process.env.NOTIFY_DATA_DIR = dir;
await seedBatch([jwtInput(1, DAY_UTC, JWT_DAY_UTC)]);
const result = await runDailyAlertSearch(
USER,
NOW_SPLIT,
cycleOpts(bothSuccessFetch().fetch)
);
assert.equal(result.completed, true);
assert.equal(result.consumed, true);
assert.equal(result.digest?.hasUpdates, false);
assert.equal(result.digest?.totalCount, 0);
assert.equal(result.startCursors, undefined);
const stored = await alertSearchCursorsDb.get(USER);
assert.equal(stored?.endorserAfterCursor, ENDORSER_CURSOR);
assert.equal(stored?.partnerAfterCursor, PARTNER_CURSOR);
});
it("sends the stored starred handle IDs and area", async () => {
await alertSearchCursorsDb.setSearchState(USER, {
planHandleIds: ["https://endorser.ch/entity/01HPLAN"],
location: { minLocLat: 40, maxLocLat: 41, minLocLon: -112, maxLocLon: -111 },
});
await seedBatch([jwtInput(1, DAY_UTC, JWT_DAY_UTC)]);
const cap = bothSuccessFetch();
await runDailyAlertSearch(USER, NOW_SPLIT, cycleOpts(cap.fetch));
const endorserUrl = new URL(
cap.urls.find((u) => u.includes("/api/v2/report/alertSearch"))!
);
assert.deepEqual(JSON.parse(endorserUrl.searchParams.get("planHandleIds")!), [
"https://endorser.ch/entity/01HPLAN",
]);
assert.equal(endorserUrl.searchParams.get("minLocLat"), "40");
const partnerUrl = new URL(
cap.urls.find((u) => u.includes("/api/partner/alertSearch"))!
);
assert.equal(partnerUrl.searchParams.get("maxLocLon"), "-111");
});
it("advances the cursors after an empty run and after a successful one", async () => {
await seedBatch([jwtInput(1, DAY_UTC, JWT_DAY_UTC)]);
await runDailyAlertSearch(
USER,
@@ -515,7 +562,8 @@ describe("runDailyAlertSearch", () => {
cycleOpts(bothEmptyFetch().fetch)
);
const afterEmpty = await alertSearchCursorsDb.get(USER);
assert.equal(afterEmpty, undefined);
assert.equal(afterEmpty?.endorserAfterCursor, ENDORSER_CURSOR);
assert.equal(afterEmpty?.partnerAfterCursor, PARTNER_CURSOR);
closeDatabase();
await seedBatch([jwtInput(1, DAY_UTC, JWT_DAY_UTC)]);
@@ -525,7 +573,7 @@ describe("runDailyAlertSearch", () => {
cycleOpts(bothSuccessFetch().fetch)
);
const afterSuccess = await alertSearchCursorsDb.get(USER);
assert.equal(afterSuccess?.endorserAfterId, ulid(10));
assert.equal(afterSuccess?.partnerAfterAt, "2026-03-01T00:00:00.000Z");
assert.equal(afterSuccess?.endorserAfterCursor, ENDORSER_CURSOR);
assert.equal(afterSuccess?.partnerAfterCursor, PARTNER_CURSOR);
});
});
+69 -6
View File
@@ -4,7 +4,16 @@ import {
ALERT_SEARCH_DIGEST_BUCKETS,
alertSearchDigestDebugSummary,
buildAlertSearchDigest,
totalAlertSearchDigestCount,
} from "../../src/alertSearch/digest.js";
import {
alertSearchNotificationBody,
buildAlertSearchNotificationContent,
} from "../../src/alertSearch/notify.js";
import {
ALERT_SEARCH_SMS_LINK,
alertSearchSmsBody,
} from "../../src/alertSearch/smsNotify.js";
import { emptyEndorserData, emptyPartnerData } from "../../src/alertSearch/client.js";
import type { AlertSearchSourceResult, RetrieveAlertSearchResult } from "../../src/alertSearch/retrieve.js";
import type {
@@ -86,10 +95,13 @@ function populatedEndorser(): EndorserAlertSearchData {
}
describe("buildAlertSearchDigest", () => {
it("preserves all six buckets and their records when populated", () => {
it("preserves every bucket and its records when populated", () => {
const endorserData = populatedEndorser();
const partnerData = {
...emptyPartnerData(),
profilesNearby: [profile(1), profile(2)],
profilesSimilar: [{ similarity: 0.91, profile: profile(3) }],
plansSimilar: [{ similarity: 0.8, plan: plan(50) }],
};
const digest = buildAlertSearchDigest(
retrieved(
@@ -105,7 +117,9 @@ describe("buildAlertSearchDigest", () => {
assert.equal(digest.counts.trackedPlanClaims, 2);
assert.equal(digest.counts.plansNearby, 1);
assert.equal(digest.counts.profilesNearby, 2);
assert.equal(digest.totalCount, 10);
assert.equal(digest.counts.profilesSimilar, 1);
assert.equal(digest.counts.plansSimilar, 1);
assert.equal(digest.totalCount, 12);
assert.deepEqual(digest.records.claims, endorserData.claims);
assert.deepEqual(
digest.records.personalPlanContributions,
@@ -115,6 +129,8 @@ describe("buildAlertSearchDigest", () => {
assert.deepEqual(digest.records.trackedPlanClaims, endorserData.trackedPlanClaims);
assert.deepEqual(digest.records.plansNearby, endorserData.plansNearby);
assert.deepEqual(digest.records.profilesNearby, partnerData.profilesNearby);
assert.deepEqual(digest.records.profilesSimilar, partnerData.profilesSimilar);
assert.deepEqual(digest.records.plansSimilar, partnerData.plansSimilar);
assert.equal(digest.records.claims[0], endorserData.claims[0]);
assert.notEqual(digest.records.claims, endorserData.claims);
});
@@ -146,7 +162,10 @@ describe("buildAlertSearchDigest", () => {
claims: [claim(1), claim(2), claim(3)],
trackedPlanUpdates: [plan(20)],
}),
partnerResult("success", { profilesNearby: [profile(1), profile(2)] })
partnerResult("success", {
...emptyPartnerData(),
profilesNearby: [profile(1), profile(2)],
})
)
);
assert.equal(digest.completed, true);
@@ -205,7 +224,10 @@ describe("buildAlertSearchDigest", () => {
reason: "network",
message: "fetch failed",
}),
partnerResult("success", { profilesNearby: [profile(1)] })
partnerResult("success", {
...emptyPartnerData(),
profilesNearby: [profile(1)],
})
)
);
assert.equal(digest.completed, false);
@@ -237,11 +259,14 @@ describe("buildAlertSearchDigest", () => {
}
});
it("sums counts across all six buckets", () => {
it("sums counts across every bucket", () => {
const digest = buildAlertSearchDigest(
retrieved(
endorserResult("success", populatedEndorser()),
partnerResult("success", { profilesNearby: [profile(1), profile(2)] })
partnerResult("success", {
...emptyPartnerData(),
profilesNearby: [profile(1), profile(2)],
})
)
);
const sum = ALERT_SEARCH_DIGEST_BUCKETS.reduce(
@@ -252,6 +277,44 @@ describe("buildAlertSearchDigest", () => {
assert.equal(digest.totalCount, 10);
});
it("announces one deduped total in the digest, the FCM heading, and the SMS sentence", () => {
const shared = { ...jwtClaim(4), claimType: "GiveAction" as const };
const digest = buildAlertSearchDigest(
retrieved(
endorserResult("success", {
...emptyEndorserData(),
personalPlanContributions: [shared],
trackedPlanClaims: [{ ...shared }],
}),
partnerResult("empty")
)
);
const raw = totalAlertSearchDigestCount(digest.counts);
assert.equal(digest.counts.personalPlanContributions, 1);
assert.equal(digest.counts.trackedPlanClaims, 1);
assert.equal(raw, 2);
assert.equal(digest.totalCount, 1);
assert.equal(digest.hasUpdates, true);
const content = buildAlertSearchNotificationContent(
digest.records,
"did:ethr:0xuser"
);
assert.equal(content.title, "You have 1 new update");
assert.equal(content.body, "- 1 new give to a project you own");
assert.equal(
alertSearchNotificationBody(digest.records, "did:ethr:0xuser"),
content.body
);
assert.equal(
Number(/You have (\d+) /.exec(content.title)?.[1]),
digest.totalCount
);
assert.equal(
alertSearchSmsBody(digest.totalCount),
`Gift Economies: you have 1 new update. ${ALERT_SEARCH_SMS_LINK} Reply STOP to end.`
);
});
it("preserves underlying records rather than reducing them to counts", () => {
const extra = { claimType: "AgreeAction", subject: "did:ethr:0xabc" };
const row = { ...claim(7), ...extra };
+140 -9
View File
@@ -9,12 +9,13 @@ import type { DailyAlertSearchResult } from "../../src/alertSearch/daily.js";
import type { AlertSearchDigest } from "../../src/alertSearch/digest.js";
import {
ALERT_SEARCH_FCM_TYPE,
ALERT_SEARCH_NOTIFICATION_TITLE,
alertSearchNotificationBody,
buildAlertSearchNotificationContent,
deliverAlertSearchNotification,
isAlertSearchNotificationEligible,
sameDayPushRerunAllowed,
} from "../../src/alertSearch/notify.js";
import { alertPushSendsDb } from "../../src/db/alertPushSendsSqlite.js";
const USER = "did:ethr:0xnotifyuser";
@@ -32,6 +33,8 @@ function emptyDigest(
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
},
records: {
claims: [],
@@ -40,6 +43,8 @@ function emptyDigest(
trackedPlanClaims: [],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
},
endorser: { outcome: "empty", completed: true },
partner: { outcome: "empty", completed: true },
@@ -59,18 +64,23 @@ function updatesDigest(totalCount: number): AlertSearchDigest {
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
},
records: {
claims: Array.from({ length: totalCount }, (_, i) => ({
id: `01H${String(i).padStart(23, "0")}`,
issuedAt: "2026-01-01T00:00:00Z",
issuer: USER,
issuer: "did:ethr:0xother",
toEntity: USER,
})),
personalPlanContributions: [],
trackedPlanUpdates: [],
trackedPlanClaims: [],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
},
endorser: { outcome: "success", completed: true },
partner: { outcome: "empty", completed: true },
@@ -144,14 +154,24 @@ describe("alertSearch notification gate", () => {
);
});
it("puts totalCount in the body without record contents", () => {
const content = buildAlertSearchNotificationContent(7);
assert.equal(content.title, ALERT_SEARCH_NOTIFICATION_TITLE);
assert.equal(content.body, "You have 7 new updates.");
it("keeps the title and FCM type and summarizes records without dumping them", () => {
const digest = updatesDigest(7);
const content = buildAlertSearchNotificationContent(digest.records, USER);
assert.equal(content.title, "You have 7 new updates");
assert.equal(content.body, "- 7 new claims to you");
assert.equal(content.type, ALERT_SEARCH_FCM_TYPE);
assert.equal(content.body.includes(USER), false);
assert.equal(content.body.includes("01H"), false);
assert.equal(alertSearchNotificationBody(1), "You have 1 new update.");
assert.equal(
alertSearchNotificationBody(digest.records, USER),
content.body
);
assert.equal(content.cursorParam, undefined);
assert.equal(
buildAlertSearchNotificationContent(digest.records, USER, "5.2-5")
.cursorParam,
"5.2-5"
);
});
});
@@ -197,7 +217,7 @@ describe("deliverAlertSearchNotification", () => {
send: async (token, content) => {
sent.push(token);
bodies.push(content.body);
assert.equal(content.title, "TimeSafari");
assert.equal(content.title, "You have 7 new updates");
assert.equal(content.type, "alert_search");
return "sent";
},
@@ -205,7 +225,24 @@ describe("deliverAlertSearchNotification", () => {
assert.equal(result.eligible, true);
assert.equal(result.sent, 2);
assert.deepEqual(sent.sort(), ["token-a", "token-b"]);
assert.equal(bodies[0], "You have 7 new updates.");
assert.equal(bodies[0], "- 7 new claims to you");
assert.equal(bodies[0].includes("You have"), false);
});
it("does not send a completed digest whose deduped total is zero", async () => {
let sends = 0;
const result = await deliverAlertSearchNotification(
daily({ digest: emptyDigest(), consumed: true }),
{
send: async () => {
sends += 1;
return "sent";
},
}
);
assert.equal(result.eligible, false);
assert.equal(result.sent, 0);
assert.equal(sends, 0);
});
it("does not send when ineligible", async () => {
@@ -232,3 +269,97 @@ describe("deliverAlertSearchNotification", () => {
assert.equal(result.failed, 1);
});
});
describe("push daily cap", () => {
let dir: string;
let previousDataDir: string | undefined;
let previousResend: string | undefined;
beforeEach(async () => {
previousDataDir = process.env.NOTIFY_DATA_DIR;
previousResend = process.env.PUSH_SAME_DAY_RESEND_DIDS;
delete process.env.PUSH_SAME_DAY_RESEND_DIDS;
dir = await mkdtemp(path.join(tmpdir(), "alert-search-push-cap-"));
process.env.NOTIFY_DATA_DIR = dir;
closeDatabase();
await fcmDb.upsert({
userId: USER,
deviceId: "d1",
fcmToken: "token-a",
platform: "android",
updatedAt: new Date(),
});
});
afterEach(async () => {
closeDatabase();
if (previousDataDir === undefined) delete process.env.NOTIFY_DATA_DIR;
else process.env.NOTIFY_DATA_DIR = previousDataDir;
if (previousResend === undefined) delete process.env.PUSH_SAME_DAY_RESEND_DIDS;
else process.env.PUSH_SAME_DAY_RESEND_DIDS = previousResend;
await rm(dir, { recursive: true, force: true });
});
const send = async (): Promise<"sent"> => "sent";
it("pushes once a UTC day, even for a batch uploaded after the first push", async () => {
const first = await deliverAlertSearchNotification(
daily({ authorizedAt: "2026-09-08T08:00:00.000Z" }),
{ send, now: new Date("2026-09-08T09:00:00.000Z") }
);
assert.equal(first.sent, 1);
const afterReset = await deliverAlertSearchNotification(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:05:00.000Z") }
);
assert.equal(afterReset.sent, 0);
assert.equal(afterReset.capped, true);
// the next UTC day is a new allowance
const nextDay = await deliverAlertSearchNotification(daily(), {
send,
now: new Date("2026-09-09T09:00:00.000Z"),
});
assert.equal(nextDay.sent, 1);
});
it("pushes a same-day-resend DID again for a later batch, once per batch", async () => {
process.env.PUSH_SAME_DAY_RESEND_DIDS = USER.toUpperCase();
await deliverAlertSearchNotification(
daily({ authorizedAt: "2026-09-08T08:00:00.000Z" }),
{ send, now: new Date("2026-09-08T09:00:00.000Z") }
);
const afterReset = await deliverAlertSearchNotification(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:05:00.000Z") }
);
assert.equal(afterReset.sent, 1);
const again = await deliverAlertSearchNotification(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:10:00.000Z") }
);
assert.equal(again.sent, 0);
});
it("does not count a push that reached no device", async () => {
await deliverAlertSearchNotification(daily(), {
send: async () => "failed",
now: new Date("2026-09-08T09:00:00.000Z"),
});
const retry = await deliverAlertSearchNotification(daily(), {
send,
now: new Date("2026-09-08T09:05:00.000Z"),
});
assert.equal(retry.sent, 1);
});
it("allows a rerun only before today's push, unless the DID may resend", async () => {
const now = new Date("2026-09-08T10:00:00.000Z");
await alertPushSendsDb.append({ userId: USER, sentAt: "2026-09-07T23:30:00.000Z" });
assert.equal(await sameDayPushRerunAllowed(USER, now), true);
await alertPushSendsDb.append({ userId: USER, sentAt: "2026-09-08T09:00:00.000Z" });
assert.equal(await sameDayPushRerunAllowed(USER, now), false);
process.env.PUSH_SAME_DAY_RESEND_DIDS = USER;
assert.equal(await sameDayPushRerunAllowed(USER, now), true);
});
});
+25 -27
View File
@@ -3,7 +3,6 @@ import { describe, it } from "node:test";
import {
alertSearchUrl,
buildAlertSearchQuery,
isAlertSearchCursorUlid,
} from "../../src/alertSearch/params.js";
import {
ENDORSER_ALERT_SEARCH_PATH,
@@ -18,10 +17,9 @@ const LOCATION = {
};
describe("alertSearch request construction", () => {
it("omits afterId on first run (does not send 0 or empty)", () => {
it("omits afterCursor on first run", () => {
const query = buildAlertSearchQuery({});
assert.equal(query.has("afterId"), false);
assert.equal(query.has("beforeId"), false);
assert.equal(query.toString(), "");
const endorser = alertSearchUrl(
"https://api.endorser.ch",
ENDORSER_ALERT_SEARCH_PATH,
@@ -39,38 +37,22 @@ describe("alertSearch request construction", () => {
);
});
it("rejects non-ULID afterId including 0", () => {
assert.equal(isAlertSearchCursorUlid("0"), false);
assert.equal(isAlertSearchCursorUlid(""), false);
const query = buildAlertSearchQuery({ afterId: "0" });
assert.equal(query.has("afterId"), false);
});
it("includes a subsequent afterId ULID", () => {
const afterId = "01H00000000000000000000001";
const query = buildAlertSearchQuery({ afterId });
assert.equal(query.get("afterId"), afterId);
});
it("builds independent Endorser vs Partner URLs and cursors", () => {
const endorserAfter = "01H0000000000000000000000A";
const partnerAfter = "01H0000000000000000000000B";
const endorser = alertSearchUrl(
"https://api.endorser.ch",
ENDORSER_ALERT_SEARCH_PATH,
buildAlertSearchQuery({ afterId: endorserAfter })
buildAlertSearchQuery({ afterCursor: "48213" })
);
const partner = alertSearchUrl(
"https://partner-api.endorser.ch",
PARTNER_ALERT_SEARCH_PATH,
buildAlertSearchQuery({ afterId: partnerAfter })
buildAlertSearchQuery({ afterCursor: "912-48213" })
);
assert.equal(endorser, "https://api.endorser.ch/api/v2/report/alertSearch?afterCursor=48213");
assert.equal(
partner,
"https://partner-api.endorser.ch/api/partner/alertSearch?afterCursor=912-48213"
);
assert.match(endorser, /afterId=01H0000000000000000000000A/);
assert.match(partner, /afterId=01H0000000000000000000000B/);
assert.equal(endorser.includes("0000000B"), false);
assert.equal(partner.includes("0000000A"), false);
assert.equal(endorser.includes("/api/v2/report/alertSearch"), true);
assert.equal(partner.includes("/api/partner/alertSearch"), true);
});
it("flattens location bbox for GET query params", () => {
@@ -88,4 +70,20 @@ describe("alertSearch request construction", () => {
});
assert.equal(query.get("planHandleIds"), JSON.stringify(["plan-1", "plan-2"]));
});
it("sends the cursor beside location and plans", () => {
const query = buildAlertSearchQuery({
afterCursor: "912-48213",
location: LOCATION,
planHandleIds: ["plan-1"],
});
assert.equal(query.get("afterCursor"), "912-48213");
assert.equal(query.get("minLocLat"), "40.7");
assert.equal(query.get("planHandleIds"), JSON.stringify(["plan-1"]));
});
it("ignores an empty 'afterCursor'", () => {
const query = buildAlertSearchQuery({ afterCursor: "" });
assert.equal(query.has("afterCursor"), false);
});
});
+385 -254
View File
@@ -3,17 +3,14 @@ import { describe, it } from "node:test";
import {
fetchEndorserAlertSearchPage,
fetchPartnerAlertSearchPage,
nextEndorserBeforeId,
type FetchLike,
} from "../../src/alertSearch/client.js";
import { retrieveAlertSearch } from "../../src/alertSearch/retrieve.js";
import { ALERT_SEARCH_PAGE_SIZE, type EndorserAlertSearchData } from "../../src/alertSearch/types.js";
import { ALERT_SEARCH_PAGE_SIZE } from "../../src/alertSearch/types.js";
const JWT = "delegated.jwt.token";
const ENDORSER_BASE = "https://api.endorser.ch";
const PARTNER_BASE = "https://partner-api.endorser.ch";
const AFTER_E = "01H0000000000000000000000A";
const AFTER_P = "01H0000000000000000000000B";
function emptyEndorserBody(overrides?: Record<string, unknown>) {
return {
@@ -70,13 +67,6 @@ function claimRows(from: number, count: number) {
}));
}
function planRows(from: number, count: number) {
return Array.from({ length: count }, (_, i) => ({
handleId: `plan-${from + i}`,
jwtId: ulid(from + i),
}));
}
describe("alertSearch HTTP pages", () => {
it("sends the delegated JWT as Bearer on Endorser GET", async () => {
const cap = captureFetch(() => jsonResponse(emptyEndorserBody()));
@@ -116,6 +106,37 @@ describe("alertSearch HTTP pages", () => {
if (!result.ok) assert.equal(result.reason, "auth");
});
it("classifies a 400 for a malformed cursor as http, with the server's error", async () => {
const cap = captureFetch(() =>
jsonResponse({ error: "Parameter 'afterCursor' must be the 'nextAfterCursor' or 'nextBeforeCursor' value of an earlier response." }, 400)
);
const result = await fetchEndorserAlertSearchPage({
baseUrl: ENDORSER_BASE,
jwt: JWT,
query: { afterCursor: "not-a-cursor" },
config: { fetch: cap.fetch },
});
assert.equal(result.ok, false);
if (!result.ok) {
assert.equal(result.reason, "http");
assert.match(result.message ?? "", /HTTP 400: Parameter 'afterCursor'/);
}
});
it("classifies a 403 and a 400 without an error as auth", async () => {
for (const response of [() => jsonResponse({}, 403), () => jsonResponse({}, 400)]) {
const cap = captureFetch(response);
const result = await fetchEndorserAlertSearchPage({
baseUrl: ENDORSER_BASE,
jwt: JWT,
query: {},
config: { fetch: cap.fetch },
});
assert.equal(result.ok, false);
if (!result.ok) assert.equal(result.reason, "auth");
}
});
it("classifies network failure", async () => {
const fetchImpl: FetchLike = async () => {
throw new TypeError("fetch failed");
@@ -159,40 +180,17 @@ describe("alertSearch HTTP pages", () => {
});
});
describe("nextEndorserBeforeId", () => {
it("uses MAX of per-bucket minima when multiple buckets hit 50", () => {
const data: EndorserAlertSearchData = {
claims: claimRows(200, ALERT_SEARCH_PAGE_SIZE),
personalPlanContributions: claimRows(50, ALERT_SEARCH_PAGE_SIZE),
trackedPlanUpdates: [],
trackedPlanClaims: [],
plansNearby: [],
};
const claimsMin = ulid(200);
const contributionsMin = ulid(50);
assert.equal(nextEndorserBeforeId(data), claimsMin);
assert.notEqual(nextEndorserBeforeId(data), contributionsMin);
});
it("uses the single truncated bucket min", () => {
const data: EndorserAlertSearchData = {
claims: claimRows(100, ALERT_SEARCH_PAGE_SIZE),
personalPlanContributions: [],
trackedPlanUpdates: [],
trackedPlanClaims: [],
plansNearby: [],
};
assert.equal(nextEndorserBeforeId(data), ulid(100));
});
});
describe("retrieveAlertSearch", () => {
it("first run omits afterId on both hosts", async () => {
it("first run omits 'afterCursor' and makes one request per host, even with hasMore", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "3-40", hasMore: true });
}
return jsonResponse(emptyEndorserBody());
return jsonResponse({
...emptyEndorserBody({ claims: claimRows(200, ALERT_SEARCH_PAGE_SIZE) }),
nextAfterCursor: "40",
hasMore: true,
});
});
const result = await retrieveAlertSearch({
jwt: JWT,
@@ -200,234 +198,44 @@ describe("retrieveAlertSearch", () => {
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "empty");
assert.equal(result.partner.outcome, "empty");
assert.equal(result.empty, true);
assert.equal(cap.urls.length, 2);
for (const url of cap.urls) {
assert.equal(url.includes("afterId="), false);
assert.equal(new URL(url).search, "");
}
// a first run only seeds the cursor: those rows predate notifications
assert.equal(result.endorser.outcome, "empty");
assert.equal(result.endorser.seeded, true);
assert.equal(result.data.claims.length, 0);
assert.equal(result.endorser.nextAfterCursor, "40");
assert.equal(result.partner.outcome, "empty");
assert.equal(result.partner.nextAfterCursor, "3-40");
});
it("passes independent afterId cursors", async () => {
it("passes independent cursors", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "5-20" });
}
return jsonResponse(emptyEndorserBody());
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "20" });
});
await retrieveAlertSearch({
jwt: JWT,
endorserAfterId: AFTER_E,
partnerAfterId: AFTER_P,
endorserAfterCursor: "20",
partnerAfterCursor: "5-20",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
const endorserUrl = cap.urls.find((u) => u.includes("/api/v2/report/")) ?? "";
const partnerUrl = cap.urls.find((u) => u.includes("/api/partner/")) ?? "";
assert.equal(endorserUrl.includes(AFTER_E), true);
assert.equal(endorserUrl.includes(AFTER_P), false);
assert.equal(partnerUrl.includes(AFTER_P), true);
assert.equal(partnerUrl.includes(AFTER_E), false);
});
it("paginates Endorser with beforeId from the limited bucket", async () => {
const page1Ids = Array.from({ length: ALERT_SEARCH_PAGE_SIZE }, (_, i) =>
ulid(100 + i)
);
const minId = [...page1Ids].sort()[0];
let endorserPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
}
endorserPages += 1;
if (endorserPages === 1) {
assert.equal(url.includes("beforeId="), false);
return jsonResponse(
emptyEndorserBody({
claims: page1Ids.map((id) => ({
id,
issuedAt: "2026-01-01T00:00:00Z",
issuer: "did:ethr:0x1",
})),
})
);
}
assert.equal(url.includes(`beforeId=${minId}`), true);
return jsonResponse(
emptyEndorserBody({
claims: [
{
id: ulid(1),
issuedAt: "2026-01-01T00:00:00Z",
issuer: "did:ethr:0x1",
},
],
})
);
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "success");
assert.equal(result.endorser.pageCount, 2);
assert.equal(result.data.claims.length, ALERT_SEARCH_PAGE_SIZE + 1);
});
it("uses MAX of per-bucket minima as shared beforeId when two buckets hit 50", async () => {
const claimsMin = ulid(200);
const contributionsMin = ulid(50);
let endorserPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
}
endorserPages += 1;
if (endorserPages === 1) {
return jsonResponse(
emptyEndorserBody({
claims: claimRows(200, ALERT_SEARCH_PAGE_SIZE),
personalPlanContributions: claimRows(50, ALERT_SEARCH_PAGE_SIZE),
})
);
}
assert.equal(url.includes(`beforeId=${claimsMin}`), true);
assert.equal(url.includes(`beforeId=${contributionsMin}`), false);
return jsonResponse(
emptyEndorserBody({
claims: claimRows(180, 5),
})
);
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "success");
assert.equal(result.endorser.pageCount, 2);
assert.equal(result.data.claims.length, ALERT_SEARCH_PAGE_SIZE + 5);
assert.equal(result.data.personalPlanContributions.length, ALERT_SEARCH_PAGE_SIZE);
});
it("classifies plansNearby hitting 50 as incomplete pagination and keeps records", async () => {
let endorserPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(emptyPartnerBody());
}
endorserPages += 1;
if (endorserPages === 1) {
return jsonResponse(
emptyEndorserBody({
claims: claimRows(1, 3),
plansNearby: planRows(300, ALERT_SEARCH_PAGE_SIZE),
})
);
}
return jsonResponse(
emptyEndorserBody({
plansNearby: planRows(250, 4),
})
);
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "pagination");
assert.equal(result.endorser.reason, "pagination");
assert.match(result.endorser.message ?? "", /plansNearby/);
assert.equal(result.data.plansNearby.length, ALERT_SEARCH_PAGE_SIZE + 4);
assert.equal(result.data.claims.length, 3);
});
it("paginates Partner with beforeDate independently", async () => {
const times = Array.from(
{ length: ALERT_SEARCH_PAGE_SIZE },
(_, i) => `2026-01-01T00:${String(i).padStart(2, "0")}:00.000Z`
);
const minTime = [...times].sort()[0];
let partnerPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/v2/report/")) {
return jsonResponse(emptyEndorserBody());
}
partnerPages += 1;
if (partnerPages === 1) {
assert.equal(url.includes("beforeDate="), false);
return jsonResponse(
emptyPartnerBody({
profilesNearby: times.map((updatedAt, i) => ({
issuerDid: `did:ethr:0x${i}`,
description: "p",
updatedAt,
rowId: i,
})),
})
);
}
assert.equal(decodeURIComponent(url).includes(`beforeDate=${minTime}`), true);
return jsonResponse(emptyPartnerBody());
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.partner.pageCount, 2);
assert.equal(result.partner.outcome, "success");
});
it("Partner full page with tied oldest updatedAt is incomplete, not a second exclusive page", async () => {
const tied = "2026-01-01T12:00:00.000Z";
let partnerPages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/v2/report/")) {
return jsonResponse(emptyEndorserBody());
}
partnerPages += 1;
assert.equal(url.includes("rowId"), false);
assert.equal(url.includes("beforeRowId"), false);
return jsonResponse(
emptyPartnerBody({
profilesNearby: Array.from(
{ length: ALERT_SEARCH_PAGE_SIZE },
(_, i) => ({
issuerDid: `did:ethr:0x${i}`,
description: "p",
updatedAt: tied,
rowId: i,
})
),
})
);
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(partnerPages, 1);
assert.equal(result.partner.pageCount, 1);
assert.equal(result.partner.outcome, "pagination");
assert.equal(result.data.profilesNearby.length, ALERT_SEARCH_PAGE_SIZE);
assert.equal(new URL(endorserUrl).searchParams.get("afterCursor"), "20");
assert.equal(new URL(partnerUrl).searchParams.get("afterCursor"), "5-20");
});
it("returns success with empty buckets", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse(emptyEndorserBody());
if (url.includes("/api/partner/")) return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "0-0" });
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "0" });
});
const result = await retrieveAlertSearch({
jwt: JWT,
@@ -442,18 +250,24 @@ describe("retrieveAlertSearch", () => {
assert.ok("profilesNearby" in result.data);
});
it("preserves all six result categories", async () => {
it("preserves all eight result categories", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse(
emptyPartnerBody({
return jsonResponse({
...emptyPartnerBody({
profilesNearby: [
{ issuerDid: "did:ethr:0x2", description: "near", extra: true },
],
})
);
profilesSimilar: [
{ similarity: 0.9, profile: { rowId: 7, issuerDid: "x", description: "d" } },
],
plansSimilar: [{ similarity: 0.8, plan: { handleId: "q", jwtId: ulid(6) } }],
}),
nextAfterCursor: "1-5",
});
}
return jsonResponse({
nextAfterCursor: "5",
data: {
claims: [{ id: ulid(1), issuedAt: "t", issuer: "did:ethr:0x1", extra: 1 }],
personalPlanContributions: [
@@ -469,12 +283,16 @@ describe("retrieveAlertSearch", () => {
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "1",
partnerAfterCursor: "1-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "success");
assert.equal(result.partner.outcome, "success");
assert.equal(result.data.profilesSimilar.length, 1);
assert.equal(result.data.plansSimilar[0]?.plan.handleId, "q");
assert.equal(result.data.claims[0]?.extra, 1);
assert.equal(result.data.profilesNearby[0]?.extra, true);
assert.equal(result.data.personalPlanContributions.length, 1);
@@ -483,10 +301,74 @@ describe("retrieveAlertSearch", () => {
assert.equal(result.data.plansNearby.length, 1);
});
it("keeps partner semantic matches and treats a missing list as empty", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({
...emptyPartnerBody({
profilesSimilar: [
{
similarity: 0.77,
profile: { issuerDid: "did:ethr:0xsim", description: "alike", rowId: 4 },
},
],
plansSimilar: [
{
similarity: 0.66,
plan: { handleId: "plan-sim", jwtId: ulid(8), name: "Alike" },
},
],
}),
nextAfterCursor: "4-8",
});
}
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "8" });
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "1",
partnerAfterCursor: "1-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.partner.outcome, "success");
assert.equal(result.empty, false);
assert.equal(result.data.profilesSimilar.length, 1);
assert.equal(result.data.profilesSimilar[0]?.similarity, 0.77);
assert.equal(result.data.profilesSimilar[0]?.profile.description, "alike");
assert.equal(result.data.plansSimilar.length, 1);
assert.equal(result.data.plansSimilar[0]?.plan.handleId, "plan-sim");
assert.equal(result.endorser.nextAfterCursor, "8");
assert.equal(result.partner.nextAfterCursor, "4-8");
});
it("rejects a partner page whose similar list is not the contract shape", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({
...emptyPartnerBody({ profilesSimilar: [{ similarity: 1 }] }),
nextAfterCursor: "1-1",
});
}
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "1" });
});
const result = await retrieveAlertSearch({
jwt: JWT,
partnerAfterCursor: "0-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.partner.outcome, "malformed");
assert.equal(result.partner.nextAfterCursor, undefined);
});
it("classifies truncation userMessage as incomplete pagination", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
if (url.includes("/api/partner/")) return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "0-0" });
return jsonResponse({
nextAfterCursor: "0",
data: {
claims: [],
personalPlanContributions: [],
@@ -508,3 +390,252 @@ describe("retrieveAlertSearch", () => {
assert.equal(result.endorser.reason, "pagination");
});
});
describe("retrieveAlertSearch cursor path", () => {
function param(url: string, key: string): string | null {
return new URL(url).searchParams.get(key);
}
it("parses nextAfterCursor and hasMore from both hosts", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "9-77", hasMore: false });
}
return jsonResponse({
...emptyEndorserBody(),
nextAfterCursor: "77",
nextBeforeCursor: "60",
hasMore: true,
});
});
const endorser = await fetchEndorserAlertSearchPage({
baseUrl: ENDORSER_BASE,
jwt: JWT,
query: {},
config: { fetch: cap.fetch },
});
const partner = await fetchPartnerAlertSearchPage({
baseUrl: PARTNER_BASE,
jwt: JWT,
query: {},
config: { fetch: cap.fetch },
});
assert.ok(endorser.ok && partner.ok);
if (endorser.ok && partner.ok) {
assert.equal(endorser.body.nextAfterCursor, "77");
assert.equal(endorser.body.nextBeforeCursor, "60");
assert.equal(endorser.body.hasMore, true);
assert.equal(partner.body.nextAfterCursor, "9-77");
assert.equal(partner.body.hasMore, false);
}
});
it("pages with after = nextAfterCursor while hasMore and returns the last nextAfterCursor", async () => {
const endorserAfters: (string | null)[] = [];
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
assert.equal(param(url, "afterCursor"), "5-100");
return jsonResponse({
...emptyPartnerBody({
profilesNearby: [{ issuerDid: "did:ethr:0x9", description: "p", changeSeq: 6 }],
}),
nextAfterCursor: "6-120",
hasMore: false,
});
}
endorserAfters.push(param(url, "afterCursor"));
if (endorserAfters.length === 1) {
return jsonResponse({
...emptyEndorserBody({ claims: claimRows(1, ALERT_SEARCH_PAGE_SIZE) }),
nextAfterCursor: "150",
hasMore: true,
});
}
return jsonResponse({
...emptyEndorserBody({ claims: claimRows(100, 3) }),
nextAfterCursor: "160",
hasMore: false,
});
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "100",
partnerAfterCursor: "5-100",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.deepEqual(endorserAfters, ["100", "150"]);
assert.equal(result.endorser.outcome, "success");
assert.equal(result.endorser.pageCount, 2);
assert.equal(result.endorser.nextAfterCursor, "160");
assert.equal(result.data.claims.length, ALERT_SEARCH_PAGE_SIZE + 3);
assert.equal(result.partner.outcome, "success");
assert.equal(result.partner.nextAfterCursor, "6-120");
});
it("an empty page still returns its nextAfterCursor", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "1-2", hasMore: false });
}
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "2", hasMore: false });
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "1",
partnerAfterCursor: "1-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "empty");
assert.equal(result.endorser.nextAfterCursor, "2");
assert.equal(result.partner.outcome, "empty");
assert.equal(result.partner.nextAfterCursor, "1-2");
});
it("stops at maxPages with success and the last nextAfterCursor reached", async () => {
let pages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "1-1", hasMore: false });
}
pages += 1;
return jsonResponse({
...emptyEndorserBody({ claims: claimRows(pages * 100, 1) }),
nextAfterCursor: String(pages * 10),
hasMore: true,
});
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "0",
partnerAfterCursor: "1-1",
maxPages: 3,
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(pages, 3);
assert.equal(result.endorser.outcome, "success");
assert.equal(result.endorser.nextAfterCursor, "30");
assert.match(result.endorser.message ?? "", /3 pages/);
});
it("a server that returns no nextAfterCursor is malformed, with no cursor", async () => {
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) return jsonResponse(emptyPartnerBody());
return jsonResponse(emptyEndorserBody({ claims: claimRows(1, 2) }));
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "10",
partnerAfterCursor: "1-10",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "malformed");
assert.equal(result.endorser.nextAfterCursor, undefined);
assert.equal(result.partner.outcome, "malformed");
});
it("hasMore without a moving nextAfterCursor is incomplete pagination, not a loop", async () => {
let pages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "1-1", hasMore: false });
}
pages += 1;
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "10", hasMore: true });
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "10",
partnerAfterCursor: "1-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(pages, 1);
assert.equal(result.endorser.outcome, "pagination");
assert.equal(result.endorser.nextAfterCursor, undefined);
});
it("a failed page returns no cursor", async () => {
let pages = 0;
const cap = captureFetch((url) => {
if (url.includes("/api/partner/")) {
return jsonResponse({ ...emptyPartnerBody(), nextAfterCursor: "1-1", hasMore: false });
}
pages += 1;
if (pages === 1) {
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "20", hasMore: true });
}
return jsonResponse({ error: "boom" }, 500);
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "10",
partnerAfterCursor: "1-1",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(result.endorser.outcome, "http");
assert.equal(result.endorser.nextAfterCursor, undefined);
});
it("dedupes plansSimilar repeated on each forward page and keeps distinct profile matches", async () => {
const plan = { handleId: "plan-sim", jwtId: ulid(9), name: "Alike" };
let partnerPages = 0;
const cap = captureFetch((url) => {
if (!url.includes("/api/partner/")) {
return jsonResponse({ ...emptyEndorserBody(), nextAfterCursor: "9", hasMore: false });
}
partnerPages += 1;
const after = param(url, "afterCursor");
if (partnerPages === 1) {
assert.equal(after, "1-10");
return jsonResponse({
...emptyPartnerBody({
profilesNearby: [{ issuerDid: "did:ethr:0x1", description: "a", rowId: 1 }],
profilesSimilar: [
{ similarity: 0.9, profile: { issuerDid: "did:ethr:0xs", description: "s", rowId: 2 } },
],
plansSimilar: [{ similarity: 0.9, plan }],
}),
nextAfterCursor: "2-20",
hasMore: true,
});
}
assert.equal(after, "2-20");
return jsonResponse({
...emptyPartnerBody({
profilesSimilar: [
{ similarity: 0.9, profile: { issuerDid: "did:ethr:0xs", description: "s", rowId: 2 } },
{ similarity: 0.5, profile: { issuerDid: "did:ethr:0xt", description: "t", rowId: 3 } },
],
plansSimilar: [{ similarity: 0.9, plan: { ...plan } }],
}),
nextAfterCursor: "3-20",
hasMore: false,
});
});
const result = await retrieveAlertSearch({
jwt: JWT,
endorserAfterCursor: "8",
partnerAfterCursor: "1-10",
endorserBaseUrl: ENDORSER_BASE,
partnerBaseUrl: PARTNER_BASE,
config: { fetch: cap.fetch },
});
assert.equal(partnerPages, 2);
assert.equal(result.partner.outcome, "success");
assert.equal(result.partner.nextAfterCursor, "3-20");
assert.equal(result.data.plansSimilar.length, 1);
assert.equal(result.data.profilesSimilar.length, 2);
assert.equal(result.data.profilesNearby.length, 1);
});
});
+14 -10
View File
@@ -46,6 +46,8 @@ function eligibleDaily(userId: string): DailyAlertSearchResult {
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
},
records: {
claims: [],
@@ -54,6 +56,8 @@ function eligibleDaily(userId: string): DailyAlertSearchResult {
trackedPlanClaims: [],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
},
endorser: { outcome: "success", completed: true },
partner: { outcome: "empty", completed: true },
@@ -394,7 +398,7 @@ describe("alertSearch scheduler pass", () => {
});
describe("alertSearch scheduler isolation from FCM", () => {
it("does not call sendPushToDevice or WAKEUP_PING", () => {
it("does not reference the retired WAKEUP_PING producer", () => {
const alertSched = readFileSync(
path.join(process.cwd(), "src/alertSearch/scheduler.ts"),
"utf8"
@@ -403,23 +407,23 @@ describe("alertSearch scheduler isolation from FCM", () => {
assert.equal(alertSched.includes("WAKEUP_PING"), false);
});
it("leaves the FCM scheduler on sendPushToDevice only", () => {
const fcmSched = readFileSync(
path.join(process.cwd(), "src/scheduler.ts"),
it("does not start the legacy FCM WAKEUP scheduler from the entrypoint", () => {
const index = readFileSync(
path.join(process.cwd(), "src/index.ts"),
"utf8"
);
assert.equal(fcmSched.includes("sendPushToDevice"), true);
assert.equal(fcmSched.includes("runDailyAlertSearch"), false);
assert.equal(fcmSched.includes("runAlertSearchSchedulerPass"), false);
assert.equal(fcmSched.includes("startAlertSearchScheduler"), false);
assert.equal(index.includes("startScheduler"), false);
assert.equal(index.includes("./scheduler.js"), false);
assert.equal(index.includes("startAlertSearchScheduler"), true);
});
it("leaves WAKEUP_PING last_notified_at logic on sendPushToDevice", () => {
it("keeps AlertSearch FCM delivery without WAKEUP_PING", () => {
const push = readFileSync(
path.join(process.cwd(), "src/services/pushService.ts"),
"utf8"
);
assert.equal(push.includes('type: "WAKEUP_PING"'), true);
assert.equal(push.includes("sendAlertSearchPushToDevice"), true);
assert.equal(push.includes("sendPushToDevice"), false);
assert.equal(push.includes("WAKEUP_PING"), false);
});
});
+21 -19
View File
@@ -34,16 +34,13 @@ afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
function ulid(n: number): string {
return `01H${String(n).padStart(23, "0")}`;
}
function retrieved(endorserUlid: string, partnerAt: string): RetrieveAlertSearchResult {
function retrieved(endorserCursor: string, partnerCursor: string): RetrieveAlertSearchResult {
const endorser: AlertSearchSourceResult<EndorserAlertSearchData> = {
outcome: "success",
pageCount: 1,
nextAfterCursor: endorserCursor,
data: {
claims: [{ id: endorserUlid, issuedAt: "2026-09-05T00:00:00Z", issuer: USER }],
claims: [{ id: "01H00000000000000000000005", issuedAt: "2026-09-05T00:00:00Z", issuer: USER }],
personalPlanContributions: [],
trackedPlanUpdates: [],
trackedPlanClaims: [],
@@ -53,7 +50,12 @@ function retrieved(endorserUlid: string, partnerAt: string): RetrieveAlertSearch
const partner: AlertSearchSourceResult<PartnerAlertSearchData> = {
outcome: "success",
pageCount: 1,
data: { profilesNearby: [{ rowId: "r1", updatedAt: partnerAt } as never] },
nextAfterCursor: partnerCursor,
data: {
profilesNearby: [{ rowId: "r1" } as never],
profilesSimilar: [],
plansSimilar: [],
},
};
return {
data: { ...endorser.data, ...partner.data },
@@ -67,13 +69,13 @@ describe("per-channel alertSearch cursors", () => {
it("advances only the SMS table for an SMS run", async () => {
await advanceAlertSearchCursors(
USER,
retrieved(ulid(5), "2026-09-05T00:00:00Z"),
retrieved("5", "15-5"),
"sms"
);
assert.equal(
(await smsAlertSearchCursorsDb.get(USER))?.endorserAfterId,
ulid(5)
(await smsAlertSearchCursorsDb.get(USER))?.endorserAfterCursor,
"5"
);
assert.equal(await alertSearchCursorsDb.get(USER), undefined);
});
@@ -81,12 +83,12 @@ describe("per-channel alertSearch cursors", () => {
it("defaults to the FCM table when no channel is named", async () => {
await advanceAlertSearchCursors(
USER,
retrieved(ulid(9), "2026-09-06T00:00:00Z")
retrieved("9", "19-9")
);
assert.equal(
(await alertSearchCursorsDb.get(USER))?.endorserAfterId,
ulid(9)
(await alertSearchCursorsDb.get(USER))?.endorserAfterCursor,
"9"
);
assert.equal(await smsAlertSearchCursorsDb.get(USER), undefined);
});
@@ -94,22 +96,22 @@ describe("per-channel alertSearch cursors", () => {
it("lets the two channels sit at different positions", async () => {
await advanceAlertSearchCursors(
USER,
retrieved(ulid(1), "2026-09-01T00:00:00Z"),
retrieved("1", "11-1"),
"fcm"
);
await advanceAlertSearchCursors(
USER,
retrieved(ulid(2), "2026-09-02T00:00:00Z"),
retrieved("2", "12-2"),
"sms"
);
assert.deepEqual(await loadAlertSearchCursors(USER, "fcm"), {
endorserAfterId: ulid(1),
partnerAfterDate: "2026-09-01T00:00:00Z",
endorserAfterCursor: "1",
partnerAfterCursor: "11-1",
});
assert.deepEqual(await loadAlertSearchCursors(USER, "sms"), {
endorserAfterId: ulid(2),
partnerAfterDate: "2026-09-02T00:00:00Z",
endorserAfterCursor: "2",
partnerAfterCursor: "12-2",
});
});
+121
View File
@@ -17,6 +17,7 @@ import {
alertSearchSmsBody,
deliverAlertSearchSms,
isAlertSearchSmsEligible,
sameDayRerunAllowed,
} from "../../src/alertSearch/smsNotify.js";
const USER = "did:ethr:0xsmsnotify";
@@ -29,6 +30,7 @@ let savedDataDir: string | undefined;
let savedSecret: string | undefined;
let savedAllowlist: string | undefined;
let savedBlocked: string | undefined;
let savedResend: string | undefined;
beforeEach(async () => {
savedDataDir = process.env.NOTIFY_DATA_DIR;
@@ -37,6 +39,8 @@ beforeEach(async () => {
delete process.env.SMS_ALLOWED_RECIPIENT_DIDS;
savedBlocked = process.env.SMS_BLOCKED_NUMBERS;
delete process.env.SMS_BLOCKED_NUMBERS;
savedResend = process.env.SMS_SAME_DAY_RESEND_NUMBERS;
delete process.env.SMS_SAME_DAY_RESEND_NUMBERS;
dir = await mkdtemp(path.join(tmpdir(), "sms-notify-"));
process.env.NOTIFY_DATA_DIR = dir;
process.env.SMS_CODE_SECRET = SECRET;
@@ -53,6 +57,8 @@ afterEach(async () => {
else process.env.SMS_ALLOWED_RECIPIENT_DIDS = savedAllowlist;
if (savedBlocked === undefined) delete process.env.SMS_BLOCKED_NUMBERS;
else process.env.SMS_BLOCKED_NUMBERS = savedBlocked;
if (savedResend === undefined) delete process.env.SMS_SAME_DAY_RESEND_NUMBERS;
else process.env.SMS_SAME_DAY_RESEND_NUMBERS = savedResend;
await rm(dir, { recursive: true, force: true });
});
@@ -64,6 +70,8 @@ function digest(overrides: Partial<AlertSearchDigest> = {}): AlertSearchDigest {
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
};
return {
completed: true,
@@ -77,6 +85,8 @@ function digest(overrides: Partial<AlertSearchDigest> = {}): AlertSearchDigest {
trackedPlanClaims: [],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
},
endorser: { outcome: "success", completed: true },
partner: { outcome: "empty", completed: true },
@@ -128,8 +138,19 @@ describe("alertSearchSmsBody", () => {
alertSearchSmsBody(1),
`Gift Economies: you have 1 new update. ${ALERT_SEARCH_SMS_LINK} Reply STOP to end.`
);
assert.ok(body.includes("https://giftopia.me/deep-link/new-activity "));
assert.equal(body.includes("giftopia.tech"), false);
});
it("carries the start cursors as 'c' and still fits one segment", () => {
const cursorParam = "123456789.12345678-123456789";
const body = alertSearchSmsBody(9999, cursorParam);
assert.ok(
body.includes(`${ALERT_SEARCH_SMS_LINK}?c=${cursorParam} Reply STOP`),
body
);
assert.ok(body.length <= SMS_SINGLE_SEGMENT_LIMIT, `length ${body.length}`);
});
});
describe("SMS notification gate", () => {
@@ -256,6 +277,67 @@ describe("deliverAlertSearchSms", () => {
assert.equal(second.sent, 0);
});
it("texts a same-day-resend number again for a batch uploaded after the first text", async () => {
process.env.SMS_SAME_DAY_RESEND_NUMBERS = "+1 555 555 0123";
await verifyPhone(PHONE);
let sends = 0;
const send = async (): Promise<SmsSendResult> => {
sends += 1;
return { status: "sent", messageId: "SM" + sends };
};
await deliverAlertSearchSms(
daily({ authorizedAt: "2026-09-08T08:00:00.000Z" }),
{ send, now: new Date("2026-09-08T09:00:00.000Z") }
);
getDatabase()
.prepare(
`UPDATE sms_phone_log SET created_at = ? WHERE action = 'alert-sent'`
)
.run("2026-09-08T09:00:00.000Z");
// A reset at 14:00 with rerunToday; its run texts the same day.
const afterReset = await deliverAlertSearchSms(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:05:00.000Z") }
);
assert.equal(afterReset.sent, 1);
// The cap still holds within that batch.
const again = await deliverAlertSearchSms(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:10:00.000Z") }
);
assert.equal(again.sent, 0);
assert.equal(sends, 2);
});
it("texts any other number once a UTC day, even for a later batch", async () => {
process.env.SMS_SAME_DAY_RESEND_NUMBERS = OTHER_PHONE;
await verifyPhone(PHONE);
let sends = 0;
const send = async (): Promise<SmsSendResult> => {
sends += 1;
return { status: "sent", messageId: "SM" + sends };
};
await deliverAlertSearchSms(
daily({ authorizedAt: "2026-09-08T08:00:00.000Z" }),
{ send, now: new Date("2026-09-08T09:00:00.000Z") }
);
getDatabase()
.prepare(
`UPDATE sms_phone_log SET created_at = ? WHERE action = 'alert-sent'`
)
.run("2026-09-08T09:00:00.000Z");
const afterReset = await deliverAlertSearchSms(
daily({ authorizedAt: "2026-09-08T14:00:00.000Z" }),
{ send, now: new Date("2026-09-08T14:05:00.000Z") }
);
assert.equal(afterReset.sent, 0);
assert.equal(sends, 1);
});
it("does not suppress a send on the next UTC day after a late-evening send", async () => {
await verifyPhone(PHONE);
let sends = 0;
@@ -478,3 +560,42 @@ describe("Twilio 21610 syncs the provider's opt-out list into ours", () => {
);
});
});
describe("sameDayRerunAllowed", () => {
async function textedAt(phone: string, createdAt: string): Promise<void> {
await smsPhoneLogDb.append({
userId: USER,
phoneE164: phone,
phoneHash: hashPhoneNumber(phone, SECRET),
action: "alert-sent",
result: "ok",
});
getDatabase()
.prepare(`UPDATE sms_phone_log SET created_at = ? WHERE action = 'alert-sent'`)
.run(createdAt);
}
it("allows a rerun for a number not texted since UTC midnight", async () => {
await textedAt(PHONE, "2026-09-07T23:30:00.000Z");
assert.equal(
await sameDayRerunAllowed(USER, [PHONE], SECRET, new Date("2026-09-08T10:00:00.000Z")),
true
);
});
it("refuses a rerun once every number was texted today", async () => {
await textedAt(PHONE, "2026-09-08T09:00:00.000Z");
assert.equal(
await sameDayRerunAllowed(USER, [PHONE], SECRET, new Date("2026-09-08T10:00:00.000Z")),
false
);
});
it("allows it when any number can still get a text today", async () => {
await textedAt(PHONE, "2026-09-08T09:00:00.000Z");
const now = new Date("2026-09-08T10:00:00.000Z");
assert.equal(await sameDayRerunAllowed(USER, [PHONE, OTHER_PHONE], SECRET, now), true);
process.env.SMS_SAME_DAY_RESEND_NUMBERS = PHONE;
assert.equal(await sameDayRerunAllowed(USER, [PHONE], SECRET, now), true);
});
});
+89 -1
View File
@@ -5,7 +5,8 @@ import path from "node:path";
import { afterEach, beforeEach, describe, it } from "node:test";
import { smsActionJwtUseDb } from "../../src/db/smsActionJwtUseSqlite.js";
import { smsAlertAuthorizationDb } from "../../src/db/smsAlertAuthorizationSqlite.js";
import { closeDatabase } from "../../src/db/sqlite.js";
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
import type { SmsAlertSearchRunInput } from "../../src/db/smsAlertSearchRunsSqlite.js";
import type { DailyAlertSearchResult } from "../../src/alertSearch/daily.js";
import {
SMS_ACTION_JWT_RETENTION_MULTIPLE,
@@ -336,6 +337,93 @@ describe("runSmsAlertSearchSchedulerPass", () => {
delete process.env.SMS_ACTION_JWT_MAX_AGE_SEC;
});
it("records each user's run with its digest and SMS counts", async () => {
const recorded: SmsAlertSearchRunInput[] = [];
await runSmsAlertSearchSchedulerPass({
concurrency: 1,
listPending: async () => due([USER, OTHER]),
runDaily: async (userId) => {
if (userId === OTHER) throw new Error("Endorser down");
return {
...daily(userId),
startCursors: { endorser: "e1", partner: "p1" },
digest: {
completed: true,
hasUpdates: true,
totalCount: 1,
counts: {
claims: 1,
personalPlanContributions: 0,
trackedPlanUpdates: 0,
trackedPlanClaims: 0,
plansNearby: 0,
profilesNearby: 0,
profilesSimilar: 0,
plansSimilar: 0,
},
records: {
claims: [{ id: "c1", issuedAt: "x", issuer: "did:a" }],
personalPlanContributions: [],
trackedPlanUpdates: [],
trackedPlanClaims: [],
plansNearby: [],
profilesNearby: [],
profilesSimilar: [],
plansSimilar: [],
},
endorser: { outcome: "success", completed: true },
partner: { outcome: "empty", completed: true },
},
};
},
notify: async () => ({ eligible: true, sent: 1, failed: 0, blocked: 0 }),
recordRun: async (run) => {
recorded.push(run);
},
prune: async () => undefined,
});
assert.equal(recorded.length, 2);
const ok = recorded.find((r) => r.userId === USER);
assert.equal(ok?.totalCount, 1);
assert.equal(ok?.smsSent, 1);
assert.equal(ok?.endorserStartCursor, "e1");
assert.equal(ok?.error, undefined);
const bad = recorded.find((r) => r.userId === OTHER);
assert.equal(bad?.error, "Endorser down");
assert.equal(bad?.completed, undefined);
});
it("writes run rows to sms_alert_search_runs by default", async () => {
await runSmsAlertSearchSchedulerPass({
concurrency: 1,
listPending: async () => due([USER]),
runDaily: async (userId) => daily(userId),
notify: async () => ({ eligible: false, sent: 0, failed: 0, blocked: 0 }),
prune: async () => undefined,
});
const rows = getDatabase()
.prepare(`SELECT user_id, completed, consumed, sms_eligible FROM sms_alert_search_runs`)
.all();
assert.deepEqual(rows, [
{ user_id: USER, completed: 1, consumed: 1, sms_eligible: 0 },
]);
});
it("does not let a failing run record fail the user", async () => {
const result = await runSmsAlertSearchSchedulerPass({
concurrency: 1,
listPending: async () => due([USER]),
runDaily: async (userId) => daily(userId),
notify: async () => undefined,
recordRun: async () => {
throw new Error("disk full");
},
prune: async () => undefined,
});
assert.equal(result.failed, 0);
});
it("survives a prune failure", async () => {
const result = await runSmsAlertSearchSchedulerPass({
concurrency: 1,
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, it } from "node:test";
import { db } from "../../src/db/fcmTokensSqlite.js";
import { closeDatabase } from "../../src/db/sqlite.js";
describe("fcm_registrations deleteByUserId", () => {
let dir: string;
let previousDataDir: string | undefined;
beforeEach(async () => {
previousDataDir = process.env.NOTIFY_DATA_DIR;
dir = await mkdtemp(path.join(tmpdir(), "fcm-tokens-"));
process.env.NOTIFY_DATA_DIR = dir;
closeDatabase();
});
afterEach(async () => {
closeDatabase();
if (previousDataDir === undefined) delete process.env.NOTIFY_DATA_DIR;
else process.env.NOTIFY_DATA_DIR = previousDataDir;
await rm(dir, { recursive: true, force: true });
});
it("removes every device of one DID and no one else's", async () => {
const add = (userId: string, deviceId: string, fcmToken: string) =>
db.upsert({ userId, deviceId, fcmToken, platform: "ios", updatedAt: new Date() });
await add("did:ethr:0xa", "d1", "t1");
await add("did:ethr:0xa", "d2", "t2");
await add("did:ethr:0xb", "d3", "t3");
assert.equal(await db.deleteByUserId("did:ethr:0xa"), 2);
assert.deepEqual(await db.getByUserId("did:ethr:0xa"), []);
assert.equal((await db.getByUserId("did:ethr:0xb")).length, 1);
assert.equal(await db.deleteByUserId("did:ethr:0xa"), 0);
});
});
+19 -2
View File
@@ -1,8 +1,12 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, describe, it } from "node:test";
import { smsConfig } from "../src/env.js";
import { smsConfig, withEnvLabel } from "../src/env.js";
const KEYS = ["SMS_ENABLED", "SMS_REQUIRE_ACTION_CLAIM"] as const;
const KEYS = [
"SMS_ENABLED",
"SMS_REQUIRE_ACTION_CLAIM",
"MESSAGE_ENV_LABEL",
] as const;
const saved: Record<string, string | undefined> = {};
@@ -58,3 +62,16 @@ describe("smsConfig boolean flags", () => {
assert.equal(smsConfig().requireActionClaim, true);
});
});
describe("withEnvLabel", () => {
it("leaves the text alone when unset or blank", () => {
assert.equal(withEnvLabel("hi"), "hi");
process.env.MESSAGE_ENV_LABEL = " ";
assert.equal(withEnvLabel("hi"), "hi");
});
it("appends the trimmed label in parentheses", () => {
process.env.MESSAGE_ENV_LABEL = " test ";
assert.equal(withEnvLabel("hi"), "hi (test)");
});
});
+30
View File
@@ -0,0 +1,30 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
AUTH_JWT_MAX_REMAINING_SEC,
authJwtLifetimeProblem,
} from "../../src/middleware/auth.js";
describe("authJwtLifetimeProblem", () => {
const now = 1_800_000_000;
it("accepts a token expiring within the limit", () => {
assert.equal(authJwtLifetimeProblem({ exp: now + 60 }, now), undefined);
assert.equal(
authJwtLifetimeProblem({ exp: now + AUTH_JWT_MAX_REMAINING_SEC }, now),
undefined
);
});
it("rejects a token with no exp, such as a published claim", () => {
assert.match(authJwtLifetimeProblem({ iat: now }, now) ?? "", /numeric "exp"/);
assert.match(authJwtLifetimeProblem({ exp: "soon" }, now) ?? "", /numeric "exp"/);
});
it("rejects a long-lived token", () => {
assert.match(
authJwtLifetimeProblem({ exp: now + AUTH_JWT_MAX_REMAINING_SEC + 1 }, now) ?? "",
/must expire within/
);
});
});
+146 -1
View File
@@ -6,6 +6,7 @@ import path from "node:path";
import { afterEach, beforeEach, describe, it } from "node:test";
import express, { type RequestHandler } from "express";
import { smsAlertAuthorizationDb } from "../../src/db/smsAlertAuthorizationSqlite.js";
import { smsAlertSearchCursorsDb } from "../../src/db/alertSearchCursorsSqlite.js";
import { smsPhoneLogDb } from "../../src/db/smsPhoneLogSqlite.js";
import { smsBlockedNumbersDb } from "../../src/db/smsBlockedNumbersSqlite.js";
import { smsRegistrationsDb } from "../../src/db/smsRegistrationsSqlite.js";
@@ -36,6 +37,7 @@ const ENV_KEYS = [
"SMS_ACTION_JWT_MAX_AGE_SEC",
"SMS_ALLOWED_RECIPIENT_DIDS",
"SMS_BLOCKED_NUMBERS",
"SMS_SAME_DAY_RESEND_NUMBERS",
"TWILIO_AUTH_TOKEN",
"TWILIO_WEBHOOK_URL",
"NODE_ENV",
@@ -755,11 +757,154 @@ describe("POST /notify-sms/alert-authorization", () => {
auth: { claim: authorizeClaim },
});
assert.equal(again.status, 200);
assert.equal(again.body.storedCount, 100);
// today already ran, so the new batch's JWT for today is skipped
assert.equal(again.body.storedCount, 99);
assert.equal(
(await smsAlertAuthorizationDb.getJwtById(first.id))?.status,
"consumed"
);
assert.equal(
await smsAlertAuthorizationDb.getUnusedForDay(USER, today),
undefined
);
});
it("with rerunToday, stores today's JWT even though today already ran", async () => {
await registerAndVerify();
await call({
path: "/notify-sms/alert-authorization",
body: batch(),
auth: { claim: authorizeClaim },
});
const today = utcCalendarDay(Math.floor(Date.now() / 1000));
const first = await smsAlertAuthorizationDb.getUnusedForDay(USER, today);
assert.ok(first);
await smsAlertAuthorizationDb.consumeUnusedJwt({
id: first.id,
userId: USER,
});
const again = await call({
path: "/notify-sms/alert-authorization",
body: { ...batch(), rerunToday: true },
auth: { claim: authorizeClaim },
});
assert.equal(again.status, 200, JSON.stringify(again.body));
assert.equal(again.body.storedCount, 100);
const rearmed = await smsAlertAuthorizationDb.getUnusedForDay(USER, today);
assert.ok(rearmed);
assert.notEqual(rearmed.id, first.id);
// the spent row stays as the record of the earlier run
assert.equal(
(await smsAlertAuthorizationDb.getJwtById(first.id))?.status,
"consumed"
);
});
it("ignores rerunToday once today's text went, unless the number may resend", async () => {
await registerAndVerify();
await call({
path: "/notify-sms/alert-authorization",
body: batch(),
auth: { claim: authorizeClaim },
});
const today = utcCalendarDay(Math.floor(Date.now() / 1000));
const first = await smsAlertAuthorizationDb.getUnusedForDay(USER, today);
assert.ok(first);
await smsAlertAuthorizationDb.consumeUnusedJwt({ id: first.id, userId: USER });
await smsPhoneLogDb.append({
userId: USER,
phoneE164: PHONE,
phoneHash: hashPhoneNumber(PHONE, SECRET),
action: "alert-sent",
result: "ok",
});
const ignored = await call({
path: "/notify-sms/alert-authorization",
body: { ...batch(), rerunToday: true },
auth: { claim: authorizeClaim },
});
assert.equal(ignored.status, 200, JSON.stringify(ignored.body));
assert.equal(ignored.body.storedCount, 99);
assert.equal(await smsAlertAuthorizationDb.getUnusedForDay(USER, today), undefined);
process.env.SMS_SAME_DAY_RESEND_NUMBERS = PHONE;
const honored = await call({
path: "/notify-sms/alert-authorization",
body: { ...batch(), rerunToday: true },
auth: { claim: authorizeClaim },
});
assert.equal(honored.status, 200, JSON.stringify(honored.body));
assert.equal(honored.body.storedCount, 100);
assert.ok(await smsAlertAuthorizationDb.getUnusedForDay(USER, today));
});
it("rejects a rerunToday that is not a boolean", async () => {
await registerAndVerify();
const result = await call({
path: "/notify-sms/alert-authorization",
body: { ...batch(), rerunToday: "yes" },
auth: { claim: authorizeClaim },
});
assert.equal(result.status, 400);
assert.ok(
(result.body.details as string[]).some((line) =>
line.startsWith("rerunToday must be a boolean")
),
JSON.stringify(result.body.details)
);
assert.equal(await smsAlertAuthorizationDb.countUnused(USER), 0);
});
it("stores the cursors, starred handle IDs and area sent with a batch", async () => {
await registerAndVerify();
const location = { minLocLat: 40, maxLocLat: 41, minLocLon: -112, maxLocLon: -111 };
const result = await call({
path: "/notify-sms/alert-authorization",
body: {
...batch(),
endorserAfterCursor: "4821",
partnerAfterCursor: "91-4821",
planHandleIds: ["https://endorser.ch/entity/01HPLAN"],
location,
},
auth: { claim: authorizeClaim },
});
assert.equal(result.status, 200, JSON.stringify(result.body));
const stored = await smsAlertSearchCursorsDb.get(USER);
assert.equal(stored?.endorserAfterCursor, "4821");
assert.equal(stored?.partnerAfterCursor, "91-4821");
assert.deepEqual(stored?.planHandleIds, ["https://endorser.ch/entity/01HPLAN"]);
assert.deepEqual(stored?.location, location);
// absent fields keep what is stored; null clears
await call({
path: "/notify-sms/alert-authorization",
body: { ...batch(), location: null },
auth: { claim: authorizeClaim },
});
const after = await smsAlertSearchCursorsDb.get(USER);
assert.equal(after?.endorserAfterCursor, "4821");
assert.deepEqual(after?.planHandleIds, ["https://endorser.ch/entity/01HPLAN"]);
assert.equal(after?.location, null);
});
it("rejects a cursor with a '.' or a malformed area, storing nothing", async () => {
await registerAndVerify();
const result = await call({
path: "/notify-sms/alert-authorization",
body: {
...batch(),
endorserAfterCursor: "1.2",
location: { minLocLat: 95, maxLocLat: 41, minLocLon: -112, maxLocLon: -111 },
},
auth: { claim: authorizeClaim },
});
assert.equal(result.status, 400);
assert.equal((result.body.details as string[]).length, 2);
assert.equal(await smsAlertSearchCursorsDb.get(USER), undefined);
assert.equal(await smsAlertAuthorizationDb.getLatestBatch(USER), undefined);
});
it("stores the hour and minute and echoes both back", async () => {
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
ALERT_SEARCH_FCM_TYPE,
buildAlertSearchFcmMessage,
} from "../../src/services/alertSearchFcmPayload.js";
describe("buildAlertSearchFcmMessage", () => {
it("sends a visible notification whose data type is alert_search", () => {
const message = buildAlertSearchFcmMessage("device-token", {
title: "AlertSearch tap test",
body: "Tap this notification.",
});
assert.equal(message.token, "device-token");
assert.equal(message.notification.title, "AlertSearch tap test");
assert.equal(message.notification.body, "Tap this notification.");
assert.equal(message.data.type, "alert_search");
assert.equal(message.data.type, ALERT_SEARCH_FCM_TYPE);
assert.equal(Object.keys(message.data).length, 1);
});
});