@broberg/tenant 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,177 @@
1
+ import * as hono_types from 'hono/types';
2
+ import { Context, MiddlewareHandler, Hono } from 'hono';
3
+
4
+ interface Tenant {
5
+ id: string;
6
+ /** Unique and immutable — the thing a URL or header names. */
7
+ slug: string;
8
+ name: string;
9
+ /** Absent means active. A suspended tenant is refused everywhere. */
10
+ status?: "active" | "suspended";
11
+ }
12
+ /**
13
+ * A user's membership of ONE tenant. `role` is the app's own vocabulary
14
+ * (owner/admin/member, owner/operator/viewer …) — the package never defines it.
15
+ * An app whose members belong to sub-units (Scout's units, cms' sites) derives
16
+ * this organisation-level membership in its store.
17
+ */
18
+ interface Membership {
19
+ userId: string;
20
+ tenantId: string;
21
+ role: string;
22
+ }
23
+ /** An invitation as stored. The token itself is NEVER stored — only its hash. */
24
+ interface StoredInvite {
25
+ id: string;
26
+ tenantId: string;
27
+ /** Lower-cased and trimmed. */
28
+ email: string;
29
+ role: string;
30
+ tokenHash: string;
31
+ invitedBy?: string;
32
+ createdAt: number;
33
+ expiresAt: number;
34
+ usedAt?: number;
35
+ usedBy?: string;
36
+ revokedAt?: number;
37
+ }
38
+ /**
39
+ * Where tenant data lives — implemented by the app against its own database.
40
+ * The package calls only these; it never opens a tenant database itself.
41
+ */
42
+ interface TenantStore {
43
+ tenantById(id: string): Promise<Tenant | null>;
44
+ tenantBySlug(slug: string): Promise<Tenant | null>;
45
+ /** Every membership the user has, across tenants. */
46
+ membershipsOf(userId: string): Promise<Membership[]>;
47
+ /** Idempotent: adding an existing (userId, tenantId) must not duplicate it. */
48
+ addMembership(m: Membership): Promise<void>;
49
+ /** Insert, or replace the invite with the same id. */
50
+ saveInvite(invite: StoredInvite): Promise<void>;
51
+ inviteByTokenHash(tokenHash: string): Promise<StoredInvite | null>;
52
+ /**
53
+ * Mark the invite used — ATOMICALLY: return true only for the call that
54
+ * changed it from unused, false when it was already used. This is what makes
55
+ * an invitation single-use when two requests race.
56
+ */
57
+ markInviteUsed(id: string, at: number, userId: string): Promise<boolean>;
58
+ }
59
+ type FallbackReason = "not_found" | "not_member" | "suspended";
60
+ interface ActiveTenant {
61
+ tenant: Tenant;
62
+ membership: Membership;
63
+ /**
64
+ * True when a STORED preference could not be used and another of the user's
65
+ * own memberships was chosen. The app should clear the stale preference, and
66
+ * the UI should say which tenant is active.
67
+ */
68
+ fellBack: boolean;
69
+ reason?: FallbackReason;
70
+ }
71
+ interface ResolveInput {
72
+ store: TenantStore;
73
+ userId: string;
74
+ /**
75
+ * An explicit choice for THIS request (path slug, header). STRICT: if the
76
+ * user cannot use it, the call throws — otherwise an answer would be shown
77
+ * under the wrong tenant's name.
78
+ */
79
+ requested?: string | null;
80
+ /**
81
+ * A standing preference (cookie, a stored «active tenant»). It goes stale
82
+ * for innocent reasons — a revoked membership, a deleted tenant — and a hard
83
+ * refusal there would lock the user out of her own system. So it falls back,
84
+ * but only to one of the user's OWN memberships, and says so (trail's
85
+ * pattern, F029 #1976).
86
+ */
87
+ preferred?: string | null;
88
+ /**
89
+ * The app's rule for choosing among several usable memberships when there is
90
+ * no request and no usable preference (e.g. the most recently used). Without
91
+ * it, one membership is chosen and several are refused (TenantChoiceRequired).
92
+ */
93
+ pickDefault?: (usable: {
94
+ tenant: Tenant;
95
+ membership: Membership;
96
+ }[]) => {
97
+ tenant: Tenant;
98
+ membership: Membership;
99
+ } | undefined;
100
+ }
101
+ interface Policy<Action extends string> {
102
+ can(role: string, action: Action): boolean;
103
+ /** Throws TenantForbidden (after onDenied) when the membership's role may not. */
104
+ assert(membership: Pick<Membership, "role">, action: Action, context?: unknown): Promise<void>;
105
+ }
106
+
107
+ /** The signed-in user, as the app knows her — from @broberg/sso's session, or anything else. */
108
+ interface TenantUser {
109
+ id: string;
110
+ email: string;
111
+ }
112
+ type UserFn = (c: Context) => TenantUser | null | Promise<TenantUser | null>;
113
+ /** The active tenant set by tenantMiddleware, or null outside it. */
114
+ declare function getTenant(c: Context): ActiveTenant | null;
115
+ /**
116
+ * JSON for every refusal this package makes. TenantNotFound and TenantNotMember
117
+ * are the SAME 404 on purpose: a non-member must not be able to learn which
118
+ * tenant slugs exist. TenantSuspended is only ever thrown to a member (the core
119
+ * decides that), so its 403 reveals nothing new.
120
+ */
121
+ declare function tenantErrorResponse(c: Context, e: unknown): Response | null;
122
+ interface TenantMiddlewareOptions extends Pick<ResolveInput, "pickDefault"> {
123
+ store: TenantStore;
124
+ user: UserFn;
125
+ /** The explicit tenant for THIS request (strict) — e.g. `(c) => c.req.param("tenant")`. */
126
+ requested?: (c: Context) => string | null | undefined;
127
+ /** The standing preference (may fall back) — e.g. a cookie. */
128
+ preferred?: (c: Context) => string | null | undefined;
129
+ /** Called when the preference was stale and another of the user's memberships was used — clear it here. */
130
+ onFellBack?: (c: Context, active: ActiveTenant) => void | Promise<void>;
131
+ }
132
+ /**
133
+ * Resolve the tenant for this request and put it on the context (`getTenant(c)`).
134
+ * 401 without a user, 404 for a tenant that is not hers (whether or not it
135
+ * exists), 403 suspended / no tenant, 409 when several memberships and nothing
136
+ * says which.
137
+ */
138
+ declare function tenantMiddleware(o: TenantMiddlewareOptions): MiddlewareHandler;
139
+ /**
140
+ * RBAC for one route: the active membership's role must be allowed `action`
141
+ * by the app's policy. 403 JSON after the policy's onDenied (the audit hook).
142
+ * Must run after tenantMiddleware — without it the route is refused, never
143
+ * opened (fail closed).
144
+ */
145
+ declare function requireCapability<Action extends string>(policy: Policy<Action>, action: Action): MiddlewareHandler;
146
+ interface TenantRoutesOptions<Action extends string> {
147
+ store: TenantStore;
148
+ user: UserFn;
149
+ /** The roles an invitation may grant (never owner or platform unless you list it). */
150
+ invitableRoles: readonly string[];
151
+ /**
152
+ * Inviting needs the active tenant (put tenantMiddleware before this app's
153
+ * /invites route), this action in the policy, AND a way to deliver the link.
154
+ * Without `deliverInvite` the route is not mounted: the token never travels
155
+ * back to the inviter's browser.
156
+ */
157
+ invite?: {
158
+ policy: Policy<Action>;
159
+ action: Action;
160
+ deliverInvite: (msg: {
161
+ to: string;
162
+ token: string;
163
+ tenant: Tenant;
164
+ role: string;
165
+ invitedBy: string;
166
+ }) => Promise<void>;
167
+ };
168
+ }
169
+ /**
170
+ * JSON routes for the membership surface:
171
+ * GET /memberships → [{ tenant: {id, slug, name, status}, role }] for the signed-in user
172
+ * POST /invites/accept {token} → { tenant, role }
173
+ * POST /invites {email, role} → { inviteId } (only with `invite`, needs tenantMiddleware)
174
+ */
175
+ declare function tenantRoutes<Action extends string>(o: TenantRoutesOptions<Action>): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
176
+
177
+ export { type TenantMiddlewareOptions, type TenantRoutesOptions, type TenantUser, getTenant, requireCapability, tenantErrorResponse, tenantMiddleware, tenantRoutes };
package/dist/hono.d.ts ADDED
@@ -0,0 +1,177 @@
1
+ import * as hono_types from 'hono/types';
2
+ import { Context, MiddlewareHandler, Hono } from 'hono';
3
+
4
+ interface Tenant {
5
+ id: string;
6
+ /** Unique and immutable — the thing a URL or header names. */
7
+ slug: string;
8
+ name: string;
9
+ /** Absent means active. A suspended tenant is refused everywhere. */
10
+ status?: "active" | "suspended";
11
+ }
12
+ /**
13
+ * A user's membership of ONE tenant. `role` is the app's own vocabulary
14
+ * (owner/admin/member, owner/operator/viewer …) — the package never defines it.
15
+ * An app whose members belong to sub-units (Scout's units, cms' sites) derives
16
+ * this organisation-level membership in its store.
17
+ */
18
+ interface Membership {
19
+ userId: string;
20
+ tenantId: string;
21
+ role: string;
22
+ }
23
+ /** An invitation as stored. The token itself is NEVER stored — only its hash. */
24
+ interface StoredInvite {
25
+ id: string;
26
+ tenantId: string;
27
+ /** Lower-cased and trimmed. */
28
+ email: string;
29
+ role: string;
30
+ tokenHash: string;
31
+ invitedBy?: string;
32
+ createdAt: number;
33
+ expiresAt: number;
34
+ usedAt?: number;
35
+ usedBy?: string;
36
+ revokedAt?: number;
37
+ }
38
+ /**
39
+ * Where tenant data lives — implemented by the app against its own database.
40
+ * The package calls only these; it never opens a tenant database itself.
41
+ */
42
+ interface TenantStore {
43
+ tenantById(id: string): Promise<Tenant | null>;
44
+ tenantBySlug(slug: string): Promise<Tenant | null>;
45
+ /** Every membership the user has, across tenants. */
46
+ membershipsOf(userId: string): Promise<Membership[]>;
47
+ /** Idempotent: adding an existing (userId, tenantId) must not duplicate it. */
48
+ addMembership(m: Membership): Promise<void>;
49
+ /** Insert, or replace the invite with the same id. */
50
+ saveInvite(invite: StoredInvite): Promise<void>;
51
+ inviteByTokenHash(tokenHash: string): Promise<StoredInvite | null>;
52
+ /**
53
+ * Mark the invite used — ATOMICALLY: return true only for the call that
54
+ * changed it from unused, false when it was already used. This is what makes
55
+ * an invitation single-use when two requests race.
56
+ */
57
+ markInviteUsed(id: string, at: number, userId: string): Promise<boolean>;
58
+ }
59
+ type FallbackReason = "not_found" | "not_member" | "suspended";
60
+ interface ActiveTenant {
61
+ tenant: Tenant;
62
+ membership: Membership;
63
+ /**
64
+ * True when a STORED preference could not be used and another of the user's
65
+ * own memberships was chosen. The app should clear the stale preference, and
66
+ * the UI should say which tenant is active.
67
+ */
68
+ fellBack: boolean;
69
+ reason?: FallbackReason;
70
+ }
71
+ interface ResolveInput {
72
+ store: TenantStore;
73
+ userId: string;
74
+ /**
75
+ * An explicit choice for THIS request (path slug, header). STRICT: if the
76
+ * user cannot use it, the call throws — otherwise an answer would be shown
77
+ * under the wrong tenant's name.
78
+ */
79
+ requested?: string | null;
80
+ /**
81
+ * A standing preference (cookie, a stored «active tenant»). It goes stale
82
+ * for innocent reasons — a revoked membership, a deleted tenant — and a hard
83
+ * refusal there would lock the user out of her own system. So it falls back,
84
+ * but only to one of the user's OWN memberships, and says so (trail's
85
+ * pattern, F029 #1976).
86
+ */
87
+ preferred?: string | null;
88
+ /**
89
+ * The app's rule for choosing among several usable memberships when there is
90
+ * no request and no usable preference (e.g. the most recently used). Without
91
+ * it, one membership is chosen and several are refused (TenantChoiceRequired).
92
+ */
93
+ pickDefault?: (usable: {
94
+ tenant: Tenant;
95
+ membership: Membership;
96
+ }[]) => {
97
+ tenant: Tenant;
98
+ membership: Membership;
99
+ } | undefined;
100
+ }
101
+ interface Policy<Action extends string> {
102
+ can(role: string, action: Action): boolean;
103
+ /** Throws TenantForbidden (after onDenied) when the membership's role may not. */
104
+ assert(membership: Pick<Membership, "role">, action: Action, context?: unknown): Promise<void>;
105
+ }
106
+
107
+ /** The signed-in user, as the app knows her — from @broberg/sso's session, or anything else. */
108
+ interface TenantUser {
109
+ id: string;
110
+ email: string;
111
+ }
112
+ type UserFn = (c: Context) => TenantUser | null | Promise<TenantUser | null>;
113
+ /** The active tenant set by tenantMiddleware, or null outside it. */
114
+ declare function getTenant(c: Context): ActiveTenant | null;
115
+ /**
116
+ * JSON for every refusal this package makes. TenantNotFound and TenantNotMember
117
+ * are the SAME 404 on purpose: a non-member must not be able to learn which
118
+ * tenant slugs exist. TenantSuspended is only ever thrown to a member (the core
119
+ * decides that), so its 403 reveals nothing new.
120
+ */
121
+ declare function tenantErrorResponse(c: Context, e: unknown): Response | null;
122
+ interface TenantMiddlewareOptions extends Pick<ResolveInput, "pickDefault"> {
123
+ store: TenantStore;
124
+ user: UserFn;
125
+ /** The explicit tenant for THIS request (strict) — e.g. `(c) => c.req.param("tenant")`. */
126
+ requested?: (c: Context) => string | null | undefined;
127
+ /** The standing preference (may fall back) — e.g. a cookie. */
128
+ preferred?: (c: Context) => string | null | undefined;
129
+ /** Called when the preference was stale and another of the user's memberships was used — clear it here. */
130
+ onFellBack?: (c: Context, active: ActiveTenant) => void | Promise<void>;
131
+ }
132
+ /**
133
+ * Resolve the tenant for this request and put it on the context (`getTenant(c)`).
134
+ * 401 without a user, 404 for a tenant that is not hers (whether or not it
135
+ * exists), 403 suspended / no tenant, 409 when several memberships and nothing
136
+ * says which.
137
+ */
138
+ declare function tenantMiddleware(o: TenantMiddlewareOptions): MiddlewareHandler;
139
+ /**
140
+ * RBAC for one route: the active membership's role must be allowed `action`
141
+ * by the app's policy. 403 JSON after the policy's onDenied (the audit hook).
142
+ * Must run after tenantMiddleware — without it the route is refused, never
143
+ * opened (fail closed).
144
+ */
145
+ declare function requireCapability<Action extends string>(policy: Policy<Action>, action: Action): MiddlewareHandler;
146
+ interface TenantRoutesOptions<Action extends string> {
147
+ store: TenantStore;
148
+ user: UserFn;
149
+ /** The roles an invitation may grant (never owner or platform unless you list it). */
150
+ invitableRoles: readonly string[];
151
+ /**
152
+ * Inviting needs the active tenant (put tenantMiddleware before this app's
153
+ * /invites route), this action in the policy, AND a way to deliver the link.
154
+ * Without `deliverInvite` the route is not mounted: the token never travels
155
+ * back to the inviter's browser.
156
+ */
157
+ invite?: {
158
+ policy: Policy<Action>;
159
+ action: Action;
160
+ deliverInvite: (msg: {
161
+ to: string;
162
+ token: string;
163
+ tenant: Tenant;
164
+ role: string;
165
+ invitedBy: string;
166
+ }) => Promise<void>;
167
+ };
168
+ }
169
+ /**
170
+ * JSON routes for the membership surface:
171
+ * GET /memberships → [{ tenant: {id, slug, name, status}, role }] for the signed-in user
172
+ * POST /invites/accept {token} → { tenant, role }
173
+ * POST /invites {email, role} → { inviteId } (only with `invite`, needs tenantMiddleware)
174
+ */
175
+ declare function tenantRoutes<Action extends string>(o: TenantRoutesOptions<Action>): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
176
+
177
+ export { type TenantMiddlewareOptions, type TenantRoutesOptions, type TenantUser, getTenant, requireCapability, tenantErrorResponse, tenantMiddleware, tenantRoutes };
package/dist/hono.js ADDED
@@ -0,0 +1,294 @@
1
+ import { Hono } from 'hono';
2
+
3
+ // src/hono.ts
4
+
5
+ // src/index.ts
6
+ var TenantError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "TenantError";
10
+ }
11
+ };
12
+ var TenantNotFound = class extends TenantError {
13
+ constructor(slug) {
14
+ super(`No tenant "${slug}".`);
15
+ this.slug = slug;
16
+ this.name = "TenantNotFound";
17
+ }
18
+ slug;
19
+ };
20
+ var TenantNotMember = class extends TenantError {
21
+ constructor(slug) {
22
+ super(`The user is not a member of "${slug}".`);
23
+ this.slug = slug;
24
+ this.name = "TenantNotMember";
25
+ }
26
+ slug;
27
+ };
28
+ var TenantSuspended = class extends TenantError {
29
+ constructor(slug) {
30
+ super(`Tenant "${slug}" is suspended.`);
31
+ this.slug = slug;
32
+ this.name = "TenantSuspended";
33
+ }
34
+ slug;
35
+ };
36
+ var TenantNoMembership = class extends TenantError {
37
+ constructor() {
38
+ super("The user has no active membership of any tenant.");
39
+ this.name = "TenantNoMembership";
40
+ }
41
+ };
42
+ var TenantChoiceRequired = class extends TenantError {
43
+ constructor(count) {
44
+ super(`The user is a member of ${count} tenants and nothing says which one \u2014 pass pickDefault.`);
45
+ this.count = count;
46
+ this.name = "TenantChoiceRequired";
47
+ }
48
+ count;
49
+ };
50
+ var InviteRefused = class extends TenantError {
51
+ constructor(reason) {
52
+ super(`Invitation refused: ${reason}.`);
53
+ this.reason = reason;
54
+ this.name = "InviteRefused";
55
+ }
56
+ reason;
57
+ };
58
+ async function memberships(store, userId) {
59
+ const all = await store.membershipsOf(userId);
60
+ const usable = [];
61
+ for (const m of all) {
62
+ const tenant = await store.tenantById(m.tenantId);
63
+ if (tenant && tenant.status !== "suspended") usable.push({ tenant, membership: m });
64
+ }
65
+ return { all, usable };
66
+ }
67
+ async function check(store, slug, m) {
68
+ const tenant = await store.tenantBySlug(slug);
69
+ if (!tenant) return { why: "not_found" };
70
+ const isMember = m.all.some((x) => x.tenantId === tenant.id);
71
+ if (!isMember) return { why: "not_member" };
72
+ if (tenant.status === "suspended") return { why: "suspended" };
73
+ const hit = m.usable.find((u) => u.tenant.id === tenant.id);
74
+ return hit ? { ok: hit } : { why: "not_member" };
75
+ }
76
+ async function resolveActiveTenant(input) {
77
+ const { store, userId } = input;
78
+ const ms = await memberships(store, userId);
79
+ const usable = ms.usable;
80
+ if (input.requested) {
81
+ const r = await check(store, input.requested, ms);
82
+ if ("ok" in r) return { ...r.ok, fellBack: false };
83
+ if (r.why === "not_found") throw new TenantNotFound(input.requested);
84
+ if (r.why === "suspended") throw new TenantSuspended(input.requested);
85
+ throw new TenantNotMember(input.requested);
86
+ }
87
+ let reason;
88
+ if (input.preferred) {
89
+ const r = await check(store, input.preferred, ms);
90
+ if ("ok" in r) return { ...r.ok, fellBack: false };
91
+ reason = r.why;
92
+ }
93
+ if (usable.length === 0) throw new TenantNoMembership();
94
+ const chosen = input.pickDefault ? input.pickDefault(usable) : usable.length === 1 ? usable[0] : void 0;
95
+ if (!chosen || !usable.some((u) => u.tenant.id === chosen.tenant.id && u.membership.userId === userId)) {
96
+ throw new TenantChoiceRequired(usable.length);
97
+ }
98
+ return { tenant: chosen.tenant, membership: chosen.membership, fellBack: reason !== void 0, ...reason ? { reason } : {} };
99
+ }
100
+ var DAY = 24 * 60 * 60 * 1e3;
101
+ var DEFAULT_INVITE_TTL_MS = 7 * DAY;
102
+ var normEmail = (e) => e.trim().toLowerCase();
103
+ function b64url(bytes) {
104
+ let s = "";
105
+ for (const b of bytes) s += String.fromCharCode(b);
106
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
107
+ }
108
+ async function hashInviteToken(token) {
109
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
110
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
111
+ }
112
+ async function createInvite(input) {
113
+ if (!input.invitableRoles.includes(input.role)) throw new InviteRefused("role_not_invitable");
114
+ const tenant = await input.store.tenantById(input.tenantId);
115
+ if (!tenant) throw new TenantNotFound(input.tenantId);
116
+ if (tenant.status === "suspended") throw new TenantSuspended(tenant.slug);
117
+ const token = b64url(crypto.getRandomValues(new Uint8Array(32)));
118
+ const now = input.now ?? Date.now();
119
+ const invite = {
120
+ id: b64url(crypto.getRandomValues(new Uint8Array(12))),
121
+ tenantId: tenant.id,
122
+ email: normEmail(input.email),
123
+ role: input.role,
124
+ tokenHash: await hashInviteToken(token),
125
+ ...input.invitedBy ? { invitedBy: input.invitedBy } : {},
126
+ createdAt: now,
127
+ expiresAt: now + (input.ttlMs ?? DEFAULT_INVITE_TTL_MS)
128
+ };
129
+ await input.store.saveInvite(invite);
130
+ return { invite, token };
131
+ }
132
+ async function acceptInvite(input) {
133
+ const { store, user } = input;
134
+ const now = input.now ?? Date.now();
135
+ const invite = await store.inviteByTokenHash(await hashInviteToken(input.token));
136
+ if (!invite) throw new InviteRefused("not_found");
137
+ if (invite.revokedAt !== void 0) throw new InviteRefused("revoked");
138
+ if (normEmail(user.email) !== invite.email) throw new InviteRefused("email_mismatch");
139
+ if (!input.invitableRoles.includes(invite.role)) throw new InviteRefused("role_not_invitable");
140
+ const membership = { userId: user.id, tenantId: invite.tenantId, role: invite.role };
141
+ if (invite.usedAt !== void 0) {
142
+ if (invite.usedBy !== user.id) throw new InviteRefused("used");
143
+ await store.addMembership(membership);
144
+ return membership;
145
+ }
146
+ if (now >= invite.expiresAt) throw new InviteRefused("expired");
147
+ const tenant = await store.tenantById(invite.tenantId);
148
+ if (!tenant) throw new TenantNotFound(invite.tenantId);
149
+ if (tenant.status === "suspended") throw new TenantSuspended(tenant.slug);
150
+ if (!await store.markInviteUsed(invite.id, now, user.id)) {
151
+ const again = await store.inviteByTokenHash(invite.tokenHash);
152
+ if (again?.usedBy !== user.id) throw new InviteRefused("used");
153
+ }
154
+ await store.addMembership(membership);
155
+ return membership;
156
+ }
157
+
158
+ // src/hono.ts
159
+ var TENANT_KEY = "broberg.tenant";
160
+ function getTenant(c) {
161
+ return c.get(TENANT_KEY) ?? null;
162
+ }
163
+ function nameOf(e) {
164
+ return e instanceof Error ? e.name : void 0;
165
+ }
166
+ function tenantErrorResponse(c, e) {
167
+ const err = e;
168
+ switch (nameOf(e)) {
169
+ case "TenantNotFound":
170
+ case "TenantNotMember":
171
+ return c.json({ error: "tenant_not_found" }, 404);
172
+ case "TenantSuspended":
173
+ return c.json({ error: "tenant_suspended" }, 403);
174
+ case "TenantNoMembership":
175
+ return c.json({ error: "no_tenant" }, 403);
176
+ case "TenantChoiceRequired":
177
+ return c.json({ error: "tenant_choice_required", count: err.count }, 409);
178
+ case "TenantForbidden":
179
+ return c.json({ error: "forbidden", action: err.action }, 403);
180
+ case "InviteRefused": {
181
+ const status = { not_found: 404, expired: 410, revoked: 410, used: 409, email_mismatch: 403, role_not_invitable: 403 }[err.reason];
182
+ return c.json({ error: `invite_${err.reason}` }, status ?? 400);
183
+ }
184
+ default:
185
+ return null;
186
+ }
187
+ }
188
+ function tenantMiddleware(o) {
189
+ return async (c, next) => {
190
+ const user = await o.user(c);
191
+ if (!user) return c.json({ error: "unauthenticated" }, 401);
192
+ let active;
193
+ try {
194
+ active = await resolveActiveTenant({
195
+ store: o.store,
196
+ userId: user.id,
197
+ requested: o.requested?.(c) ?? null,
198
+ preferred: o.preferred?.(c) ?? null,
199
+ ...o.pickDefault ? { pickDefault: o.pickDefault } : {}
200
+ });
201
+ } catch (e) {
202
+ const res = tenantErrorResponse(c, e);
203
+ if (res) return res;
204
+ throw e;
205
+ }
206
+ if (active.fellBack) await o.onFellBack?.(c, active);
207
+ c.set(TENANT_KEY, active);
208
+ await next();
209
+ };
210
+ }
211
+ function requireCapability(policy, action) {
212
+ return async (c, next) => {
213
+ const active = getTenant(c);
214
+ if (!active) return c.json({ error: "no_tenant_context" }, 500);
215
+ try {
216
+ await policy.assert(active.membership, action, { tenantId: active.tenant.id, userId: active.membership.userId });
217
+ } catch (e) {
218
+ const res = tenantErrorResponse(c, e);
219
+ if (res) return res;
220
+ throw e;
221
+ }
222
+ await next();
223
+ };
224
+ }
225
+ function tenantRoutes(o) {
226
+ const app = new Hono();
227
+ app.use("*", async (c, next) => {
228
+ c.header("Cache-Control", "no-store");
229
+ await next();
230
+ });
231
+ app.use("*", async (c, next) => {
232
+ const site = c.req.header("sec-fetch-site");
233
+ if (c.req.method !== "GET" && site !== void 0 && site !== "same-origin" && site !== "none") {
234
+ return c.json({ error: "cross_site" }, 403);
235
+ }
236
+ await next();
237
+ });
238
+ app.get("/memberships", async (c) => {
239
+ const user = await o.user(c);
240
+ if (!user) return c.json({ error: "unauthenticated" }, 401);
241
+ const out = [];
242
+ for (const m of await o.store.membershipsOf(user.id)) {
243
+ const t = await o.store.tenantById(m.tenantId);
244
+ if (t) out.push({ tenant: { id: t.id, slug: t.slug, name: t.name, ...t.status ? { status: t.status } : {} }, role: m.role });
245
+ }
246
+ return c.json(out);
247
+ });
248
+ app.post("/invites/accept", async (c) => {
249
+ const user = await o.user(c);
250
+ if (!user) return c.json({ error: "unauthenticated" }, 401);
251
+ const body = await c.req.json().catch(() => null);
252
+ if (typeof body?.token !== "string" || body.token === "") return c.json({ error: "invalid_request" }, 400);
253
+ try {
254
+ const m = await acceptInvite({ store: o.store, token: body.token, user, invitableRoles: o.invitableRoles });
255
+ const t = await o.store.tenantById(m.tenantId);
256
+ return c.json({ tenant: t ? { id: t.id, slug: t.slug, name: t.name } : { id: m.tenantId }, role: m.role });
257
+ } catch (e) {
258
+ const res = tenantErrorResponse(c, e);
259
+ if (res) return res;
260
+ throw e;
261
+ }
262
+ });
263
+ if (o.invite) {
264
+ const inv = o.invite;
265
+ app.post("/invites", requireCapability(inv.policy, inv.action), async (c) => {
266
+ const active = getTenant(c);
267
+ const body = await c.req.json().catch(() => null);
268
+ if (typeof body?.email !== "string" || !body.email.includes("@") || typeof body.role !== "string") {
269
+ return c.json({ error: "invalid_request" }, 400);
270
+ }
271
+ try {
272
+ const { invite, token } = await createInvite({
273
+ store: o.store,
274
+ tenantId: active.tenant.id,
275
+ email: body.email,
276
+ role: body.role,
277
+ invitableRoles: o.invitableRoles,
278
+ invitedBy: active.membership.userId
279
+ });
280
+ await inv.deliverInvite({ to: invite.email, token, tenant: active.tenant, role: invite.role, invitedBy: active.membership.userId });
281
+ return c.json({ inviteId: invite.id }, 201);
282
+ } catch (e) {
283
+ const res = tenantErrorResponse(c, e);
284
+ if (res) return res;
285
+ throw e;
286
+ }
287
+ });
288
+ }
289
+ return app;
290
+ }
291
+
292
+ export { getTenant, requireCapability, tenantErrorResponse, tenantMiddleware, tenantRoutes };
293
+ //# sourceMappingURL=hono.js.map
294
+ //# sourceMappingURL=hono.js.map