@benchme/site-kit 0.10.0 → 0.12.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 (78) hide show
  1. package/dist/auth-routes.js +5 -2
  2. package/dist/auth-routes.js.map +1 -1
  3. package/dist/auth-service.d.ts +9 -1
  4. package/dist/auth-service.js +14 -3
  5. package/dist/auth-service.js.map +1 -1
  6. package/dist/domain-error.d.ts +6 -0
  7. package/dist/domain-error.js +12 -0
  8. package/dist/domain-error.js.map +1 -0
  9. package/dist/doors/bridge-credential.d.ts +47 -0
  10. package/dist/doors/bridge-credential.js +80 -0
  11. package/dist/doors/bridge-credential.js.map +1 -0
  12. package/dist/doors/caller.d.ts +25 -0
  13. package/dist/doors/caller.js +22 -0
  14. package/dist/doors/caller.js.map +1 -0
  15. package/dist/doors/door.d.ts +12 -0
  16. package/dist/doors/door.js +18 -0
  17. package/dist/doors/door.js.map +1 -0
  18. package/dist/doors/register-doors.d.ts +44 -0
  19. package/dist/doors/register-doors.js +92 -0
  20. package/dist/doors/register-doors.js.map +1 -0
  21. package/dist/doors/request-door.d.ts +19 -0
  22. package/dist/doors/request-door.js +29 -0
  23. package/dist/doors/request-door.js.map +1 -0
  24. package/dist/doors/session-carrier.d.ts +42 -0
  25. package/dist/doors/session-carrier.js +44 -0
  26. package/dist/doors/session-carrier.js.map +1 -0
  27. package/dist/doors/sign-in-tools.d.ts +23 -0
  28. package/dist/doors/sign-in-tools.js +69 -0
  29. package/dist/doors/sign-in-tools.js.map +1 -0
  30. package/dist/doors/sign-in.d.ts +20 -0
  31. package/dist/doors/sign-in.js +31 -0
  32. package/dist/doors/sign-in.js.map +1 -0
  33. package/dist/html.d.ts +5 -1
  34. package/dist/html.js +23 -4
  35. package/dist/html.js.map +1 -1
  36. package/dist/index.d.ts +18 -3
  37. package/dist/index.js +18 -3
  38. package/dist/index.js.map +1 -1
  39. package/dist/ledger/auth-rules.d.ts +11 -0
  40. package/dist/ledger/auth-rules.js +21 -0
  41. package/dist/ledger/auth-rules.js.map +1 -0
  42. package/dist/ledger/entry.d.ts +219 -0
  43. package/dist/ledger/entry.js +40 -0
  44. package/dist/ledger/entry.js.map +1 -0
  45. package/dist/ledger/ledger-route.d.ts +15 -0
  46. package/dist/ledger/ledger-route.js +25 -0
  47. package/dist/ledger/ledger-route.js.map +1 -0
  48. package/dist/ledger/ledger.d.ts +38 -0
  49. package/dist/ledger/ledger.js +55 -0
  50. package/dist/ledger/ledger.js.map +1 -0
  51. package/dist/ledger/ledgered.d.ts +36 -0
  52. package/dist/ledger/ledgered.js +108 -0
  53. package/dist/ledger/ledgered.js.map +1 -0
  54. package/dist/ledger/rules.d.ts +45 -0
  55. package/dist/ledger/rules.js +22 -0
  56. package/dist/ledger/rules.js.map +1 -0
  57. package/dist/ledger/schema.d.ts +23 -0
  58. package/dist/ledger/schema.js +56 -0
  59. package/dist/ledger/schema.js.map +1 -0
  60. package/dist/mcp-server.d.ts +11 -6
  61. package/dist/mcp-server.js +24 -15
  62. package/dist/mcp-server.js.map +1 -1
  63. package/dist/refusal.d.ts +8 -0
  64. package/dist/refusal.js +8 -0
  65. package/dist/refusal.js.map +1 -0
  66. package/dist/request-header.d.ts +3 -0
  67. package/dist/request-header.js +6 -0
  68. package/dist/request-header.js.map +1 -0
  69. package/dist/users-repo.d.ts +32 -0
  70. package/dist/users-repo.js +69 -0
  71. package/dist/users-repo.js.map +1 -1
  72. package/dist/webmcp.d.ts +19 -2
  73. package/dist/webmcp.js +25 -4
  74. package/dist/webmcp.js.map +1 -1
  75. package/dist/workspace-scope.d.ts +18 -2
  76. package/dist/workspace-scope.js +36 -8
  77. package/dist/workspace-scope.js.map +1 -1
  78. package/package.json +2 -2
@@ -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,11 @@
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 { refusalOf } from "./refusal.js";
6
+ export { DomainError } from "./domain-error.js";
7
+ /** An MCP session's id, told apart at a glance from a site's own session tokens. */
8
+ export const newMcpSessionId = () => `mcp-${randomUUID()}`;
14
9
  /** A fresh MCP server bound to one workspace (stateless per request). */
15
10
  export function buildMcpServer(d, ctx) {
16
11
  const server = new McpServer({ name: d.serverName, version: d.version });
@@ -21,9 +16,10 @@ export function buildMcpServer(d, ctx) {
21
16
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
22
17
  }
23
18
  catch (err) {
24
- if (err instanceof DomainError) {
25
- return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: err.code, message: err.message }) }] };
26
- }
19
+ // A rule's refusal, a sign-in's, or a write by nobody: the tool's own answer, never a protocol error.
20
+ const refusal = refusalOf(err);
21
+ if (refusal)
22
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: refusal.code, message: refusal.message }) }] };
27
23
  throw err;
28
24
  }
29
25
  });
@@ -53,7 +49,7 @@ export function registerMcp(app, d) {
53
49
  });
54
50
  app.all("/mcp", async (req, reply) => {
55
51
  const server = buildMcpServer(d, d.context(req.workspaceId, req.prefix));
56
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
52
+ const transport = new StreamableHTTPServerTransport(d.sessions ? sessionOptions(req) : { sessionIdGenerator: undefined });
57
53
  reply.hijack();
58
54
  reply.raw.on("close", () => {
59
55
  void transport.close();
@@ -63,4 +59,17 @@ export function registerMcp(app, d) {
63
59
  await transport.handleRequest(req.raw, reply.raw, req.body);
64
60
  });
65
61
  }
62
+ /**
63
+ * One transport per request, as ever. The request that initializes gets a
64
+ * session id to repeat; every later one is taken as it comes, with no session
65
+ * held here to check it against. A page's bridge (a call that proved it is
66
+ * one: `req.door`, from the workspace scope) 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: req.door === "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;QAEZ,WAAM,GAAN,MAAM,CAAM;QAGrB,IAAI,CAAC,IA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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;;;;;GAKG;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,GAAG,CAAC,IAAI,KAAK,QAAQ;KAC1C,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"}
@@ -0,0 +1,3 @@
1
+ import type { FastifyRequest } from "fastify";
2
+ /** A request header's value: the first, when a client sent it more than once. */
3
+ export declare function header(req: FastifyRequest, name: string): string | undefined;
@@ -0,0 +1,6 @@
1
+ /** A request header's value: the first, when a client sent it more than once. */
2
+ export function header(req, name) {
3
+ const v = req.headers[name];
4
+ return Array.isArray(v) ? v[0] : v;
5
+ }
6
+ //# sourceMappingURL=request-header.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-header.js","sourceRoot":"","sources":["../src/request-header.ts"],"names":[],"mappings":"AAEA,iFAAiF;AACjF,MAAM,UAAU,MAAM,CAAC,GAAmB,EAAE,IAAY;IACtD,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACrC,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,CAAC,CAAO,EAAW,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC,YAAY,EAAE,UAAU,EAAE,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC;AAEzI,MAAM,MAAM,GAAG,oBAAoB,CAAC;AAEpC;;;GAGG;AACH,MAAM,OAAO,WAAW;IAGH;IAFF,CAAC,CAAS;IAC3B,YACmB,IAAU,EAC3B,MAAc;QADG,SAAI,GAAJ,IAAI,CAAM;QAG3B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,EAAE,CAAC,CAAC;QAC5E,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,EAAU,EAAE,KAAa,EAAE,YAAoB,EAAE,WAAmB;QACnF,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAC7B,eAAe,IAAI,CAAC,CAAC,+FAA+F,EACpH,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,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K,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
@@ -1,12 +1,29 @@
1
+ import type { FastifyRequest } from "fastify";
1
2
  import type { ToolRegistry } from "./tool-registry.js";
2
3
  export declare const WEBMCP_SCRIPT_MARKER = "data-webmcp=\"bridge\"";
3
4
  /** The global a late-injecting agent sidecar can call once it has installed a modelContext. */
4
5
  export declare const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
6
+ /**
7
+ * The page's WebMCP bridge for this request, to render before </body>; nothing
8
+ * at all when the request's workspace is not served through the WebMCP door,
9
+ * so a page then names neither the site's /mcp nor a single tool.
10
+ *
11
+ * The bridge carries a token for the browser's bridge cookie, which the site
12
+ * sets on this response when the browser holds none yet (the workspace scope
13
+ * does, see `registerWorkspaceScope`), and every tool call it makes sends the
14
+ * token back. The site counts a call to /mcp as the page's bridge only when
15
+ * the token is the one for the cookie the call carries: see
16
+ * `BridgeCredential`.
17
+ */
18
+ export declare function webmcpBridge<C>(req: FastifyRequest, tools: ToolRegistry<C>): string;
5
19
  /**
6
20
  * WebMCP tools are closures inside the page. This script registers one per
7
21
  * catalog entry and bridges `execute` to the app's own `/mcp` (JSON-RPC
8
22
  * `tools/call`), so the page surface and the MCP surface can never disagree:
9
- * both are rendered from `ToolRegistry.list()`.
23
+ * both are rendered from `ToolRegistry.list()`. Every call it makes is a
24
+ * same-origin request, so the browser sends the site's cookies with it (the
25
+ * bridge cookie and, once signed in, the session), and it sends the page's
26
+ * token in BRIDGE_TOKEN_HEADER.
10
27
  *
11
28
  * Two globals carry the API today, and a page cannot know which browser it is
12
29
  * in, so it registers on EVERY distinct one present:
@@ -29,4 +46,4 @@ export declare const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
29
46
  * read defensively: a non-browser runtime must be a no-op, never a
30
47
  * ReferenceError that kills the rest of the page's scripts.
31
48
  */
32
- export declare function webmcpScript<C>(tools: ToolRegistry<C>, prefix: string): string;
49
+ export declare function bridgeScript<C>(tools: ToolRegistry<C>, prefix: string, token: string): string;
package/dist/webmcp.js CHANGED
@@ -1,12 +1,33 @@
1
+ import { BRIDGE_TOKEN_HEADER } from "./doors/bridge-credential.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. */
4
5
  export const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
6
+ /**
7
+ * The page's WebMCP bridge for this request, to render before </body>; nothing
8
+ * at all when the request's workspace is not served through the WebMCP door,
9
+ * so a page then names neither the site's /mcp nor a single tool.
10
+ *
11
+ * The bridge carries a token for the browser's bridge cookie, which the site
12
+ * sets on this response when the browser holds none yet (the workspace scope
13
+ * does, see `registerWorkspaceScope`), and every tool call it makes sends the
14
+ * token back. The site counts a call to /mcp as the page's bridge only when
15
+ * the token is the one for the cookie the call carries: see
16
+ * `BridgeCredential`.
17
+ */
18
+ export function webmcpBridge(req, tools) {
19
+ if (!req.bridge || !req.doors.has("webmcp"))
20
+ return "";
21
+ return bridgeScript(tools, req.prefix, req.bridge.issue());
22
+ }
5
23
  /**
6
24
  * WebMCP tools are closures inside the page. This script registers one per
7
25
  * catalog entry and bridges `execute` to the app's own `/mcp` (JSON-RPC
8
26
  * `tools/call`), so the page surface and the MCP surface can never disagree:
9
- * both are rendered from `ToolRegistry.list()`.
27
+ * both are rendered from `ToolRegistry.list()`. Every call it makes is a
28
+ * same-origin request, so the browser sends the site's cookies with it (the
29
+ * bridge cookie and, once signed in, the session), and it sends the page's
30
+ * token in BRIDGE_TOKEN_HEADER.
10
31
  *
11
32
  * Two globals carry the API today, and a page cannot know which browser it is
12
33
  * in, so it registers on EVERY distinct one present:
@@ -29,11 +50,11 @@ export const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
29
50
  * read defensively: a non-browser runtime must be a no-op, never a
30
51
  * ReferenceError that kills the rest of the page's scripts.
31
52
  */
32
- export function webmcpScript(tools, prefix) {
53
+ export function bridgeScript(tools, prefix, token) {
33
54
  const catalog = tools.list().map((t) => ({ name: t.name, description: t.description, inputSchema: toolInputJsonSchema(t) }));
34
- const json = JSON.stringify({ endpoint: `${prefix}/mcp`, tools: catalog }).replace(/<\//g, "<\\/");
55
+ const json = JSON.stringify({ endpoint: `${prefix}/mcp`, token, tools: catalog }).replace(/<\//g, "<\\/");
35
56
  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)})}
57
+ function call(name,args){return fetch(cfg.endpoint,{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json","accept":"application/json, text/event-stream","${BRIDGE_TOKEN_HEADER}":cfg.token},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
58
  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
59
  function register(){contexts().forEach(function(mc){if(done.indexOf(mc)>=0)return;done.push(mc);
39
60
  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,mBAAmB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC7H,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnG,OAAO,WAAW,oBAAoB,wBAAwB,IAAI;;;;;wCAK5B,sBAAsB;;kIAEoE,CAAC;AACnI,CAAC"}
1
+ {"version":3,"file":"webmcp.js","sourceRoot":"","sources":["../src/webmcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,8B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
2
+ import type { FastifyInstance } from "fastify";
3
+ import { BridgeCredential } from "./doors/bridge-credential.js";
4
+ export { header } from "./request-header.js";
2
5
  declare module "fastify" {
3
6
  interface FastifyRequest {
4
7
  /** Bound by the gateway (signed); every tenant query is scoped by it. */
5
8
  workspaceId: string;
6
9
  /** The public path prefix the gateway stripped ("/w/<id>/<app>"), for links + cookie paths. */
7
10
  prefix: string;
11
+ /** The doors the gateway serves this request's workspace through (signed): every door when it named none. */
12
+ doors: DoorSet;
13
+ /** The door this request came through, or null for what is no door (the probes, /internal/). */
14
+ door: Door | null;
15
+ /** This request's WebMCP bridge credential; null on a path outside any workspace. */
16
+ bridge: BridgeCredential | null;
8
17
  }
9
18
  }
10
19
  /**
11
20
  * Trust the workspace ONLY from the gateway's signed header. A request without
12
21
  * it (or with a bad signature) never reaches a tenant query. Paths in
13
22
  * `unscopedPrefixes` (internal endpoints authenticated some other way) skip it.
23
+ *
24
+ * The doors come with it, signed for the same workspace (or not at all, from
25
+ * a gateway older than doors: then every door is open). A request through a
26
+ * door its workspace is not served through is told there is no such thing,
27
+ * before any handler, body parser or JSON-RPC reads it: the gateway closes the
28
+ * door by path first, and this is the second lock, the one that knows a
29
+ * page's bridge from a direct MCP client. And a page that renders its WebMCP
30
+ * bridge (`webmcpBridge`) gets the bridge cookie set on its response here.
14
31
  */
15
32
  export declare function registerWorkspaceScope(app: FastifyInstance, gatewaySecret: string, unscopedPrefixes?: readonly string[]): void;
16
- export declare function header(req: FastifyRequest, name: string): string | undefined;
@@ -1,28 +1,56 @@
1
- import { FORWARDED_PREFIX_HEADER, WORKSPACE_HEADER, WORKSPACE_SIG_HEADER, isWorkspaceId, verifyWorkspaceHeader } from "@benchme/core";
1
+ import { DOORS_HEADER, DOORS_SIG_HEADER, DoorSet, FORWARDED_PREFIX_HEADER, WORKSPACE_HEADER, WORKSPACE_SIG_HEADER, doorsFromHeaders, isWorkspaceId, verifyWorkspaceHeader, } from "@benchme/core";
2
+ import { BridgeCredential, bridgeSetCookie } from "./doors/bridge-credential.js";
3
+ import { isClosed, requestDoor } from "./doors/request-door.js";
4
+ import { header } from "./request-header.js";
5
+ export { header } from "./request-header.js";
2
6
  const UNSCOPED = new Set(["/healthz", "/readyz"]);
7
+ const notThroughGateway = (reply) => reply.code(401).send({ error: "NO_WORKSPACE", message: "requests must come through the benchme gateway" });
3
8
  /**
4
9
  * Trust the workspace ONLY from the gateway's signed header. A request without
5
10
  * it (or with a bad signature) never reaches a tenant query. Paths in
6
11
  * `unscopedPrefixes` (internal endpoints authenticated some other way) skip it.
12
+ *
13
+ * The doors come with it, signed for the same workspace (or not at all, from
14
+ * a gateway older than doors: then every door is open). A request through a
15
+ * door its workspace is not served through is told there is no such thing,
16
+ * before any handler, body parser or JSON-RPC reads it: the gateway closes the
17
+ * door by path first, and this is the second lock, the one that knows a
18
+ * page's bridge from a direct MCP client. And a page that renders its WebMCP
19
+ * bridge (`webmcpBridge`) gets the bridge cookie set on its response here.
7
20
  */
8
21
  export function registerWorkspaceScope(app, gatewaySecret, unscopedPrefixes = []) {
9
22
  app.decorateRequest("workspaceId", "");
10
23
  app.decorateRequest("prefix", "");
24
+ app.decorateRequest("doors");
25
+ app.decorateRequest("door");
26
+ app.decorateRequest("bridge");
11
27
  app.addHook("onRequest", async (req, reply) => {
28
+ req.doors = DoorSet.ALL;
29
+ req.door = null;
30
+ req.bridge = null;
12
31
  const path = req.url.split("?")[0] ?? "";
13
32
  if (UNSCOPED.has(path) || unscopedPrefixes.some((p) => path.startsWith(p)))
14
33
  return;
15
34
  const id = header(req, WORKSPACE_HEADER);
16
35
  const sig = header(req, WORKSPACE_SIG_HEADER);
17
- if (!id || !isWorkspaceId(id) || !sig || !verifyWorkspaceHeader(gatewaySecret, id, sig)) {
18
- return reply.code(401).send({ error: "NO_WORKSPACE", message: "requests must come through the benchme gateway" });
19
- }
36
+ if (!id || !isWorkspaceId(id) || !sig || !verifyWorkspaceHeader(gatewaySecret, id, sig))
37
+ return notThroughGateway(reply);
38
+ const doors = doorsFromHeaders(gatewaySecret, id, header(req, DOORS_HEADER), header(req, DOORS_SIG_HEADER));
39
+ if (!doors)
40
+ return notThroughGateway(reply);
20
41
  req.workspaceId = id;
21
42
  req.prefix = header(req, FORWARDED_PREFIX_HEADER) ?? "";
43
+ req.doors = doors;
44
+ req.bridge = BridgeCredential.of(gatewaySecret, id, header(req, "cookie"));
45
+ req.door = requestDoor(req, req.bridge);
46
+ if (isClosed(req, gatewaySecret))
47
+ return reply.code(404).send({ error: "NOT_FOUND" });
48
+ });
49
+ app.addHook("onSend", async (req, reply, payload) => {
50
+ const minted = req.bridge?.mintedCookie;
51
+ if (minted)
52
+ reply.header("set-cookie", bridgeSetCookie(minted, `${req.prefix}/`));
53
+ return payload;
22
54
  });
23
- }
24
- export function header(req, name) {
25
- const v = req.headers[name];
26
- return Array.isArray(v) ? v[0] : v;
27
55
  }
28
56
  //# sourceMappingURL=workspace-scope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-scope.js","sourceRoot":"","sources":["../src/workspace-scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAYtI,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,GAAoB,EAAE,aAAqB,EAAE,mBAAsC,EAAE;IAC1H,GAAG,CAAC,eAAe,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;IACvC,GAAG,CAAC,eAAe,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClC,GAAG,CAAC,OAAO,CAAC,WAAW,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;QAC5C,MAAM,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC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AC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;IACxF,CAAC,CAAC,CAAC;IACH,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QAClD,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;QACxC,IAAI,MAAM;YAAE,KAAK,CAAC,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAClF,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,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.12.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.12.0",
20
20
  "@modelcontextprotocol/sdk": "^1.12.0",
21
21
  "fastify": "^5.2.0",
22
22
  "zod": "^3.24.0",