@broberg/tenant 0.0.0-stage → 0.2.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,205 @@
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
+ /**
24
+ * What accepting an invitation WRITES: a Membership plus the invitation's
25
+ * `scope`, when it had one. `scope` is opaque to the package — Scout puts a
26
+ * unit id there. It exists only on the write side: `membershipsOf` keeps
27
+ * returning ONE organisation-level Membership per tenant, so a user in two
28
+ * units of one org is still one tenant choice with one role.
29
+ */
30
+ interface MembershipGrant extends Membership {
31
+ scope?: string;
32
+ }
33
+ /** An invitation as stored. The token itself is NEVER stored — only its hash. */
34
+ interface StoredInvite {
35
+ id: string;
36
+ tenantId: string;
37
+ /** Lower-cased and trimmed. */
38
+ email: string;
39
+ role: string;
40
+ /** Opaque to the package; carried into addMembership on accept. */
41
+ scope?: string;
42
+ tokenHash: string;
43
+ invitedBy?: string;
44
+ createdAt: number;
45
+ expiresAt: number;
46
+ usedAt?: number;
47
+ usedBy?: string;
48
+ revokedAt?: number;
49
+ }
50
+ /**
51
+ * Where tenant data lives — implemented by the app against its own database.
52
+ * The package calls only these; it never opens a tenant database itself.
53
+ */
54
+ interface TenantStore {
55
+ tenantById(id: string): Promise<Tenant | null>;
56
+ tenantBySlug(slug: string): Promise<Tenant | null>;
57
+ /**
58
+ * Every membership the user has, across tenants — ONE organisation-level row
59
+ * per tenant, never one per scope (derive it, as Scout does from units).
60
+ */
61
+ membershipsOf(userId: string): Promise<Membership[]>;
62
+ /**
63
+ * Idempotent: adding an existing (userId, tenantId) must not duplicate it —
64
+ * keyed (userId, tenantId, scope) when the grant carries a scope. A grant
65
+ * with a scope must also leave the user a member of the tenant as a whole.
66
+ */
67
+ addMembership(m: MembershipGrant): Promise<void>;
68
+ /** Insert, or replace the invite with the same id. */
69
+ saveInvite(invite: StoredInvite): Promise<void>;
70
+ inviteByTokenHash(tokenHash: string): Promise<StoredInvite | null>;
71
+ /**
72
+ * Mark the invite used — ATOMICALLY: return true only for the call that
73
+ * changed it from unused, false when it was already used. This is what makes
74
+ * an invitation single-use when two requests race.
75
+ */
76
+ markInviteUsed(id: string, at: number, userId: string): Promise<boolean>;
77
+ }
78
+ type FallbackReason = "not_found" | "not_member" | "suspended";
79
+ interface ActiveTenant {
80
+ tenant: Tenant;
81
+ membership: Membership;
82
+ /**
83
+ * True when a STORED preference could not be used and another of the user's
84
+ * own memberships was chosen. The app should clear the stale preference, and
85
+ * the UI should say which tenant is active.
86
+ */
87
+ fellBack: boolean;
88
+ reason?: FallbackReason;
89
+ }
90
+ interface ResolveInput {
91
+ store: TenantStore;
92
+ userId: string;
93
+ /**
94
+ * An explicit choice for THIS request (path slug, header). STRICT: if the
95
+ * user cannot use it, the call throws — otherwise an answer would be shown
96
+ * under the wrong tenant's name.
97
+ */
98
+ requested?: string | null;
99
+ /**
100
+ * A standing preference (cookie, a stored «active tenant»). It goes stale
101
+ * for innocent reasons — a revoked membership, a deleted tenant — and a hard
102
+ * refusal there would lock the user out of her own system. So it falls back,
103
+ * but only to one of the user's OWN memberships, and says so (trail's
104
+ * pattern, F029 #1976).
105
+ */
106
+ preferred?: string | null;
107
+ /**
108
+ * The app's rule for choosing among several usable memberships when there is
109
+ * no request and no usable preference (e.g. the most recently used). Without
110
+ * it, one membership is chosen and several are refused (TenantChoiceRequired).
111
+ */
112
+ pickDefault?: (usable: {
113
+ tenant: Tenant;
114
+ membership: Membership;
115
+ }[]) => {
116
+ tenant: Tenant;
117
+ membership: Membership;
118
+ } | undefined;
119
+ }
120
+ interface Policy<Action extends string> {
121
+ can(role: string, action: Action): boolean;
122
+ /** Throws TenantForbidden (after onDenied) when the membership's role may not. */
123
+ assert(membership: Pick<Membership, "role">, action: Action, context?: unknown): Promise<void>;
124
+ }
125
+
126
+ /** The signed-in user, as the app knows her — from @broberg/sso's session, or anything else. */
127
+ interface TenantUser {
128
+ id: string;
129
+ email: string;
130
+ }
131
+ type UserFn = (c: Context) => TenantUser | null | Promise<TenantUser | null>;
132
+ /** The active tenant set by tenantMiddleware, or null outside it. */
133
+ declare function getTenant(c: Context): ActiveTenant | null;
134
+ /**
135
+ * JSON for every refusal this package makes. TenantNotFound and TenantNotMember
136
+ * are the SAME 404 on purpose: a non-member must not be able to learn which
137
+ * tenant slugs exist. TenantSuspended is only ever thrown to a member (the core
138
+ * decides that), so its 403 reveals nothing new.
139
+ */
140
+ declare function tenantErrorResponse(c: Context, e: unknown): Response | null;
141
+ interface TenantMiddlewareOptions extends Pick<ResolveInput, "pickDefault"> {
142
+ store: TenantStore;
143
+ user: UserFn;
144
+ /** The explicit tenant for THIS request (strict) — e.g. `(c) => c.req.param("tenant")`. */
145
+ requested?: (c: Context) => string | null | undefined;
146
+ /** The standing preference (may fall back) — e.g. a cookie. */
147
+ preferred?: (c: Context) => string | null | undefined;
148
+ /** Called when the preference was stale and another of the user's memberships was used — clear it here. */
149
+ onFellBack?: (c: Context, active: ActiveTenant) => void | Promise<void>;
150
+ }
151
+ /**
152
+ * Resolve the tenant for this request and put it on the context (`getTenant(c)`).
153
+ * 401 without a user, 404 for a tenant that is not hers (whether or not it
154
+ * exists), 403 suspended / no tenant, 409 when several memberships and nothing
155
+ * says which.
156
+ */
157
+ declare function tenantMiddleware(o: TenantMiddlewareOptions): MiddlewareHandler;
158
+ /**
159
+ * RBAC for one route: the active membership's role must be allowed `action`
160
+ * by the app's policy. 403 JSON after the policy's onDenied (the audit hook).
161
+ * Must run after tenantMiddleware — without it the route is refused, never
162
+ * opened (fail closed).
163
+ */
164
+ declare function requireCapability<Action extends string>(policy: Policy<Action>, action: Action): MiddlewareHandler;
165
+ interface TenantRoutesOptions<Action extends string> {
166
+ store: TenantStore;
167
+ user: UserFn;
168
+ /** The roles an invitation may grant (never owner or platform unless you list it). */
169
+ invitableRoles: readonly string[];
170
+ /**
171
+ * Inviting needs the active tenant (put tenantMiddleware before this app's
172
+ * /invites route), this action in the policy, AND a way to deliver the link.
173
+ * Without `deliverInvite` the route is not mounted: the token never travels
174
+ * back to the inviter's browser.
175
+ */
176
+ invite?: {
177
+ policy: Policy<Action>;
178
+ action: Action;
179
+ deliverInvite: (msg: {
180
+ to: string;
181
+ token: string;
182
+ tenant: Tenant;
183
+ role: string;
184
+ invitedBy: string;
185
+ scope?: string;
186
+ }) => Promise<void>;
187
+ /**
188
+ * Required for an invitation with a `scope` (a unit below the organisation).
189
+ * Only the app knows its unit tree, so only the app can say whether THIS
190
+ * inviter may grant this role there. Without it a body carrying `scope` is
191
+ * refused 400; a false answer is refused 403 `scope_not_allowed`. A scope is
192
+ * never silently dropped.
193
+ */
194
+ authorizeScope?: (inviter: Membership, scope: string, role: string) => boolean | Promise<boolean>;
195
+ };
196
+ }
197
+ /**
198
+ * JSON routes for the membership surface:
199
+ * GET /memberships → [{ tenant: {id, slug, name, status}, role }] for the signed-in user
200
+ * POST /invites/accept {token} → { tenant, role }
201
+ * POST /invites {email, role} → { inviteId } (only with `invite`, needs tenantMiddleware)
202
+ */
203
+ declare function tenantRoutes<Action extends string>(o: TenantRoutesOptions<Action>): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
204
+
205
+ export { type TenantMiddlewareOptions, type TenantRoutesOptions, type TenantUser, getTenant, requireCapability, tenantErrorResponse, tenantMiddleware, tenantRoutes };
package/dist/hono.d.ts ADDED
@@ -0,0 +1,205 @@
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
+ /**
24
+ * What accepting an invitation WRITES: a Membership plus the invitation's
25
+ * `scope`, when it had one. `scope` is opaque to the package — Scout puts a
26
+ * unit id there. It exists only on the write side: `membershipsOf` keeps
27
+ * returning ONE organisation-level Membership per tenant, so a user in two
28
+ * units of one org is still one tenant choice with one role.
29
+ */
30
+ interface MembershipGrant extends Membership {
31
+ scope?: string;
32
+ }
33
+ /** An invitation as stored. The token itself is NEVER stored — only its hash. */
34
+ interface StoredInvite {
35
+ id: string;
36
+ tenantId: string;
37
+ /** Lower-cased and trimmed. */
38
+ email: string;
39
+ role: string;
40
+ /** Opaque to the package; carried into addMembership on accept. */
41
+ scope?: string;
42
+ tokenHash: string;
43
+ invitedBy?: string;
44
+ createdAt: number;
45
+ expiresAt: number;
46
+ usedAt?: number;
47
+ usedBy?: string;
48
+ revokedAt?: number;
49
+ }
50
+ /**
51
+ * Where tenant data lives — implemented by the app against its own database.
52
+ * The package calls only these; it never opens a tenant database itself.
53
+ */
54
+ interface TenantStore {
55
+ tenantById(id: string): Promise<Tenant | null>;
56
+ tenantBySlug(slug: string): Promise<Tenant | null>;
57
+ /**
58
+ * Every membership the user has, across tenants — ONE organisation-level row
59
+ * per tenant, never one per scope (derive it, as Scout does from units).
60
+ */
61
+ membershipsOf(userId: string): Promise<Membership[]>;
62
+ /**
63
+ * Idempotent: adding an existing (userId, tenantId) must not duplicate it —
64
+ * keyed (userId, tenantId, scope) when the grant carries a scope. A grant
65
+ * with a scope must also leave the user a member of the tenant as a whole.
66
+ */
67
+ addMembership(m: MembershipGrant): Promise<void>;
68
+ /** Insert, or replace the invite with the same id. */
69
+ saveInvite(invite: StoredInvite): Promise<void>;
70
+ inviteByTokenHash(tokenHash: string): Promise<StoredInvite | null>;
71
+ /**
72
+ * Mark the invite used — ATOMICALLY: return true only for the call that
73
+ * changed it from unused, false when it was already used. This is what makes
74
+ * an invitation single-use when two requests race.
75
+ */
76
+ markInviteUsed(id: string, at: number, userId: string): Promise<boolean>;
77
+ }
78
+ type FallbackReason = "not_found" | "not_member" | "suspended";
79
+ interface ActiveTenant {
80
+ tenant: Tenant;
81
+ membership: Membership;
82
+ /**
83
+ * True when a STORED preference could not be used and another of the user's
84
+ * own memberships was chosen. The app should clear the stale preference, and
85
+ * the UI should say which tenant is active.
86
+ */
87
+ fellBack: boolean;
88
+ reason?: FallbackReason;
89
+ }
90
+ interface ResolveInput {
91
+ store: TenantStore;
92
+ userId: string;
93
+ /**
94
+ * An explicit choice for THIS request (path slug, header). STRICT: if the
95
+ * user cannot use it, the call throws — otherwise an answer would be shown
96
+ * under the wrong tenant's name.
97
+ */
98
+ requested?: string | null;
99
+ /**
100
+ * A standing preference (cookie, a stored «active tenant»). It goes stale
101
+ * for innocent reasons — a revoked membership, a deleted tenant — and a hard
102
+ * refusal there would lock the user out of her own system. So it falls back,
103
+ * but only to one of the user's OWN memberships, and says so (trail's
104
+ * pattern, F029 #1976).
105
+ */
106
+ preferred?: string | null;
107
+ /**
108
+ * The app's rule for choosing among several usable memberships when there is
109
+ * no request and no usable preference (e.g. the most recently used). Without
110
+ * it, one membership is chosen and several are refused (TenantChoiceRequired).
111
+ */
112
+ pickDefault?: (usable: {
113
+ tenant: Tenant;
114
+ membership: Membership;
115
+ }[]) => {
116
+ tenant: Tenant;
117
+ membership: Membership;
118
+ } | undefined;
119
+ }
120
+ interface Policy<Action extends string> {
121
+ can(role: string, action: Action): boolean;
122
+ /** Throws TenantForbidden (after onDenied) when the membership's role may not. */
123
+ assert(membership: Pick<Membership, "role">, action: Action, context?: unknown): Promise<void>;
124
+ }
125
+
126
+ /** The signed-in user, as the app knows her — from @broberg/sso's session, or anything else. */
127
+ interface TenantUser {
128
+ id: string;
129
+ email: string;
130
+ }
131
+ type UserFn = (c: Context) => TenantUser | null | Promise<TenantUser | null>;
132
+ /** The active tenant set by tenantMiddleware, or null outside it. */
133
+ declare function getTenant(c: Context): ActiveTenant | null;
134
+ /**
135
+ * JSON for every refusal this package makes. TenantNotFound and TenantNotMember
136
+ * are the SAME 404 on purpose: a non-member must not be able to learn which
137
+ * tenant slugs exist. TenantSuspended is only ever thrown to a member (the core
138
+ * decides that), so its 403 reveals nothing new.
139
+ */
140
+ declare function tenantErrorResponse(c: Context, e: unknown): Response | null;
141
+ interface TenantMiddlewareOptions extends Pick<ResolveInput, "pickDefault"> {
142
+ store: TenantStore;
143
+ user: UserFn;
144
+ /** The explicit tenant for THIS request (strict) — e.g. `(c) => c.req.param("tenant")`. */
145
+ requested?: (c: Context) => string | null | undefined;
146
+ /** The standing preference (may fall back) — e.g. a cookie. */
147
+ preferred?: (c: Context) => string | null | undefined;
148
+ /** Called when the preference was stale and another of the user's memberships was used — clear it here. */
149
+ onFellBack?: (c: Context, active: ActiveTenant) => void | Promise<void>;
150
+ }
151
+ /**
152
+ * Resolve the tenant for this request and put it on the context (`getTenant(c)`).
153
+ * 401 without a user, 404 for a tenant that is not hers (whether or not it
154
+ * exists), 403 suspended / no tenant, 409 when several memberships and nothing
155
+ * says which.
156
+ */
157
+ declare function tenantMiddleware(o: TenantMiddlewareOptions): MiddlewareHandler;
158
+ /**
159
+ * RBAC for one route: the active membership's role must be allowed `action`
160
+ * by the app's policy. 403 JSON after the policy's onDenied (the audit hook).
161
+ * Must run after tenantMiddleware — without it the route is refused, never
162
+ * opened (fail closed).
163
+ */
164
+ declare function requireCapability<Action extends string>(policy: Policy<Action>, action: Action): MiddlewareHandler;
165
+ interface TenantRoutesOptions<Action extends string> {
166
+ store: TenantStore;
167
+ user: UserFn;
168
+ /** The roles an invitation may grant (never owner or platform unless you list it). */
169
+ invitableRoles: readonly string[];
170
+ /**
171
+ * Inviting needs the active tenant (put tenantMiddleware before this app's
172
+ * /invites route), this action in the policy, AND a way to deliver the link.
173
+ * Without `deliverInvite` the route is not mounted: the token never travels
174
+ * back to the inviter's browser.
175
+ */
176
+ invite?: {
177
+ policy: Policy<Action>;
178
+ action: Action;
179
+ deliverInvite: (msg: {
180
+ to: string;
181
+ token: string;
182
+ tenant: Tenant;
183
+ role: string;
184
+ invitedBy: string;
185
+ scope?: string;
186
+ }) => Promise<void>;
187
+ /**
188
+ * Required for an invitation with a `scope` (a unit below the organisation).
189
+ * Only the app knows its unit tree, so only the app can say whether THIS
190
+ * inviter may grant this role there. Without it a body carrying `scope` is
191
+ * refused 400; a false answer is refused 403 `scope_not_allowed`. A scope is
192
+ * never silently dropped.
193
+ */
194
+ authorizeScope?: (inviter: Membership, scope: string, role: string) => boolean | Promise<boolean>;
195
+ };
196
+ }
197
+ /**
198
+ * JSON routes for the membership surface:
199
+ * GET /memberships → [{ tenant: {id, slug, name, status}, role }] for the signed-in user
200
+ * POST /invites/accept {token} → { tenant, role }
201
+ * POST /invites {email, role} → { inviteId } (only with `invite`, needs tenantMiddleware)
202
+ */
203
+ declare function tenantRoutes<Action extends string>(o: TenantRoutesOptions<Action>): Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
204
+
205
+ export { type TenantMiddlewareOptions, type TenantRoutesOptions, type TenantUser, getTenant, requireCapability, tenantErrorResponse, tenantMiddleware, tenantRoutes };