@plitzi/sdk-kernel 0.0.0-stage → 0.39.3

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 (142) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-BAV5YeT9.mjs +273 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +195 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
@@ -0,0 +1,278 @@
1
+ import { CredentialCarrier } from './credentials';
2
+ import { SSRSession } from '../types';
3
+ /**
4
+ * An account, as whatever stores accounts reports one. Deliberately not a user model: these are the only fields any
5
+ * decision here is made on, and a deployment maps its own row onto them.
6
+ */
7
+ export interface AccountRecord {
8
+ id: number;
9
+ username: string;
10
+ email: string;
11
+ /** Suspended, deactivated, whatever the deployment calls it — an inactive account never gets a session. */
12
+ active: boolean;
13
+ /** Confirmed their address. An unverified account may still sign in; what it may *do* is a matter for RBAC. */
14
+ verified: boolean;
15
+ /** Absent for accounts that have no password — one created through an identity provider, for instance. */
16
+ passwordHash?: string;
17
+ /**
18
+ * Unix seconds the refresh credential being renewed dies at, reported by `findByRefreshToken` — an override: left
19
+ * out, the credential's own expiry decides.
20
+ */
21
+ refreshExpiresAt?: number;
22
+ /**
23
+ * Unix seconds the session being renewed BEGAN, for `lifetimes.session` — the cap on how long one may live
24
+ * however often it renews. Only `findByRefreshToken` needs to report it, and only a deployment that sets a cap.
25
+ *
26
+ * The renewal window is already an idle timeout: a session nobody refreshes dies with its refresh token. This is
27
+ * the other half, and without it a session that renews quietly renews forever.
28
+ */
29
+ sessionStartedAt?: number;
30
+ }
31
+ export interface AccountAccess {
32
+ roles: string[];
33
+ permissions: string[];
34
+ }
35
+ /** What a session was created from, so a "your devices" list can name it. */
36
+ export interface SessionClient {
37
+ userAgent?: string;
38
+ ip?: string;
39
+ /**
40
+ * The host it was signed in on: a space's own (`acme.plitzi.app`), where its visitors sign in through the platform,
41
+ * or the platform's. What "sign out of this site everywhere" ends — a host's cookies are its own, so its sessions
42
+ * are what a visitor holds there, on every device.
43
+ */
44
+ host?: string;
45
+ /**
46
+ * The application holding it, when it is not a browser: a native client names itself when it registers
47
+ * (`Plitzi CLI on dev-laptop`, software `plitzi-cli`). A user agent says which browser; this says which app.
48
+ */
49
+ app?: SessionApp;
50
+ }
51
+ export interface SessionApp {
52
+ name: string;
53
+ /** A stable name for the software, the same on every machine — what a list picks an icon by. */
54
+ softwareId?: string;
55
+ }
56
+ /**
57
+ * What an account is allowed to be. `inactive` is the account's own doing (deactivated, never confirmed);
58
+ * `blocked` is the deployment's. Neither may hold a session — the distinction is for whoever has to explain it.
59
+ */
60
+ export type AccountStatus = 'active' | 'inactive' | 'blocked';
61
+ /** One live session, as its owner may see it. Never the credential itself. */
62
+ export interface SessionSummary {
63
+ id: number;
64
+ userAgent?: string;
65
+ ip?: string;
66
+ app?: SessionApp;
67
+ /** Where it was signed in (`SessionClient.host`): a space's own host, or the platform's. */
68
+ host?: string;
69
+ createdAt: number;
70
+ /** When it was last used, where the store keeps it; a session never seen since it was made has none. */
71
+ lastActiveAt?: number;
72
+ expiresAt: number;
73
+ /** The session asking. A device list without it invites someone to revoke the one they are using. */
74
+ current: boolean;
75
+ }
76
+ /** A second factor as the store keeps it. `secret` is the TOTP seed; `recoveryCodes` are already hashed. */
77
+ export interface MfaRecord {
78
+ secret: string;
79
+ /** Unix seconds the enrolment was proven with a real code. Absent means started and never finished. */
80
+ confirmedAt?: number;
81
+ recoveryCodes?: string[];
82
+ /**
83
+ * The time step of the last code that was accepted. A code of that step or an earlier one is refused: a code is valid
84
+ * for its whole window, and one watched over a shoulder or lifted from a phishing page would otherwise sign a second
85
+ * person in within that window (RFC 6238 §5.2).
86
+ */
87
+ lastUsedStep?: number;
88
+ }
89
+ /** Something worth writing down. Fed to an audit log, a webhook, a SIEM — whatever the deployment has. */
90
+ export interface SecurityEvent {
91
+ type: 'login' | 'login.failed' | 'login.mfa-required' | 'logout' | 'signup' | 'password.changed' | 'password.reset' | 'profile.changed' | 'email.changed' | 'account.deleted' | 'session.revoked' | 'mfa.enabled' | 'mfa.disabled' | 'mfa.failed' | 'admin.status-changed' | 'admin.roles-changed' | 'admin.account-deleted' | 'admin.impersonated';
92
+ /** Who it happened to. Absent when the attempt named nobody that exists. */
93
+ userId?: number;
94
+ /** Who did it, when that is somebody else — an administrator acting on an account. */
95
+ actorId?: number;
96
+ at: number;
97
+ detail?: Record<string, unknown>;
98
+ carrier?: CredentialCarrier;
99
+ }
100
+ export interface AccountQuery {
101
+ /** Matched against username and email. */
102
+ search?: string;
103
+ status?: AccountStatus;
104
+ limit?: number;
105
+ offset?: number;
106
+ }
107
+ /**
108
+ * Why a session is being written — which is not something the pair itself can say, and the difference matters to
109
+ * any store that keeps more than one session per account.
110
+ *
111
+ * A sign-in creates a session. A renewal **replaces one**, and a store that cannot tell them apart grows a row per
112
+ * renewal: a device list that fills with ghosts of the same browser, and a revoked session that comes back because
113
+ * the row it was meant to overwrite is still there. A store that keeps a single pair on the account row ignores
114
+ * this and overwrites either way, which is what it always did.
115
+ */
116
+ export interface SessionContext {
117
+ /** The credential being renewed. Absent for a fresh sign-in. */
118
+ replaces?: {
119
+ refreshToken?: string;
120
+ accessToken?: string;
121
+ };
122
+ client?: SessionClient;
123
+ }
124
+ /**
125
+ * The user agent and the address, off whatever carried the request — what lets somebody tell their devices apart.
126
+ * Nothing else here reads headers, so it is done once. The address is the host's when it resolved one, the proxies'
127
+ * otherwise; it names a session in a list and decides nothing.
128
+ */
129
+ export interface AccountAdapters {
130
+ /**
131
+ * Persist a freshly minted pair.
132
+ *
133
+ * `context` says whether this is a new session or one replacing another — see {@link SessionContext}. A store
134
+ * with one pair per account may ignore it and overwrite; a store with a `session` table must not, or every
135
+ * renewal leaves a row behind.
136
+ */
137
+ saveSession: (userId: number, session: SSRSession, context?: SessionContext) => Promise<void>;
138
+ /**
139
+ * Clear the pair, by whichever half the caller holds, or by account — and with `host` beside `userId`, only that
140
+ * account's sessions signed in on that host (`SessionClient.host`): a site's sign-out everywhere, not the account's.
141
+ */
142
+ clearSession: (target: {
143
+ accessToken?: string;
144
+ refreshToken?: string;
145
+ userId?: number;
146
+ host?: string;
147
+ }) => Promise<void>;
148
+ /** Global roles and permissions, for the body a grant answers with. */
149
+ loadAccess: (userId: number) => Promise<AccountAccess>;
150
+ /** By id. Needed wherever a flow acts on the account already signed in — changing a password, deleting itself. */
151
+ findById?: (userId: number) => Promise<AccountRecord | undefined>;
152
+ /**
153
+ * Change what an account says about itself. Only the keys present are touched — an absent `email` means "leave
154
+ * it", never "clear it", which is what an implementation writing every column unconditionally would do.
155
+ */
156
+ updateAccount?: (userId: number, changes: {
157
+ username?: string;
158
+ email?: string;
159
+ }) => Promise<AccountRecord>;
160
+ /**
161
+ * Suspend, block or restore. Separate from `deleteAccount` because they are different acts with different
162
+ * consequences: a suspension is reversible and keeps everything the account made.
163
+ */
164
+ setStatus?: (userId: number, status: AccountStatus) => Promise<void>;
165
+ /**
166
+ * Erase the account. Whether that means deleting a row or anonymising one is the deployment's call and it is a
167
+ * real one — content, audit logs and invoices usually have to outlive the person. Either way it must end every
168
+ * session, which deleting the account's sessions does.
169
+ */
170
+ deleteAccount?: (userId: number) => Promise<void>;
171
+ /**
172
+ * What would be lost if this account were deleted now, in sentences its owner can act on — "“Studio” has 3 spaces;
173
+ * delete them or make somebody else an owner". Any at all and the deletion is refused, with the list.
174
+ *
175
+ * The account is what holds things a deployment cannot simply drop: a workspace nobody else owns, the spaces in it,
176
+ * a plan still being paid for. Deleting it anyway leaves them orphaned — unreachable by anyone, and possibly still
177
+ * billed. Optional, for a deployment whose accounts own nothing.
178
+ */
179
+ deletionBlockers?: (userId: number) => Promise<string[]>;
180
+ /** Page through accounts, for an administrator. `total` is the count before the page was taken. */
181
+ listAccounts?: (query: AccountQuery) => Promise<{
182
+ accounts: AccountRecord[];
183
+ total: number;
184
+ }>;
185
+ /** Replace an account's global roles with exactly these. */
186
+ setRoles?: (userId: number, roles: string[]) => Promise<void>;
187
+ /** The account's live sessions. `currentToken` marks the one asking, so a device list can say "this device". */
188
+ listSessions?: (userId: number, currentToken?: string) => Promise<SessionSummary[]>;
189
+ /** End one session. Scoped by account: a session id from another account must not resolve. */
190
+ revokeSession?: (userId: number, sessionId: number) => Promise<boolean>;
191
+ /** End every session except the one asking. */
192
+ revokeOtherSessions?: (userId: number, currentToken: string) => Promise<number>;
193
+ findByUsername?: (username: string) => Promise<AccountRecord | undefined>;
194
+ findByRefreshToken?: (token: string) => Promise<AccountRecord | undefined>;
195
+ createAccount?: (account: {
196
+ username: string;
197
+ email: string;
198
+ passwordHash: string;
199
+ /** The terms the person accepted as they signed up, when the deployment asks for them (`terms`). */
200
+ termsAccepted?: {
201
+ version: string;
202
+ at: Date;
203
+ };
204
+ }) => Promise<AccountRecord>;
205
+ findByEmail?: (email: string) => Promise<AccountRecord | undefined>;
206
+ /**
207
+ * Why `account` may not sign in with a password, if it may not: its organization requires its own single sign-on.
208
+ * Asked only once the password is proved right — what is said of an account before that is said to anybody who
209
+ * types its address. The refusal is a 401 with the reason `sso-required` and these words — a 401 like `unverified`,
210
+ * the other refusal of a right password: it is what a browser's sign-in reads a reason from.
211
+ */
212
+ passwordSignInRefused?: (account: AccountRecord) => Promise<string | undefined>;
213
+ setPassword?: (userId: number, passwordHash: string) => Promise<void>;
214
+ setResetToken?: (userId: number, token: string) => Promise<void>;
215
+ findByResetToken?: (token: string) => Promise<AccountRecord | undefined>;
216
+ setValidationToken?: (userId: number, token: string) => Promise<void>;
217
+ findByValidationToken?: (token: string) => Promise<AccountRecord | undefined>;
218
+ /**
219
+ * Park an address the account asked to move to, with the token that will confirm it. It is NOT the account's
220
+ * address yet, and nothing may sign in with it — the whole point is that the old one keeps working until the new
221
+ * one is proven, so a typo is a nuisance instead of a lockout.
222
+ *
223
+ * Supplying these three (with `sendMail`) is what turns an email change into a confirmed one. A deployment that
224
+ * leaves them out changes the address on the spot, which is the simpler thing and a legitimate choice.
225
+ */
226
+ setPendingEmail?: (userId: number, email: string, token: string) => Promise<void>;
227
+ /** The account waiting on this confirmation, and the address it is waiting for. */
228
+ findByPendingEmail?: (token: string) => Promise<{
229
+ account: AccountRecord;
230
+ email: string;
231
+ } | undefined>;
232
+ /** Forget the parked address — it was confirmed, superseded, or the account was closed. */
233
+ clearPendingEmail?: (userId: number) => Promise<void>;
234
+ /**
235
+ * Confirm or un-confirm the address. Both directions from one adapter, because changing an email has to be able
236
+ * to take verification away — a `markVerified` that only ever set it made that impossible to express.
237
+ */
238
+ setVerified?: (userId: number, verified: boolean) => Promise<void>;
239
+ /**
240
+ * A one-time code, hashed. `purpose` separates a sign-in link from anything else that uses the same table, and
241
+ * `identifier` is what it was issued against — an email address, usually.
242
+ */
243
+ saveOtp?: (code: {
244
+ purpose: string;
245
+ identifier: string;
246
+ codeHash: string;
247
+ expiresAt: number;
248
+ userId?: number;
249
+ }) => Promise<void>;
250
+ /** The live code for this purpose and identifier, if there is one. Expired rows may be returned or not. */
251
+ findOtp?: (purpose: string, identifier: string) => Promise<{
252
+ id: number;
253
+ codeHash: string;
254
+ expiresAt: number;
255
+ userId?: number;
256
+ } | undefined>;
257
+ /** Spend it. Deleting rather than flagging: a spent code that still exists is one a lookup can forget to exclude. */
258
+ consumeOtp?: (id: number) => Promise<void>;
259
+ /** The second factor for this account, if it has one. Without it, no MFA is offered at all. */
260
+ loadMfa?: (userId: number) => Promise<MfaRecord | undefined>;
261
+ saveMfa?: (userId: number, record: MfaRecord) => Promise<void>;
262
+ deleteMfa?: (userId: number) => Promise<void>;
263
+ /** Called for validation and password-reset mail. Without it neither flow is offered. */
264
+ sendMail?: (message: {
265
+ to: string;
266
+ template: string;
267
+ data: Record<string, string>;
268
+ }) => Promise<void>;
269
+ /**
270
+ * Turn a credential the browser obtained from an identity provider into an account here. Everything that decides
271
+ * whether the credential is any good — which providers this deployment trusts, and that the token was minted for
272
+ * *this* application — lives in the implementation, because only it knows.
273
+ */
274
+ exchangeCredential?: (provider: string, token: string, carrier: CredentialCarrier) => Promise<AccountRecord | {
275
+ error: string;
276
+ status?: number;
277
+ } | undefined>;
278
+ }
@@ -0,0 +1,96 @@
1
+ import { CredentialCarrier } from './credentials';
2
+ import { Actor, Grant, Identity } from './identity';
3
+ import { AuthFailure } from './scopes';
4
+ /**
5
+ * Strings match exactly — a prefix test would make '/' match every route and silently expose everything under it.
6
+ * Regexes and predicates cover the cases that genuinely need to look at sub-paths (a predicate so social-auth routes
7
+ * can resolve a provider registry rather than trusting the shape of a URL).
8
+ */
9
+ export type PathMatcher = string | RegExp | ((path: string) => boolean);
10
+ /**
11
+ * Both credentials are resolved for every non-public request; the requirement only says which must be there.
12
+ * Resolving the one that is absent is nearly free — a token of the wrong kind fails on its `scope` claim before any
13
+ * database lookup.
14
+ */
15
+ export type Requirement =
16
+ /** No credential is read and nothing is checked. */
17
+ 'public'
18
+ /**
19
+ * Neither is required. Authorization happens deeper in (GraphQL guards each operation), so the transport must let
20
+ * anonymous requests through to be refused there properly rather than with a bare 401.
21
+ */
22
+ | 'optional'
23
+ /** A valid space grant. Says which space — never that the caller may change it. */
24
+ | 'grant'
25
+ /** A verified account. */
26
+ | 'actor'
27
+ /**
28
+ * Both: the space is named by the token, the authority comes from the session. What anything that writes on
29
+ * behalf of a person needs.
30
+ */
31
+ | 'grant+actor';
32
+ export interface AuthPolicy {
33
+ rules: {
34
+ match: PathMatcher[];
35
+ requirement: Requirement;
36
+ }[];
37
+ fallback: Requirement;
38
+ }
39
+ export type AuthorizeResult = {
40
+ ok: true;
41
+ actor?: Actor;
42
+ grant?: Grant;
43
+ } | {
44
+ ok: false;
45
+ status: number;
46
+ reason: AuthFailure;
47
+ };
48
+ export declare const requirementFor: (policy: AuthPolicy, path: string) => Requirement;
49
+ /**
50
+ * Decides whether a request may proceed, and with what identity — the same decision on every transport, which is
51
+ * the point of it living here rather than inside one framework's middleware. Callers bind it to their own: Express
52
+ * puts the result on `req` and answers 401 itself, this server's pipeline does the same with its own response.
53
+ */
54
+ export declare const createAuthorizer: (identity: Identity, policy: AuthPolicy) => (carrier: CredentialCarrier, path: string) => Promise<AuthorizeResult>;
55
+ export type Authorizer = ReturnType<typeof createAuthorizer>;
56
+ export type PermissionCheck = {
57
+ ok: true;
58
+ } | {
59
+ ok: false;
60
+ status: number;
61
+ error: string;
62
+ };
63
+ /**
64
+ * A global capability, checked off the actor the guard already resolved — no query. This is the whole of RBAC that
65
+ * applies outside a space: platform-wide routes rather than "may you touch this space", which is `identity.can()` and
66
+ * needs the membership half too.
67
+ *
68
+ * An answer rather than a middleware, so it reads the same from any host. The distinction it exists to make is 401
69
+ * against 403: "nobody is here" and "you are here and this is not yours" are different facts, and collapsing them
70
+ * tells a signed-in caller to sign in again.
71
+ */
72
+ export declare const checkPermission: (actor: Actor | undefined, permission: string) => PermissionCheck;
73
+ /** What a membership row has to say for the check below. A deployment's own row will carry far more. */
74
+ export interface MembershipFacts {
75
+ isOwner: boolean;
76
+ }
77
+ export type SpaceAccessCheck = {
78
+ ok: true;
79
+ } | {
80
+ ok: false;
81
+ status: number;
82
+ error: string;
83
+ };
84
+ /**
85
+ * The space half: may this actor act on this space at all, and is being its owner required?
86
+ *
87
+ * The answer that matters is the middle one. A non-member gets **404, not 403** — telling a stranger "you may not
88
+ * touch this space" confirms the space exists, and whether a given slug belongs to somebody is not a fact an
89
+ * outsider gets to establish by asking. Owners and members are told apart afterwards, because by then the caller has
90
+ * already proved they belong there and 403 gives away nothing.
91
+ *
92
+ * Resolving the membership is the deployment's — its tables, and whether a route names a space by id or by slug.
93
+ */
94
+ export declare const checkSpaceAccess: (actor: Actor | undefined, membership: MembershipFacts | undefined, { owner }?: {
95
+ owner?: boolean;
96
+ }) => SpaceAccessCheck;
@@ -0,0 +1,40 @@
1
+ import { IncomingHttpHeaders } from 'node:http';
2
+ /**
3
+ * The shape both an Express `Request` and this server's own `SSRRequest` satisfy. Everything that reads a credential
4
+ * off a request goes through it, so header/cookie precedence is stated once instead of once per transport.
5
+ */
6
+ export interface CredentialCarrier {
7
+ headers: IncomingHttpHeaders;
8
+ hostname: string;
9
+ query?: Record<string, unknown>;
10
+ /** Populated by cookie-parser on Express; absent elsewhere, where the header is parsed. */
11
+ cookies?: Record<string, string>;
12
+ /** The client's address as the host resolved it (Express's `req.ip`, honouring its `trust proxy`). */
13
+ ip?: string;
14
+ }
15
+ export declare const readCookies: (carrier: CredentialCarrier) => Record<string, string>;
16
+ /**
17
+ * Where a credential of each kind is allowed to ride.
18
+ *
19
+ * `Authorization: Bearer` carries a session token on one role and a space token on another, so it is a candidate for
20
+ * both and the typed verifier decides which it actually is — that is what `scope` is for. Trying the wrong kind
21
+ * costs nothing: it fails on its scope claim before any database is touched.
22
+ */
23
+ /** The query parameter a space token rides in: how a page on a host serving many spaces names the one it is. */
24
+ export declare const SPACE_TOKEN_PARAM = "access-token";
25
+ export declare const createCarriers: (sessionCookieName: (hostname: string) => string) => {
26
+ userTokenCandidates: (carrier: CredentialCarrier) => string[];
27
+ spaceTokenCandidates: (carrier: CredentialCarrier) => string[];
28
+ };
29
+ /**
30
+ * The origin the caller claims to be presenting from — the `Origin` header, and nothing else. Distinct from this
31
+ * server's own origin (see `requestOrigin` in the request parser): this one is the claim a credential's domain
32
+ * binding is checked against.
33
+ *
34
+ * Empty when the header is absent, which is a fact the caller downstream has to be able to see. This used to fall
35
+ * back to `carrier.hostname`, and that fallback could only ever deny: a hostname carries no scheme, so it matched no
36
+ * entry in any origins list, and every server-to-server caller — a self-hosted deployment reading its own space
37
+ * through `createCloudAdapters`, most of all — was refused with `origin-not-allowed` while the branch written to
38
+ * handle a missing Origin was unreachable.
39
+ */
40
+ export declare const presentedOrigin: (carrier: CredentialCarrier) => string;
@@ -0,0 +1,139 @@
1
+ import { CookieRequest, CookieSink } from './session';
2
+ import { SSRAuthCookie } from '../types';
3
+ export interface CsrfConfig {
4
+ /** Signs the tokens. `createAuth` uses the token secret, so a deployment never states this either. */
5
+ secret: string;
6
+ /** Naming and scope for the cookie, so it lands beside the session one. */
7
+ cookie?: SSRAuthCookie;
8
+ /**
9
+ * Origins that count as this deployment's own, beyond the request's own origin.
10
+ *
11
+ * What it decides is which cross-site page may hand out a session — see `foreign` below. `createAuth` fills it
12
+ * from `identity.platformOrigins`, so a deployment that already declared its hosts has said this too, and this
13
+ * whole module ends up configuring itself.
14
+ */
15
+ allowedOrigins?: string[] | ((origin: string) => boolean);
16
+ }
17
+ /**
18
+ * What kind of flow a request is reaching, which is what decides when a token is demanded.
19
+ *
20
+ * - **`write`** — an action taken as somebody. Guarded whenever a cookie could have authenticated it.
21
+ * - **`signIn`** — hands out a session. There is no cookie to protect yet, and the attack is different: another
22
+ * site signing a visitor into an account IT controls, so that what they do next is recorded against it. Guarded
23
+ * by where the request came from, since that is what separates the attack from every legitimate sign-in.
24
+ * - **`delegated`** — also hands out a session, but the flow checks the caller's origin itself against something
25
+ * narrower than any list here: `/auth/exchange` acts for a space and is refused unless the origin is one that
26
+ * space declared. Applying the check below on top would refuse every legitimate embed.
27
+ */
28
+ export type CsrfSubject = 'write' | 'signIn' | 'delegated';
29
+ export type CsrfFailure = 'missing' | 'malformed' | 'expired' | 'mismatch' | 'foreign';
30
+ export declare const csrfFailureMessage: Record<CsrfFailure, string>;
31
+ export type CsrfResult = {
32
+ ok: true;
33
+ } | {
34
+ ok: false;
35
+ reason: CsrfFailure;
36
+ };
37
+ /** What a request has to look like for this to read it. Satisfied by Express, `node:http` plus a parse, and ours. */
38
+ export interface CsrfCarrier {
39
+ method?: string;
40
+ headers: Record<string, string | string[] | undefined>;
41
+ hostname: string;
42
+ cookies?: Record<string, string>;
43
+ body?: unknown;
44
+ }
45
+ /**
46
+ * The carrier, read off whatever request a host hands over — named field by field, never spread.
47
+ *
48
+ * A spread copies OWN properties, and on Node's `IncomingMessage` (which an Express request is) `headers` is a getter on
49
+ * the prototype: `{ ...req }` arrives with no headers at all, and the first header read throws. Every guard built on a
50
+ * spread failed that way on every request.
51
+ */
52
+ export declare const carrierOf: (req: {
53
+ method?: string;
54
+ headers: CsrfCarrier["headers"];
55
+ hostname: string;
56
+ cookies?: unknown;
57
+ body?: unknown;
58
+ }, method?: string | undefined) => CsrfCarrier;
59
+ /**
60
+ * Did a page of another ORIGIN cause this request — `allowed` naming the origins this deployment counts as its own?
61
+ *
62
+ * This is what protects signing in, where there is no session to bind a token to and no cookie to look for, and
63
+ * every write a page server answers, cookie or none (`crossSiteWritesStage`). It rests on two headers a page CANNOT
64
+ * set — the browser attaches both, and script may not override either:
65
+ *
66
+ * - **`Sec-Fetch-Site`** is the browser's own account of where the request came from, and is believed first.
67
+ * `same-origin`, and `none` (a typed URL, a bookmark), are this server's own; `same-site` and `cross-site` are a
68
+ * page of another origin, foreign unless its origin was named.
69
+ * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
70
+ * **exactly** — host and port, over HTTP/1.1 and HTTP/2 alike; one port does not serve two schemes — against the
71
+ * authority the request was addressed to, or an origin the deployment named.
72
+ *
73
+ * **`same-site` is not trusted, and was once.** A site is a registrable domain, with no port in it: another port of
74
+ * this host, or a sibling sub-domain, is the same site. Both are where somebody else's code is served by design —
75
+ * `createAuthoringHost` on a port of its own, every space of a platform on a sub-domain of one domain (two spaces at
76
+ * `*.plitzi.app` are one site until that domain is on the public suffix list) — and trusting the site let any of them
77
+ * write here as if they were this server's own pages. A sibling that IS this deployment's own is named, as it always
78
+ * had to be in production, where the app and its spaces are on different sites: `createAuth` fills the list from
79
+ * `identity.platformOrigins`, a page server from `crossSiteWrites.origins`.
80
+ *
81
+ * Nor is a domain boundary guessed: this once compared *registrable domains*, last-two-labels, and with no public
82
+ * suffix list every other `.co.uk` counted as the same site as a deployment at `acme.co.uk`.
83
+ *
84
+ * **Neither header means this is not a browser**, and a client that is not a browser cannot be made to forge
85
+ * anything: there is no victim's session sitting in it. That is what keeps every API client, mobile app and
86
+ * script signing in with nothing extra to send.
87
+ */
88
+ export declare const crossSiteRequest: (carrier: CsrfCarrier, allowed?: (origin: string) => boolean) => boolean;
89
+ export declare const createCsrf: (config: CsrfConfig) => {
90
+ issue: (sessionToken?: string) => string;
91
+ /** The name the cookie lands under, for a client that reads it by hand. */
92
+ cookieName: (hostname: string) => string;
93
+ /** The header the echo is expected in, published by `GET /auth/csrf` so a client is never told it twice. */
94
+ headerName: string;
95
+ /** Readable on purpose: `httpOnly` would make it impossible for a page to echo it back. It is not a credential. */
96
+ write: (req: CookieRequest, res: CookieSink, token: string) => void;
97
+ /**
98
+ * Drops the cookie, on the same attributes it was written with — anything else leaves the original in place and
99
+ * adds a second one the browser then has to choose between.
100
+ *
101
+ * Called when a session ends. Nothing depended on it going: the token is signed over the session it belongs to,
102
+ * so once that session is revoked it verifies against nothing, and a write is only ever asked for a token when a
103
+ * session cookie is present. But a logout that leaves a cookie behind is one somebody has to reason about to
104
+ * dismiss, and on a shared browser "signed out" should mean nothing of the session is still sitting there.
105
+ */
106
+ clear: (req: CookieRequest, res: CookieSink) => void;
107
+ read: (carrier: CsrfCarrier) => string | undefined;
108
+ /**
109
+ * Does this request need a token at all?
110
+ *
111
+ * Two requests can never be forged into, whatever they are reaching, and neither is ever asked:
112
+ *
113
+ * - a **safe method**, which changes nothing;
114
+ * - one presenting **`Authorization: Bearer`** — a cross-origin page cannot set that header without a
115
+ * preflight this server would have to allow, so requiring a token would break every API client to protect
116
+ * nobody.
117
+ *
118
+ * After that it depends on what the flow does, which is what `subject` says — an action taken as somebody is
119
+ * protected by the session cookie's presence, a sign-in by where the request came from. See {@link CsrfSubject}.
120
+ */
121
+ required: (carrier: CsrfCarrier, subject?: CsrfSubject) => boolean;
122
+ /**
123
+ * Whether a browser sent this from a site this deployment does not recognise — its own origins, and
124
+ * `alsoAllowed` (the origins a SPACE declared, for a request that carries that space's credential).
125
+ *
126
+ * The rule `signIn` flows are guarded by, offered on its own for a router whose writes cannot all carry a token:
127
+ * a cookie-carried write that a foreign page caused is refused by where it came from — see
128
+ * `createOriginGuardMiddleware`. A request with neither Fetch Metadata nor `Origin` is not a browser's, and is
129
+ * never foreign: there is no victim's session in a script.
130
+ */
131
+ crossSite: (carrier: CsrfCarrier, alsoAllowed?: readonly string[]) => boolean;
132
+ /**
133
+ * The whole check. The echoed token must verify against the session the request carries, and — when the
134
+ * cookie is also present — match it. The second half costs nothing and blocks a token that leaked somewhere
135
+ * the cookie did not.
136
+ */
137
+ verify: (carrier: CsrfCarrier, sessionToken?: string) => CsrfResult;
138
+ };
139
+ export type Csrf = ReturnType<typeof createCsrf>;
@@ -0,0 +1,24 @@
1
+ import { Schema } from '@plitzi/sdk-shared';
2
+ type DebugConfig = {
3
+ debugMode?: boolean;
4
+ devMode?: boolean;
5
+ };
6
+ type DebugSettings = Pick<Schema['settings'], 'debugMode'> | undefined;
7
+ /**
8
+ * Whether a page — and what its flows did — may be debugged. One rule for the render and for every run it reports.
9
+ *
10
+ * The server decides first, through `debugMode`: set, it speaks for every space, and `false` is a refusal no space can
11
+ * turn around. Left unset, a development server authorizes it, and so does a space whose own settings switched
12
+ * `debugMode` on. The settings are what this server loaded, never anything the request carries.
13
+ *
14
+ * A page nobody authorized is told nothing: not the steps behind it, not even that a flow ran.
15
+ */
16
+ export declare const authorizesDebugging: (config: DebugConfig, settings: DebugSettings) => boolean;
17
+ /**
18
+ * The same rule, for a request that has not loaded the space yet.
19
+ *
20
+ * The settings are read only when the server left the answer to the space. A space that cannot be read authorizes
21
+ * nothing: debugging is the one thing about a page that fails closed.
22
+ */
23
+ export declare const resolveDebugAuthorization: (config: DebugConfig, loadSettings: () => Promise<DebugSettings>) => Promise<boolean>;
24
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Declared domains are stored and signed as full origins (`https://site.example.com`) while a request host is bare
3
+ * (`site.example.com`), so both sides are reduced to a hostname before being compared. A non-web value still reduces
4
+ * to something — `plitzi-desktop` to itself, `chrome-extension://…` to its authority — but neither is a host a
5
+ * request ever reports, so it never matches.
6
+ */
7
+ export declare const hostnameOf: (value: string) => string;
8
+ /** The wildcard a space sets when its embed target is genuinely unknown. Named so an API can warn about it. */
9
+ export declare const ANY_DOMAIN = "*";
10
+ /**
11
+ * May a token declaring `origins` be presented on `host`?
12
+ *
13
+ * `platformHosts` are this deployment's own — its builder, its renderer, its MCP endpoint — which serve first-party
14
+ * traffic for every space and are therefore valid destinations for any token, whatever domains it declares. They are
15
+ * passed in rather than read from configuration here because only the deployment knows what it runs.
16
+ */
17
+ export declare const domainAllowed: (host: string, origins: string[], platformHosts?: string[]) => boolean;
18
+ /**
19
+ * User input arrives as whatever someone typed — `example.com`, `https://example.com/`, `HTTPS://Example.com/x`. It
20
+ * is stored as a canonical origin so the signed claim, the stored column and the comparison all agree.
21
+ */
22
+ export declare const normalizeDomain: (value: string) => string | undefined;
23
+ /**
24
+ * Who may put this space in an iframe, as CSP `frame-ancestors` sources.
25
+ *
26
+ * The deployment's own hosts are the floor — a builder previews every space in one — and a space widens it with the
27
+ * domains its owner declared. `*` opts out entirely. Without this a published space is framable from any site on the
28
+ * web, which is how one customer wraps another's space inside their own page and passes it off as theirs.
29
+ *
30
+ * Unlike the token's domain binding, this one is enforced by the browser, which is why it is worth stating even
31
+ * though a determined caller can ignore the header: it stops the attack that needs a real visitor's browser.
32
+ */
33
+ export declare const frameAncestors: (declared: string[], platformHosts?: string[]) => string[];
34
+ /**
35
+ * Which origins a request bearing this grant may be answered for.
36
+ *
37
+ * A space is reachable from the origins its own token declares, plus this deployment's own apps; `*` means anywhere,
38
+ * and a grant that declares nothing at all falls back to the deployment's own unless it allows anonymous origins.
39
+ * Returning `true` means "reflect whatever asked", which is what a CORS layer wants for the wildcard case.
40
+ */
41
+ export declare const corsOrigins: (declared: string[] | undefined, platformOrigins?: string[], allowWithoutOrigin?: boolean) => true | string[];