@plitzi/sdk-kernel 0.0.0-stage → 0.39.2

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 +10 -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-CBd5tXut.mjs +262 -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 +190 -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,1203 @@
1
+ import { n as selectOne, r as selectRows, t as execute } from "../chunks/query-DGbrN3mN.mjs";
2
+ import { i as hashPassword, n as activityDue } from "../chunks/sessionActivity-Ch7xuQ_o.mjs";
3
+ // src/mysql/sessions.ts
4
+ /**
5
+ * The sessions of one account, as a thing that can be looked at and taken away one at a time.
6
+ *
7
+ * This is what a `session` table buys over a token pair on the account row, and it is the whole reason to pay for
8
+ * it: somebody who left themselves signed in on a machine they no longer have can end that session and keep the
9
+ * ones they are using. Revoking everything is `clearSession({ userId })` and is a blunter instrument.
10
+ */
11
+ var createSessionStore = (db, t) => {
12
+ const list = async (accountId, currentToken) => {
13
+ return (await selectRows(db, `SELECT id, token, user_agent, ip, app_name, app_id, host, created_at, last_active_at, expires_at
14
+ FROM ${t.session}
15
+ WHERE account_id = ?
16
+ ORDER BY created_at DESC`, [accountId])).map((row) => ({
17
+ id: row.id,
18
+ ...row.user_agent ? { userAgent: row.user_agent } : {},
19
+ ...row.ip ? { ip: row.ip } : {},
20
+ ...row.app_name ? { app: {
21
+ name: row.app_name,
22
+ ...row.app_id ? { softwareId: row.app_id } : {}
23
+ } } : {},
24
+ ...row.host ? { host: row.host } : {},
25
+ createdAt: Math.floor(row.created_at.getTime() / 1e3),
26
+ ...row.last_active_at ? { lastActiveAt: row.last_active_at } : {},
27
+ expiresAt: row.expires_at,
28
+ current: currentToken !== void 0 && row.token === currentToken
29
+ }));
30
+ };
31
+ return {
32
+ list,
33
+ /** Scoped by account as well as id, or one account could end another's session by guessing a number. */
34
+ revoke: async (accountId, sessionId) => {
35
+ return (await execute(db, `DELETE FROM ${t.session} WHERE id = ? AND account_id = ?`, [sessionId, accountId])).affectedRows > 0;
36
+ },
37
+ /** "Sign out everywhere else" — the one thing to do from a device you still trust after losing one you do not. */
38
+ revokeOthers: async (accountId, currentToken) => {
39
+ return (await execute(db, `DELETE FROM ${t.session} WHERE account_id = ? AND token <> ?`, [accountId, currentToken])).affectedRows;
40
+ },
41
+ /**
42
+ * Delete what has aged out. Nothing depends on this for correctness — an expired session is refused by its
43
+ * expiry, not by its absence — so it is housekeeping a deployment schedules, not a step in any request.
44
+ */
45
+ purgeExpired: async () => {
46
+ const now = Math.floor(Date.now() / 1e3);
47
+ return (await execute(db, `DELETE FROM ${t.session}
48
+ WHERE expires_at < ? AND (refresh_expires_at IS NULL OR refresh_expires_at < ?)`, [now, now])).affectedRows;
49
+ }
50
+ };
51
+ };
52
+ // src/mysql/accounts.ts
53
+ var ACCOUNT_COLUMNS = "a.id, a.username, a.email, a.password_hash, a.status, a.verified";
54
+ var toRecord$1 = (row) => ({
55
+ id: row.id,
56
+ username: row.username,
57
+ email: row.email,
58
+ active: row.status === "active",
59
+ verified: row.verified === 1,
60
+ ...row.password_hash ? { passwordHash: row.password_hash } : {},
61
+ ...row.refresh_expires_at !== null && row.refresh_expires_at !== void 0 ? { refreshExpiresAt: row.refresh_expires_at } : {},
62
+ ...row.session_started_at !== null && row.session_started_at !== void 0 ? { sessionStartedAt: row.session_started_at } : {}
63
+ });
64
+ /**
65
+ * An opaque single-use token, as a lookup key. Empty is not one.
66
+ *
67
+ * Clearing a reset token is written as `setResetToken(userId, '')` — the flows say so — and an empty string stored
68
+ * as an empty string is a value that MATCHES: one lookup would then return whichever account was cleared first, and
69
+ * a password-reset link with no token in it would work. Stored as NULL, and never looked up when blank.
70
+ */
71
+ var asLookup = (token) => token.trim() === "" ? void 0 : token;
72
+ var accessRows = (rows) => {
73
+ const roles = /* @__PURE__ */ new Set();
74
+ const permissions = /* @__PURE__ */ new Set();
75
+ for (const row of rows) {
76
+ roles.add(row.role);
77
+ if (row.permission) permissions.add(row.permission);
78
+ }
79
+ return {
80
+ roles: [...roles],
81
+ permissions: [...permissions]
82
+ };
83
+ };
84
+ var createAccountStore = (db, t) => {
85
+ const sessions = createSessionStore(db, t);
86
+ const findBy = (column, value) => selectOne(db, `SELECT ${ACCOUNT_COLUMNS} FROM ${t.account} a WHERE a.${column} = ? LIMIT 1`, [value]);
87
+ const loadAccess = async (userId) => accessRows(await selectRows(db, `SELECT r.name AS role, p.name AS permission
88
+ FROM ${t.accountRole} ar
89
+ JOIN ${t.role} r ON r.id = ar.role_id
90
+ LEFT JOIN ${t.rolePermission} rp ON rp.role_id = r.id
91
+ LEFT JOIN ${t.permission} p ON p.id = rp.permission_id
92
+ WHERE ar.account_id = ?`, [userId]));
93
+ return {
94
+ /**
95
+ * Looked up BY THE TOKEN, which is what makes a session revocable: writing a new pair over the row retires the
96
+ * previous one, so a credential that no longer matches is dead however valid its signature still is.
97
+ *
98
+ * A suspended account resolves to nothing at all rather than to an actor the caller then has to remember to
99
+ * check — deactivating somebody has to end the session they are already holding, not just the next login.
100
+ */
101
+ findAccountByToken: async (token) => {
102
+ const row = await selectOne(db, `SELECT ${ACCOUNT_COLUMNS}, s.id AS session_id, s.expires_at AS session_expires_at,
103
+ s.last_active_at AS session_last_active_at
104
+ FROM ${t.session} s
105
+ JOIN ${t.account} a ON a.id = s.account_id
106
+ WHERE s.token = ? AND a.status = 'active'
107
+ LIMIT 1`, [token]);
108
+ if (!row) return;
109
+ const now = Math.floor(Date.now() / 1e3);
110
+ if (row.session_id !== void 0 && activityDue(row.session_last_active_at, now)) execute(db, `UPDATE ${t.session} SET last_active_at = ? WHERE id = ?`, [now, row.session_id]).catch(() => void 0);
111
+ const { roles, permissions } = await loadAccess(row.id);
112
+ return {
113
+ id: row.id,
114
+ username: row.username,
115
+ email: row.email,
116
+ verified: row.verified === 1,
117
+ roles,
118
+ permissions,
119
+ token,
120
+ expiresAt: row.session_expires_at ?? 0
121
+ };
122
+ },
123
+ findSpaceToken: async (token) => {
124
+ const row = await selectOne(db, `SELECT space_id, scope, account_id FROM ${t.spaceToken} WHERE token = ? LIMIT 1`, [token]);
125
+ if (!row) return;
126
+ return {
127
+ spaceId: row.space_id,
128
+ scope: row.scope,
129
+ ...row.account_id !== null ? { userId: row.account_id } : {}
130
+ };
131
+ },
132
+ findMembership: async (userId, spaceId) => {
133
+ const rows = await selectRows(db, `SELECT sm.is_owner, r.name AS role, p.name AS permission
134
+ FROM ${t.spaceMember} sm
135
+ JOIN ${t.role} r ON r.id = sm.role_id
136
+ LEFT JOIN ${t.rolePermission} rp ON rp.role_id = r.id
137
+ LEFT JOIN ${t.permission} p ON p.id = rp.permission_id
138
+ WHERE sm.account_id = ? AND sm.space_id = ?`, [userId, spaceId]);
139
+ if (rows.length === 0) return;
140
+ const { roles, permissions } = accessRows(rows);
141
+ return {
142
+ spaceId,
143
+ isOwner: rows[0].is_owner === 1,
144
+ role: roles[0],
145
+ permissions
146
+ };
147
+ },
148
+ loadAccess,
149
+ /**
150
+ * A sign-in adds a session; a renewal replaces the one it names.
151
+ *
152
+ * The replace is an UPDATE on purpose, not a delete-then-insert: it keeps the row's identity, so the device
153
+ * somebody sees in their session list is still the same device after it renews, and a session revoked in the
154
+ * instant between the two cannot come back. When the update matches nothing — the session was revoked while
155
+ * this renewal was in flight — **no row is written**. The caller walks away with a credential that is not
156
+ * stored, which is a signed-out user rather than a revoked session resurrected.
157
+ */
158
+ saveSession: async (userId, session, context) => {
159
+ const replaces = context?.replaces;
160
+ if (replaces?.refreshToken !== void 0 || replaces?.accessToken !== void 0) {
161
+ const column = replaces.refreshToken !== void 0 ? "refresh_token" : "token";
162
+ const value = replaces.refreshToken ?? replaces.accessToken;
163
+ await execute(db, `UPDATE ${t.session}
164
+ SET token = ?, expires_at = ?, refresh_token = ?, refresh_expires_at = ?
165
+ WHERE ${column} = ? AND account_id = ?`, [
166
+ session.token,
167
+ session.expiresAt,
168
+ session.refreshToken ?? null,
169
+ session.refreshExpiresAt ?? null,
170
+ value,
171
+ userId
172
+ ]);
173
+ return;
174
+ }
175
+ await execute(db, `INSERT INTO ${t.session}
176
+ (account_id, token, expires_at, refresh_token, refresh_expires_at, user_agent, ip, app_name, app_id, host)
177
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
178
+ userId,
179
+ session.token,
180
+ session.expiresAt,
181
+ session.refreshToken ?? null,
182
+ session.refreshExpiresAt ?? null,
183
+ context?.client?.userAgent?.slice(0, 255) ?? null,
184
+ context?.client?.ip ?? null,
185
+ context?.client?.app?.name.slice(0, 120) ?? null,
186
+ context?.client?.app?.softwareId?.slice(0, 64) ?? null,
187
+ context?.client?.host?.slice(0, 255) ?? null
188
+ ]);
189
+ },
190
+ /**
191
+ * By whichever half the caller is holding, or every session of an account.
192
+ *
193
+ * An empty target clears NOTHING — a `WHERE` assembled from no conditions is a `WHERE` that matches every row,
194
+ * and the statement that would sign out an entire deployment must not be reachable by leaving an argument off.
195
+ */
196
+ clearSession: async (target) => {
197
+ if (target.host !== void 0) {
198
+ if (target.userId !== void 0) await execute(db, `DELETE FROM ${t.session} WHERE account_id = ? AND host = ?`, [target.userId, target.host]);
199
+ return;
200
+ }
201
+ const conditions = [];
202
+ const params = [];
203
+ if (target.userId !== void 0) {
204
+ conditions.push("account_id = ?");
205
+ params.push(target.userId);
206
+ }
207
+ if (target.accessToken !== void 0) {
208
+ conditions.push("token = ?");
209
+ params.push(target.accessToken);
210
+ }
211
+ if (target.refreshToken !== void 0) {
212
+ conditions.push("refresh_token = ?");
213
+ params.push(target.refreshToken);
214
+ }
215
+ if (conditions.length === 0) return;
216
+ await execute(db, `DELETE FROM ${t.session} WHERE ${conditions.join(" OR ")}`, params);
217
+ },
218
+ findByUsername: async (username) => {
219
+ const row = await findBy("username", username);
220
+ return row ? toRecord$1(row) : void 0;
221
+ },
222
+ findByEmail: async (email) => {
223
+ const row = await findBy("email", email);
224
+ return row ? toRecord$1(row) : void 0;
225
+ },
226
+ /** `refreshExpiresAt` comes off the ROW: it is the deadline renewal honours, over the token's own expiry. */
227
+ findByRefreshToken: async (token) => {
228
+ const row = await selectOne(db, `SELECT ${ACCOUNT_COLUMNS}, s.refresh_expires_at, UNIX_TIMESTAMP(s.created_at) AS session_started_at
229
+ FROM ${t.session} s
230
+ JOIN ${t.account} a ON a.id = s.account_id
231
+ WHERE s.refresh_token = ?
232
+ LIMIT 1`, [token]);
233
+ return row ? toRecord$1(row) : void 0;
234
+ },
235
+ createAccount: async (account) => {
236
+ return {
237
+ id: (await execute(db, `INSERT INTO ${t.account} (username, email, password_hash, terms_version, terms_accepted_at) VALUES (?, ?, ?, ?, ?)`, [
238
+ account.username,
239
+ account.email,
240
+ account.passwordHash,
241
+ account.termsAccepted?.version ?? null,
242
+ account.termsAccepted?.at ?? null
243
+ ])).insertId,
244
+ username: account.username,
245
+ email: account.email,
246
+ active: true,
247
+ verified: false,
248
+ passwordHash: account.passwordHash
249
+ };
250
+ },
251
+ setPassword: async (userId, passwordHash) => {
252
+ await execute(db, `UPDATE ${t.account} SET password_hash = ? WHERE id = ?`, [passwordHash, userId]);
253
+ },
254
+ setResetToken: async (userId, token) => {
255
+ await execute(db, `UPDATE ${t.account} SET reset_token = ? WHERE id = ?`, [asLookup(token) ?? null, userId]);
256
+ },
257
+ findByResetToken: async (token) => {
258
+ const lookup = asLookup(token);
259
+ if (!lookup) return;
260
+ const row = await findBy("reset_token", lookup);
261
+ return row ? toRecord$1(row) : void 0;
262
+ },
263
+ setValidationToken: async (userId, token) => {
264
+ await execute(db, `UPDATE ${t.account} SET validation_token = ? WHERE id = ?`, [asLookup(token) ?? null, userId]);
265
+ },
266
+ findByValidationToken: async (token) => {
267
+ const lookup = asLookup(token);
268
+ if (!lookup) return;
269
+ const row = await findBy("validation_token", lookup);
270
+ return row ? toRecord$1(row) : void 0;
271
+ },
272
+ /**
273
+ * The address is parked in its own column, so nothing that resolves an account by email can find it: it is not
274
+ * this account's address until it is confirmed, and a lookup that matched it would let an unconfirmed change
275
+ * take over a sign-in identifier.
276
+ */
277
+ setPendingEmail: async (userId, email, token) => {
278
+ await execute(db, `UPDATE ${t.account} SET pending_email = ?, pending_email_token = ? WHERE id = ?`, [
279
+ email,
280
+ asLookup(token) ?? null,
281
+ userId
282
+ ]);
283
+ },
284
+ findByPendingEmail: async (token) => {
285
+ const lookup = asLookup(token);
286
+ if (!lookup) return;
287
+ const row = await selectOne(db, `SELECT ${ACCOUNT_COLUMNS}, a.pending_email FROM ${t.account} a WHERE a.pending_email_token = ? LIMIT 1`, [lookup]);
288
+ return row?.pending_email ? {
289
+ account: toRecord$1(row),
290
+ email: row.pending_email
291
+ } : void 0;
292
+ },
293
+ clearPendingEmail: async (userId) => {
294
+ await execute(db, `UPDATE ${t.account} SET pending_email = NULL, pending_email_token = NULL WHERE id = ?`, [userId]);
295
+ },
296
+ setVerified: async (userId, verified) => {
297
+ await execute(db, `UPDATE ${t.account} SET verified = ?, validation_token = NULL WHERE id = ?`, [verified ? 1 : 0, userId]);
298
+ },
299
+ findById: async (userId) => {
300
+ const row = await findBy("id", userId);
301
+ return row ? toRecord$1(row) : void 0;
302
+ },
303
+ /**
304
+ * Only the columns the caller named. A blanket UPDATE cannot tell "leave the email alone" from "clear it", and
305
+ * a profile form that posts one field would wipe the other.
306
+ */
307
+ updateAccount: async (userId, changes) => {
308
+ const columns = [];
309
+ const params = [];
310
+ if (changes.username !== void 0) {
311
+ columns.push("username = ?");
312
+ params.push(changes.username);
313
+ }
314
+ if (changes.email !== void 0) {
315
+ columns.push("email = ?");
316
+ params.push(changes.email);
317
+ }
318
+ if (columns.length > 0) await execute(db, `UPDATE ${t.account} SET ${columns.join(", ")} WHERE id = ?`, [...params, userId]);
319
+ const row = await findBy("id", userId);
320
+ if (!row) throw new Error(`@plitzi/sdk-kernel/mysql: account ${userId} disappeared while being updated.`);
321
+ return toRecord$1(row);
322
+ },
323
+ setStatus: async (userId, status) => {
324
+ await execute(db, `UPDATE ${t.account} SET status = ? WHERE id = ?`, [status, userId]);
325
+ },
326
+ /**
327
+ * The row goes, and its sessions with it — the foreign key cascades, so there is no window in which a deleted
328
+ * account still has a working credential. A deployment that has to keep the row for its content or its invoices
329
+ * replaces this adapter with one that anonymises instead; the sessions still have to go.
330
+ */
331
+ deleteAccount: async (userId) => {
332
+ await execute(db, `DELETE FROM ${t.account} WHERE id = ?`, [userId]);
333
+ },
334
+ listAccounts: async (query) => {
335
+ const conditions = [];
336
+ const params = [];
337
+ if (query.search) {
338
+ conditions.push("(a.username LIKE ? OR a.email LIKE ?)");
339
+ const like = `%${query.search.replace(/[%_\\]/g, (character) => `\\${character}`)}%`;
340
+ params.push(like, like);
341
+ }
342
+ if (query.status) {
343
+ conditions.push("a.status = ?");
344
+ params.push(query.status);
345
+ }
346
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
347
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 200);
348
+ const offset = Math.max(query.offset ?? 0, 0);
349
+ const counted = await selectOne(db, `SELECT COUNT(*) AS total FROM ${t.account} a ${where}`, params);
350
+ return {
351
+ accounts: (await selectRows(db, `SELECT ${ACCOUNT_COLUMNS} FROM ${t.account} a ${where} ORDER BY a.id ASC LIMIT ? OFFSET ?`, [
352
+ ...params,
353
+ limit,
354
+ offset
355
+ ])).map(toRecord$1),
356
+ total: counted?.total ?? 0
357
+ };
358
+ },
359
+ /** Exactly these roles, which means the ones not named are taken away. Unknown names are ignored, not created. */
360
+ setRoles: async (userId, roles) => {
361
+ await execute(db, `DELETE FROM ${t.accountRole} WHERE account_id = ?`, [userId]);
362
+ if (roles.length === 0) return;
363
+ const placeholders = roles.map(() => "?").join(", ");
364
+ await execute(db, `INSERT INTO ${t.accountRole} (account_id, role_id)
365
+ SELECT ?, id FROM ${t.role} WHERE name IN (${placeholders})`, [userId, ...roles]);
366
+ },
367
+ saveOtp: async (code) => {
368
+ await execute(db, `DELETE FROM ${t.otp} WHERE purpose = ? AND identifier = ?`, [code.purpose, code.identifier]);
369
+ await execute(db, `INSERT INTO ${t.otp} (account_id, purpose, identifier, code_hash, expires_at) VALUES (?, ?, ?, ?, ?)`, [
370
+ code.userId ?? null,
371
+ code.purpose,
372
+ code.identifier,
373
+ code.codeHash,
374
+ code.expiresAt
375
+ ]);
376
+ },
377
+ findOtp: async (purpose, identifier) => {
378
+ const row = await selectOne(db, `SELECT id, code_hash, expires_at, account_id FROM ${t.otp}
379
+ WHERE purpose = ? AND identifier = ? ORDER BY id DESC LIMIT 1`, [purpose, identifier]);
380
+ if (!row) return;
381
+ return {
382
+ id: row.id,
383
+ codeHash: row.code_hash,
384
+ expiresAt: row.expires_at,
385
+ ...row.account_id !== null ? { userId: row.account_id } : {}
386
+ };
387
+ },
388
+ consumeOtp: async (id) => {
389
+ await execute(db, `DELETE FROM ${t.otp} WHERE id = ?`, [id]);
390
+ },
391
+ /**
392
+ * The second factor. `recovery_codes` is a newline-separated list of digests, not a JSON blob: it is only ever
393
+ * read whole and written whole, and a text column that a human can read in a crisis beats one they cannot.
394
+ */
395
+ loadMfa: async (userId) => {
396
+ const row = await selectOne(db, `SELECT secret, confirmed_at, recovery_codes, last_used_step FROM ${t.mfa} WHERE account_id = ? LIMIT 1`, [userId]);
397
+ if (!row) return;
398
+ return {
399
+ secret: row.secret,
400
+ ...row.confirmed_at !== null ? { confirmedAt: row.confirmed_at } : {},
401
+ recoveryCodes: (row.recovery_codes ?? "").split("\n").filter(Boolean),
402
+ ...row.last_used_step !== null ? { lastUsedStep: row.last_used_step } : {}
403
+ };
404
+ },
405
+ saveMfa: async (userId, mfaRecord) => {
406
+ await execute(db, `INSERT INTO ${t.mfa} (account_id, secret, confirmed_at, recovery_codes, last_used_step) VALUES (?, ?, ?, ?, ?)
407
+ ON DUPLICATE KEY UPDATE
408
+ secret = VALUES(secret), confirmed_at = VALUES(confirmed_at), recovery_codes = VALUES(recovery_codes),
409
+ last_used_step = VALUES(last_used_step)`, [
410
+ userId,
411
+ mfaRecord.secret,
412
+ mfaRecord.confirmedAt ?? null,
413
+ (mfaRecord.recoveryCodes ?? []).join("\n"),
414
+ mfaRecord.lastUsedStep ?? null
415
+ ]);
416
+ },
417
+ deleteMfa: async (userId) => {
418
+ await execute(db, `DELETE FROM ${t.mfa} WHERE account_id = ?`, [userId]);
419
+ },
420
+ listSessions: (userId, currentToken) => sessions.list(userId, currentToken),
421
+ revokeSession: (userId, sessionId) => sessions.revoke(userId, sessionId),
422
+ revokeOtherSessions: (userId, currentToken) => sessions.revokeOthers(userId, currentToken)
423
+ };
424
+ };
425
+ // src/mysql/admin.ts
426
+ /**
427
+ * Everything that puts rows in these tables that no request ever will.
428
+ *
429
+ * The auth flows read accounts, roles and memberships; almost none of them create one. Signing up creates an
430
+ * account and that is the whole of it — a role, a permission, a space membership and a space's first credential all
431
+ * come from somewhere else: a seed script, an admin screen, the moment a space is created. That somewhere else
432
+ * needs statements, and a deployment writing them by hand against a schema it did not design is a deployment about
433
+ * to get a join wrong.
434
+ *
435
+ * Every operation is idempotent, because the place they are called from is usually a startup path that runs again.
436
+ */
437
+ var createAdmin = (pool, t) => {
438
+ const idOf = async (table, name) => {
439
+ return (await selectOne(pool, `SELECT id FROM ${table} WHERE name = ? LIMIT 1`, [name]))?.id;
440
+ };
441
+ const ensurePermissions = async (names) => {
442
+ if (names.length === 0) return;
443
+ const values = names.map(() => "(?)").join(", ");
444
+ await execute(pool, `INSERT IGNORE INTO ${t.permission} (name) VALUES ${values}`, names);
445
+ };
446
+ /**
447
+ * Declarative: the permission list given is the permission list the role ends up with. A role that only ever
448
+ * gained permissions could never lose one, and the first thing anybody does with a role is take something away.
449
+ */
450
+ const ensureRole = async (name, options = {}) => {
451
+ const { permissions = [], description } = options;
452
+ await execute(pool, `INSERT INTO ${t.role} (name, description) VALUES (?, ?)
453
+ ON DUPLICATE KEY UPDATE description = COALESCE(VALUES(description), description)`, [name, description ?? null]);
454
+ const roleId = await idOf(t.role, name);
455
+ if (roleId === void 0) throw new Error(`@plitzi/sdk-kernel/mysql: role "${name}" could not be read back after being written.`);
456
+ await ensurePermissions(permissions);
457
+ const connection = await pool.getConnection();
458
+ try {
459
+ await connection.beginTransaction();
460
+ await execute(connection, `DELETE FROM ${t.rolePermission} WHERE role_id = ?`, [roleId]);
461
+ if (permissions.length > 0) {
462
+ const placeholders = permissions.map(() => "?").join(", ");
463
+ await execute(connection, `INSERT INTO ${t.rolePermission} (role_id, permission_id)
464
+ SELECT ?, id FROM ${t.permission} WHERE name IN (${placeholders})`, [roleId, ...permissions]);
465
+ }
466
+ await connection.commit();
467
+ } catch (error) {
468
+ await connection.rollback();
469
+ throw error;
470
+ } finally {
471
+ connection.release();
472
+ }
473
+ return roleId;
474
+ };
475
+ const requireRole = async (name) => {
476
+ const roleId = await idOf(t.role, name);
477
+ if (roleId === void 0) throw new Error(`@plitzi/sdk-kernel/mysql: no role named "${name}". Create it with ensureRole() first.`);
478
+ return roleId;
479
+ };
480
+ const grantRole = async (accountId, role) => {
481
+ const roleId = await requireRole(role);
482
+ await execute(pool, `INSERT IGNORE INTO ${t.accountRole} (account_id, role_id) VALUES (?, ?)`, [accountId, roleId]);
483
+ };
484
+ const revokeRole = async (accountId, role) => {
485
+ const roleId = await requireRole(role);
486
+ await execute(pool, `DELETE FROM ${t.accountRole} WHERE account_id = ? AND role_id = ?`, [accountId, roleId]);
487
+ };
488
+ /**
489
+ * Keyed by username. The password is re-hashed on every call so a seed stays the source of truth for it — which
490
+ * is what a seed is for, and the reason this must never be pointed at a database where people change their own.
491
+ */
492
+ const ensureAccount = async (seed) => {
493
+ const passwordHash = seed.password === void 0 ? null : await hashPassword(seed.password);
494
+ await execute(pool, `INSERT INTO ${t.account} (username, email, password_hash, verified) VALUES (?, ?, ?, ?)
495
+ ON DUPLICATE KEY UPDATE
496
+ email = VALUES(email),
497
+ password_hash = COALESCE(VALUES(password_hash), password_hash),
498
+ verified = VALUES(verified)`, [
499
+ seed.username,
500
+ seed.email,
501
+ passwordHash,
502
+ seed.verified ? 1 : 0
503
+ ]);
504
+ const row = await selectOne(pool, `SELECT id FROM ${t.account} WHERE username = ? LIMIT 1`, [seed.username]);
505
+ if (!row) throw new Error(`@plitzi/sdk-kernel/mysql: account "${seed.username}" could not be read back after writing.`);
506
+ for (const role of seed.roles ?? []) await grantRole(row.id, role);
507
+ return row.id;
508
+ };
509
+ return {
510
+ ensurePermissions,
511
+ ensureRole,
512
+ grantRole,
513
+ revokeRole,
514
+ ensureAccount,
515
+ /** Membership of one space, with the role that decides what they may do inside it. */
516
+ addMember: async (spaceId, accountId, role, options = {}) => {
517
+ const roleId = await requireRole(role);
518
+ await execute(pool, `INSERT INTO ${t.spaceMember} (space_id, account_id, role_id, is_owner) VALUES (?, ?, ?, ?)
519
+ ON DUPLICATE KEY UPDATE role_id = VALUES(role_id), is_owner = VALUES(is_owner)`, [
520
+ spaceId,
521
+ accountId,
522
+ roleId,
523
+ options.owner ? 1 : 0
524
+ ]);
525
+ },
526
+ removeMember: async (spaceId, accountId) => {
527
+ await execute(pool, `DELETE FROM ${t.spaceMember} WHERE space_id = ? AND account_id = ?`, [spaceId, accountId]);
528
+ },
529
+ listMembers: (spaceId) => selectRows(pool, `SELECT sm.account_id AS accountId, a.username, r.name AS role, sm.is_owner AS owner
530
+ FROM ${t.spaceMember} sm
531
+ JOIN ${t.account} a ON a.id = sm.account_id
532
+ JOIN ${t.role} r ON r.id = sm.role_id
533
+ WHERE sm.space_id = ?`, [spaceId]),
534
+ /**
535
+ * A space's credential row. Replaces the default one rather than adding a second: exactly one row per space
536
+ * carries `is_default`, and two of them make `loadDefault` answer whichever the database happened to return.
537
+ */
538
+ createSpaceToken: async (spaceId, seed) => {
539
+ const isDefault = seed.isDefault ?? true;
540
+ if (isDefault) await execute(pool, `DELETE FROM ${t.spaceToken} WHERE space_id = ? AND is_default = 1`, [spaceId]);
541
+ return (await execute(pool, `INSERT INTO ${t.spaceToken} (space_id, token, scope, is_default, origins, expires_at, account_id)
542
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
543
+ spaceId,
544
+ seed.token,
545
+ seed.scope ?? "render",
546
+ isDefault ? 1 : 0,
547
+ (seed.origins ?? []).join(","),
548
+ seed.expiresAt ?? null,
549
+ seed.accountId ?? null
550
+ ])).insertId;
551
+ }
552
+ };
553
+ };
554
+ // src/mysql/config.ts
555
+ /**
556
+ * The tables the auth kernel needs. Named after the kernel's own vocabulary — an `AccountRecord` is stored in
557
+ * `account` — rather than after any one deployment's user table, which is a thing it maps ONTO these.
558
+ */
559
+ var TABLE_NAMES = {
560
+ schemaVersion: "schema_version",
561
+ account: "account",
562
+ session: "session",
563
+ identity: "account_identity",
564
+ mfa: "account_mfa",
565
+ otp: "account_otp",
566
+ role: "role",
567
+ permission: "permission",
568
+ rolePermission: "role_permission",
569
+ accountRole: "account_role",
570
+ spaceMember: "space_member",
571
+ spaceToken: "space_token"
572
+ };
573
+ var resolveTables = (prefix) => {
574
+ const entries = Object.entries(TABLE_NAMES).map(([key, name]) => [key, `\`${prefix}${name}\``]);
575
+ return Object.fromEntries(entries);
576
+ };
577
+ /** The bare, unquoted names — for a migration tool, or an error that has to say which table it meant. */
578
+ var tableNames = (prefix) => {
579
+ const entries = Object.entries(TABLE_NAMES).map(([key, name]) => [key, `${prefix}${name}`]);
580
+ return Object.fromEntries(entries);
581
+ };
582
+ // src/mysql/identities.ts
583
+ /**
584
+ * External identities, as rows.
585
+ *
586
+ * Deliberately NOT part of the auth adapters: whether a Google account with a matching email is the same person is
587
+ * a judgement only a deployment can make, and it lives in `exchangeCredential` / the social `linkAccount` hook.
588
+ * What is mechanical is the storage, and a self-hoster should not have to design the table for it.
589
+ *
590
+ * The unique key is `(provider, subject)`, never the email. A provider that does not verify addresses lets anybody
591
+ * claim any account by signing up with one — which is the single most common way social linking is got wrong.
592
+ */
593
+ var createIdentityStore = (db, t) => ({
594
+ find: async (provider, subject) => {
595
+ const row = await selectOne(db, `SELECT account_id FROM ${t.identity} WHERE provider = ? AND subject = ? LIMIT 1`, [provider, subject]);
596
+ return row ? { accountId: row.account_id } : void 0;
597
+ },
598
+ /** Idempotent: signing in again with the same provider identity must not be an error. */
599
+ link: async (accountId, identity) => {
600
+ await execute(db, `INSERT INTO ${t.identity} (account_id, provider, subject, email) VALUES (?, ?, ?, ?)
601
+ ON DUPLICATE KEY UPDATE account_id = VALUES(account_id), email = VALUES(email)`, [
602
+ accountId,
603
+ identity.provider,
604
+ identity.subject,
605
+ identity.email ?? null
606
+ ]);
607
+ },
608
+ list: async (accountId) => {
609
+ return (await selectRows(db, `SELECT id, provider, subject, email, created_at FROM ${t.identity} WHERE account_id = ? ORDER BY id ASC`, [accountId])).map((row) => ({
610
+ id: row.id,
611
+ provider: row.provider,
612
+ subject: row.subject,
613
+ ...row.email ? { email: row.email } : {},
614
+ createdAt: Math.floor(row.created_at.getTime() / 1e3)
615
+ }));
616
+ },
617
+ /** Scoped by account, or one person could unlink another's provider by guessing a number. */
618
+ unlink: async (accountId, provider) => {
619
+ return (await execute(db, `DELETE FROM ${t.identity} WHERE account_id = ? AND provider = ?`, [accountId, provider])).affectedRows > 0;
620
+ }
621
+ });
622
+ // src/mysql/pool.ts
623
+ var driver;
624
+ /**
625
+ * `mysql2` is an OPTIONAL peer dependency: this is the only module in the package that speaks to a database, and a
626
+ * deployment bringing its own store should not download a driver to find that out. Loaded dynamically so its absence
627
+ * is a sentence rather than a bare `ERR_MODULE_NOT_FOUND` from a file the reader has never heard of.
628
+ */
629
+ var loadDriver = async () => {
630
+ if (driver) return driver;
631
+ try {
632
+ driver = await import("mysql2/promise");
633
+ } catch {
634
+ throw new Error("@plitzi/sdk-kernel/mysql needs the `mysql2` driver, which is not installed. Add it with `yarn add mysql2` (or `npm install mysql2`). It is an optional peer dependency so that a deployment bringing its own account store never downloads a database driver it does not use.");
635
+ }
636
+ return driver;
637
+ };
638
+ /**
639
+ * The configured connection string, as the driver wants it.
640
+ *
641
+ * Parsed rather than handed to `createPool` as `uri`, and that is not a style choice: **that option is ignored** —
642
+ * only `createPool(uriString)` reads a URL, and that form takes no options. Passing both silently drops the URL and
643
+ * connects to the driver's own defaults, which on a machine that happens to run MySQL locally is a connection to
644
+ * the wrong database rather than an error. Anything unparseable is refused here, where the message can say so.
645
+ */
646
+ var fromUrl = (url) => {
647
+ let parsed;
648
+ try {
649
+ parsed = new URL(url);
650
+ } catch {
651
+ throw new Error("@plitzi/sdk-kernel/mysql: `url` is not a valid database URL");
652
+ }
653
+ const database = parsed.pathname.replace(/^\//, "");
654
+ if (!parsed.hostname) throw new Error("@plitzi/sdk-kernel/mysql: `url` names no host");
655
+ return {
656
+ host: parsed.hostname,
657
+ port: parsed.port ? Number(parsed.port) : 3306,
658
+ user: decodeURIComponent(parsed.username),
659
+ password: decodeURIComponent(parsed.password),
660
+ database
661
+ };
662
+ };
663
+ var createPool = async (config) => {
664
+ if (config.pool) return config.pool;
665
+ const { url, host, port, user, password, database, ssl, connectionLimit = 10 } = config;
666
+ const options = {
667
+ ...url ? fromUrl(url) : {},
668
+ ...host !== void 0 ? { host } : {},
669
+ ...port !== void 0 ? { port } : {},
670
+ ...user !== void 0 ? { user } : {},
671
+ ...password !== void 0 ? { password } : {},
672
+ ...database !== void 0 ? { database } : {},
673
+ ...ssl !== void 0 ? { ssl } : {},
674
+ connectionLimit,
675
+ supportBigNumbers: true,
676
+ bigNumberStrings: false,
677
+ waitForConnections: true,
678
+ queueLimit: 0
679
+ };
680
+ if (!options.database) throw new Error("@plitzi/sdk-kernel/mysql: no database was given. Pass `database`, or a `url` that ends in one — a connection with no database selected fails later, on the first query, as a much less obvious error.");
681
+ const mysql = await loadDriver();
682
+ if (config.ensureDatabase) await createDatabase(mysql, options);
683
+ return mysql.createPool(options);
684
+ };
685
+ /**
686
+ * A database name cannot be a bound parameter — it is an identifier, not a value — so it is quoted by hand, and
687
+ * anything that could end the quoting is refused rather than escaped. The set of legal MySQL database names is
688
+ * small and this is all of it.
689
+ */
690
+ var quoteDatabase = (name) => {
691
+ if (!/^[A-Za-z0-9_$]+$/.test(name)) throw new Error(`@plitzi/sdk-kernel/mysql: "${name}" is not a database name that can be created safely. Use letters, digits, underscores and dollar signs, or create the database yourself and leave \`ensureDatabase\` off.`);
692
+ return `\`${name}\``;
693
+ };
694
+ /** Connects to the SERVER rather than to the database, which is the only way to ask for one that is not there. */
695
+ var createDatabase = async (mysql, options) => {
696
+ const { database, ...server } = options;
697
+ const name = quoteDatabase(database ?? "");
698
+ const connection = await mysql.createConnection(server);
699
+ try {
700
+ await connection.query(`CREATE DATABASE IF NOT EXISTS ${name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
701
+ } catch (error) {
702
+ if (error.code === "ER_DBACCESS_DENIED_ERROR") throw new Error(`@plitzi/sdk-kernel/mysql: the user "${String(options.user)}" may not create the database ${name}. Create it once as an administrator — CREATE DATABASE ${name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; — and grant that user rights on it, then turn \`ensureDatabase\` off. Creating databases is not a right an application should hold in the first place.`, { cause: error });
703
+ throw error;
704
+ } finally {
705
+ await connection.end();
706
+ }
707
+ };
708
+ // src/mysql/schema.ts
709
+ /**
710
+ * The tables, as SQL.
711
+ *
712
+ * Two decisions in here are worth stating, because getting either wrong fails much later and looks like something
713
+ * else entirely:
714
+ *
715
+ * **Tokens are `TEXT`, not `VARCHAR`.** A session credential is a JWT, and a JWT's length is set by its `aud` claim
716
+ * — one host per environment. A stack with seven audiences mints a 549-character refresh token, so a `VARCHAR(512)`
717
+ * kills every login with "value too long" on the deployment that has the most environments and nowhere else. They
718
+ * are indexed by prefix instead; the comparison is still exact, MySQL rechecks the full value against the row.
719
+ *
720
+ * **Unix seconds are `BIGINT`, not `INT`.** A signed `INT` runs out on 19 January 2038, and the credential this
721
+ * schema stores that is allowed to live forever is exactly the one that would be written with a far-future date.
722
+ */
723
+ var CHARSET = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
724
+ var step1 = (t) => [
725
+ `CREATE TABLE IF NOT EXISTS ${t.account} (
726
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
727
+ username VARCHAR(191) NOT NULL,
728
+ email VARCHAR(191) NOT NULL,
729
+ password_hash VARCHAR(255) NULL,
730
+ status ENUM('active','inactive','blocked') NOT NULL DEFAULT 'active',
731
+ verified TINYINT(1) NOT NULL DEFAULT 0,
732
+ reset_token VARCHAR(191) NULL,
733
+ validation_token VARCHAR(191) NULL,
734
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
735
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
736
+ PRIMARY KEY (id),
737
+ UNIQUE KEY account_username (username),
738
+ UNIQUE KEY account_email (email),
739
+ KEY account_reset_token (reset_token),
740
+ KEY account_validation_token (validation_token)
741
+ ) ${CHARSET}`,
742
+ `CREATE TABLE IF NOT EXISTS ${t.session} (
743
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
744
+ account_id INT UNSIGNED NOT NULL,
745
+ token TEXT NOT NULL,
746
+ expires_at BIGINT NOT NULL,
747
+ refresh_token TEXT NULL,
748
+ refresh_expires_at BIGINT NULL,
749
+ user_agent VARCHAR(255) NULL,
750
+ ip VARCHAR(45) NULL,
751
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
752
+ PRIMARY KEY (id),
753
+ KEY session_account (account_id),
754
+ KEY session_token (token(191)),
755
+ KEY session_refresh_token (refresh_token(191)),
756
+ KEY session_expires_at (expires_at),
757
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE
758
+ ) ${CHARSET}`,
759
+ `CREATE TABLE IF NOT EXISTS ${t.role} (
760
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
761
+ name VARCHAR(64) NOT NULL,
762
+ description VARCHAR(255) NULL,
763
+ PRIMARY KEY (id),
764
+ UNIQUE KEY role_name (name)
765
+ ) ${CHARSET}`,
766
+ `CREATE TABLE IF NOT EXISTS ${t.permission} (
767
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
768
+ name VARCHAR(64) NOT NULL,
769
+ description VARCHAR(255) NULL,
770
+ PRIMARY KEY (id),
771
+ UNIQUE KEY permission_name (name)
772
+ ) ${CHARSET}`,
773
+ `CREATE TABLE IF NOT EXISTS ${t.rolePermission} (
774
+ role_id INT UNSIGNED NOT NULL,
775
+ permission_id INT UNSIGNED NOT NULL,
776
+ PRIMARY KEY (role_id, permission_id),
777
+ KEY role_permission_permission (permission_id),
778
+ FOREIGN KEY (role_id) REFERENCES ${t.role} (id) ON DELETE CASCADE,
779
+ FOREIGN KEY (permission_id) REFERENCES ${t.permission} (id) ON DELETE CASCADE
780
+ ) ${CHARSET}`,
781
+ `CREATE TABLE IF NOT EXISTS ${t.accountRole} (
782
+ account_id INT UNSIGNED NOT NULL,
783
+ role_id INT UNSIGNED NOT NULL,
784
+ PRIMARY KEY (account_id, role_id),
785
+ KEY account_role_role (role_id),
786
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE,
787
+ FOREIGN KEY (role_id) REFERENCES ${t.role} (id) ON DELETE CASCADE
788
+ ) ${CHARSET}`,
789
+ `CREATE TABLE IF NOT EXISTS ${t.spaceMember} (
790
+ space_id BIGINT UNSIGNED NOT NULL,
791
+ account_id INT UNSIGNED NOT NULL,
792
+ role_id INT UNSIGNED NOT NULL,
793
+ is_owner TINYINT(1) NOT NULL DEFAULT 0,
794
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
795
+ PRIMARY KEY (space_id, account_id),
796
+ KEY space_member_account (account_id),
797
+ KEY space_member_role (role_id),
798
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE,
799
+ FOREIGN KEY (role_id) REFERENCES ${t.role} (id)
800
+ ) ${CHARSET}`,
801
+ `CREATE TABLE IF NOT EXISTS ${t.spaceToken} (
802
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
803
+ space_id BIGINT UNSIGNED NOT NULL,
804
+ token TEXT NOT NULL,
805
+ scope ENUM('render','agent') NOT NULL DEFAULT 'render',
806
+ is_default TINYINT(1) NOT NULL DEFAULT 0,
807
+ origins TEXT NULL,
808
+ expires_at BIGINT NULL,
809
+ account_id INT UNSIGNED NULL,
810
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
811
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
812
+ PRIMARY KEY (id),
813
+ KEY space_token_space (space_id),
814
+ KEY space_token_token (token(191)),
815
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE
816
+ ) ${CHARSET}`
817
+ ];
818
+ /**
819
+ * Everything an account can be besides a password: an identity at another provider, a second factor, and a
820
+ * one-time code. Added as step 2 rather than folded into step 1 — step 1 is released.
821
+ */
822
+ var step2 = (t) => [
823
+ `CREATE TABLE IF NOT EXISTS ${t.identity} (
824
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
825
+ account_id INT UNSIGNED NOT NULL,
826
+ provider VARCHAR(64) NOT NULL,
827
+ subject VARCHAR(191) NOT NULL,
828
+ email VARCHAR(191) NULL,
829
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
830
+ PRIMARY KEY (id),
831
+ UNIQUE KEY identity_provider_subject (provider, subject),
832
+ KEY identity_account (account_id),
833
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE
834
+ ) ${CHARSET}`,
835
+ `CREATE TABLE IF NOT EXISTS ${t.mfa} (
836
+ account_id INT UNSIGNED NOT NULL,
837
+ secret VARCHAR(191) NOT NULL,
838
+ confirmed_at BIGINT NULL,
839
+ recovery_codes TEXT NULL,
840
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
841
+ PRIMARY KEY (account_id),
842
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE
843
+ ) ${CHARSET}`,
844
+ `CREATE TABLE IF NOT EXISTS ${t.otp} (
845
+ id INT UNSIGNED NOT NULL AUTO_INCREMENT,
846
+ account_id INT UNSIGNED NULL,
847
+ purpose VARCHAR(32) NOT NULL,
848
+ identifier VARCHAR(191) NOT NULL,
849
+ code_hash VARCHAR(191) NOT NULL,
850
+ expires_at BIGINT NOT NULL,
851
+ attempts INT UNSIGNED NOT NULL DEFAULT 0,
852
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
853
+ PRIMARY KEY (id),
854
+ KEY otp_lookup (purpose, identifier),
855
+ KEY otp_expires_at (expires_at),
856
+ FOREIGN KEY (account_id) REFERENCES ${t.account} (id) ON DELETE CASCADE
857
+ ) ${CHARSET}`
858
+ ];
859
+ /**
860
+ * DDL that can be run twice.
861
+ *
862
+ * MySQL has `CREATE TABLE IF NOT EXISTS` and nothing else: `ADD COLUMN IF NOT EXISTS` is MariaDB's, and a plain
863
+ * `ADD COLUMN` on a second run is an error. That matters because MySQL cannot roll back DDL — a step that fails
864
+ * halfway has already applied some of its statements, and the retry has to survive meeting them again.
865
+ *
866
+ * So a conditional is built out of what MySQL does have: look in `information_schema`, and prepare either the real
867
+ * statement or a no-op. Emitted as separate statements because the driver sends one at a time.
868
+ *
869
+ * Every step after the first should be written with these. `schemaStatements()` still returns plain SQL, so a
870
+ * deployment migrating with its own tool gets the same guards.
871
+ */
872
+ var QUOTE = String.fromCharCode(39);
873
+ /** A SQL string literal. The statement being embedded is DDL, so it routinely contains quotes of its own. */
874
+ var literal = (value) => `${QUOTE}${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}${QUOTE}`;
875
+ var conditional = (test, statement) => [
876
+ `SET @plitzi_ddl := (SELECT IF(${test}, ${literal(statement)}, 'DO 0'))`,
877
+ "PREPARE plitzi_ddl_stmt FROM @plitzi_ddl",
878
+ "EXECUTE plitzi_ddl_stmt",
879
+ "DEALLOCATE PREPARE plitzi_ddl_stmt"
880
+ ];
881
+ var columnExists = (table, column) => `SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '${table}' AND COLUMN_NAME = '${column}'`;
882
+ var indexExists = (table, index) => `SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '${table}' AND INDEX_NAME = '${index}'`;
883
+ /** Adds a column unless it is already there. `definition` is everything after the column name. */
884
+ var addColumn = (table, column, definition) => conditional(`(${columnExists(table, column)}) = 0`, `ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${definition}`);
885
+ /** Adds an index unless one of that name exists. `definition` is the parenthesised column list. */
886
+ var addIndex = (table, index, definition) => conditional(`(${indexExists(table, index)}) = 0`, `ALTER TABLE \`${table}\` ADD INDEX \`${index}\` ${definition}`);
887
+ /** The bare name, for the `information_schema` lookups above — they compare against a string, not an identifier. */
888
+ var unquote = (name) => name.replace(/`/g, "");
889
+ /**
890
+ * An address the account asked to move to, and the token that will confirm it.
891
+ *
892
+ * Parked in two columns rather than applied, so the account keeps a working sign-in identifier until the new one
893
+ * answers a confirmation — see `confirmEmailChange`. Written with the idempotent helpers, being a step after the
894
+ * first: this is the migration path every later change to these tables takes.
895
+ */
896
+ var step3 = (t) => {
897
+ const account = unquote(t.account);
898
+ return [
899
+ ...addColumn(account, "pending_email", "VARCHAR(191) NULL AFTER email"),
900
+ ...addColumn(account, "pending_email_token", "VARCHAR(191) NULL AFTER pending_email"),
901
+ ...addIndex(account, "account_pending_email_token", "(pending_email_token)")
902
+ ];
903
+ };
904
+ /**
905
+ * What tells one device from another in the account's session list: the application holding it, when it is not a
906
+ * browser (`Plitzi CLI on dev-laptop`, software `plitzi-cli`), and when it was last used — see `sessionActivity`.
907
+ */
908
+ var step4 = (t) => {
909
+ const session = unquote(t.session);
910
+ return [
911
+ ...addColumn(session, "app_name", "VARCHAR(120) NULL AFTER ip"),
912
+ ...addColumn(session, "app_id", "VARCHAR(64) NULL AFTER app_name"),
913
+ ...addColumn(session, "last_active_at", "BIGINT NULL AFTER created_at")
914
+ ];
915
+ };
916
+ /**
917
+ * The time step of the last second-factor code accepted, so the same code cannot sign in twice within the window it
918
+ * stays valid for (RFC 6238 §5.2) — see `MfaRecord.lastUsedStep`.
919
+ */
920
+ var step5 = (t) => [...addColumn(unquote(t.mfa), "last_used_step", "BIGINT NULL AFTER recovery_codes")];
921
+ /**
922
+ * The host a session was signed in on (`SessionClient.host`), and an index to end a site's sessions by: a space's
923
+ * visitors sign in on its own host, and "sign out of this site everywhere" is every session of the account there.
924
+ */
925
+ var step6 = (t) => {
926
+ const session = unquote(t.session);
927
+ return [...addColumn(session, "host", "VARCHAR(255) NULL AFTER app_id"), ...addIndex(session, "session_account_host", "(account_id, host(191))")];
928
+ };
929
+ /**
930
+ * The terms an account was opened under, and when they were accepted (`AuthApiConfig.terms`, `termsAccepted` on
931
+ * `createAccount`): the record of what each person agreed to. Null for an account opened before a deployment named
932
+ * terms, or through another provider.
933
+ */
934
+ var step7 = (t) => {
935
+ const account = unquote(t.account);
936
+ return [...addColumn(account, "terms_version", "VARCHAR(32) NULL AFTER verified"), ...addColumn(account, "terms_accepted_at", "DATETIME NULL AFTER terms_version")];
937
+ };
938
+ /** Append only. A released version is never edited — the deployments that already ran it would never see the change. */
939
+ var STEPS = [
940
+ {
941
+ version: 1,
942
+ statements: step1
943
+ },
944
+ {
945
+ version: 2,
946
+ statements: step2
947
+ },
948
+ {
949
+ version: 3,
950
+ statements: step3
951
+ },
952
+ {
953
+ version: 4,
954
+ statements: step4
955
+ },
956
+ {
957
+ version: 5,
958
+ statements: step5
959
+ },
960
+ {
961
+ version: 6,
962
+ statements: step6
963
+ },
964
+ {
965
+ version: 7,
966
+ statements: step7
967
+ }
968
+ ];
969
+ var SCHEMA_VERSION = STEPS[STEPS.length - 1].version;
970
+ /**
971
+ * Every statement this schema is made of, in order — for a deployment that runs `autoMigrate: false` and applies
972
+ * DDL through its own migration tool, which is the normal arrangement anywhere the application's database user is
973
+ * not allowed to alter tables.
974
+ */
975
+ var schemaStatements = (tables, fromVersion = 0) => STEPS.filter((step) => step.version > fromVersion).flatMap((step) => step.statements(tables));
976
+ /**
977
+ * The order tables must be dropped in, children first. Foreign keys make the wrong order an error rather than a
978
+ * silent mess, but the error names a constraint and not what to do about it.
979
+ */
980
+ var DROP_ORDER = [
981
+ "otp",
982
+ "mfa",
983
+ "identity",
984
+ "spaceToken",
985
+ "spaceMember",
986
+ "accountRole",
987
+ "rolePermission",
988
+ "session",
989
+ "account",
990
+ "role",
991
+ "permission",
992
+ "schemaVersion"
993
+ ];
994
+ /** Which of OUR tables the database already has. Asked of `information_schema`, scoped to this database. */
995
+ var existingTables = async (pool, prefix) => {
996
+ const wanted = Object.values(tableNames(prefix));
997
+ const placeholders = wanted.map(() => "?").join(", ");
998
+ return (await selectRows(pool, `SELECT TABLE_NAME AS name FROM information_schema.TABLES
999
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (${placeholders})`, wanted)).map((row) => row.name);
1000
+ };
1001
+ var readVersion = async (pool, tables) => {
1002
+ return (await selectOne(pool, `SELECT version FROM ${tables.schemaVersion} WHERE component = 'sdk-server-auth'`))?.version ?? 0;
1003
+ };
1004
+ /**
1005
+ * Brings the schema up to date, once.
1006
+ *
1007
+ * The advisory lock is not decoration: an all-in-one deployment starts several roles against one database at the
1008
+ * same moment, and without it they race to create the same tables and to bump the same version row. `IF NOT EXISTS`
1009
+ * makes the statements survive that; the version bump would not.
1010
+ */
1011
+ var migrate = async (pool, tables, options) => {
1012
+ const { prefix, adoptExisting = false, log } = options;
1013
+ /**
1014
+ * A database this schema has never been migrated into, that already has tables with these names, is almost
1015
+ * certainly somebody else's — `role`, `permission` and `session` are among the most ordinary names there are, and
1016
+ * this module is explicitly meant to be pointed at a database with unrelated tables in it.
1017
+ *
1018
+ * `CREATE TABLE IF NOT EXISTS` would quietly ADOPT them, and the failure would surface much later as a query
1019
+ * against columns that are not there. Refused instead, naming the fix.
1020
+ */
1021
+ if (!adoptExisting) {
1022
+ const present = await existingTables(pool, prefix);
1023
+ const migrated = present.includes(tableNames(prefix).schemaVersion) && await readVersion(pool, tables) > 0;
1024
+ if (present.length > 0 && !migrated) throw new Error(`@plitzi/sdk-kernel/mysql: this database already has tables named ${present.join(", ")}, and they were not created by this schema. Point it at another database, set \`tablePrefix\` so the names cannot collide, or pass \`adoptExisting: true\` if they really are this schema’s and you are re-attaching.`);
1025
+ }
1026
+ await execute(pool, `CREATE TABLE IF NOT EXISTS ${tables.schemaVersion} (
1027
+ component VARCHAR(64) NOT NULL,
1028
+ version INT UNSIGNED NOT NULL,
1029
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
1030
+ PRIMARY KEY (component)
1031
+ ) ${CHARSET}`);
1032
+ const connection = await pool.getConnection();
1033
+ const lockName = `${tables.schemaVersion.replace(/`/g, "")}_sdk_server`.slice(0, 64);
1034
+ try {
1035
+ if ((await selectOne(connection, "SELECT GET_LOCK(?, 30) AS acquired", [lockName]))?.acquired !== 1) throw new Error(`@plitzi/sdk-kernel/mysql: timed out waiting for the schema lock "${lockName}". Another process is migrating this database, or one died holding the lock.`);
1036
+ try {
1037
+ const current = await readVersion(pool, tables);
1038
+ /**
1039
+ * The database is ahead of the code. That means an older process has been started against a schema a newer
1040
+ * one migrated, and letting it run is worse than refusing: it would read and write rows shaped by rules it
1041
+ * does not have. The usual cause is a rollback that rolled back the code and not the database.
1042
+ */
1043
+ if (current > SCHEMA_VERSION) throw new Error(`@plitzi/sdk-kernel/mysql: this database is at auth schema version ${current} and this build only knows ${SCHEMA_VERSION}. Upgrade @plitzi/sdk-server, or point this process at a database it understands.`);
1044
+ if (current === SCHEMA_VERSION) return current;
1045
+ /**
1046
+ * One step at a time, with the version written after EACH.
1047
+ *
1048
+ * MySQL cannot roll back DDL, so a step that fails halfway leaves the database between two versions. Bumping
1049
+ * once at the end would make the next run start over from `current` and re-apply the statements that had
1050
+ * already succeeded — which is exactly when a non-idempotent `ADD COLUMN` turns a recoverable failure into a
1051
+ * stuck deployment. Recording each step means a retry resumes at the one that failed.
1052
+ */
1053
+ for (const step of STEPS.filter((candidate) => candidate.version > current)) {
1054
+ for (const statement of step.statements(tables)) await execute(connection, statement);
1055
+ await execute(connection, `INSERT INTO ${tables.schemaVersion} (component, version) VALUES ('sdk-server-auth', ?)
1056
+ ON DUPLICATE KEY UPDATE version = VALUES(version)`, [step.version]);
1057
+ log?.(`[mysql] auth schema migrated to version ${step.version}`);
1058
+ }
1059
+ return SCHEMA_VERSION;
1060
+ } finally {
1061
+ await connection.query("SELECT RELEASE_LOCK(?)", [lockName]);
1062
+ }
1063
+ } finally {
1064
+ connection.release();
1065
+ }
1066
+ };
1067
+ /**
1068
+ * Removes this schema and nothing else.
1069
+ *
1070
+ * For a deployment that pointed the store at a database it shares with other things and has now stopped using
1071
+ * `@plitzi/sdk-server` — dropping the database would take the rest of their application with it, and working out
1072
+ * which nine tables were ours is not something anybody should have to do by hand at that moment.
1073
+ *
1074
+ * It drops **only** the names this schema owns, children first so the foreign keys allow it, and it refuses to
1075
+ * touch a database it was never migrated into: without that check, a typo in `tablePrefix` turns this into a tool
1076
+ * that deletes somebody else's `role` table.
1077
+ */
1078
+ var dropSchema = async (pool, tables, options) => {
1079
+ const { prefix, force = false, log } = options;
1080
+ const present = await existingTables(pool, prefix);
1081
+ if (present.length === 0) return [];
1082
+ if (!force && !present.includes(tableNames(prefix).schemaVersion)) throw new Error(`@plitzi/sdk-kernel/mysql: refusing to drop ${present.join(", ")} — there is no ${tableNames(prefix).schemaVersion} table, so this schema was never migrated into this database and those tables are somebody else’s. Check \`tablePrefix\`, or pass \`force: true\` if you are certain.`);
1083
+ const dropped = [];
1084
+ for (const key of DROP_ORDER) {
1085
+ const name = tableNames(prefix)[key];
1086
+ if (present.includes(name)) {
1087
+ await execute(pool, `DROP TABLE IF EXISTS ${tables[key]}`);
1088
+ dropped.push(name);
1089
+ }
1090
+ }
1091
+ log?.(`[mysql] dropped ${dropped.length} auth tables: ${dropped.join(", ")}`);
1092
+ return dropped;
1093
+ };
1094
+ // src/mysql/spaceTokens.ts
1095
+ var COLUMNS = "id, token, scope, is_default, origins, expires_at, account_id, created_at, updated_at";
1096
+ var seconds = (value) => Math.floor(value.getTime() / 1e3);
1097
+ var toRecord = (row) => ({
1098
+ id: row.id,
1099
+ token: row.token,
1100
+ scope: row.scope,
1101
+ isDefault: row.is_default === 1,
1102
+ origins: (row.origins ?? "").split(",").map((entry) => entry.trim()).filter(Boolean),
1103
+ expiresAt: row.expires_at,
1104
+ userId: row.account_id,
1105
+ createdAt: seconds(row.created_at),
1106
+ updatedAt: seconds(row.updated_at)
1107
+ });
1108
+ /**
1109
+ * The stored half of a space credential.
1110
+ *
1111
+ * Note what is NOT here: nothing creates a row. The space-token API rotates, re-scopes and revokes credentials for
1112
+ * a space that already has one, and issuing a space's first credential happens when the space itself is created —
1113
+ * which is the deployment's event, not auth's. `createSpaceToken` on the store's `admin` surface does it.
1114
+ */
1115
+ var createSpaceTokenStore = (db, t) => ({
1116
+ loadDefault: async (spaceId) => {
1117
+ const row = await selectOne(db, `SELECT ${COLUMNS} FROM ${t.spaceToken} WHERE space_id = ? AND is_default = 1 LIMIT 1`, [spaceId]);
1118
+ return row ? toRecord(row) : void 0;
1119
+ },
1120
+ /** Scoped by space as well as id: a token id from another space must not resolve, or it is an IDOR. */
1121
+ find: async (spaceId, tokenId) => {
1122
+ const row = await selectOne(db, `SELECT ${COLUMNS} FROM ${t.spaceToken} WHERE space_id = ? AND id = ? LIMIT 1`, [spaceId, tokenId]);
1123
+ return row ? toRecord(row) : void 0;
1124
+ },
1125
+ list: async (spaceId) => {
1126
+ return (await selectRows(db, `SELECT ${COLUMNS} FROM ${t.spaceToken} WHERE space_id = ? ORDER BY is_default DESC, id ASC`, [spaceId])).map(toRecord);
1127
+ },
1128
+ /**
1129
+ * Only the fields the caller named. `origins` and `expiresAt` are each meaningful as "unchanged" and as "cleared",
1130
+ * and a blanket UPDATE cannot tell those apart — it would wipe a domain list on every plain rotation.
1131
+ */
1132
+ save: async (id, values) => {
1133
+ const columns = ["token = ?"];
1134
+ const params = [values.token];
1135
+ if (values.origins !== void 0) {
1136
+ columns.push("origins = ?");
1137
+ params.push(values.origins.join(","));
1138
+ }
1139
+ if (values.expiresAt !== void 0) {
1140
+ columns.push("expires_at = ?");
1141
+ params.push(values.expiresAt);
1142
+ }
1143
+ params.push(id);
1144
+ await execute(db, `UPDATE ${t.spaceToken} SET ${columns.join(", ")} WHERE id = ?`, params);
1145
+ },
1146
+ remove: async (id) => {
1147
+ await execute(db, `DELETE FROM ${t.spaceToken} WHERE id = ?`, [id]);
1148
+ }
1149
+ });
1150
+ // src/mysql/store.ts
1151
+ /**
1152
+ * An account store on MySQL, with the tables it needs.
1153
+ *
1154
+ * This is the batteries-included half of `createAuth`. A deployment that already has users implements the adapters
1155
+ * against its own tables and never comes here; a deployment standing one up gets the schema, the queries and the
1156
+ * traps already handled:
1157
+ *
1158
+ * ```ts
1159
+ * const store = await createMysqlStore({ url: process.env.DATABASE_URL });
1160
+ *
1161
+ * const auth = createAuth({
1162
+ * tokens: { keys, issuer },
1163
+ * secret,
1164
+ * adapters: store.authAdapters,
1165
+ * });
1166
+ * ```
1167
+ *
1168
+ * It connects to a MySQL server; it does not start one. Where the database lives is a deployment decision and one
1169
+ * this cannot make well — a container in development, a managed instance in production, and neither of them
1170
+ * something a library should be launching behind your back.
1171
+ */
1172
+ var createMysqlStore = async (config) => {
1173
+ const { tablePrefix, autoMigrate = true, log } = config;
1174
+ const tables = resolveTables(tablePrefix);
1175
+ const pool = await createPool(config);
1176
+ const owned = !config.pool;
1177
+ if (autoMigrate) await migrate(pool, tables, {
1178
+ prefix: tablePrefix,
1179
+ adoptExisting: config.adoptExisting,
1180
+ log
1181
+ });
1182
+ return {
1183
+ pool,
1184
+ tables: tableNames(tablePrefix),
1185
+ schemaVersion: SCHEMA_VERSION,
1186
+ authAdapters: createAccountStore(pool, tables),
1187
+ spaceTokenAdapters: createSpaceTokenStore(pool, tables),
1188
+ sessions: createSessionStore(pool, tables),
1189
+ identities: createIdentityStore(pool, tables),
1190
+ admin: createAdmin(pool, tables),
1191
+ uninstall: (options = {}) => dropSchema(pool, tables, {
1192
+ prefix: tablePrefix,
1193
+ force: options.force,
1194
+ log
1195
+ }),
1196
+ close: async () => {
1197
+ if (owned) await pool.end();
1198
+ }
1199
+ };
1200
+ };
1201
+ /** The DDL, for a deployment whose database user may not run it — see `MysqlConfig.autoMigrate`. */
1202
+ var mysqlSchemaStatements = (tablePrefix, fromVersion = 0) => schemaStatements(resolveTables(tablePrefix), fromVersion);
1203
+ export { SCHEMA_VERSION, TABLE_NAMES, createMysqlStore, createPool, dropSchema, execute, migrate, mysqlSchemaStatements, resolveTables, selectOne, selectRows, tableNames };