@benchme/site-kit 0.10.0 → 0.11.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.
Files changed (61) hide show
  1. package/dist/auth-service.d.ts +9 -1
  2. package/dist/auth-service.js +14 -3
  3. package/dist/auth-service.js.map +1 -1
  4. package/dist/domain-error.d.ts +6 -0
  5. package/dist/domain-error.js +12 -0
  6. package/dist/domain-error.js.map +1 -0
  7. package/dist/doors/caller.d.ts +25 -0
  8. package/dist/doors/caller.js +22 -0
  9. package/dist/doors/caller.js.map +1 -0
  10. package/dist/doors/door.d.ts +23 -0
  11. package/dist/doors/door.js +30 -0
  12. package/dist/doors/door.js.map +1 -0
  13. package/dist/doors/register-doors.d.ts +44 -0
  14. package/dist/doors/register-doors.js +92 -0
  15. package/dist/doors/register-doors.js.map +1 -0
  16. package/dist/doors/session-carrier.d.ts +42 -0
  17. package/dist/doors/session-carrier.js +44 -0
  18. package/dist/doors/session-carrier.js.map +1 -0
  19. package/dist/doors/sign-in-tools.d.ts +23 -0
  20. package/dist/doors/sign-in-tools.js +69 -0
  21. package/dist/doors/sign-in-tools.js.map +1 -0
  22. package/dist/doors/sign-in.d.ts +20 -0
  23. package/dist/doors/sign-in.js +31 -0
  24. package/dist/doors/sign-in.js.map +1 -0
  25. package/dist/index.d.ts +16 -2
  26. package/dist/index.js +16 -2
  27. package/dist/index.js.map +1 -1
  28. package/dist/ledger/auth-rules.d.ts +11 -0
  29. package/dist/ledger/auth-rules.js +21 -0
  30. package/dist/ledger/auth-rules.js.map +1 -0
  31. package/dist/ledger/entry.d.ts +219 -0
  32. package/dist/ledger/entry.js +40 -0
  33. package/dist/ledger/entry.js.map +1 -0
  34. package/dist/ledger/ledger-route.d.ts +15 -0
  35. package/dist/ledger/ledger-route.js +25 -0
  36. package/dist/ledger/ledger-route.js.map +1 -0
  37. package/dist/ledger/ledger.d.ts +38 -0
  38. package/dist/ledger/ledger.js +55 -0
  39. package/dist/ledger/ledger.js.map +1 -0
  40. package/dist/ledger/ledgered.d.ts +36 -0
  41. package/dist/ledger/ledgered.js +108 -0
  42. package/dist/ledger/ledgered.js.map +1 -0
  43. package/dist/ledger/rules.d.ts +45 -0
  44. package/dist/ledger/rules.js +22 -0
  45. package/dist/ledger/rules.js.map +1 -0
  46. package/dist/ledger/schema.d.ts +23 -0
  47. package/dist/ledger/schema.js +56 -0
  48. package/dist/ledger/schema.js.map +1 -0
  49. package/dist/mcp-server.d.ts +11 -6
  50. package/dist/mcp-server.js +24 -15
  51. package/dist/mcp-server.js.map +1 -1
  52. package/dist/refusal.d.ts +8 -0
  53. package/dist/refusal.js +8 -0
  54. package/dist/refusal.js.map +1 -0
  55. package/dist/users-repo.d.ts +32 -0
  56. package/dist/users-repo.js +69 -0
  57. package/dist/users-repo.js.map +1 -1
  58. package/dist/webmcp.d.ts +2 -1
  59. package/dist/webmcp.js +4 -2
  60. package/dist/webmcp.js.map +1 -1
  61. package/package.json +2 -2
@@ -0,0 +1,108 @@
1
+ import { DomainError } from "../domain-error.js";
2
+ import { SIGN_IN_REQUIRED_CODE, SignInRequired } from "../doors/sign-in.js";
3
+ import { refusalOf } from "../refusal.js";
4
+ import { NOT_FOUND_CODE } from "./entry.js";
5
+ /** For a site whose rows are not in Postgres (tests): each write runs as it comes, with nothing to make atomic. */
6
+ export const untransacted = { run: (fn) => fn() };
7
+ /**
8
+ * A site's rules with the ledger kept. Pages, REST and the MCP tools (and,
9
+ * through the bridge, the WebMCP tools) all reach a site's rows through one
10
+ * repository, so recording there records every door, and no route or tool can
11
+ * leave it out. The wrapped object is the repository's own type: every caller
12
+ * keeps calling what it called.
13
+ *
14
+ * Each recorded method notes who called (the door and whoever is signed in,
15
+ * from the request's caller scope), then what came of it: `ok`, or `refused`
16
+ * with the rule's reason code. A read that found nothing is refused with
17
+ * NOT_FOUND. The verifier's own reads pass through unrecorded. A call with no
18
+ * caller in scope is a door that never said which one it is, and it throws.
19
+ *
20
+ * It is also where a write asks for a sign-in, for the same reason: asked
21
+ * here, every door asks the same, and a new door cannot forget to. A write by
22
+ * nobody is recorded as refused with the one sign-in code and never reaches
23
+ * the repository; the door it came through says so in its own way.
24
+ *
25
+ * A write (or a step of signing up or in) and its entry are one transaction:
26
+ * both are kept, or neither is, so the ledger never shows a change that did
27
+ * not happen, nor misses one that did. A refused write changed nothing: its
28
+ * transaction is rolled back and the refusal is kept on its own.
29
+ */
30
+ export function ledgered(repo, rules, d) {
31
+ const ruleOf = (name) => (Object.hasOwn(rules, name) ? rules[name] : undefined);
32
+ return new Proxy(repo, {
33
+ get(target, name) {
34
+ const member = Reflect.get(target, name, target);
35
+ // What every object has (toString, constructor …) is no method of the site's rules.
36
+ if (typeof member !== "function" || typeof name === "symbol" || name in Object.prototype)
37
+ return member;
38
+ const method = member;
39
+ const rule = ruleOf(name);
40
+ if (!rule) {
41
+ return () => {
42
+ throw new Error(`${String(name)} has no ledger rule: say whether it is a read, a write or unrecorded`);
43
+ };
44
+ }
45
+ if (rule.kind === "skip")
46
+ return method.bind(target);
47
+ return (ws, ...args) => recorded(target, method, String(name), rule, d, ws, args);
48
+ },
49
+ });
50
+ }
51
+ async function recorded(target, method, name, rule, d, ws, args) {
52
+ const caller = d.callers.current();
53
+ if (!caller)
54
+ throw new Error(`${name} was called outside a door: no caller is in scope`);
55
+ if (caller.observer) {
56
+ if (rule.kind !== "read")
57
+ throw new DomainError("READ_ONLY", "the verifier only reads", 403);
58
+ return method.call(target, ws, ...args);
59
+ }
60
+ const subjectId = rule.subject?.id(args) ?? null;
61
+ const entry = (result, outcome, code, actor) => ({
62
+ kind: rule.kind,
63
+ entity: { type: rule.entity, id: rule.id(args, result) ?? null },
64
+ subject: rule.subject && subjectId ? { type: rule.subject.type, id: subjectId } : null,
65
+ action: rule.action,
66
+ door: caller.door,
67
+ actor,
68
+ outcome,
69
+ code,
70
+ });
71
+ const actor = await caller.actor();
72
+ if (rule.kind === "write" && actor === null) {
73
+ await d.ledger.record(ws, entry(undefined, "refused", SIGN_IN_REQUIRED_CODE, null));
74
+ throw new SignInRequired(caller.door);
75
+ }
76
+ if (rule.kind === "read")
77
+ return recordedRead(target, method, d, ws, args, entry, actor);
78
+ try {
79
+ return await d.transactions.run(async () => {
80
+ const result = await method.call(target, ws, ...args);
81
+ await d.ledger.record(ws, entry(result, "ok", null, actor));
82
+ return result;
83
+ });
84
+ }
85
+ catch (err) {
86
+ const refusal = refusalOf(err);
87
+ if (refusal)
88
+ await d.ledger.record(ws, entry(undefined, "refused", refusal.code, actor));
89
+ throw err;
90
+ }
91
+ }
92
+ /** A read changes nothing, so it needs no transaction: what it found, or why it found nothing, is kept after it. */
93
+ async function recordedRead(target, method, d, ws, args, entry, actor) {
94
+ let result;
95
+ try {
96
+ result = await method.call(target, ws, ...args);
97
+ }
98
+ catch (err) {
99
+ const refusal = refusalOf(err);
100
+ if (refusal)
101
+ await d.ledger.record(ws, entry(undefined, "refused", refusal.code, actor));
102
+ throw err;
103
+ }
104
+ const missing = result === null || result === undefined;
105
+ await d.ledger.record(ws, missing ? entry(undefined, "refused", NOT_FOUND_CODE, actor) : entry(result, "ok", null, actor));
106
+ return result;
107
+ }
108
+ //# sourceMappingURL=ledgered.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledgered.js","sourceRoot":"","sources":["../../src/ledger/ledgered.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAuB,MAAM,YAAY,CAAC;AAWjE,mHAAmH;AACnH,MAAM,CAAC,MAAM,YAAY,GAA8B,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;AAK7E;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UA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AC,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,OAAO;YAAE,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;QACzF,MAAM,GAAG,CAAC;IACZ,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC;IACxD,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;IAC3H,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { type LedgerKind } from "./entry.js";
2
+ /**
3
+ * How one method of a site's rules shows in the ledger. `id` names the entity
4
+ * from the call's arguments (after the workspace) and, when the call returned,
5
+ * its result: a create has no id until the row exists.
6
+ */
7
+ export type Recorded<A extends unknown[], T> = {
8
+ kind: LedgerKind;
9
+ /** The entity's type, in the site's own word: "booking", "order", "showtime". */
10
+ entity: string;
11
+ action: string;
12
+ id: (args: A, result: T | undefined) => string | null | undefined;
13
+ /** What the request is about besides its entity (see `about`): kept made or refused, since it comes from the request. */
14
+ subject?: Subject<A>;
15
+ };
16
+ /** The thing a request names besides the entity it writes: `about("order", ([req]) => req.orderNo)`. */
17
+ export type Subject<A extends unknown[]> = {
18
+ type: string;
19
+ id: (args: A) => string | null | undefined;
20
+ };
21
+ /** A method the ledger leaves out: a list, a search, a lookup of what is on offer. */
22
+ export type Unrecorded = {
23
+ kind: "skip";
24
+ };
25
+ export type LedgerRule<A extends unknown[], T> = Recorded<A, T> | Unrecorded;
26
+ /**
27
+ * One rule for EVERY method of a site's rules, by name. The mapped type is the
28
+ * point: a method added to a repository does not compile until someone says
29
+ * whether it is a read, a write or neither, so none is left out by forgetting.
30
+ */
31
+ export type LedgerRules<R> = {
32
+ [K in keyof R]: R[K] extends (ws: string, ...args: infer A) => Promise<infer T> ? LedgerRule<A, T> : never;
33
+ };
34
+ export declare const unrecorded: Unrecorded;
35
+ /** A read of one entity: a booking, an order, a showtime's seat map, a product. */
36
+ export declare function read<A extends unknown[], T>(entity: string, id: Recorded<A, T>["id"]): LedgerRule<A, T>;
37
+ /**
38
+ * A change to the site's rows, made or refused. Only someone signed in may make one. A create names what it is about
39
+ * (`about`), so that its refusal, which has no entity yet, still says which order, showtime or event it was for.
40
+ */
41
+ export declare function write<A extends unknown[], T>(entity: string, action: string, id: Recorded<A, T>["id"], subject?: Subject<A>): LedgerRule<A, T>;
42
+ /** The subject of a write: its type, and its id from the call's arguments. */
43
+ export declare function about<A extends unknown[]>(type: string, id: Subject<A>["id"]): Subject<A>;
44
+ /** A step of signing up or in. Recorded, and never counted as a change to what the site sells. */
45
+ export declare function authStep<A extends unknown[], T>(action: string, id: Recorded<A, T>["id"]): LedgerRule<A, T>;
@@ -0,0 +1,22 @@
1
+ import { READ_ACTION } from "./entry.js";
2
+ export const unrecorded = { kind: "skip" };
3
+ /** A read of one entity: a booking, an order, a showtime's seat map, a product. */
4
+ export function read(entity, id) {
5
+ return { kind: "read", entity, action: READ_ACTION, id };
6
+ }
7
+ /**
8
+ * A change to the site's rows, made or refused. Only someone signed in may make one. A create names what it is about
9
+ * (`about`), so that its refusal, which has no entity yet, still says which order, showtime or event it was for.
10
+ */
11
+ export function write(entity, action, id, subject) {
12
+ return { kind: "write", entity, action, id, ...(subject ? { subject } : {}) };
13
+ }
14
+ /** The subject of a write: its type, and its id from the call's arguments. */
15
+ export function about(type, id) {
16
+ return { type, id };
17
+ }
18
+ /** A step of signing up or in. Recorded, and never counted as a change to what the site sells. */
19
+ export function authStep(action, id) {
20
+ return { kind: "auth", entity: "account", action, id };
21
+ }
22
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.js","sourceRoot":"","sources":["../../src/ledger/rules.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmB,MAAM,YAAY,CAAC;AA+B1D,MAAM,CAAC,MAAM,UAAU,GAAe,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAEvD,mFAAmF;AACnF,MAAM,UAAU,IAAI,CAAyB,MAAc,EAAE,EAAwB;IACnF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;AAC3D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,KAAK,CAAyB,MAAc,EAAE,MAAc,EAAE,EAAwB,EAAE,OAAoB;IAC1H,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAChF,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,KAAK,CAAsB,IAAY,EAAE,EAAoB;IAC3E,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;AACtB,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,QAAQ,CAAyB,MAAc,EAAE,EAAwB;IACvF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AACzD,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The ledger's table, for one app schema. Every site's own migration
3
+ * (`apps/<app>/migrations/*_ledger.sql`) carries exactly this text for its
4
+ * schema, as each carries the users and sessions tables: the apps own their
5
+ * schemas, and a test holds every copy to this one.
6
+ *
7
+ * `at` is `clock_timestamp()`, the wall clock at the insert and not the
8
+ * transaction's start, and the database's clock is the one clock every site
9
+ * shares, so entries of two sites can be put in order.
10
+ */
11
+ export declare function ledgerTableSql(schema: string): string;
12
+ /**
13
+ * The ledger's second migration: what a request was about (`subject`), so a refused create, which has no entity
14
+ * id, still names the order, showtime or event it was for. Every site's `*_ledger_subject.sql` carries this text.
15
+ */
16
+ export declare function ledgerSubjectSql(schema: string): string;
17
+ /** The ledger's migrations, in order: the file suffix each site names one with, and its text for that site's schema. */
18
+ export declare const LEDGER_MIGRATIONS: readonly {
19
+ suffix: string;
20
+ sql: (schema: string) => string;
21
+ }[];
22
+ /** Every ledger migration for one schema, as one script: what a test that builds a ledger table of its own runs. */
23
+ export declare const ledgerSql: (schema: string) => string;
@@ -0,0 +1,56 @@
1
+ const SCHEMA = /^[a-z_][a-z0-9_]*$/;
2
+ const checked = (schema) => {
3
+ if (!SCHEMA.test(schema))
4
+ throw new Error(`invalid schema name: ${schema}`);
5
+ return schema;
6
+ };
7
+ /**
8
+ * The ledger's table, for one app schema. Every site's own migration
9
+ * (`apps/<app>/migrations/*_ledger.sql`) carries exactly this text for its
10
+ * schema, as each carries the users and sessions tables: the apps own their
11
+ * schemas, and a test holds every copy to this one.
12
+ *
13
+ * `at` is `clock_timestamp()`, the wall clock at the insert and not the
14
+ * transaction's start, and the database's clock is the one clock every site
15
+ * shares, so entries of two sites can be put in order.
16
+ */
17
+ export function ledgerTableSql(schema) {
18
+ checked(schema);
19
+ return `CREATE TABLE IF NOT EXISTS ${schema}.ledger (
20
+ workspace_id TEXT NOT NULL REFERENCES core.workspaces(id) ON DELETE CASCADE,
21
+ seq BIGINT GENERATED ALWAYS AS IDENTITY,
22
+ at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
23
+ kind TEXT NOT NULL CHECK (kind IN ('read', 'write', 'auth')),
24
+ entity_type TEXT NOT NULL,
25
+ entity_id TEXT,
26
+ action TEXT NOT NULL,
27
+ door TEXT NOT NULL CHECK (door IN ('page', 'rest', 'mcp', 'webmcp')),
28
+ actor TEXT,
29
+ outcome TEXT NOT NULL CHECK (outcome IN ('ok', 'refused')),
30
+ code TEXT,
31
+ PRIMARY KEY (workspace_id, seq)
32
+ );
33
+ `;
34
+ }
35
+ /**
36
+ * The ledger's second migration: what a request was about (`subject`), so a refused create, which has no entity
37
+ * id, still names the order, showtime or event it was for. Every site's `*_ledger_subject.sql` carries this text.
38
+ */
39
+ export function ledgerSubjectSql(schema) {
40
+ const s = checked(schema);
41
+ return `ALTER TABLE ${s}.ledger ADD COLUMN IF NOT EXISTS subject_type TEXT;
42
+ ALTER TABLE ${s}.ledger ADD COLUMN IF NOT EXISTS subject_id TEXT;
43
+ DO $$ BEGIN
44
+ ALTER TABLE ${s}.ledger ADD CONSTRAINT ledger_subject_whole CHECK ((subject_type IS NULL) = (subject_id IS NULL));
45
+ EXCEPTION WHEN duplicate_object THEN NULL;
46
+ END $$;
47
+ `;
48
+ }
49
+ /** The ledger's migrations, in order: the file suffix each site names one with, and its text for that site's schema. */
50
+ export const LEDGER_MIGRATIONS = [
51
+ { suffix: "ledger", sql: ledgerTableSql },
52
+ { suffix: "ledger_subject", sql: ledgerSubjectSql },
53
+ ];
54
+ /** Every ledger migration for one schema, as one script: what a test that builds a ledger table of its own runs. */
55
+ export const ledgerSql = (schema) => LEDGER_MIGRATIONS.map((m) => m.sql(schema)).join("\n");
56
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/ledger/schema.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,GAAG,oBAAoB,CAAC;AACpC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAU,EAAE;IACzC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,EAAE,CAAC,CAAC;IAC5E,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,MAAc;IAC3C,OAAO,CAAC,MAAM,CAAC,CAAC;IAChB,OAAO,8BAA8B,MAAM;;;;;;;;;;;;;;CAc5C,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAc;IAC7C,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1B,OAAO,eAAe,CAAC;cACX,CAAC;;gBAEC,CAAC;;;CAGhB,CAAC;AACF,CAAC;AAED,wHAAwH;AACxH,MAAM,CAAC,MAAM,iBAAiB,GAAmE;IAC/F,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,cAAc,EAAE;IACzC,EAAE,MAAM,EAAE,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE;CACpD,CAAC;AAEF,oHAAoH;AACpH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,MAAc,EAAU,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC"}
@@ -1,12 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import type { FastifyInstance } from "fastify";
3
3
  import type { ToolRegistry } from "./tool-registry.js";
4
- /** Thrown by a tool/domain operation to render a structured error (never a 500). */
5
- export declare class DomainError extends Error {
6
- readonly code: string;
7
- readonly status: number;
8
- constructor(code: string, message: string, status?: number);
9
- }
4
+ export { DomainError } from "./domain-error.js";
10
5
  export type McpDeps<C> = {
11
6
  serverName: string;
12
7
  version: string;
@@ -15,7 +10,17 @@ export type McpDeps<C> = {
15
10
  context: (workspaceId: string, prefix: string) => C;
16
11
  /** Register anything beyond tools (resources, prompts) — run after the tool loop. */
17
12
  extras?: (server: McpServer, ctx: C) => void;
13
+ /**
14
+ * For a site whose tools sign in (`Doors.withSignIn`): hand each client a
15
+ * session id when it initializes, which it then repeats on every request and
16
+ * a sign-in is kept under, and answer a page's bridge in one JSON body so
17
+ * the answer can carry the browser's session cookie. The server stays
18
+ * stateless either way: the id is a name, held nowhere here.
19
+ */
20
+ sessions?: boolean;
18
21
  };
22
+ /** An MCP session's id, told apart at a glance from a site's own session tokens. */
23
+ export declare const newMcpSessionId: () => string;
19
24
  /** A fresh MCP server bound to one workspace (stateless per request). */
20
25
  export declare function buildMcpServer<C>(d: McpDeps<C>, ctx: C): McpServer;
21
26
  /**
@@ -1,16 +1,12 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
- /** Thrown by a tool/domain operation to render a structured error (never a 500). */
4
- export class DomainError extends Error {
5
- code;
6
- status;
7
- constructor(code, message, status = 422) {
8
- super(message);
9
- this.code = code;
10
- this.status = status;
11
- this.name = "DomainError";
12
- }
13
- }
3
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { doorOf } from "./doors/door.js";
6
+ import { refusalOf } from "./refusal.js";
7
+ export { DomainError } from "./domain-error.js";
8
+ /** An MCP session's id, told apart at a glance from a site's own session tokens. */
9
+ export const newMcpSessionId = () => `mcp-${randomUUID()}`;
14
10
  /** A fresh MCP server bound to one workspace (stateless per request). */
15
11
  export function buildMcpServer(d, ctx) {
16
12
  const server = new McpServer({ name: d.serverName, version: d.version });
@@ -21,9 +17,10 @@ export function buildMcpServer(d, ctx) {
21
17
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
22
18
  }
23
19
  catch (err) {
24
- if (err instanceof DomainError) {
25
- return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: err.code, message: err.message }) }] };
26
- }
20
+ // A rule's refusal, a sign-in's, or a write by nobody: the tool's own answer, never a protocol error.
21
+ const refusal = refusalOf(err);
22
+ if (refusal)
23
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: refusal.code, message: refusal.message }) }] };
27
24
  throw err;
28
25
  }
29
26
  });
@@ -53,7 +50,7 @@ export function registerMcp(app, d) {
53
50
  });
54
51
  app.all("/mcp", async (req, reply) => {
55
52
  const server = buildMcpServer(d, d.context(req.workspaceId, req.prefix));
56
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
53
+ const transport = new StreamableHTTPServerTransport(d.sessions ? sessionOptions(req) : { sessionIdGenerator: undefined });
57
54
  reply.hijack();
58
55
  reply.raw.on("close", () => {
59
56
  void transport.close();
@@ -63,4 +60,16 @@ export function registerMcp(app, d) {
63
60
  await transport.handleRequest(req.raw, reply.raw, req.body);
64
61
  });
65
62
  }
63
+ /**
64
+ * One transport per request, as ever. The request that initializes gets a
65
+ * session id to repeat; every later one is taken as it comes, with no session
66
+ * held here to check it against. A page's bridge reads one JSON body.
67
+ */
68
+ function sessionOptions(req) {
69
+ const messages = Array.isArray(req.body) ? req.body : [req.body];
70
+ return {
71
+ sessionIdGenerator: messages.some((m) => isInitializeRequest(m)) ? newMcpSessionId : undefined,
72
+ enableJsonResponse: doorOf(req.url, req.headers) === "webmcp",
73
+ };
74
+ }
66
75
  //# sourceMappingURL=mcp-server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-server.js","sourceRoot":"","sources":["../src/mcp-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AAInG,oFAAoF;AACpF,MAAM,OAAO,WAAY,SAAQ,KAAK;IAEzB;IAEA;IAHX,YACW,IAAY,EACrB,OAAe,EACN,SAAS,GAAG;QAErB,KAAK,CAAC,OAAO,CAAC,CAAC;QAJN,SAAI,GAAJ,IAAI,CAAQ;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K,MAAM,CAAC,KAAK,EAAE,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAChC,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAC9D,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAS,cAAc,CAAC,GAAmB;IACzC,MAAM,QAAQ,GAAc,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC5E,OAAO;QACL,kBAAkB,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS;QAC9F,kBAAkB,EAAE,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,QAAQ;KAC9D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,8 @@
1
+ /** What a site says when it refuses something: a reason code a caller can act on, the words, and the HTTP status. */
2
+ export type Refusal = {
3
+ code: string;
4
+ message: string;
5
+ status: number;
6
+ };
7
+ /** The refusal an error carries, or null for anything that is not the site saying no (a bug, a lost connection). */
8
+ export declare function refusalOf(err: unknown): Refusal | null;
@@ -0,0 +1,8 @@
1
+ import { AuthError } from "./auth-service.js";
2
+ import { DomainError } from "./domain-error.js";
3
+ import { SignInRequired } from "./doors/sign-in.js";
4
+ /** The refusal an error carries, or null for anything that is not the site saying no (a bug, a lost connection). */
5
+ export function refusalOf(err) {
6
+ return err instanceof DomainError || err instanceof AuthError || err instanceof SignInRequired ? { code: err.code, message: err.message, status: err.status } : null;
7
+ }
8
+ //# sourceMappingURL=refusal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refusal.js","sourceRoot":"","sources":["../src/refusal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAKpD,oHAAoH;AACpH,MAAM,UAAU,SAAS,CAAC,GAAY;IACpC,OAAO,GAAG,YAAY,WAAW,IAAI,GAAG,YAAY,SAAS,IAAI,GAAG,YAAY,cAAc,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACvK,CAAC"}
@@ -43,3 +43,35 @@ export declare class PgUsersRepo implements UsersRepo {
43
43
  setApiToken(ws: string, email: string, token: string): Promise<void>;
44
44
  getUserByApiToken(ws: string, token: string): Promise<UserRow | null>;
45
45
  }
46
+ /** An account a scenario's workspace starts with: signed up and verified already. */
47
+ export type SeedAccount = {
48
+ email: string;
49
+ name: string;
50
+ password: string;
51
+ };
52
+ /**
53
+ * Signs a scenario's accounts up on a site, verified, as if each owner had
54
+ * signed up and read their code. The salt comes from the schema and the
55
+ * email, so the same seed gives byte-identical rows in every workspace; the
56
+ * password still only matches through scrypt, as any other account's does.
57
+ * An account already there is left as it is.
58
+ */
59
+ export declare function seedAccounts(pool: Pool, schema: string, ws: string, accounts: readonly SeedAccount[]): Promise<void>;
60
+ /** The same contract in memory, for tests of what signs people up and in. */
61
+ export declare class MemoryUsersRepo implements UsersRepo {
62
+ private readonly users;
63
+ private readonly codes;
64
+ private readonly sessions;
65
+ private readonly key;
66
+ createUser(ws: string, email: string, passwordHash: string, displayName: string): Promise<UserRow>;
67
+ getUser(ws: string, email: string): Promise<(UserRow & {
68
+ passwordHash: string;
69
+ }) | null>;
70
+ setVerificationCode(ws: string, email: string, code: string, expiresAt: Date): Promise<void>;
71
+ consumeVerificationCode(ws: string, email: string, code: string, now: Date): Promise<boolean>;
72
+ createSession(ws: string, token: string, email: string, expiresAt: Date): Promise<void>;
73
+ getSessionEmail(ws: string, token: string, now: Date): Promise<string | null>;
74
+ deleteSession(ws: string, token: string): Promise<void>;
75
+ setApiToken(ws: string, email: string, token: string): Promise<void>;
76
+ getUserByApiToken(ws: string, token: string): Promise<UserRow | null>;
77
+ }
@@ -1,3 +1,5 @@
1
+ import { createHash } from "node:crypto";
2
+ import { hashPassword } from "./auth-service.js";
1
3
  const toUser = (r) => ({ email: r.email, displayName: r.display_name, verifiedAt: r.verified_at, apiToken: r.api_token });
2
4
  const SCHEMA = /^[a-z_][a-z0-9_]*$/;
3
5
  /**
@@ -51,4 +53,71 @@ export class PgUsersRepo {
51
53
  return r.rows[0] ? toUser(r.rows[0]) : null;
52
54
  }
53
55
  }
56
+ /** When a seeded account was verified: one fixed moment, so two workspaces of one seed hold the same rows. */
57
+ const SEEDED_AT = "2027-01-01T00:00:00Z";
58
+ /**
59
+ * Signs a scenario's accounts up on a site, verified, as if each owner had
60
+ * signed up and read their code. The salt comes from the schema and the
61
+ * email, so the same seed gives byte-identical rows in every workspace; the
62
+ * password still only matches through scrypt, as any other account's does.
63
+ * An account already there is left as it is.
64
+ */
65
+ export async function seedAccounts(pool, schema, ws, accounts) {
66
+ if (!SCHEMA.test(schema))
67
+ throw new Error(`invalid schema name: ${schema}`);
68
+ for (const a of accounts) {
69
+ const email = a.email.trim().toLowerCase();
70
+ const salt = createHash("sha256").update(`${schema}:${email}`).digest("hex").slice(0, 32);
71
+ await pool.query(`INSERT INTO ${schema}.users (workspace_id, email, password_hash, display_name, verified_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (workspace_id, email) DO NOTHING`, [ws, email, await hashPassword(a.password, salt), a.name, SEEDED_AT]);
72
+ }
73
+ }
74
+ /** The same contract in memory, for tests of what signs people up and in. */
75
+ export class MemoryUsersRepo {
76
+ users = new Map();
77
+ codes = new Map();
78
+ sessions = new Map();
79
+ key = (ws, id) => `${ws} ${id}`;
80
+ async createUser(ws, email, passwordHash, displayName) {
81
+ const user = { email, displayName, verifiedAt: null, apiToken: null, passwordHash };
82
+ this.users.set(this.key(ws, email), user);
83
+ return { email, displayName, verifiedAt: null, apiToken: null };
84
+ }
85
+ async getUser(ws, email) {
86
+ return this.users.get(this.key(ws, email)) ?? null;
87
+ }
88
+ async setVerificationCode(ws, email, code, expiresAt) {
89
+ this.codes.set(this.key(ws, email), { code, expiresAt });
90
+ }
91
+ async consumeVerificationCode(ws, email, code, now) {
92
+ const held = this.codes.get(this.key(ws, email));
93
+ if (!held || held.code !== code || held.expiresAt <= now)
94
+ return false;
95
+ this.codes.delete(this.key(ws, email));
96
+ const user = this.users.get(this.key(ws, email));
97
+ if (user)
98
+ user.verifiedAt ??= now;
99
+ return true;
100
+ }
101
+ async createSession(ws, token, email, expiresAt) {
102
+ this.sessions.set(this.key(ws, token), { email, expiresAt });
103
+ }
104
+ async getSessionEmail(ws, token, now) {
105
+ const s = this.sessions.get(this.key(ws, token));
106
+ return s && s.expiresAt > now ? s.email : null;
107
+ }
108
+ async deleteSession(ws, token) {
109
+ this.sessions.delete(this.key(ws, token));
110
+ }
111
+ async setApiToken(ws, email, token) {
112
+ const user = this.users.get(this.key(ws, email));
113
+ if (user)
114
+ user.apiToken = token;
115
+ }
116
+ async getUserByApiToken(ws, token) {
117
+ for (const [k, u] of this.users)
118
+ if (k.startsWith(`${ws} `) && u.apiToken === token)
119
+ return { email: u.email, displayName: u.displayName, verifiedAt: u.verifiedAt, apiToken: u.apiToken };
120
+ return null;
121
+ }
122
+ }
54
123
  //# sourceMappingURL=users-repo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"users-repo.js","sourceRoot":"","sources":["../src/users-repo.ts"],"names":[],"mappings":"AAkBA,MAAM,MAAM,GAAG,CAA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AAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,EAAU,EAAE,KAAa;QAC3C,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,EAAU,EAAE,KAAa,EAAE,KAAa;QACxD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,IAAI;YAAE,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,EAAU,EAAE,KAAa;QAC/C,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK;YAAE,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,KAAK,KAAK;gBAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC3L,OAAO,IAAI,CAAC;IACd,CAAC;CACF"}
package/dist/webmcp.d.ts CHANGED
@@ -6,7 +6,8 @@ export declare const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
6
6
  * WebMCP tools are closures inside the page. This script registers one per
7
7
  * catalog entry and bridges `execute` to the app's own `/mcp` (JSON-RPC
8
8
  * `tools/call`), so the page surface and the MCP surface can never disagree:
9
- * both are rendered from `ToolRegistry.list()`.
9
+ * both are rendered from `ToolRegistry.list()`. Every call it makes carries
10
+ * the door header, so the site knows the call came through a page's tool.
10
11
  *
11
12
  * Two globals carry the API today, and a page cannot know which browser it is
12
13
  * in, so it registers on EVERY distinct one present:
package/dist/webmcp.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { DOOR_HEADER, WEBMCP_DOOR_VALUE } from "./doors/door.js";
1
2
  import { toolInputJsonSchema } from "./tool-schema.js";
2
3
  export const WEBMCP_SCRIPT_MARKER = 'data-webmcp="bridge"';
3
4
  /** The global a late-injecting agent sidecar can call once it has installed a modelContext. */
@@ -6,7 +7,8 @@ export const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
6
7
  * WebMCP tools are closures inside the page. This script registers one per
7
8
  * catalog entry and bridges `execute` to the app's own `/mcp` (JSON-RPC
8
9
  * `tools/call`), so the page surface and the MCP surface can never disagree:
9
- * both are rendered from `ToolRegistry.list()`.
10
+ * both are rendered from `ToolRegistry.list()`. Every call it makes carries
11
+ * the door header, so the site knows the call came through a page's tool.
10
12
  *
11
13
  * Two globals carry the API today, and a page cannot know which browser it is
12
14
  * in, so it registers on EVERY distinct one present:
@@ -33,7 +35,7 @@ export function webmcpScript(tools, prefix) {
33
35
  const catalog = tools.list().map((t) => ({ name: t.name, description: t.description, inputSchema: toolInputJsonSchema(t) }));
34
36
  const json = JSON.stringify({ endpoint: `${prefix}/mcp`, tools: catalog }).replace(/<\//g, "<\\/");
35
37
  return `<script ${WEBMCP_SCRIPT_MARKER}>(function(){var cfg=${json};var seq=0;var done=[];
36
- function call(name,args){return fetch(cfg.endpoint,{method:"POST",headers:{"content-type":"application/json","accept":"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:++seq,method:"tools/call",params:{name:name,arguments:args||{}}})}).then(function(r){return r.text()}).then(function(t){var line=t.split("\\n").filter(function(l){return l.indexOf("data:")===0}).pop();var body=JSON.parse(line?line.slice(5):t);var c=body.result&&body.result.content;return c&&c[0]&&c[0].text?c[0].text:JSON.stringify(body.result||body.error)})}
38
+ function call(name,args){return fetch(cfg.endpoint,{method:"POST",headers:{"content-type":"application/json","accept":"application/json, text/event-stream","${DOOR_HEADER}":"${WEBMCP_DOOR_VALUE}"},body:JSON.stringify({jsonrpc:"2.0",id:++seq,method:"tools/call",params:{name:name,arguments:args||{}}})}).then(function(r){return r.text()}).then(function(t){var line=t.split("\\n").filter(function(l){return l.indexOf("data:")===0}).pop();var body=JSON.parse(line?line.slice(5):t);var c=body.result&&body.result.content;return c&&c[0]&&c[0].text?c[0].text:JSON.stringify(body.result||body.error)})}
37
39
  function contexts(){var out=[];if(typeof document!=="undefined"&&document&&document.modelContext)out.push(document.modelContext);if(typeof navigator!=="undefined"&&navigator&&navigator.modelContext&&out.indexOf(navigator.modelContext)<0)out.push(navigator.modelContext);return out.filter(function(mc){return typeof mc.registerTool==="function"})}
38
40
  function register(){contexts().forEach(function(mc){if(done.indexOf(mc)>=0)return;done.push(mc);
39
41
  cfg.tools.forEach(function(t){try{mc.registerTool({name:t.name,description:t.description,inputSchema:t.inputSchema,execute:function(a){return call(t.name,a)}})}catch(e){if(typeof console!=="undefined")console.warn("webmcp: "+t.name+" not registered: "+e)}})});return done.length>0}
@@ -1 +1 @@
1
- {"version":3,"file":"webmcp.js","sourceRoot":"","sources":["../src/webmcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAE3D,+FAA+F;AAC/F,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,YAAY,CAAI,KAAsB,EAAE,MAAc;IACpE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE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oE,CAAC;AACnI,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@benchme/site-kit",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",
@@ -16,7 +16,7 @@
16
16
  "test": "vitest run"
17
17
  },
18
18
  "dependencies": {
19
- "@benchme/core": "0.10.0",
19
+ "@benchme/core": "0.11.0",
20
20
  "@modelcontextprotocol/sdk": "^1.12.0",
21
21
  "fastify": "^5.2.0",
22
22
  "zod": "^3.24.0",