@connextar/house 0.22.2 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +574 -62
- package/dist/admin/index.d.ts +2 -2
- package/dist/admin/index.d.ts.map +1 -1
- package/dist/admin/index.js +2 -2
- package/dist/admin/index.js.map +1 -1
- package/dist/admin/proof.d.ts +49 -9
- package/dist/admin/proof.d.ts.map +1 -1
- package/dist/admin/proof.js +83 -4
- package/dist/admin/proof.js.map +1 -1
- package/dist/admin/second-factor.d.ts +3 -1
- package/dist/admin/second-factor.d.ts.map +1 -1
- package/dist/admin/second-factor.js +3 -2
- package/dist/admin/second-factor.js.map +1 -1
- package/dist/admin/view-as.d.ts +37 -5
- package/dist/admin/view-as.d.ts.map +1 -1
- package/dist/admin/view-as.js +67 -6
- package/dist/admin/view-as.js.map +1 -1
- package/dist/analytics/browser.d.ts +108 -0
- package/dist/analytics/browser.d.ts.map +1 -0
- package/dist/analytics/browser.js +319 -0
- package/dist/analytics/browser.js.map +1 -0
- package/dist/analytics/client-index.d.ts +6 -0
- package/dist/analytics/client-index.d.ts.map +1 -0
- package/dist/analytics/client-index.js +6 -0
- package/dist/analytics/client-index.js.map +1 -0
- package/dist/analytics/config.d.ts +50 -0
- package/dist/analytics/config.d.ts.map +1 -0
- package/dist/analytics/config.js +39 -0
- package/dist/analytics/config.js.map +1 -0
- package/dist/analytics/index.d.ts +10 -0
- package/dist/analytics/index.d.ts.map +1 -0
- package/dist/analytics/index.js +10 -0
- package/dist/analytics/index.js.map +1 -0
- package/dist/analytics/ingest.d.ts +30 -0
- package/dist/analytics/ingest.d.ts.map +1 -0
- package/dist/analytics/ingest.js +64 -0
- package/dist/analytics/ingest.js.map +1 -0
- package/dist/analytics/react-index.d.ts +6 -0
- package/dist/analytics/react-index.d.ts.map +1 -0
- package/dist/analytics/react-index.js +6 -0
- package/dist/analytics/react-index.js.map +1 -0
- package/dist/analytics/react.d.ts +75 -0
- package/dist/analytics/react.d.ts.map +1 -0
- package/dist/analytics/react.js +159 -0
- package/dist/analytics/react.js.map +1 -0
- package/dist/analytics/redact.d.ts +35 -0
- package/dist/analytics/redact.d.ts.map +1 -0
- package/dist/analytics/redact.js +109 -0
- package/dist/analytics/redact.js.map +1 -0
- package/dist/analytics/server-index.d.ts +6 -0
- package/dist/analytics/server-index.d.ts.map +1 -0
- package/dist/analytics/server-index.js +6 -0
- package/dist/analytics/server-index.js.map +1 -0
- package/dist/analytics/server.d.ts +89 -0
- package/dist/analytics/server.d.ts.map +1 -0
- package/dist/analytics/server.js +211 -0
- package/dist/analytics/server.js.map +1 -0
- package/dist/jobs/idle.d.ts +49 -0
- package/dist/jobs/idle.d.ts.map +1 -0
- package/dist/jobs/idle.js +61 -0
- package/dist/jobs/idle.js.map +1 -0
- package/dist/jobs/index.d.ts +2 -1
- package/dist/jobs/index.d.ts.map +1 -1
- package/dist/jobs/index.js +2 -1
- package/dist/jobs/index.js.map +1 -1
- package/dist/jobs/next-index.d.ts +5 -0
- package/dist/jobs/next-index.d.ts.map +1 -0
- package/dist/jobs/next-index.js +5 -0
- package/dist/jobs/next-index.js.map +1 -0
- package/dist/jobs/next.d.ts +25 -0
- package/dist/jobs/next.d.ts.map +1 -0
- package/dist/jobs/next.js +51 -0
- package/dist/jobs/next.js.map +1 -0
- package/dist/jobs/prisma-index.d.ts +6 -0
- package/dist/jobs/prisma-index.d.ts.map +1 -0
- package/dist/jobs/prisma-index.js +6 -0
- package/dist/jobs/prisma-index.js.map +1 -0
- package/dist/jobs/prisma.d.ts +77 -0
- package/dist/jobs/prisma.d.ts.map +1 -0
- package/dist/jobs/prisma.js +92 -0
- package/dist/jobs/prisma.js.map +1 -0
- package/dist/jobs/scheduler.d.ts +7 -0
- package/dist/jobs/scheduler.d.ts.map +1 -1
- package/dist/jobs/scheduler.js +10 -0
- package/dist/jobs/scheduler.js.map +1 -1
- package/dist/maintenance/react.d.ts +9 -2
- package/dist/maintenance/react.d.ts.map +1 -1
- package/dist/maintenance/react.js +15 -4
- package/dist/maintenance/react.js.map +1 -1
- package/dist/rate-limit/better-auth.d.ts +50 -0
- package/dist/rate-limit/better-auth.d.ts.map +1 -0
- package/dist/rate-limit/better-auth.js +64 -0
- package/dist/rate-limit/better-auth.js.map +1 -0
- package/dist/rate-limit/index.d.ts +13 -0
- package/dist/rate-limit/index.d.ts.map +1 -0
- package/dist/rate-limit/index.js +13 -0
- package/dist/rate-limit/index.js.map +1 -0
- package/dist/rate-limit/keys.d.ts +45 -0
- package/dist/rate-limit/keys.d.ts.map +1 -0
- package/dist/rate-limit/keys.js +95 -0
- package/dist/rate-limit/keys.js.map +1 -0
- package/dist/rate-limit/limiter.d.ts +114 -0
- package/dist/rate-limit/limiter.d.ts.map +1 -0
- package/dist/rate-limit/limiter.js +166 -0
- package/dist/rate-limit/limiter.js.map +1 -0
- package/dist/rate-limit/prisma-index.d.ts +6 -0
- package/dist/rate-limit/prisma-index.d.ts.map +1 -0
- package/dist/rate-limit/prisma-index.js +6 -0
- package/dist/rate-limit/prisma-index.js.map +1 -0
- package/dist/rate-limit/prisma.d.ts +116 -0
- package/dist/rate-limit/prisma.d.ts.map +1 -0
- package/dist/rate-limit/prisma.js +79 -0
- package/dist/rate-limit/prisma.js.map +1 -0
- package/dist/rate-limit/store.d.ts +27 -0
- package/dist/rate-limit/store.d.ts.map +1 -0
- package/dist/rate-limit/store.js +28 -0
- package/dist/rate-limit/store.js.map +1 -0
- package/docs/Maintenance.md +7 -2
- package/package.json +36 -1
package/README.md
CHANGED
|
@@ -87,6 +87,15 @@ sessions may inherit the proof, whether a revoked session still counts, whether
|
|
|
87
87
|
the view-as cookie is signed. The module is AltEd's model with each of those
|
|
88
88
|
settled the safe way, and the app's words kept.
|
|
89
89
|
|
|
90
|
+
`rate-limit` and `analytics`, in 0.23.0, are the admin case again, at eleven
|
|
91
|
+
copies and three. Every app with a `rate_limit` table wrote its own limiter, and
|
|
92
|
+
all but one failed open on every database error, including the long key that
|
|
93
|
+
switched a limit off. Three apps carried near-copies of the same 900 lines of
|
|
94
|
+
consent, PostHog gate and error reporting, and within three weeks they had
|
|
95
|
+
drifted on the privacy fixes, each found in one app and left out of another.
|
|
96
|
+
Both modules are the union, each rule the strictest of the copies, and both sit
|
|
97
|
+
on the app's own table or client so that adopting them needs no migration.
|
|
98
|
+
|
|
90
99
|
## Modules
|
|
91
100
|
|
|
92
101
|
### `@connextar/house/errors`
|
|
@@ -600,7 +609,7 @@ export const access = adminAccess(
|
|
|
600
609
|
(await prisma.user.findUnique({ where: { id }, select: { twoFactorEnabled: true } }))?.twoFactorEnabled === true,
|
|
601
610
|
sessionLive: async (id, userId) =>
|
|
602
611
|
(await prisma.session.count({ where: { id, userId, expiresAt: { gt: new Date() } } })) > 0,
|
|
603
|
-
// sessionProven: defaults to the plugin's record, read through `auth`
|
|
612
|
+
// sessionProven: defaults to the plugin's record, read (and only read) through `auth`
|
|
604
613
|
},
|
|
605
614
|
{
|
|
606
615
|
auth,
|
|
@@ -642,6 +651,16 @@ An administrator gets in only when all of these hold, checked in this order:
|
|
|
642
651
|
- `AdminRefusalError` (`status`, `reason`, `refusal`) and
|
|
643
652
|
`assertAdminAccess(decision, makeError?)` are for code that answers by
|
|
644
653
|
throwing. Pass `makeError` to throw the app's own `ForbiddenError`.
|
|
654
|
+
- **The default `sessionProven` only reads.** Better Auth's own
|
|
655
|
+
`findVerificationValue` deletes every expired `verification` row each time it
|
|
656
|
+
reads one. The check runs under "view as" too, where the write guard refuses
|
|
657
|
+
that delete, so until 0.23.0 an administrator's view could never be honoured
|
|
658
|
+
and PM Tool, senco and MAS read the record from Prisma themselves. The reader
|
|
659
|
+
now asks the same places Better Auth would, in the same order (secondary
|
|
660
|
+
storage, then the newest database row, under a hashed identifier where
|
|
661
|
+
`verification.storeIdentifier` says so), and never writes. Those apps drop
|
|
662
|
+
their own readers and pass `auth`. `readVerificationValue(context, identifier)`
|
|
663
|
+
is exported for any other read of the table that must not write.
|
|
645
664
|
|
|
646
665
|
#### Server: the plugin
|
|
647
666
|
|
|
@@ -652,7 +671,7 @@ plugins: [
|
|
|
652
671
|
twoFactor({ … }),
|
|
653
672
|
passkey({ … }),
|
|
654
673
|
secondFactorEverywhere(),
|
|
655
|
-
adminSecondFactorSessions({ // after twoFactor() and secondFactorEverywhere()
|
|
674
|
+
adminSecondFactorSessions({ // after twoFactor() and secondFactorEverywhere(); before stepUp() and nextCookies()
|
|
656
675
|
isAdmin: (id) => isPlatformAdmin(id),
|
|
657
676
|
recordPrefix: "admin-second-factor:", // the app's existing prefix, so its sessions keep counting
|
|
658
677
|
onAdminSignedIn: (event) => writeAuditLog(event),
|
|
@@ -716,6 +735,12 @@ start if the plugin is listed before `twoFactor()` or `secondFactorEverywhere()`
|
|
|
716
735
|
while `onAdminSignedIn` is set. Without the callback, the record does not depend
|
|
717
736
|
on order.
|
|
718
737
|
|
|
738
|
+
**List it before `stepUp()`.** Both refuse an administrator's factor change, and
|
|
739
|
+
whichever is listed first answers. After `stepUp()`, an administrator on an
|
|
740
|
+
unproven session is asked to confirm it is them, and then refused anyway with
|
|
741
|
+
`ADMIN_SECOND_FACTOR_REQUIRED`. AltEd met this. Listed first, the plugin says
|
|
742
|
+
why at once. A test pins both orders.
|
|
743
|
+
|
|
719
744
|
| Option | Default | What it does |
|
|
720
745
|
| --------------------- | ---------------------- | --------------------------------------------------------------------------------- |
|
|
721
746
|
| `isAdmin` | required | Whether the account is an administrator now, read from the database. |
|
|
@@ -796,10 +821,20 @@ AltEd's rules, made safe by default:
|
|
|
796
821
|
AuditLog: ["create"], // the view's own start and stop
|
|
797
822
|
}),
|
|
798
823
|
getViewing: async () => (await getRequestActor())?.viewingAs ?? null,
|
|
824
|
+
appName: "Quickie", // "You’re viewing Quickie as Pat. Stop viewing as them before changing anything."
|
|
799
825
|
makeError: (message) => new ForbiddenError(message),
|
|
800
826
|
});
|
|
801
827
|
```
|
|
802
828
|
|
|
829
|
+
**Better Auth's verification cleanup.** Better Auth deletes expired
|
|
830
|
+
`verification` rows every time it reads one through `findVerificationValue`:
|
|
831
|
+
a trusted-device check, the two-factor cookie, an email link. The house's
|
|
832
|
+
proof reader no longer goes that way, so the allow-list needs nothing for
|
|
833
|
+
administration. An app's own call to it under "view as" still meets the
|
|
834
|
+
guard. Allow `Verification: ["deleteMany"]` only if such a read has to work
|
|
835
|
+
while viewing. Otherwise set Better Auth's `verification.disableCleanup` and
|
|
836
|
+
prune the table from a job.
|
|
837
|
+
|
|
803
838
|
- **Outside calls** (Stripe, GoCardless, Xero, AI, email, SMS) are refused by
|
|
804
839
|
default, not route by route. Quickie had to add `refuseWhileViewingAs` to thirty
|
|
805
840
|
handlers by hand, and the next route would have had to remember. Instead, build
|
|
@@ -828,6 +863,30 @@ AltEd's rules, made safe by default:
|
|
|
828
863
|
`refuseWhileViewingAs(user, "starting a checkout", { makeError })` stays, for
|
|
829
864
|
explicit use first in a route.
|
|
830
865
|
|
|
866
|
+
- **The words are the app's.** `viewingAsGate`, `refuseWhileViewingAs` and
|
|
867
|
+
`viewAsWriteGuard` take `appName` ("You’re viewing Quickie as Pat. Stop
|
|
868
|
+
viewing as them before sending an email.") or `message`, a template
|
|
869
|
+
`({ name, what, appName }) => string` for the whole sentence.
|
|
870
|
+
`viewingAsMessage(name, what, words)` gives the same sentence anywhere else.
|
|
871
|
+
Quickie's regex rewrite of the house's text (`inQuickieWords`) goes, since it
|
|
872
|
+
would have stopped matching silently at the first changed character.
|
|
873
|
+
|
|
874
|
+
- **From request headers.** Better Auth's hooks have the request, not Next's
|
|
875
|
+
`cookies()`. `cookieJarFromHeaders(headers)` is a read-only jar over the
|
|
876
|
+
`Cookie` header for `view.read` there:
|
|
877
|
+
|
|
878
|
+
```ts
|
|
879
|
+
const viewFromHeaders = (headers: Headers) => viewAs({ ...options, cookies: () => cookieJarFromHeaders(headers) });
|
|
880
|
+
```
|
|
881
|
+
|
|
882
|
+
It never throws. A value that is not valid percent-encoding (`x=%zz`, set by
|
|
883
|
+
a sibling `*.connextar.com` site) is kept as it came, a nameless pair is
|
|
884
|
+
skipped, and the first of two cookies with one name wins. PharmaLine's own
|
|
885
|
+
parser had an unguarded `decodeURIComponent`, and one such cookie failed every
|
|
886
|
+
sign-in from that browser. `set` throws and `delete` does nothing. PharmaLine's
|
|
887
|
+
`headerCookies` and the hand-parsed `Cookie` headers in PM Tool, FB Web and
|
|
888
|
+
senco go.
|
|
889
|
+
|
|
831
890
|
`start` refuses yourself and another administrator with a `400`, and an
|
|
832
891
|
administrator who does not pass `adminAccess` with that refusal. It sets the
|
|
833
892
|
cookie `httpOnly`, `sameSite: lax`, and `secure` in production.
|
|
@@ -1643,8 +1702,10 @@ cronPrefix?, apiPrefix? })` → the response to send during a window, or
|
|
|
1643
1702
|
- `<MaintenanceBanner appName="AltEd" />` — at the top of the root layout. Drawn
|
|
1644
1703
|
after load from the state route, so a page built ahead of time shows it without
|
|
1645
1704
|
a rebuild. Dismissal is remembered per window (a moved window shows again);
|
|
1646
|
-
under way it says until when and can't be dismissed.
|
|
1647
|
-
every
|
|
1705
|
+
under way it says until when and can't be dismissed. It asks again every 15 s
|
|
1706
|
+
during a window (so it goes as soon as the work finishes early), every 30 s in
|
|
1707
|
+
the quarter hour before one, every five minutes otherwise. Tailwind token
|
|
1708
|
+
classes, as every house component.
|
|
1648
1709
|
- `useServiceCheck()` → `"checking" | "up" | "down" | "maintenance" | "unknown"`,
|
|
1649
1710
|
for `error.tsx`. In production an error page gets a digest, never the message,
|
|
1650
1711
|
so it asks the state route to probe instead: `maintenance` and `down` deserve
|
|
@@ -2479,7 +2540,7 @@ app that imports `/ai` needs them; `/ai/config` needs none. The SDKs refuse to r
|
|
|
2479
2540
|
environment, so a Vitest suite that calls the harness needs
|
|
2480
2541
|
`// @vitest-environment node` on the file.
|
|
2481
2542
|
|
|
2482
|
-
### `@connextar/house/jobs`, `/jobs/react`
|
|
2543
|
+
### `@connextar/house/jobs`, `/jobs/react`, `/jobs/prisma`, `/jobs/next`
|
|
2483
2544
|
|
|
2484
2545
|
Scheduled jobs: declared once, run once per window, switched off and on by
|
|
2485
2546
|
name, and honest about their health. `/jobs` is server code — the registry, the
|
|
@@ -2588,6 +2649,15 @@ export async function GET(request: Request) {
|
|
|
2588
2649
|
return apiSuccess({ results }, summariseTick(results)); // "2 ran, 1 failed, 1 paused, 5 not due"
|
|
2589
2650
|
}
|
|
2590
2651
|
|
|
2652
|
+
// …or, on a serverless database, the idle tick (below)
|
|
2653
|
+
const tickMemo = nextTickMemo(); // @connextar/house/jobs/next
|
|
2654
|
+
export async function GET(request: Request) {
|
|
2655
|
+
const auth = checkCronRequest(request, { publicSecrets: ["dev-cron-secret"] });
|
|
2656
|
+
if (!auth.ok) return apiError(auth.message, auth.status);
|
|
2657
|
+
const outcome = await idleTick(scheduler, tickMemo);
|
|
2658
|
+
return apiSuccess(outcome, outcome.summary); // { status: "ran", results } or { status: "idle" }
|
|
2659
|
+
}
|
|
2660
|
+
|
|
2591
2661
|
// app/api/cron/harvest/route.ts — a job on its own clock
|
|
2592
2662
|
const result = await scheduler.runOwn("harvest");
|
|
2593
2663
|
|
|
@@ -2764,68 +2834,21 @@ ALTER TABLE "cron_run" ADD COLUMN "tenant_id" VARCHAR(64), ADD COLUMN "triggered
|
|
|
2764
2834
|
CREATE INDEX "cron_run_job_tenant_id_started_at_idx" ON "cron_run"("job", "tenant_id", "started_at");
|
|
2765
2835
|
```
|
|
2766
2836
|
|
|
2837
|
+
Since 0.23.0 the adapter for that model is in the package,
|
|
2838
|
+
`@connextar/house/jobs/prisma`. It imports no Prisma: the client is passed in.
|
|
2839
|
+
The switches stay the app's, because every app keeps them somewhere different
|
|
2840
|
+
and writes their audit entry in its own transaction:
|
|
2841
|
+
|
|
2767
2842
|
```ts
|
|
2768
2843
|
// lib/jobs/store.ts
|
|
2769
2844
|
import "server-only";
|
|
2770
|
-
import
|
|
2845
|
+
import { prismaJobStore } from "@connextar/house/jobs/prisma";
|
|
2771
2846
|
|
|
2772
|
-
import { Prisma } from "@/lib/db/generated/client";
|
|
2773
2847
|
import { prisma } from "@lib/db/prisma";
|
|
2774
2848
|
|
|
2775
|
-
export const jobStore
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
const row = await prisma.cronRun.create({ data: { job, windowKey, tenantId, triggeredBy: by, startedAt } });
|
|
2779
|
-
return row.id;
|
|
2780
|
-
} catch (error) {
|
|
2781
|
-
// The unique index refusing a second claim is the answer "already ran", not a failure.
|
|
2782
|
-
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") return null;
|
|
2783
|
-
throw error;
|
|
2784
|
-
}
|
|
2785
|
-
},
|
|
2786
|
-
async finishRun(id, { finishedAt, ok, counts, error }) {
|
|
2787
|
-
await prisma.cronRun.update({ where: { id }, data: { finishedAt, ok, error, ...(counts ? { counts } : {}) } });
|
|
2788
|
-
},
|
|
2789
|
-
async latestRun({ job, tenants, ok, manualOnly }) {
|
|
2790
|
-
const row = await prisma.cronRun.findFirst({
|
|
2791
|
-
where: {
|
|
2792
|
-
job,
|
|
2793
|
-
OR: tenants.map((tenantId) => ({ tenantId })), // `{ tenantId: null }` matches the whole-tenant runs
|
|
2794
|
-
...(ok ? { ok: true } : {}),
|
|
2795
|
-
...(manualOnly ? { windowKey: { startsWith: "manual:" } } : {}),
|
|
2796
|
-
},
|
|
2797
|
-
// `id` breaks a tie the way `pruneRuns` does, so the row read as latest is the row kept as latest.
|
|
2798
|
-
orderBy: [{ startedAt: "desc" }, { id: "desc" }],
|
|
2799
|
-
});
|
|
2800
|
-
return row && { ...row, by: row.triggeredBy };
|
|
2801
|
-
},
|
|
2802
|
-
// Since 0.12.0 — needed once a job's Run now offers both scopes.
|
|
2803
|
-
async latestUnfinishedRun(job) {
|
|
2804
|
-
const row = await prisma.cronRun.findFirst({
|
|
2805
|
-
where: { job, finishedAt: null }, // any tenant: a platform run must wait for every tenant's
|
|
2806
|
-
orderBy: [{ startedAt: "desc" }, { id: "desc" }],
|
|
2807
|
-
});
|
|
2808
|
-
return row && { ...row, by: row.triggeredBy };
|
|
2809
|
-
},
|
|
2810
|
-
// Since 0.12.0 — `pruneJobRuns` calls it from the housekeeping job. One statement, at most `limit` rows, oldest
|
|
2811
|
-
// first. `PARTITION BY` groups every NULL tenant together, which is exactly "the runs over every tenant".
|
|
2812
|
-
async pruneRuns({ startedBefore, limit }) {
|
|
2813
|
-
return prisma.$executeRaw`
|
|
2814
|
-
DELETE FROM "cron_run" WHERE "id" IN (
|
|
2815
|
-
SELECT "id" FROM (
|
|
2816
|
-
SELECT "id", "ok", "started_at", "finished_at",
|
|
2817
|
-
ROW_NUMBER() OVER (PARTITION BY "job", "tenant_id" ORDER BY "started_at" DESC, "id" DESC) AS "nth",
|
|
2818
|
-
ROW_NUMBER() OVER (PARTITION BY "job", "tenant_id", "ok" ORDER BY "started_at" DESC, "id" DESC) AS "nth_of_kind"
|
|
2819
|
-
FROM "cron_run"
|
|
2820
|
-
) AS "ranked"
|
|
2821
|
-
WHERE "started_at" < ${startedBefore}
|
|
2822
|
-
AND "finished_at" IS NOT NULL -- never a run still under way
|
|
2823
|
-
AND "nth" > 1 -- never the latest run of a job for its tenant
|
|
2824
|
-
AND NOT ("ok" AND "nth_of_kind" = 1) -- nor its latest success
|
|
2825
|
-
ORDER BY "started_at", "id"
|
|
2826
|
-
LIMIT ${limit}
|
|
2827
|
-
)`;
|
|
2828
|
-
},
|
|
2849
|
+
export const jobStore = prismaJobStore({
|
|
2850
|
+
runs: prisma.cronRun,
|
|
2851
|
+
sql: prisma, // for pruneRuns, one statement Prisma's query API cannot say
|
|
2829
2852
|
async readSwitches() {
|
|
2830
2853
|
const rows = await prisma.cronSwitch.findMany();
|
|
2831
2854
|
return new Map(rows.map((r) => [r.job, { paused: r.paused, at: r.switchedAt, by: r.switchedByName }]));
|
|
@@ -2848,10 +2871,29 @@ export const jobStore: JobStore = {
|
|
|
2848
2871
|
},
|
|
2849
2872
|
}),
|
|
2850
2873
|
]);
|
|
2874
|
+
expireIdleTick(); // a job switched back on inside its window runs on the next tick, not the next window
|
|
2851
2875
|
},
|
|
2852
|
-
};
|
|
2876
|
+
});
|
|
2853
2877
|
```
|
|
2854
2878
|
|
|
2879
|
+
**The claim is `INSERT … ON CONFLICT DO NOTHING`.** Prisma writes it as
|
|
2880
|
+
`createManyAndReturn({ data: [run], skipDuplicates: true })` (Prisma 5.14 or
|
|
2881
|
+
later, on Postgres). A second claim of a window comes back empty, which means
|
|
2882
|
+
"already ran", and Postgres raises nothing. Until 0.23.0 this README said to
|
|
2883
|
+
`create` and catch the unique index's refusal as P2002. Postgres raises and logs
|
|
2884
|
+
that refusal as an error, and rolls the statement back, every time. AltEd's
|
|
2885
|
+
server counted 127 of them a night before v0.173.4 moved to `ON CONFLICT`.
|
|
2886
|
+
Quickie (`lib/repos/cron.repo.ts`) and senco (`lib/jobs/store.ts`) still claim
|
|
2887
|
+
the old way and move to `prismaJobStore`.
|
|
2888
|
+
|
|
2889
|
+
The rest is the 0.12.0 adapter: `latestRun` and `latestUnfinishedRun` order by
|
|
2890
|
+
`startedAt` then `id`, the way pruning does. `pruneRuns` is one bounded
|
|
2891
|
+
statement over window functions, run through `$executeRawUnsafe` with its two
|
|
2892
|
+
values as parameters. `table` and `columns` name a table that is not the
|
|
2893
|
+
reference one, and anything but a plain identifier is refused.
|
|
2894
|
+
`prisma.test.ts` runs the store against real Postgres (PGlite) and holds it to
|
|
2895
|
+
the memory store's pruning, row for row.
|
|
2896
|
+
|
|
2855
2897
|
`createMemoryJobStore()` is the same contract in memory, unique index and
|
|
2856
2898
|
pruning rules included, for the app's own tests of its binding.
|
|
2857
2899
|
|
|
@@ -2896,6 +2938,38 @@ where the privacy policy names a period for operator activity, use that — the
|
|
|
2896
2938
|
included; a quiet job's single last run is the price of its health staying
|
|
2897
2939
|
true.
|
|
2898
2940
|
|
|
2941
|
+
**The idle tick.** Vercel Cron calls the tick every few minutes, and most calls
|
|
2942
|
+
have nothing to do: every job's window is one already claimed. Finding that out
|
|
2943
|
+
asks the database, which keeps a serverless one (Neon) awake around the clock.
|
|
2944
|
+
AltEd measured about twenty compute hours a day spent that way. The scheduler
|
|
2945
|
+
already knows every window, so it can tell without the database whether
|
|
2946
|
+
anything could have changed:
|
|
2947
|
+
|
|
2948
|
+
- `scheduler.signature(now)` (or `tickSignature(jobs, now)`) is every tick job's
|
|
2949
|
+
window key now, `-` where it is not due: `digest=2026-09-30T12|billing=-`.
|
|
2950
|
+
Own-schedule jobs have their own routes and are not in it.
|
|
2951
|
+
- `idleTick(scheduler, memo, now?)` runs the tick once per signature and
|
|
2952
|
+
answers `{ status: "ran", results, summary }`, or
|
|
2953
|
+
`{ status: "idle", summary }` when an earlier call already ran those windows.
|
|
2954
|
+
A tick in which a job failed before it could claim its window (its switches
|
|
2955
|
+
unreadable, its store down) is not remembered, so the next call tries again.
|
|
2956
|
+
- `nextTickMemo({ tag, revalidateSeconds })`, from `@connextar/house/jobs/next`,
|
|
2957
|
+
keeps the answer in Next's shared data cache for at most an hour by default.
|
|
2958
|
+
Each call builds its own cached function around its own flag. Next keys the
|
|
2959
|
+
cache on the function's source, the key parts and the arguments, so every call
|
|
2960
|
+
shares one entry while each knows whether it ran. Quickie's module-level
|
|
2961
|
+
`ranJustNow` flag was shared by concurrent calls on one instance (Fluid
|
|
2962
|
+
compute), so a response could say "idle" for a run. Outside Next's runtime,
|
|
2963
|
+
as in a test calling the handler, the tick simply runs.
|
|
2964
|
+
`memoryTickMemo()` is the same in memory, for tests.
|
|
2965
|
+
- **Expire it where the signature cannot see a change:** `expireIdleTick(tag?)`
|
|
2966
|
+
in `writeSwitch`, so a job switched back on inside its window runs on the next
|
|
2967
|
+
tick and not the next window. Run now and own-schedule routes do not go
|
|
2968
|
+
through the memo.
|
|
2969
|
+
|
|
2970
|
+
`/jobs/next` is the only jobs entry that imports Next, and `/jobs/prisma`
|
|
2971
|
+
imports nothing. `entry-points.test.ts` holds both against the build.
|
|
2972
|
+
|
|
2899
2973
|
**What should not be a scheduled job.**
|
|
2900
2974
|
|
|
2901
2975
|
- **Anything a person is waiting for.** A report they asked for, a model call,
|
|
@@ -3057,6 +3131,444 @@ its per-organisation jobs that are safe to re-sweep dual.
|
|
|
3057
3131
|
is a promise to schools about how long evidence is kept; say the ledger's 90
|
|
3058
3132
|
days in the same place.
|
|
3059
3133
|
|
|
3134
|
+
**Upgrading to 0.23.0 — the reference store and the idle tick.** Nothing about
|
|
3135
|
+
what runs, or when, changes.
|
|
3136
|
+
|
|
3137
|
+
- **AltEd** — `lib/jobs/store.ts` keeps its own switches (`PlatformSetting`) and
|
|
3138
|
+
becomes `prismaJobStore({ runs: prisma.cronRun, sql: prisma, readSwitches,
|
|
3139
|
+
writeSwitch })`. Its claim is already `ON CONFLICT`. Its tick route takes
|
|
3140
|
+
`idleTick` with `nextTickMemo()`, and `writeSwitch` calls `expireIdleTick()`.
|
|
3141
|
+
The per-minute crons keep `lib/server/idle-checks.ts`, which caches a "nothing
|
|
3142
|
+
to do" for routes that are not the scheduler's.
|
|
3143
|
+
- **Quickie** — `lib/repos/cron.repo.ts` becomes `prismaJobStore` over its
|
|
3144
|
+
`CronSwitch` code, which ends the P2002 claim. The tick route drops
|
|
3145
|
+
`tickOnce`, `ranJustNow` and the `incrementalCache missing` match for
|
|
3146
|
+
`idleTick(scheduler, nextTickMemo({ tag: CRON_TICK_TAG }))`, and
|
|
3147
|
+
`tickSignature` in `lib/services/cron.service.ts` goes, since
|
|
3148
|
+
`scheduler.signature` is the same string.
|
|
3149
|
+
- **senco** — `lib/jobs/store.ts` becomes `prismaJobStore` over its
|
|
3150
|
+
`CronSwitchChange` code, which ends the P2002 claim. `lib/jobs/tick.ts` takes
|
|
3151
|
+
`idleTick`, because its database is serverless too.
|
|
3152
|
+
|
|
3153
|
+
### `@connextar/house/rate-limit`, `/rate-limit/prisma`
|
|
3154
|
+
|
|
3155
|
+
A fixed-window limiter over the app's own table. Every app with a `rate_limit`
|
|
3156
|
+
table wrote one, eleven in all, from 89 lines (Canisters) to 640 (AltEd). Each
|
|
3157
|
+
had something the others lacked, and all but PharmaLine failed open on every
|
|
3158
|
+
database error:
|
|
3159
|
+
|
|
3160
|
+
| Concern | Had it | Here |
|
|
3161
|
+
| ------------------------ | ------------------------------ | ------------------------------------------------------------------------------------------------ |
|
|
3162
|
+
| Fail closed, per rule | AltEd | `failClosed` on the rule; open by default |
|
|
3163
|
+
| Variable cost | AltEd (`1 + lessons.length`) | `consume(key, rule, amount)` |
|
|
3164
|
+
| Ceilings over everyone | AltEd (18 `-everyone` keys) | `rule.everyone`, checked after the caller's own, never spent by a caller already refused |
|
|
3165
|
+
| Read without spending | Quickie `usage`, PharmaLine | `usage(key, rule)`, which fails closed under `failClosed` as PharmaLine's `peek` did |
|
|
3166
|
+
| Over-long keys | Quickie (security round 7, M1) | hashed, in Quickie's format; every other app's `VARCHAR(200)` refused them, and the limit opened |
|
|
3167
|
+
| Private values in keys | Quickie `privateKey` | `limiter.privateKey(prefix, …parts)`; AltEd stored sign-in emails in plain text |
|
|
3168
|
+
| IPv6 | AltEd, Quickie | `/64`, IPv4-mapped to IPv4, zones dropped |
|
|
3169
|
+
| Which forwarded entry | four different answers | `x-vercel-forwarded-for`, `x-real-ip`, then the right-most `x-forwarded-for` |
|
|
3170
|
+
| The count | `upsert`, a P2002, a retry | one `INSERT … ON CONFLICT … RETURNING` on Postgres |
|
|
3171
|
+
| Pruning | five ways; KRP and MAS never | `prune()` from a job, or `autoPrune` where there is none |
|
|
3172
|
+
| Better Auth's own limits | eleven hand-written adapters | `betterAuthRateLimitStorage(limiter)` and `rateLimitConfigProblems` |
|
|
3173
|
+
|
|
3174
|
+
```ts
|
|
3175
|
+
// lib/services/rate-limit.service.ts
|
|
3176
|
+
import "server-only";
|
|
3177
|
+
import { createRateLimiter, defineRateLimits } from "@connextar/house/rate-limit";
|
|
3178
|
+
import { prismaRateLimitStore } from "@connextar/house/rate-limit/prisma";
|
|
3179
|
+
import { after } from "next/server";
|
|
3180
|
+
|
|
3181
|
+
import { prisma } from "@lib/db/prisma";
|
|
3182
|
+
|
|
3183
|
+
export const limiter = createRateLimiter({
|
|
3184
|
+
store: prismaRateLimitStore({ model: prisma.rateLimit, sql: prisma }),
|
|
3185
|
+
secret: process.env.BETTER_AUTH_SECRET!, // for privateKey
|
|
3186
|
+
// Only for an app with no housekeeping job:
|
|
3187
|
+
// autoPrune: { chance: 0.01, batch: 500, schedule: (task) => after(task) },
|
|
3188
|
+
});
|
|
3189
|
+
|
|
3190
|
+
const HOUR = 3_600_000;
|
|
3191
|
+
const DAY = 24 * HOUR;
|
|
3192
|
+
export const RATE_LIMITS = defineRateLimits({
|
|
3193
|
+
summaries: { limit: 40, windowMs: DAY, failClosed: true }, // a paid model call
|
|
3194
|
+
classRequests: {
|
|
3195
|
+
limit: 5,
|
|
3196
|
+
windowMs: DAY,
|
|
3197
|
+
failClosed: true,
|
|
3198
|
+
everyone: { key: "class-requests-everyone", limit: 300 },
|
|
3199
|
+
},
|
|
3200
|
+
calendarFeed: { limit: 60, windowMs: HOUR }, // a refusal would only stop someone reading their own feed
|
|
3201
|
+
});
|
|
3202
|
+
|
|
3203
|
+
// A route
|
|
3204
|
+
const result = await limiter.consume(`summaries:${user.id}`, RATE_LIMITS.summaries);
|
|
3205
|
+
if (!result.allowed) return apiError("Too many summaries today.", 429, rateLimitHeaders(result));
|
|
3206
|
+
|
|
3207
|
+
// A key with something private in it
|
|
3208
|
+
await limiter.consume(limiter.privateKey("sign-in-codes", email.trim().toLowerCase()), RATE_LIMITS.signInCodes);
|
|
3209
|
+
|
|
3210
|
+
// A key per caller address
|
|
3211
|
+
await limiter.consume(`calendar-feed:${callerIp(request)}`, RATE_LIMITS.calendarFeed);
|
|
3212
|
+
```
|
|
3213
|
+
|
|
3214
|
+
- **Fixed windows, aligned to the epoch.** `windowAt` is now rounded down to
|
|
3215
|
+
`windowMs`, so a daily rule's day is the UTC day and two instances agree on a
|
|
3216
|
+
window without talking. These are the windows every app already stores, so
|
|
3217
|
+
their rows keep counting on the day they move.
|
|
3218
|
+
- **`RateLimitResult`** is `{ allowed, remaining, limit, resetAt, retryAfter,
|
|
3219
|
+
refusedBy?, failed? }`. `refusedBy` says whether the caller's own limit
|
|
3220
|
+
refused or the ceiling over everyone. `failed` says the store could not
|
|
3221
|
+
count, and the rule's `failClosed` decided; the error is logged with the
|
|
3222
|
+
stored key.
|
|
3223
|
+
- **`rateLimitHeaders(result)`** gives `x-ratelimit-limit`, `-remaining`,
|
|
3224
|
+
`-reset` (epoch seconds) and, when refused, `retry-after`.
|
|
3225
|
+
- **`defineRateLimits(rules)`** checks a rule table where it is declared, and
|
|
3226
|
+
`consume` checks every rule it is handed. A limit below 1 or a window below a
|
|
3227
|
+
second throws, because neither is a limit anybody meant.
|
|
3228
|
+
- **`storedKey(key)`** keeps a key that fits the column (200 by default, and
|
|
3229
|
+
`maxKeyLength` for a wider one). A longer key becomes its surface up to the
|
|
3230
|
+
first `:` (at most 40 characters), `#`, and the SHA-256 of the whole key: still
|
|
3231
|
+
its own window, never wider than 105.
|
|
3232
|
+
- **`callerIp(request, { headers, forwarded })`** reads the first header that is
|
|
3233
|
+
present, and `ipBucket` reduces it. The right-most `x-forwarded-for` entry is
|
|
3234
|
+
the one the app's proxy added; the left-most is whatever the client sent.
|
|
3235
|
+
`forwarded: { trustedProxies: n }` is for an app behind more than one proxy of
|
|
3236
|
+
its own. Quickie, Canisters, MAS and PharmaLine took the left-most entry, so
|
|
3237
|
+
on any host that appends, a client could name its own bucket.
|
|
3238
|
+
- **`prune({ olderThanMs, batch })`** deletes windows older than seven days by
|
|
3239
|
+
default, at most 1,000 a call, oldest first. Call it from the app's
|
|
3240
|
+
housekeeping job (`windowsPruned`). `autoPrune` is for an app with no job:
|
|
3241
|
+
after an allowed `consume`, with the given chance, it runs a prune through
|
|
3242
|
+
`schedule` (Next's `after`), and a failed prune is logged, never thrown.
|
|
3243
|
+
|
|
3244
|
+
**The store.** The package owns no schema: the app's table sits behind
|
|
3245
|
+
`RateLimitStore` (`increment`, `read`, `prune`), as `jobs` keeps its ledger.
|
|
3246
|
+
`memoryRateLimitStore()` is the contract in memory, for tests.
|
|
3247
|
+
`prismaRateLimitStore({ model, sql?, table?, columns?, uniqueName? })` is the
|
|
3248
|
+
adapter for the `RateLimit` model every app already has:
|
|
3249
|
+
|
|
3250
|
+
- **With `sql`** (the Prisma client, on Postgres) the count is one statement:
|
|
3251
|
+
`INSERT … ON CONFLICT ("key", "window_at") DO UPDATE SET "count" = "count" + n
|
|
3252
|
+
RETURNING "count"`. It is atomic, and it never raises. Every app's own copy
|
|
3253
|
+
upserted and, when two first requests in a window raced, caught the unique
|
|
3254
|
+
violation and retried. That is the job claims' P2002 lesson again: Postgres
|
|
3255
|
+
logs each one as an error. The new row's `id` is a random UUID, because no
|
|
3256
|
+
table has a default for it. The window is passed as an ISO string and made a
|
|
3257
|
+
UTC timestamp in SQL, as Prisma stores `DateTime`, so a database session in
|
|
3258
|
+
another time zone cannot move it.
|
|
3259
|
+
- **Without `sql`** (MAS, on MongoDB) it is the apps' upsert, with the retry on
|
|
3260
|
+
the update.
|
|
3261
|
+
- `read` and `prune` go through the model, so under "view as" the limiter keeps
|
|
3262
|
+
counting through raw SQL, which the write guard does not see. Keep the
|
|
3263
|
+
`RateLimit` entry in the allow-list for the MongoDB path.
|
|
3264
|
+
|
|
3265
|
+
How each app's table maps (from the 2026-11-09 survey). **None needs a
|
|
3266
|
+
migration.**
|
|
3267
|
+
|
|
3268
|
+
| App | Table | Configuration |
|
|
3269
|
+
| ------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
3270
|
+
| Quickie, senco, PM Tool, FB Web, KRP | `rate_limit`, `key VARCHAR(200)` | `{ model: prisma.rateLimit, sql: prisma }` |
|
|
3271
|
+
| AltEd | `rate_limit`, `key TEXT` | the same. Keys over 200 characters are now stored hashed. Its column could hold them, and nothing else changes. |
|
|
3272
|
+
| PharmaLine, Tracker C, Stripe gateway | `rate_limit` + `last_request BIGINT` | the same. `last_request` stays NULL, as it already does under `consume`. Rows the old get/set path wrote age out. |
|
|
3273
|
+
| Canisters | `"RateLimit"`, `"windowAt"` | `{ model: prisma.rateLimit, sql: prisma, table: "RateLimit", columns: { windowAt: "windowAt" } }` |
|
|
3274
|
+
| MAS | MongoDB `rate_limit` | `{ model: prisma.rateLimit }`, with no `sql` |
|
|
3275
|
+
|
|
3276
|
+
MAS's second limiter, `PublicRouteRateLimitBucket` (`scope`, `key`,
|
|
3277
|
+
`windowStart`, `expiresAt`), keeps its own table until its routes move onto
|
|
3278
|
+
`consume`. Its keys are a SHA-256 of the address, user agent and email with no
|
|
3279
|
+
secret, which `privateKey` replaces. Tracker C's table is migrated from
|
|
3280
|
+
`cx-tracker-api`, which needs no change either.
|
|
3281
|
+
|
|
3282
|
+
**Better Auth.** AltEd's outage on 2026-09-01 was two limiters fighting over
|
|
3283
|
+
one table. Better Auth was set to `storage: "database"`, wrote its own
|
|
3284
|
+
`{ key, count, lastRequest }` rows into the model named `rateLimit`, which was
|
|
3285
|
+
the app's `RateLimit` with a different shape, and every sign-in failed on
|
|
3286
|
+
"Argument windowAt is missing". Every app then counted Better Auth through its
|
|
3287
|
+
own limiter, by hand. Now:
|
|
3288
|
+
|
|
3289
|
+
```ts
|
|
3290
|
+
// auth.ts
|
|
3291
|
+
rateLimit: { enabled: constants.env.prod, customStorage: betterAuthRateLimitStorage(limiter) },
|
|
3292
|
+
|
|
3293
|
+
// lib/auth/rate-limit-config.test.ts — the test every app wrote, in one line
|
|
3294
|
+
expect(rateLimitConfigProblems(authOptions)).toEqual([]);
|
|
3295
|
+
```
|
|
3296
|
+
|
|
3297
|
+
- Better Auth calls `consume(key, { window, max })`, with the window in seconds
|
|
3298
|
+
and the key `<ip>|<path>`. It does so on 1.7, and on 1.6.33 whenever the
|
|
3299
|
+
storage has it. The adapter counts it as `auth:<ip>|<path>`, the prefix every
|
|
3300
|
+
app's rows already use. `failClosed` defaults to true here, because a password
|
|
3301
|
+
guess the limiter cannot count is one more than it allowed.
|
|
3302
|
+
- `get` and `set` are only there because 1.6's type lists them. A Better Auth
|
|
3303
|
+
that calls them predates `consume`. Each call is refused with an error that
|
|
3304
|
+
says to upgrade, rather than counted without atomicity. MAS's and the Stripe
|
|
3305
|
+
gateway's adapters had only `get`/`set`, so on 1.6.33 Better Auth counted
|
|
3306
|
+
them with its non-atomic fallback, and that ends here. The gateway's install
|
|
3307
|
+
is 1.6.2 against a declared `~1.6.33`, which the lockfile refresh fixes.
|
|
3308
|
+
- `rateLimitConfigProblems(options)` names, as sentences: `storage: "database"`,
|
|
3309
|
+
a missing `customStorage`, one without `consume`, and one that is not the
|
|
3310
|
+
house's adapter.
|
|
3311
|
+
- `better-auth.test.ts` runs a real instance on both lines. It checks that the
|
|
3312
|
+
fourth sign-in from one address in ten seconds is refused while another
|
|
3313
|
+
address is not, that every row is an `auth:` key, and that Better Auth's own
|
|
3314
|
+
`rateLimit` model stays empty. A pinned test shows that
|
|
3315
|
+
`storage: "database"` does write there, so the check can fail.
|
|
3316
|
+
|
|
3317
|
+
**Adopting it, per app.** Each app's `lib/services/rate-limit.service.ts`
|
|
3318
|
+
becomes the binding above: its `RATE_LIMITS` table, its keys, and its
|
|
3319
|
+
`callerIp` options where it differs. Callers keep their names. `consume`,
|
|
3320
|
+
`usage`, `rateLimitHeaders`, `pruneRateLimits` (now `limiter.prune()`) and
|
|
3321
|
+
`authRateLimitStorage` (now `betterAuthRateLimitStorage(limiter)`) are
|
|
3322
|
+
re-exported from the binding, so routes do not change.
|
|
3323
|
+
|
|
3324
|
+
- **AltEd** keeps its 119 rules and their `failClosed`. Its `-everyone` keys
|
|
3325
|
+
become `everyone` on the rule they guard, where the two are always spent
|
|
3326
|
+
together. `harvest-control.service.ts`'s direct `findUnique` becomes `usage`,
|
|
3327
|
+
and the email in `sign-in-codes:` becomes a `privateKey`, so a window in
|
|
3328
|
+
progress at deploy starts again once. `result.failed` keeps its one reader.
|
|
3329
|
+
- **Quickie** loses `storedKey`, `privateKey`, `usage` and `ipBucket` to the
|
|
3330
|
+
package and gains `failClosed` on its paid and outbound rules. Its
|
|
3331
|
+
`callerIp` moves from the left-most entry to the right-most: on Vercel the two
|
|
3332
|
+
are the same.
|
|
3333
|
+
- **PharmaLine**'s identity gate keeps its read-then-spend order with `usage`
|
|
3334
|
+
under `failClosed: true` (it was `peek(…, { failOpen: false })`).
|
|
3335
|
+
`lib/utils/rate-limit.ts` (in memory, left-most `clientIp`) goes, and its
|
|
3336
|
+
three routes take `callerIp`. Its get/set adapter goes.
|
|
3337
|
+
- **senco, PM Tool, FB Web, KRP** move from their 125–222 lines to the
|
|
3338
|
+
binding. PM Tool's `x-vercel-forwarded-for` first is now the default. FB Web
|
|
3339
|
+
keeps its 1% prune as `autoPrune` with `after`. KRP gains pruning, which it
|
|
3340
|
+
never had, as `autoPrune`.
|
|
3341
|
+
- **MAS** takes the store without `sql`, and Better Auth gets `consume` at
|
|
3342
|
+
last. `checkAuthRouteRateLimit` and the public-route limiter stay until their
|
|
3343
|
+
routes move.
|
|
3344
|
+
- **Tracker C** keeps `autoPrune`, now scheduled after the response rather
|
|
3345
|
+
than awaited in it. Its `customRules` stay in the Better Auth options.
|
|
3346
|
+
- **Canisters** maps its unmapped table. Its single upsert, which failed open on
|
|
3347
|
+
the first race, becomes the `ON CONFLICT` count.
|
|
3348
|
+
- **The Stripe gateway**'s hourly claimed prune becomes `limiter.prune()` from
|
|
3349
|
+
its delivery cron, and Better Auth gets `consume`.
|
|
3350
|
+
|
|
3351
|
+
### `@connextar/house/analytics`, `/analytics/client`, `/analytics/react`, `/analytics/server`
|
|
3352
|
+
|
|
3353
|
+
Consent, Google Tag Manager, PostHog's configuration and gate, the same-origin
|
|
3354
|
+
`/ingest` relay, GA4's server-side `sign_up`, and server error reports. AltEd
|
|
3355
|
+
wrote these, and Quickie and PharmaLine copied them on 2026-10-21, about 900
|
|
3356
|
+
lines each. Within three weeks the copies had drifted on exactly the parts that
|
|
3357
|
+
matter. PharmaLine and Quickie stopped posthog-js asking for feature flags,
|
|
3358
|
+
whose request carries the first page's full address past `before_send`. They
|
|
3359
|
+
honoured `Sec-GPC` on the server-side `sign_up`, and reduced Prisma errors to
|
|
3360
|
+
their code. AltEd did none of the three. That was the open finding
|
|
3361
|
+
`alt-ed-posthog-flags-leak`. FB Web, MAS and Canisters start PostHog with no
|
|
3362
|
+
consent at all, and MAS and Canisters render GTM on every page. senco imports
|
|
3363
|
+
posthog-js and never initialises it.
|
|
3364
|
+
|
|
3365
|
+
| Entry point | What | Imports |
|
|
3366
|
+
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
|
|
3367
|
+
| `@connextar/house/analytics` | `defineAnalytics`, `createRedactor`, `ingestProxy`, `logsSink`, the marker attributes | nothing |
|
|
3368
|
+
| `/analytics/client` | `createBrowserAnalytics`: consent, GTM, PostHog's config, the gate, replay | nothing; the app's posthog-js is handed in |
|
|
3369
|
+
| `/analytics/react` | `<SiteAnalytics>`, `<ConsentKnownScript>`, `<CookieSettingsButton>`, `<RecordingAllowed>`, `<NotMeasured>`, `useAnalyticsConsent` | React, `next/navigation.js` |
|
|
3370
|
+
| `/analytics/server` | `createServerAnalytics` (error reports, events), `measurementProtocol` | nothing; posthog-node and `after` are handed in |
|
|
3371
|
+
|
|
3372
|
+
The server half imports no browser package, and in fact no package at all.
|
|
3373
|
+
`entry-points.test.ts` holds all four against the build, so a server route can
|
|
3374
|
+
never pull posthog-js into its bundle and the PostHog versions stay the app's.
|
|
3375
|
+
`browser.test.ts` and `server.test.ts` check the structural types against
|
|
3376
|
+
posthog-js 1.438 and posthog-node 5.56 themselves.
|
|
3377
|
+
|
|
3378
|
+
**Declaring it, once:**
|
|
3379
|
+
|
|
3380
|
+
```ts
|
|
3381
|
+
// lib/analytics/config.ts — no "use client"; imported by browser and server code alike
|
|
3382
|
+
import { defineAnalytics } from "@connextar/house/analytics";
|
|
3383
|
+
|
|
3384
|
+
export const analytics = defineAnalytics({
|
|
3385
|
+
app: "quickie", // quickie.analytics-consent.v1, quickie:cookie-settings, Symbol.for("quickie.unhandled-error-reporter")
|
|
3386
|
+
taggedPaths: ["/", "/changelog", "/compare", "/features", "/guides", "/industries", "/pricing", "/privacy", "/terms"],
|
|
3387
|
+
recordablePath: (p) => (p === "/dashboard" || p.startsWith("/dashboard/")) && !p.startsWith("/dashboard/admin"),
|
|
3388
|
+
redaction: {
|
|
3389
|
+
tokenPathPrefixes: ["/api/calendar", "/card", "/c", "/claim", "/dd/join", "/dd", "/i", "/q", "/r", "/s"],
|
|
3390
|
+
sensitiveQueryParams: ["token", "code", "state", "otp", "secret", "session_id", "email", "q", "postcode", "to"],
|
|
3391
|
+
},
|
|
3392
|
+
events: ["begin_sign_up", "go_to_app", "select_billing_interval"],
|
|
3393
|
+
});
|
|
3394
|
+
|
|
3395
|
+
// lib/analytics/browser.ts
|
|
3396
|
+
import { createBrowserAnalytics } from "@connextar/house/analytics/client";
|
|
3397
|
+
export const browser = createBrowserAnalytics(analytics);
|
|
3398
|
+
|
|
3399
|
+
// instrumentation-client.ts
|
|
3400
|
+
import posthog from "posthog-js";
|
|
3401
|
+
if (process.env.NEXT_PUBLIC_POSTHOG_KEY) posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, browser.posthogConfig());
|
|
3402
|
+
|
|
3403
|
+
// components/analytics/site-analytics.tsx — the app's own client wrapper, since a definition holding functions
|
|
3404
|
+
// cannot cross from a server component to a client one
|
|
3405
|
+
"use client";
|
|
3406
|
+
import posthog from "posthog-js";
|
|
3407
|
+
import { SiteAnalytics as HouseSiteAnalytics } from "@connextar/house/analytics/react";
|
|
3408
|
+
export function SiteAnalytics(props: { containerId: string; posthogKey: string }) {
|
|
3409
|
+
return <HouseSiteAnalytics browser={browser} posthog={posthog} leavingEvent={leavingEvent} {...props} />;
|
|
3410
|
+
}
|
|
3411
|
+
|
|
3412
|
+
// app/ingest/[...path]/route.ts
|
|
3413
|
+
export const runtime = "edge";
|
|
3414
|
+
const proxy = ingestProxy({ projectKey: process.env.NEXT_PUBLIC_POSTHOG_KEY });
|
|
3415
|
+
export const GET = proxy.handle, POST = proxy.handle;
|
|
3416
|
+
// app/ingest/i/v1/logs/route.ts
|
|
3417
|
+
export const POST = () => logsSink();
|
|
3418
|
+
```
|
|
3419
|
+
|
|
3420
|
+
**The rules, the strictest of the three copies:**
|
|
3421
|
+
|
|
3422
|
+
- **Consent before anything is loaded or kept.** GTM loads only after a yes, on
|
|
3423
|
+
a tagged page, and `loadGtm` checks all three itself. A document that began
|
|
3424
|
+
on a private page reloads rather than loading GTM into it, and arriving on a
|
|
3425
|
+
private page with GTM loaded reloads too. PostHog keeps nothing
|
|
3426
|
+
(`persistence: "memory"`, `person_profiles: "never"`). Its gate sends nothing
|
|
3427
|
+
but a redacted error until somebody says yes, on a page that may be measured.
|
|
3428
|
+
Consent Mode v2 grants analytics only. Ads, ad data and personalisation are
|
|
3429
|
+
denied.
|
|
3430
|
+
- **Global Privacy Control is a no**, and outranks a stored yes, in the
|
|
3431
|
+
browser and on the server. `optsOut` adds an app's own reason: AltEd's
|
|
3432
|
+
learner using the family's browser.
|
|
3433
|
+
- **Never a private page, never while viewing as somebody.** A page is measured
|
|
3434
|
+
only if it is tagged (whole segments: `/pricing` covers `/pricing/teams`,
|
|
3435
|
+
never `/pricingx`), or is one of the app's `recordablePath`s with
|
|
3436
|
+
`<RecordingAllowed />` on it. The app renders that only for an ordinary member,
|
|
3437
|
+
never an administrator or a view. Nothing is measured while `ViewingAsBanner`
|
|
3438
|
+
(`data-viewing-as`) or `<NotMeasured />` (`data-analytics-private`) is on the
|
|
3439
|
+
page, tagged or not. `<NotMeasured />` is for a public address a signed-in
|
|
3440
|
+
person sees differently, like the internal changelog a PharmaLine
|
|
3441
|
+
administrator reads at `/changelog` (finding `pharmaline-signed-in-on-tagged-pages`).
|
|
3442
|
+
AltEd's `startsWith("/dashboard")` also matched `/dashboardX` and the admin
|
|
3443
|
+
pages. With no `recordablePath`, nothing signed-in is ever measured, which is
|
|
3444
|
+
PharmaLine's rule.
|
|
3445
|
+
- **One gate, deny by default** (`before_send`). An `$exception` always goes,
|
|
3446
|
+
redacted whole by walking its plain objects, which is Quickie's and
|
|
3447
|
+
PharmaLine's way. AltEd stringified it to JSON, which only worked because it
|
|
3448
|
+
had no number rule. Every other event goes only while `measuredHere()`. Every
|
|
3449
|
+
property whose name says url, pathname, referrer or href is cleaned, in
|
|
3450
|
+
`properties`, `$set` and `$set_once`. A heatmap batch keeps only this page's
|
|
3451
|
+
clicks. Replay's own addresses (rrweb Meta and Custom events) are cleaned.
|
|
3452
|
+
Dead clicks are off, and one that arrives anyway is stripped of its text and
|
|
3453
|
+
every attribute but its class.
|
|
3454
|
+
- **No feature flags.** `advanced_disable_flags` is on, and the relay refuses
|
|
3455
|
+
`/flags` and `/decide` (PharmaLine security round 5, S1). It also refuses
|
|
3456
|
+
`/i/v1/logs`, which `logsSink` answers itself, and anything that is not on
|
|
3457
|
+
the list posthog-js needs (`/e`, `/i/v0/e`, `/s`, `/batch`, `/static`,
|
|
3458
|
+
`/array`). With `projectKey`, `/array/*` serves this project's configuration
|
|
3459
|
+
only. Quickie's allowed any project's.
|
|
3460
|
+
- **The relay forwards** `content-type`, `content-encoding`, `user-agent` and
|
|
3461
|
+
`accept`, and returns `content-type` and `cache-control`. No cookie, no
|
|
3462
|
+
referer, no authorization, no client address. Next's rewrites, which FB Web,
|
|
3463
|
+
MAS and Canisters use, forward all of them.
|
|
3464
|
+
- **Replay** masks every input and all text, blocks images, video, canvas,
|
|
3465
|
+
iframes and SVG images, and records no headers or bodies. It starts only while
|
|
3466
|
+
measured (`syncRecording`, which `<SiteAnalytics>` calls on each page and each
|
|
3467
|
+
answer). Heatmap clicks gathered before measuring began are cleared, never
|
|
3468
|
+
sent.
|
|
3469
|
+
- **Cookies are cleared from this host only** on a no: `_ga`, `_ga_*`, `_gid`
|
|
3470
|
+
on the host, `.host` and, for `www.`, the bare domain. That is Quickie's and
|
|
3471
|
+
PharmaLine's rule, paired with `cookie_domain: none` in the GTM container.
|
|
3472
|
+
AltEd cleared every parent domain, which on a shared parent like
|
|
3473
|
+
`.connextar.com` can clear another of our sites' cookies.
|
|
3474
|
+
|
|
3475
|
+
**Redaction.** `createRedactor(rules)`, which `defineAnalytics` builds from
|
|
3476
|
+
`redaction`, gives `redact`, `cleanUrl` and `redactDeep`:
|
|
3477
|
+
|
|
3478
|
+
- **Token paths:** the segment after an app's `tokenPathPrefixes`, in plain and
|
|
3479
|
+
percent-encoded forms, becomes `:token`. A route pattern's placeholder
|
|
3480
|
+
(`/i/[token]`) is left alone.
|
|
3481
|
+
- **Ids:** a cuid or UUID path segment becomes `[id]`, and so does the segment
|
|
3482
|
+
after a named collection (`idSegments`, PharmaLine's `/patients/<id>`), except
|
|
3483
|
+
`new` and `import`.
|
|
3484
|
+
- **Query values:** every one is redacted, and `sensitiveQueryParams` are also
|
|
3485
|
+
redacted where only half an address appears.
|
|
3486
|
+
- **Emails, long digit runs, UK postcodes:** emails, runs of ten or more
|
|
3487
|
+
digits (cards, phone numbers) and UK postcodes are replaced. AltEd had none
|
|
3488
|
+
of these three rules.
|
|
3489
|
+
- **Patterns:** the app's own `patterns`, applied last.
|
|
3490
|
+
- **`cleanUrl`:** for this site's addresses it keeps the path and redacts it in
|
|
3491
|
+
full, which is PharmaLine's rule and the strictest. It drops the query and
|
|
3492
|
+
fragment. For anybody else's address it keeps only the origin.
|
|
3493
|
+
|
|
3494
|
+
**The server half:**
|
|
3495
|
+
|
|
3496
|
+
```ts
|
|
3497
|
+
// lib/server/analytics.ts
|
|
3498
|
+
import { createServerAnalytics, measurementProtocol } from "@connextar/house/analytics/server";
|
|
3499
|
+
import { headers } from "next/headers";
|
|
3500
|
+
import { after } from "next/server";
|
|
3501
|
+
import { PostHog } from "posthog-node";
|
|
3502
|
+
|
|
3503
|
+
let client: PostHog | null = null;
|
|
3504
|
+
export const server = createServerAnalytics({
|
|
3505
|
+
analytics,
|
|
3506
|
+
posthog: () => (key ? (client ??= new PostHog(key, { host, flushAt: 1, flushInterval: 0 })) : null),
|
|
3507
|
+
isViewingAs: () => viewing.isViewingAs(), // the app's viewingAsGate
|
|
3508
|
+
requestHeaders: () => headers(),
|
|
3509
|
+
after,
|
|
3510
|
+
});
|
|
3511
|
+
export const ga4 = measurementProtocol({
|
|
3512
|
+
measurementId: process.env.GA4_MEASUREMENT_ID,
|
|
3513
|
+
apiSecret: process.env.GA4_API_SECRET,
|
|
3514
|
+
productionHosts: ["quickie.cx", "www.quickie.cx"],
|
|
3515
|
+
});
|
|
3516
|
+
|
|
3517
|
+
// instrumentation.ts
|
|
3518
|
+
export async function register() {
|
|
3519
|
+
if (process.env.NEXT_RUNTIME === "nodejs") (await import("@lib/server/analytics")).server.registerErrorReporter();
|
|
3520
|
+
}
|
|
3521
|
+
export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
|
|
3522
|
+
if (process.env.NEXT_RUNTIME !== "nodejs") return;
|
|
3523
|
+
await (await import("@lib/server/analytics")).server.onRequestError(error, request, context);
|
|
3524
|
+
};
|
|
3525
|
+
|
|
3526
|
+
// lib/utils/api.utils.ts — handleError's 500s
|
|
3527
|
+
registeredErrorReporter(analytics)(error, { source: "api" });
|
|
3528
|
+
|
|
3529
|
+
// auth.ts
|
|
3530
|
+
databaseHooks: { user: { create: { after: async (_user, context) => ga4.recordSignUp(context) } } },
|
|
3531
|
+
```
|
|
3532
|
+
|
|
3533
|
+
- **Error reports** come from `onRequestError` and the handled 500s. Each is
|
|
3534
|
+
sent anonymously, with no distinct id and `$process_person_profile: false`.
|
|
3535
|
+
A Prisma error becomes `Prisma P2002`, or "message withheld" without a code,
|
|
3536
|
+
because a Prisma message quotes the query's values. Any other message is
|
|
3537
|
+
redacted and cut to 1,000 characters. The stack is rebuilt from V8 frames
|
|
3538
|
+
only, each redacted, taken after the original `name: message` head, so a
|
|
3539
|
+
message line like ` at 12 High Street` cannot pass as a frame (Quickie's
|
|
3540
|
+
rule). `onRequestError` sends the route pattern, never the URL.
|
|
3541
|
+
`reportServerErrorAfterResponse` waits for `after`, and sends at once
|
|
3542
|
+
outside a request.
|
|
3543
|
+
- **Product events** (`captureServerEvent`) are refused while viewing as
|
|
3544
|
+
somebody. This is senco's rule; Quickie's had none. A lookup that throws
|
|
3545
|
+
counts as a view. They are also refused for a request with `Sec-GPC: 1`, and
|
|
3546
|
+
their properties are redacted. senco's 69 call sites keep their names.
|
|
3547
|
+
- **`sign_up` by Measurement Protocol** is sent only on a production host, never
|
|
3548
|
+
with `Sec-GPC: 1`, and only with both Google cookies. A stray `_ga` from
|
|
3549
|
+
another site is not a visit; AltEd accepted one. A malformed cookie is read
|
|
3550
|
+
as itself, never thrown. Clearing the cookies on a no is what withdraws it.
|
|
3551
|
+
There is a two-second timeout, and it never throws into the sign-up.
|
|
3552
|
+
|
|
3553
|
+
**Adopting it, per app.**
|
|
3554
|
+
|
|
3555
|
+
| App | Today | Moves to |
|
|
3556
|
+
| ---------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
3557
|
+
| AltEd | the origin copy, without the three fixes | the module. `optsOut` is the learner browser. Its CSP (`lib/security/csp.ts`) and friction counting stay. `consentVersion: 2` keeps its key. |
|
|
3558
|
+
| Quickie | the strictest copy | the module. `leavingEvent`, `captureServerEvent` gains the viewing-as gate, and `lib/analytics-redaction.ts` becomes `redaction`. |
|
|
3559
|
+
| PharmaLine | close behind Quickie, measures public pages only | the module with no `recordablePath`. `<NotMeasured />` on `/changelog` for an administrator. |
|
|
3560
|
+
| FB Web | PostHog with no consent, defaults everywhere, rewrites forwarding cookies | the module: a consent card, the relay routes, the gate. `onRequestError` stops reading a distinct id from the PostHog cookie. |
|
|
3561
|
+
| MAS | PostHog and GTM on every page, no consent; checkout captures a Stripe `clientSecret` | the module. The GTM line goes, and the checkout's `identify` and `clientSecret` captures go. |
|
|
3562
|
+
| Canisters | PostHog and GTM on every page, no consent; `CaptureLink` | the module. `CaptureLink` goes through `track`. |
|
|
3563
|
+
| senco | posthog-js imported, never initialised; server events with a viewing-as gate, no redaction | the server half (events redacted, its gate kept, error reports). The browser half only if the owner wants public-page measurement. |
|
|
3564
|
+
|
|
3565
|
+
Each app's own cookie card in Settings keeps its UI primitives and takes
|
|
3566
|
+
`useAnalyticsConsent(browser)`. The pre-paint CSS rule,
|
|
3567
|
+
`html[data-consent-known] [data-cookie-card]:not([data-reopened]) { display: none }`,
|
|
3568
|
+
stays in each app's global stylesheet. The env names are already the same
|
|
3569
|
+
everywhere: `NEXT_PUBLIC_POSTHOG_KEY`, `NEXT_PUBLIC_POSTHOG_HOST`,
|
|
3570
|
+
`NEXT_PUBLIC_GTM_ID`, `GA4_MEASUREMENT_ID`, `GA4_API_SECRET`.
|
|
3571
|
+
|
|
3060
3572
|
### Styles — `@connextar/house/house.css`
|
|
3061
3573
|
|
|
3062
3574
|
What the components need that utility classes cannot say: rich text, the editor's
|