gencow 0.1.299 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/gencow.mjs +0 -6
- package/core/package.json +1 -1
- package/docs/packaging.md +14 -4
- package/lib/cli-artifact-guard.mjs +53 -3
- package/lib/cli-dev-runtime.mjs +1 -0
- package/lib/cli-project-runtime.mjs +26 -14
- package/lib/codegen-command.mjs +16 -0
- package/lib/coding-guardrails.mjs +2 -0
- package/lib/dashboard-artifact.mjs +65 -0
- package/lib/dashboard-assets.mjs +20 -0
- package/lib/db-command.mjs +121 -80
- package/lib/db-migration-command-steps.mjs +19 -16
- package/lib/db-push-command.mjs +1 -1
- package/lib/deploy-codegen-preflight.mjs +1 -0
- package/lib/dev-cloud-command.mjs +1 -1
- package/lib/dev-local-command.mjs +19 -56
- package/lib/document-local-converter.mjs +11 -0
- package/lib/local-dashboard-plan.mjs +60 -0
- package/lib/local-database-commands.mjs +127 -0
- package/lib/local-development-migrations.mjs +157 -0
- package/lib/local-drizzle-database.config.mjs +10 -0
- package/lib/local-runtime-features.mjs +12 -0
- package/lib/rag-selection.mjs +7 -0
- package/lib/runtime-local-worker.mjs +116 -0
- package/lib/runtime-mode.mjs +3 -0
- package/lib/standalone-codegen-adapter.mjs +91 -0
- package/lib/ts-codegen-import-extension.mjs +228 -19
- package/package.json +16 -9
- package/runtime/config.mjs +218 -2
- package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
- package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
- package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
- package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
- package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
- package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
- package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
- package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
- package/runtime/engine/chunk-5575APCJ.mjs +215 -0
- package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
- package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
- package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
- package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
- package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
- package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
- package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
- package/runtime/engine/chunk-6W653LXI.mjs +13 -0
- package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
- package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
- package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
- package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
- package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
- package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
- package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
- package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
- package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
- package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
- package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
- package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
- package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
- package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
- package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
- package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
- package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
- package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
- package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
- package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
- package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
- package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
- package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
- package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
- package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
- package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
- package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
- package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
- package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
- package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
- package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
- package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
- package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
- package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
- package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
- package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
- package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
- package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
- package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
- package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
- package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
- package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
- package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
- package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
- package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
- package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
- package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
- package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
- package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
- package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
- package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
- package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
- package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
- package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
- package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
- package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
- package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
- package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
- package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
- package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
- package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
- package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
- package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
- package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
- package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
- package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
- package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
- package/runtime/engine/chunk-YRHM272W.mjs +528 -0
- package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
- package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
- package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
- package/runtime/engine/composition.mjs +325 -0
- package/runtime/engine/document-local.mjs +504 -0
- package/runtime/engine/graph.json +4134 -0
- package/runtime/engine/index.mjs +265 -0
- package/runtime/engine/local-postgres-support.mjs +69 -0
- package/runtime/engine/local.mjs +3275 -0
- package/runtime/engine/pglite-directory-lock.mjs +8 -0
- package/runtime/engine/rag.mjs +11 -0
- package/runtime/engine/search.mjs +18 -0
- package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
- package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
- package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
- package/runtime/framework-migrations/manifest.json +56 -0
- package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
- package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
- package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
- package/runtime/runtime-metadata.json +27 -0
- package/runtime/tooling.mjs +10399 -8951
- package/scripts/bundle-runtime-config.mjs +23 -0
- package/scripts/bundle-runtime.mjs +100 -0
- package/scripts/bundle-runtime.test.mjs +33 -0
- package/scripts/bundle-shared.mjs +3 -0
- package/scripts/copy-dashboard.mjs +16 -0
- package/scripts/pre-publish-check.mjs +23 -11
- package/templateFeature/sso/sso-auth-callback.tsx +37 -5
- package/templateFeature/tools/manifest.json +2 -1
- package/templateFeature/tools/tools.ts +3 -3
- package/runtime/server.mjs +0 -14389
- package/scripts/bundle-server.mjs +0 -223
- package/server/config.js +0 -1
- package/server/index.js +0 -1
- package/server/package.json +0 -6
|
@@ -0,0 +1,3104 @@
|
|
|
1
|
+
import {
|
|
2
|
+
loadBetterAuthSdk
|
|
3
|
+
} from "./chunk-WJOO4XTB.mjs";
|
|
4
|
+
import {
|
|
5
|
+
authAdministrationFailure,
|
|
6
|
+
authStartupError,
|
|
7
|
+
captureRequestBody,
|
|
8
|
+
createAuthGenerationAccessTokenVerifier,
|
|
9
|
+
isRuntimeOriginAllowed,
|
|
10
|
+
issueAccessToken,
|
|
11
|
+
resolveAuthRateLimitPolicy,
|
|
12
|
+
runtimeNullLogger,
|
|
13
|
+
toRuntimeIdentity,
|
|
14
|
+
validateAuthProfileId,
|
|
15
|
+
validateAuthProfileUpdate
|
|
16
|
+
} from "./chunk-67YO53WW.mjs";
|
|
17
|
+
import {
|
|
18
|
+
trustedRuntimeQuerySqlState
|
|
19
|
+
} from "./chunk-A5BMQ5IC.mjs";
|
|
20
|
+
import {
|
|
21
|
+
runtimeDatabaseExecutionScope,
|
|
22
|
+
runtimeDatabaseFailureRecord,
|
|
23
|
+
runtimeVettedAuthRead,
|
|
24
|
+
runtimeVettedAuthReadScope
|
|
25
|
+
} from "./chunk-YRHM272W.mjs";
|
|
26
|
+
import {
|
|
27
|
+
runtimeWorkflowListReadTaskId
|
|
28
|
+
} from "./chunk-7KUJ2H2S.mjs";
|
|
29
|
+
import {
|
|
30
|
+
ownedPostgresQueryFailure,
|
|
31
|
+
ownedPostgresQueryRejection,
|
|
32
|
+
ownedPostgresQuerySqlStateInCause
|
|
33
|
+
} from "./chunk-KX2PRQPS.mjs";
|
|
34
|
+
import "./chunk-IFMOTJNU.mjs";
|
|
35
|
+
import {
|
|
36
|
+
RuntimeDiagnosticError,
|
|
37
|
+
defaultRlsSessionContext,
|
|
38
|
+
ownedPostgresLoginDiagnostic,
|
|
39
|
+
renderRuntimeError,
|
|
40
|
+
runtimeDiagnostic,
|
|
41
|
+
runtimeRequestCorrelation
|
|
42
|
+
} from "./chunk-AEBW7XZJ.mjs";
|
|
43
|
+
|
|
44
|
+
// ../runtime/dist/adapters/auth/better-auth/session.js
|
|
45
|
+
function sessionTokenToCookieHeader(sessionToken) {
|
|
46
|
+
return `better-auth.session_token=${encodeURIComponent(sessionToken)}; __Secure-better-auth.session_token=${encodeURIComponent(sessionToken)}`;
|
|
47
|
+
}
|
|
48
|
+
function extractSessionTokens(cookieHeader) {
|
|
49
|
+
if (!cookieHeader)
|
|
50
|
+
return [];
|
|
51
|
+
const result = [];
|
|
52
|
+
const pattern = /(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=([^;]+)/gu;
|
|
53
|
+
let match;
|
|
54
|
+
while (match = pattern.exec(cookieHeader)) {
|
|
55
|
+
try {
|
|
56
|
+
const value = decodeURIComponent(match[1]);
|
|
57
|
+
if (value)
|
|
58
|
+
result.push(value);
|
|
59
|
+
} catch {
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return [...new Set(result)];
|
|
63
|
+
}
|
|
64
|
+
function candidateSessionToken(request) {
|
|
65
|
+
const bearer = request.headers.get("authorization");
|
|
66
|
+
if (bearer?.startsWith("Bearer "))
|
|
67
|
+
return bearer.slice("Bearer ".length).trim() || null;
|
|
68
|
+
return extractSessionTokens(request.headers.get("cookie"))[0] ?? null;
|
|
69
|
+
}
|
|
70
|
+
function sessionCreatedAtMs(value) {
|
|
71
|
+
const session = value?.session;
|
|
72
|
+
const createdAt = session?.createdAt ?? session?.created_at;
|
|
73
|
+
if (createdAt instanceof Date)
|
|
74
|
+
return createdAt.getTime();
|
|
75
|
+
if (typeof createdAt === "string" || typeof createdAt === "number") {
|
|
76
|
+
const time = new Date(createdAt).getTime();
|
|
77
|
+
return Number.isFinite(time) ? time : 0;
|
|
78
|
+
}
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ../runtime/dist/adapters/auth/better-auth/identity-observation.js
|
|
83
|
+
import { performance as performance2 } from "node:perf_hooks";
|
|
84
|
+
var authIdentityObservationTaskId = runtimeWorkflowListReadTaskId;
|
|
85
|
+
var authIdentityObservationMaxRecords = 64;
|
|
86
|
+
var processRecordBudget = { startedRecords: 0 };
|
|
87
|
+
function createAuthIdentityObservationObserver(options = {}) {
|
|
88
|
+
let selected = false;
|
|
89
|
+
try {
|
|
90
|
+
const environment = options.environment ?? process.env;
|
|
91
|
+
selected = environment.GENCOW_RUNTIME_TEST_TASK_ID === authIdentityObservationTaskId && typeof environment.GENCOW_RUNTIME_TEST_METRICS_DIR === "string" && environment.GENCOW_RUNTIME_TEST_METRICS_DIR.length > 0;
|
|
92
|
+
} catch {
|
|
93
|
+
}
|
|
94
|
+
if (!selected)
|
|
95
|
+
return void 0;
|
|
96
|
+
let monotonicNow;
|
|
97
|
+
try {
|
|
98
|
+
monotonicNow = options.monotonicNow ?? (() => performance2.now());
|
|
99
|
+
} catch {
|
|
100
|
+
monotonicNow = () => Number.NaN;
|
|
101
|
+
}
|
|
102
|
+
let write;
|
|
103
|
+
try {
|
|
104
|
+
write = options.write ?? ((line) => process.stdout.write(`${line}
|
|
105
|
+
`));
|
|
106
|
+
} catch {
|
|
107
|
+
write = () => void 0;
|
|
108
|
+
}
|
|
109
|
+
let recordBudget = processRecordBudget;
|
|
110
|
+
try {
|
|
111
|
+
recordBudget = options.recordBudget ?? processRecordBudget;
|
|
112
|
+
} catch {
|
|
113
|
+
}
|
|
114
|
+
return Object.freeze({
|
|
115
|
+
begin() {
|
|
116
|
+
if (recordBudget.startedRecords >= authIdentityObservationMaxRecords)
|
|
117
|
+
return void 0;
|
|
118
|
+
const ordinal = ++recordBudget.startedRecords;
|
|
119
|
+
let clockInvalid = false;
|
|
120
|
+
let finished = false;
|
|
121
|
+
const durations = {};
|
|
122
|
+
function readTime() {
|
|
123
|
+
if (clockInvalid)
|
|
124
|
+
return void 0;
|
|
125
|
+
try {
|
|
126
|
+
const value = monotonicNow();
|
|
127
|
+
if (Number.isFinite(value) && value >= 0)
|
|
128
|
+
return value;
|
|
129
|
+
} catch {
|
|
130
|
+
}
|
|
131
|
+
clockInvalid = true;
|
|
132
|
+
return void 0;
|
|
133
|
+
}
|
|
134
|
+
const measurement = {
|
|
135
|
+
phaseStarted() {
|
|
136
|
+
return readTime();
|
|
137
|
+
},
|
|
138
|
+
phaseFinished(phase, startedAt) {
|
|
139
|
+
const endedAt = readTime();
|
|
140
|
+
if (startedAt === void 0 || endedAt === void 0 || endedAt < startedAt) {
|
|
141
|
+
clockInvalid = true;
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const duration = Math.round((endedAt - startedAt) * 1e3) / 1e3;
|
|
145
|
+
if (!Number.isFinite(duration) || duration < 0) {
|
|
146
|
+
clockInvalid = true;
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
durations[phase] = duration;
|
|
150
|
+
},
|
|
151
|
+
finish() {
|
|
152
|
+
if (finished)
|
|
153
|
+
return;
|
|
154
|
+
finished = true;
|
|
155
|
+
const field = (phase) => {
|
|
156
|
+
const value = durations[phase];
|
|
157
|
+
return clockInvalid || value === void 0 ? "na" : String(value);
|
|
158
|
+
};
|
|
159
|
+
const line = `[runtime-test] AUTH_IDENTITY ${authIdentityObservationTaskId} ordinal=${ordinal} jwtVerifyMs=${field("jwtVerifyMs")} selectedUserLookupMs=${field("selectedUserLookupMs")}`;
|
|
160
|
+
try {
|
|
161
|
+
setImmediate(() => {
|
|
162
|
+
try {
|
|
163
|
+
const result = write(line);
|
|
164
|
+
if (result !== void 0)
|
|
165
|
+
void Promise.resolve(result).catch(() => {
|
|
166
|
+
});
|
|
167
|
+
} catch {
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
} catch {
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
return Object.freeze(measurement);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ../runtime/dist/adapters/auth/better-auth/identity-resolution.js
|
|
180
|
+
function record(value) {
|
|
181
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
182
|
+
}
|
|
183
|
+
function classifyBetterAuthCredential(request) {
|
|
184
|
+
if (request.headers.has("authorization"))
|
|
185
|
+
return "present";
|
|
186
|
+
const cookie = request.headers.get("cookie");
|
|
187
|
+
if (!cookie)
|
|
188
|
+
return "absent";
|
|
189
|
+
return cookie.split(";").some((part) => {
|
|
190
|
+
const separator = part.indexOf("=");
|
|
191
|
+
const name = (separator < 0 ? part : part.slice(0, separator)).trim();
|
|
192
|
+
return name === "better-auth.session_token" || name === "__Secure-better-auth.session_token";
|
|
193
|
+
}) ? "present" : "absent";
|
|
194
|
+
}
|
|
195
|
+
function selectedAuthDeletionEnabled(context) {
|
|
196
|
+
return record(record(record(record(context)?.options)?.user)?.deleteUser)?.enabled === true;
|
|
197
|
+
}
|
|
198
|
+
function verifiedSession(session) {
|
|
199
|
+
if (session === null || session === void 0)
|
|
200
|
+
return void 0;
|
|
201
|
+
const value = record(session);
|
|
202
|
+
const id = value?.id;
|
|
203
|
+
if (typeof id !== "string" || !id.trim() || id.length > 256)
|
|
204
|
+
throw Error("Selected Auth session metadata is invalid");
|
|
205
|
+
const expiresAt = value?.expiresAt;
|
|
206
|
+
let normalizedExpiry;
|
|
207
|
+
if (expiresAt !== void 0 && expiresAt !== null) {
|
|
208
|
+
if (expiresAt instanceof Date && Number.isFinite(expiresAt.getTime())) {
|
|
209
|
+
normalizedExpiry = expiresAt.toISOString();
|
|
210
|
+
} else if (typeof expiresAt === "string" && expiresAt.length <= 64 && Number.isFinite(Date.parse(expiresAt))) {
|
|
211
|
+
normalizedExpiry = new Date(expiresAt).toISOString();
|
|
212
|
+
} else {
|
|
213
|
+
throw Error("Selected Auth session expiry is invalid");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const metadata = {
|
|
217
|
+
id,
|
|
218
|
+
...normalizedExpiry ? { expiresAt: normalizedExpiry } : {}
|
|
219
|
+
};
|
|
220
|
+
return Object.freeze(metadata);
|
|
221
|
+
}
|
|
222
|
+
function selectedSessionState(session) {
|
|
223
|
+
if (session === null || session === void 0)
|
|
224
|
+
return void 0;
|
|
225
|
+
const value = record(session);
|
|
226
|
+
if (!value)
|
|
227
|
+
throw Error("Selected Auth session result is invalid");
|
|
228
|
+
const metadata = verifiedSession(value.session);
|
|
229
|
+
if (value.user === null || value.user === void 0)
|
|
230
|
+
return void 0;
|
|
231
|
+
const user = record(value.user);
|
|
232
|
+
if (!user)
|
|
233
|
+
throw Error("Selected Auth session user is invalid");
|
|
234
|
+
const identity = toRuntimeIdentity(user);
|
|
235
|
+
if (!identity)
|
|
236
|
+
throw Error("Selected Auth session user is invalid");
|
|
237
|
+
return Object.freeze({
|
|
238
|
+
method: "session",
|
|
239
|
+
identity,
|
|
240
|
+
...metadata ? { session: metadata } : {}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function anonymousState() {
|
|
244
|
+
return Object.freeze({ method: "anonymous", identity: null });
|
|
245
|
+
}
|
|
246
|
+
function createAuthIdentityResolver(input, observationOptions) {
|
|
247
|
+
const observation = createAuthIdentityObservationObserver(observationOptions);
|
|
248
|
+
const verifyToken = createAuthGenerationAccessTokenVerifier(input.key);
|
|
249
|
+
return async (request) => {
|
|
250
|
+
const authorization = request.headers.get("authorization");
|
|
251
|
+
if (authorization?.startsWith("Bearer ")) {
|
|
252
|
+
const measurement = observation?.begin();
|
|
253
|
+
try {
|
|
254
|
+
const candidate = authorization.slice("Bearer ".length).trim();
|
|
255
|
+
const jwtStartedAt = measurement?.phaseStarted("jwtVerifyMs");
|
|
256
|
+
let jwt;
|
|
257
|
+
try {
|
|
258
|
+
jwt = await verifyToken(candidate);
|
|
259
|
+
} finally {
|
|
260
|
+
measurement?.phaseFinished("jwtVerifyMs", jwtStartedAt);
|
|
261
|
+
}
|
|
262
|
+
if (jwt) {
|
|
263
|
+
const context = record(await (await input.ensure()).$context);
|
|
264
|
+
const adapter = record(context?.internalAdapter);
|
|
265
|
+
if (input.requireSelectedUser || adapter) {
|
|
266
|
+
const find = adapter?.findUserById;
|
|
267
|
+
if (typeof find !== "function")
|
|
268
|
+
throw Error("Selected Auth identity lookup unavailable");
|
|
269
|
+
const userLookupStartedAt = measurement?.phaseStarted("selectedUserLookupMs");
|
|
270
|
+
let user;
|
|
271
|
+
try {
|
|
272
|
+
user = await input.observe(() => find.call(adapter, jwt.id));
|
|
273
|
+
} finally {
|
|
274
|
+
measurement?.phaseFinished("selectedUserLookupMs", userLookupStartedAt);
|
|
275
|
+
}
|
|
276
|
+
if (user === null || user === void 0)
|
|
277
|
+
return anonymousState();
|
|
278
|
+
const selectedUser = record(user);
|
|
279
|
+
if (!selectedUser || selectedUser.id !== jwt.id || !toRuntimeIdentity(selectedUser))
|
|
280
|
+
throw Error("Selected Auth identity lookup did not verify the user");
|
|
281
|
+
}
|
|
282
|
+
return Object.freeze({ method: "jwt", identity: jwt });
|
|
283
|
+
}
|
|
284
|
+
const session = await input.getSession(request, candidate);
|
|
285
|
+
return selectedSessionState(session) ?? anonymousState();
|
|
286
|
+
} finally {
|
|
287
|
+
measurement?.finish();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const tokens = extractSessionTokens(request.headers.get("cookie"));
|
|
291
|
+
if (tokens.length === 0)
|
|
292
|
+
return Object.freeze({ method: "anonymous", identity: null });
|
|
293
|
+
const candidates = await Promise.all(tokens.map(async (token, index) => {
|
|
294
|
+
const session = await input.getSession(request, token);
|
|
295
|
+
const selected2 = selectedSessionState(session);
|
|
296
|
+
return selected2?.method === "session" ? { session, selected: selected2, index } : null;
|
|
297
|
+
}));
|
|
298
|
+
const valid = candidates.filter((candidate) => candidate !== null);
|
|
299
|
+
valid.sort((left, right) => sessionCreatedAtMs(right.session) - sessionCreatedAtMs(left.session) || left.index - right.index);
|
|
300
|
+
const selected = valid[0];
|
|
301
|
+
if (!selected)
|
|
302
|
+
return anonymousState();
|
|
303
|
+
return selected.selected;
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ../runtime/dist/adapters/auth/better-auth/administration-deletes.js
|
|
308
|
+
function record2(value) {
|
|
309
|
+
return value !== null && typeof value === "object" ? value : void 0;
|
|
310
|
+
}
|
|
311
|
+
function configured(context) {
|
|
312
|
+
const selected = record2(context);
|
|
313
|
+
const deletion = record2(record2(record2(selected?.options)?.user)?.deleteUser);
|
|
314
|
+
const cookieCache = record2(record2(record2(selected?.options)?.session)?.cookieCache);
|
|
315
|
+
const adapter = record2(selected?.internalAdapter);
|
|
316
|
+
return deletion?.enabled === true && !deletion.sendDeleteAccountVerification && !cookieCache?.enabled && ["findUserById", "deleteUser", "deleteUserSessions"].every((key) => typeof adapter?.[key] === "function");
|
|
317
|
+
}
|
|
318
|
+
function createAuthProfileDeleteOperation() {
|
|
319
|
+
const owner = /* @__PURE__ */ Symbol("runtime-auth-delete-owner");
|
|
320
|
+
const receipts = /* @__PURE__ */ new WeakMap();
|
|
321
|
+
const name = "gencowRuntimeDeleteUser";
|
|
322
|
+
const method = (instance) => {
|
|
323
|
+
const selected = record2(instance.api)?.[name];
|
|
324
|
+
if (typeof selected !== "function")
|
|
325
|
+
return;
|
|
326
|
+
const metadata = record2(record2(Reflect.get(selected, "options"))?.metadata);
|
|
327
|
+
if (metadata?.runtimeAdministrationOwner !== owner || metadata.SERVER_ONLY !== true || Reflect.get(selected, "path") !== void 0)
|
|
328
|
+
return;
|
|
329
|
+
return selected;
|
|
330
|
+
};
|
|
331
|
+
return Object.freeze({
|
|
332
|
+
async available(instance) {
|
|
333
|
+
return method(instance) !== void 0 && configured(await instance.$context);
|
|
334
|
+
},
|
|
335
|
+
plugin(sdk, transaction) {
|
|
336
|
+
return {
|
|
337
|
+
id: "gencow-runtime-user-administration",
|
|
338
|
+
endpoints: {
|
|
339
|
+
[name]: sdk.createAuthEndpoint.serverOnly({ method: "POST", metadata: { runtimeAdministrationOwner: owner } }, async (ctx) => {
|
|
340
|
+
const permit = record2(ctx.body)?.permit;
|
|
341
|
+
const receipt = permit && typeof permit === "object" ? receipts.get(permit) : void 0;
|
|
342
|
+
if (!receipt || !configured(ctx.context))
|
|
343
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
344
|
+
receipts.delete(permit);
|
|
345
|
+
const user = await ctx.context.internalAdapter.findUserById(receipt.id);
|
|
346
|
+
if (!user)
|
|
347
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_NOT_FOUND");
|
|
348
|
+
const config = ctx.context.options.user.deleteUser;
|
|
349
|
+
await config.beforeDelete?.(user, ctx.request);
|
|
350
|
+
await transaction(ctx.context.options, async () => {
|
|
351
|
+
await ctx.context.internalAdapter.deleteUserSessions(receipt.id);
|
|
352
|
+
await ctx.context.internalAdapter.deleteUser(receipt.id);
|
|
353
|
+
if (await ctx.context.internalAdapter.findUserById(receipt.id))
|
|
354
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_DELETE_FAILED");
|
|
355
|
+
});
|
|
356
|
+
await config.afterDelete?.(user, ctx.request);
|
|
357
|
+
receipt.acknowledgement = Object.freeze({ success: true, id: receipt.id });
|
|
358
|
+
return ctx.json(receipt.acknowledgement);
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
},
|
|
363
|
+
async delete(instance, input) {
|
|
364
|
+
validateAuthProfileId(input.id);
|
|
365
|
+
const selected = method(instance);
|
|
366
|
+
if (!selected || !configured(await instance.$context))
|
|
367
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
368
|
+
const permit = Object.freeze({});
|
|
369
|
+
const receipt = { id: input.id };
|
|
370
|
+
receipts.set(permit, receipt);
|
|
371
|
+
try {
|
|
372
|
+
await selected.call(record2(instance.api), {
|
|
373
|
+
body: { permit },
|
|
374
|
+
request: input.request,
|
|
375
|
+
headers: input.request.headers,
|
|
376
|
+
asResponse: false
|
|
377
|
+
});
|
|
378
|
+
if (!receipt.acknowledgement)
|
|
379
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_DELETE_FAILED");
|
|
380
|
+
return receipt.acknowledgement;
|
|
381
|
+
} catch (error) {
|
|
382
|
+
const typed = runtimeDiagnostic(error);
|
|
383
|
+
if (typed)
|
|
384
|
+
throw new RuntimeDiagnosticError({
|
|
385
|
+
...typed,
|
|
386
|
+
dataImpact: "unknown",
|
|
387
|
+
retryable: false,
|
|
388
|
+
retryPrecondition: "Explicitly inspect current Auth profiles, sessions and configured callback effects before any new action.",
|
|
389
|
+
nextAction: "Refresh Auth and inspect this profile. The SDK hook pipeline was entered; no rollback or automatic replay is claimed."
|
|
390
|
+
});
|
|
391
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_DELETE_FAILED");
|
|
392
|
+
} finally {
|
|
393
|
+
receipts.delete(permit);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// ../runtime/dist/adapters/auth/better-auth/administration-profile.js
|
|
400
|
+
function record3(value) {
|
|
401
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
402
|
+
}
|
|
403
|
+
function timestamp(value) {
|
|
404
|
+
const date = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
|
|
405
|
+
if (!date || !Number.isFinite(date.getTime()))
|
|
406
|
+
throw authAdministrationFailure("RUNTIME_AUTH_INSPECTION_FAILED");
|
|
407
|
+
return date.toISOString();
|
|
408
|
+
}
|
|
409
|
+
function safeAuthAdministrationProfile(value) {
|
|
410
|
+
const user = record3(value);
|
|
411
|
+
if (!user || typeof user.id !== "string" || !user.id || user.id.length > 256 || typeof user.email !== "string" || user.email.length > 320 || typeof user.emailVerified !== "boolean" || user.name !== null && (typeof user.name !== "string" || user.name.length > 512) || user.image !== null && (typeof user.image !== "string" || user.image.length > 2048))
|
|
412
|
+
throw authAdministrationFailure("RUNTIME_AUTH_INSPECTION_FAILED");
|
|
413
|
+
return {
|
|
414
|
+
id: user.id,
|
|
415
|
+
name: user.name,
|
|
416
|
+
email: user.email,
|
|
417
|
+
image: user.image,
|
|
418
|
+
emailVerified: user.emailVerified,
|
|
419
|
+
createdAt: timestamp(user.createdAt),
|
|
420
|
+
updatedAt: timestamp(user.updatedAt)
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ../runtime/dist/adapters/auth/better-auth/administration-updates.js
|
|
425
|
+
var methodName = "gencowRuntimeUpdateProfile";
|
|
426
|
+
function record4(value) {
|
|
427
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
428
|
+
}
|
|
429
|
+
function createAuthProfileUpdateOperation() {
|
|
430
|
+
let isSdkApiError;
|
|
431
|
+
let profileEmailIsValid;
|
|
432
|
+
const owner = /* @__PURE__ */ Symbol("runtime-auth-administration-owner");
|
|
433
|
+
const receipts = /* @__PURE__ */ new WeakMap();
|
|
434
|
+
const selectedMethod = (instance) => {
|
|
435
|
+
const method = record4(instance.api)?.[methodName];
|
|
436
|
+
if (typeof method !== "function")
|
|
437
|
+
return;
|
|
438
|
+
const options = record4(Reflect.get(method, "options"));
|
|
439
|
+
const metadata = record4(options?.metadata);
|
|
440
|
+
if (metadata?.runtimeAdministrationOwner !== owner || metadata.SERVER_ONLY !== true || Reflect.get(method, "path") !== void 0)
|
|
441
|
+
return;
|
|
442
|
+
return method;
|
|
443
|
+
};
|
|
444
|
+
return Object.freeze({
|
|
445
|
+
validate(input) {
|
|
446
|
+
const captured = validateAuthProfileUpdate(input);
|
|
447
|
+
const patch = captured.patch;
|
|
448
|
+
if (typeof patch.email === "string" && (!profileEmailIsValid || !profileEmailIsValid(patch.email)))
|
|
449
|
+
throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
|
|
450
|
+
return captured;
|
|
451
|
+
},
|
|
452
|
+
available: (instance) => selectedMethod(instance) !== void 0,
|
|
453
|
+
plugin(sdk, transaction) {
|
|
454
|
+
profileEmailIsValid = sdk.profileEmailIsValid;
|
|
455
|
+
isSdkApiError = sdk.isAPIError;
|
|
456
|
+
return {
|
|
457
|
+
id: "gencow-runtime-profile-administration",
|
|
458
|
+
endpoints: {
|
|
459
|
+
[methodName]: sdk.createAuthEndpoint.serverOnly({ method: "POST", metadata: { runtimeAdministrationOwner: owner } }, async (ctx) => {
|
|
460
|
+
const permit = record4(ctx.body)?.permit;
|
|
461
|
+
const receipt = permit && typeof permit === "object" ? receipts.get(permit) : void 0;
|
|
462
|
+
if (!receipt)
|
|
463
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
464
|
+
receipts.delete(permit);
|
|
465
|
+
const profile = await transaction(ctx.context.options, async () => {
|
|
466
|
+
const current = await ctx.context.internalAdapter.findUserById(receipt.id);
|
|
467
|
+
if (!current)
|
|
468
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_NOT_FOUND");
|
|
469
|
+
const model = ctx.context.tables.user;
|
|
470
|
+
if (!model)
|
|
471
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
472
|
+
const fields = Object.fromEntries(Object.entries(model.fields).filter(([key]) => ["name", "email", "image", "emailVerified"].includes(key)).map(([key, value]) => [key, { ...value, input: true }]));
|
|
473
|
+
const parsed = sdk.parseInputData({ ...receipt.patch }, { fields, action: "update" });
|
|
474
|
+
if (Object.keys(parsed).length !== Object.keys(receipt.patch).length)
|
|
475
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
476
|
+
const updated = await ctx.context.internalAdapter.updateUser(receipt.id, parsed);
|
|
477
|
+
const profile2 = safeAuthAdministrationProfile(updated);
|
|
478
|
+
if (profile2.id !== receipt.id)
|
|
479
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_UPDATE_FAILED");
|
|
480
|
+
return profile2;
|
|
481
|
+
});
|
|
482
|
+
receipt.acknowledgement = profile;
|
|
483
|
+
return ctx.json(profile);
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
},
|
|
488
|
+
async update(instance, input) {
|
|
489
|
+
const method = selectedMethod(instance);
|
|
490
|
+
if (!method)
|
|
491
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
492
|
+
const permit = Object.freeze({});
|
|
493
|
+
const receipt = {
|
|
494
|
+
id: input.id,
|
|
495
|
+
patch: Object.freeze(Object.fromEntries(Object.entries(input.patch).map(([key, value]) => [
|
|
496
|
+
key === "email_verified" ? "emailVerified" : key,
|
|
497
|
+
value
|
|
498
|
+
])))
|
|
499
|
+
};
|
|
500
|
+
receipts.set(permit, receipt);
|
|
501
|
+
try {
|
|
502
|
+
await method.call(record4(instance.api), {
|
|
503
|
+
body: { permit },
|
|
504
|
+
request: input.request,
|
|
505
|
+
headers: input.request.headers,
|
|
506
|
+
asResponse: false
|
|
507
|
+
});
|
|
508
|
+
if (!receipt.acknowledgement)
|
|
509
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_UPDATE_FAILED");
|
|
510
|
+
return receipt.acknowledgement;
|
|
511
|
+
} catch (error) {
|
|
512
|
+
const typed = runtimeDiagnostic(error);
|
|
513
|
+
if (typed)
|
|
514
|
+
throw new RuntimeDiagnosticError({
|
|
515
|
+
...typed,
|
|
516
|
+
dataImpact: "unknown",
|
|
517
|
+
retryable: false,
|
|
518
|
+
retryPrecondition: typed.retryPrecondition + " Inspect current Auth profiles and any configured callback effects before deliberately repeating a write.",
|
|
519
|
+
nextAction: typed.nextAction + " This entered the provider hook pipeline; no rollback or automatic replay is claimed."
|
|
520
|
+
});
|
|
521
|
+
if (isSdkApiError?.(error) && ["VALIDATION_ERROR", "FIELD_NOT_ALLOWED", "MISSING_FIELD", "INVALID_EMAIL"].includes(typeof error.body?.code === "string" ? error.body.code : ""))
|
|
522
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_INPUT_REJECTED");
|
|
523
|
+
throw authAdministrationFailure("RUNTIME_AUTH_PROFILE_UPDATE_FAILED");
|
|
524
|
+
} finally {
|
|
525
|
+
receipts.delete(permit);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ../runtime/dist/adapters/auth/better-auth/administration-inspection.js
|
|
532
|
+
function record5(value) {
|
|
533
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
534
|
+
}
|
|
535
|
+
function validateQuery(input) {
|
|
536
|
+
if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100 || !Number.isSafeInteger(input.offset) || input.offset < 0 || input.offset > 1e6 || input.search !== void 0 && (typeof input.search !== "string" || input.search.length > 128 || /[\x00-\x1f]/u.test(input.search)))
|
|
537
|
+
throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
|
|
538
|
+
}
|
|
539
|
+
function createAuthAdministrationInspection(ensure, admit, updates, deletes) {
|
|
540
|
+
const selected = async () => {
|
|
541
|
+
const context = record5(await (await ensure()).$context);
|
|
542
|
+
const adapter = record5(context?.internalAdapter);
|
|
543
|
+
if (!adapter || typeof adapter.listUsers !== "function" || typeof adapter.countTotalUsers !== "function")
|
|
544
|
+
return;
|
|
545
|
+
return adapter;
|
|
546
|
+
};
|
|
547
|
+
return Object.freeze({
|
|
548
|
+
operations: () => admit(async () => {
|
|
549
|
+
let inspect = false;
|
|
550
|
+
try {
|
|
551
|
+
inspect = Boolean(await selected());
|
|
552
|
+
} catch {
|
|
553
|
+
}
|
|
554
|
+
const updateProfile = inspect && updates !== void 0 && updates.available(await ensure());
|
|
555
|
+
const deleteUser = inspect && deletes !== void 0 && await deletes.available(await ensure());
|
|
556
|
+
return Object.freeze({ inspect, updateProfile, deleteUser });
|
|
557
|
+
}),
|
|
558
|
+
...updates ? {
|
|
559
|
+
validateUpdateProfile: updates.validate,
|
|
560
|
+
updateProfile: async (input) => {
|
|
561
|
+
const captured = updates.validate(input);
|
|
562
|
+
return admit(async () => updates.update(await ensure(), captured));
|
|
563
|
+
}
|
|
564
|
+
} : {},
|
|
565
|
+
...deletes ? {
|
|
566
|
+
deleteUser: async (input) => admit(async () => deletes.delete(await ensure(), input))
|
|
567
|
+
} : {},
|
|
568
|
+
async inspect(input) {
|
|
569
|
+
validateQuery(input);
|
|
570
|
+
const query = Object.freeze({ limit: input.limit, offset: input.offset, search: input.search });
|
|
571
|
+
return admit(async () => {
|
|
572
|
+
const adapter = await selected().catch(() => void 0);
|
|
573
|
+
if (!adapter)
|
|
574
|
+
throw authAdministrationFailure("RUNTIME_AUTH_ADMINISTRATION_UNAVAILABLE");
|
|
575
|
+
const where = query.search ? [{ field: "email", operator: "contains", value: query.search }] : void 0;
|
|
576
|
+
try {
|
|
577
|
+
const rows2 = await adapter.listUsers(query.limit, query.offset, { field: "createdAt", direction: "desc" }, where);
|
|
578
|
+
const total = await adapter.countTotalUsers(where);
|
|
579
|
+
if (!Array.isArray(rows2) || rows2.length > query.limit || !Number.isSafeInteger(total) || total < 0)
|
|
580
|
+
throw authAdministrationFailure("RUNTIME_AUTH_INSPECTION_FAILED");
|
|
581
|
+
return {
|
|
582
|
+
data: rows2.map(safeAuthAdministrationProfile),
|
|
583
|
+
total,
|
|
584
|
+
limit: query.limit,
|
|
585
|
+
offset: query.offset
|
|
586
|
+
};
|
|
587
|
+
} catch {
|
|
588
|
+
throw authAdministrationFailure("RUNTIME_AUTH_INSPECTION_FAILED");
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// ../runtime/dist/adapters/auth/better-auth/rate-limit-admission.js
|
|
596
|
+
var ownerKey = /* @__PURE__ */ Symbol.for("gencow.runtime.better-auth.native-memory-owner.v1");
|
|
597
|
+
function admitAuthRateLimit(policy, appId, logger) {
|
|
598
|
+
if (policy.enabled && !policy.customStorage && policy.storage === "memory") {
|
|
599
|
+
const registry = globalThis;
|
|
600
|
+
const owner = registry[ownerKey];
|
|
601
|
+
if (owner !== void 0 && owner !== appId) {
|
|
602
|
+
throw authStartupError("RUNTIME_AUTH_RATE_LIMIT_CONFIG_INVALID", "Native memory rate limiting supports one app per process. Run this app in its own process or select database storage for a host that serves multiple apps.");
|
|
603
|
+
}
|
|
604
|
+
registry[ownerKey] = appId;
|
|
605
|
+
}
|
|
606
|
+
try {
|
|
607
|
+
if (!policy.enabled)
|
|
608
|
+
logger.warn("runtime.auth.rate_limit.disabled", {
|
|
609
|
+
"runtime.capability": "auth",
|
|
610
|
+
"runtime.auth.rate_limit.enabled": false
|
|
611
|
+
});
|
|
612
|
+
else if (!policy.customStorage && policy.storage === "memory")
|
|
613
|
+
logger.warn("runtime.auth.rate_limit.memory", {
|
|
614
|
+
"runtime.capability": "auth",
|
|
615
|
+
"runtime.auth.rate_limit.storage": "memory",
|
|
616
|
+
"runtime.auth.rate_limit.durability": "process-local",
|
|
617
|
+
"runtime.auth.rate_limit.legacy": policy.context === "hosted"
|
|
618
|
+
});
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// ../runtime/dist/adapters/auth/better-auth/rate-limit-increment.js
|
|
624
|
+
import { and, eq, gt, gte, lt, lte, getTableColumns, sql } from "drizzle-orm";
|
|
625
|
+
async function incrementAuthRateLimit(database, table, input) {
|
|
626
|
+
const columns = getTableColumns(table);
|
|
627
|
+
function predicate(condition) {
|
|
628
|
+
const column = columns[condition.field];
|
|
629
|
+
if (!column || condition.connector === "OR")
|
|
630
|
+
throw Error("Unsupported native rate-limit predicate");
|
|
631
|
+
switch (condition.operator ?? "eq") {
|
|
632
|
+
case "eq":
|
|
633
|
+
return eq(column, condition.value);
|
|
634
|
+
case "lt":
|
|
635
|
+
return lt(column, condition.value);
|
|
636
|
+
case "lte":
|
|
637
|
+
return lte(column, condition.value);
|
|
638
|
+
case "gt":
|
|
639
|
+
return gt(column, condition.value);
|
|
640
|
+
case "gte":
|
|
641
|
+
return gte(column, condition.value);
|
|
642
|
+
default:
|
|
643
|
+
throw Error("Unsupported native rate-limit predicate");
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (!input.where.some((condition) => condition.field === "key" && (condition.operator === void 0 || condition.operator === "eq")))
|
|
647
|
+
throw Error("Missing native rate-limit unique key");
|
|
648
|
+
const assignments = {};
|
|
649
|
+
for (const [field, delta] of Object.entries(input.increment)) {
|
|
650
|
+
const column = columns[field];
|
|
651
|
+
if (!column || !Number.isFinite(delta))
|
|
652
|
+
throw Error("Unsupported native rate-limit increment");
|
|
653
|
+
assignments[field] = sql`${column} + ${delta}`;
|
|
654
|
+
}
|
|
655
|
+
for (const [field, value] of Object.entries(input.set ?? {})) {
|
|
656
|
+
if (!columns[field])
|
|
657
|
+
throw Error("Unsupported native rate-limit assignment");
|
|
658
|
+
assignments[field] = value;
|
|
659
|
+
}
|
|
660
|
+
const [row] = await database.drizzle.update(table).set(assignments).where(and(...input.where.map(predicate))).returning();
|
|
661
|
+
return row ?? null;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// ../runtime/dist/adapters/auth/better-auth/rate-limit-storage.js
|
|
665
|
+
function protectCall(operation, dataImpact = "none") {
|
|
666
|
+
return Promise.resolve().then(operation).catch((error) => {
|
|
667
|
+
if (runtimeDiagnostic(error))
|
|
668
|
+
throw error;
|
|
669
|
+
throw new RuntimeDiagnosticError({
|
|
670
|
+
code: "RUNTIME_AUTH_RATE_LIMIT_STORAGE_UNAVAILABLE",
|
|
671
|
+
stage: "request",
|
|
672
|
+
capability: "auth",
|
|
673
|
+
servingStarted: "unchanged",
|
|
674
|
+
dataImpact,
|
|
675
|
+
retryable: false,
|
|
676
|
+
retryPrecondition: dataImpact === "none" ? "Restore the selected rate-limit storage before retrying; no credential handler ran." : "Restore the selected rate-limit storage and verify existing account/session state and application callback/provider effects before retrying; do not blindly repeat mutations.",
|
|
677
|
+
nextAction: "Restore the selected rate-limit storage and verify its availability before retrying the auth request. For database storage, verify the selected database. Runtime will not fall back to memory or disable rate limiting." + (dataImpact === "unknown" ? " Inspect existing account/session state using GET /api/auth/me and verify application callback/provider effects before repeating an operation." : "")
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
function protectCustomRateLimitStorage(storage) {
|
|
682
|
+
const get = storage.get;
|
|
683
|
+
const set = storage.set;
|
|
684
|
+
return {
|
|
685
|
+
consume: (key, rule) => protectCall(() => storage.consume(key, rule), "unknown"),
|
|
686
|
+
...get ? { get: (key) => protectCall(() => get.call(storage, key), "unknown") } : {},
|
|
687
|
+
...set ? {
|
|
688
|
+
set: (key, value, update) => protectCall(() => set.call(storage, key, value, update), "unknown")
|
|
689
|
+
} : {}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
function protectRateLimitDatabase(factory, borrowed, schema, dataImpact) {
|
|
693
|
+
return (options) => {
|
|
694
|
+
const database = factory(options);
|
|
695
|
+
return new Proxy(database, {
|
|
696
|
+
get(target, key, receiver) {
|
|
697
|
+
const method = Reflect.get(target, key, receiver);
|
|
698
|
+
if (typeof method !== "function")
|
|
699
|
+
return method;
|
|
700
|
+
return (...args) => {
|
|
701
|
+
const input = args[0];
|
|
702
|
+
const rateLimit = input && typeof input === "object" && "model" in input && input.model === "rateLimit";
|
|
703
|
+
if (!rateLimit)
|
|
704
|
+
return Reflect.apply(method, target, args);
|
|
705
|
+
return protectCall(() => key === "incrementOne" ? incrementAuthRateLimit(borrowed, schema.rateLimit, input) : Reflect.apply(method, target, args), dataImpact());
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// ../runtime/dist/adapters/auth/better-auth/signup-events.js
|
|
713
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
714
|
+
function record6(value) {
|
|
715
|
+
return value && typeof value === "object" ? value : {};
|
|
716
|
+
}
|
|
717
|
+
function createSignupEvents(config, database, logger) {
|
|
718
|
+
const observations = new AsyncLocalStorage();
|
|
719
|
+
const hook = config.events?.afterSignUp;
|
|
720
|
+
return {
|
|
721
|
+
databaseHooks(existing) {
|
|
722
|
+
const hooks = record6(existing);
|
|
723
|
+
const userHooks = record6(hooks.user);
|
|
724
|
+
const createHooks = record6(userHooks.create);
|
|
725
|
+
const after = createHooks.after;
|
|
726
|
+
return {
|
|
727
|
+
...hooks,
|
|
728
|
+
user: {
|
|
729
|
+
...userHooks,
|
|
730
|
+
create: {
|
|
731
|
+
...createHooks,
|
|
732
|
+
async after(user, context) {
|
|
733
|
+
if (typeof after === "function")
|
|
734
|
+
await after(user, context);
|
|
735
|
+
if (!hook || typeof user.id !== "string" || typeof user.email !== "string")
|
|
736
|
+
return;
|
|
737
|
+
observations.getStore()?.users.set(user.id, {
|
|
738
|
+
...user,
|
|
739
|
+
id: user.id,
|
|
740
|
+
email: user.email,
|
|
741
|
+
name: typeof user.name === "string" ? user.name : null,
|
|
742
|
+
emailVerified: user.emailVerified === true,
|
|
743
|
+
...user.createdAt instanceof Date ? { createdAt: user.createdAt.toISOString() } : {},
|
|
744
|
+
...user.updatedAt instanceof Date ? { updatedAt: user.updatedAt.toISOString() } : {}
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
},
|
|
751
|
+
async run(request, execute) {
|
|
752
|
+
if (!hook)
|
|
753
|
+
return execute();
|
|
754
|
+
return observations.run({ users: /* @__PURE__ */ new Map() }, async () => {
|
|
755
|
+
const response = await execute();
|
|
756
|
+
if (response.status >= 400)
|
|
757
|
+
return response;
|
|
758
|
+
for (const user of observations.getStore().users.values()) {
|
|
759
|
+
try {
|
|
760
|
+
await hook({ user, inviteCode: null }, { request, db: database.drizzle });
|
|
761
|
+
} catch {
|
|
762
|
+
try {
|
|
763
|
+
logger.error("runtime.auth.signup.event.failed", {
|
|
764
|
+
"runtime.public_code": "RUNTIME_AUTH_AFTER_SIGN_UP_FAILED",
|
|
765
|
+
"runtime.stage": "request",
|
|
766
|
+
"runtime.capability": "auth",
|
|
767
|
+
"runtime.serving_started": "unchanged",
|
|
768
|
+
"runtime.data_impact": "committed",
|
|
769
|
+
"runtime.retryable": false,
|
|
770
|
+
"runtime.retry_precondition": "Do not repeat successful signup to retry its notification callback.",
|
|
771
|
+
"runtime.next_action": "Inspect the configured afterSignUp callback and existing account; account creation succeeded.",
|
|
772
|
+
"request.id": runtimeRequestCorrelation(request)
|
|
773
|
+
});
|
|
774
|
+
} catch {
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return response;
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// ../runtime/dist/adapters/auth/better-auth/request-errors.js
|
|
785
|
+
var RuntimeAuthSessionTimeoutError = class extends RuntimeDiagnosticError {
|
|
786
|
+
constructor() {
|
|
787
|
+
super({
|
|
788
|
+
code: "RUNTIME_AUTH_SESSION_OBSERVATION_TIMEOUT",
|
|
789
|
+
stage: "request",
|
|
790
|
+
capability: "auth",
|
|
791
|
+
servingStarted: "unchanged",
|
|
792
|
+
dataImpact: "unknown",
|
|
793
|
+
retryable: false,
|
|
794
|
+
retryPrecondition: "Do not retry while the original session query remains unsettled; its connection and result are still owned by this Runtime generation.",
|
|
795
|
+
nextAction: "Wait for the in-flight session query to settle before making another request; do not start an overlapping retry."
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
function sessionLookupFailure(error) {
|
|
800
|
+
const failureRecord = runtimeDatabaseFailureRecord(error);
|
|
801
|
+
const diagnostic = runtimeDiagnostic(error);
|
|
802
|
+
if (failureRecord && diagnostic) {
|
|
803
|
+
return new RuntimeDiagnosticError({
|
|
804
|
+
...diagnostic,
|
|
805
|
+
dataImpact: "unknown",
|
|
806
|
+
retryable: false,
|
|
807
|
+
retryPrecondition: `${diagnostic.retryPrecondition} The enclosing auth request may also have performed hooks or other effects; verify them before starting a new request.`,
|
|
808
|
+
nextAction: `${diagnostic.nextAction} Verify any earlier account, session, hook, or provider effects before repeating the enclosing request.`
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
if (diagnostic)
|
|
812
|
+
return error;
|
|
813
|
+
return new RuntimeDiagnosticError({
|
|
814
|
+
code: "RUNTIME_AUTH_SESSION_UNAVAILABLE",
|
|
815
|
+
stage: "request",
|
|
816
|
+
servingStarted: "unchanged",
|
|
817
|
+
dataImpact: "unknown",
|
|
818
|
+
retryable: false,
|
|
819
|
+
retryPrecondition: "Verify provider readiness and existing session state before repeating an operation with presented credentials.",
|
|
820
|
+
nextAction: "Inspect auth/database readiness and existing session state before retrying; do not blindly repeat mutations.",
|
|
821
|
+
capability: "auth"
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
function credentialFailure(error, isSdkApiError) {
|
|
825
|
+
if (runtimeDiagnostic(error))
|
|
826
|
+
return error;
|
|
827
|
+
if (!isSdkApiError(error))
|
|
828
|
+
return error;
|
|
829
|
+
const value = error;
|
|
830
|
+
return credentialResponseFailure(value.statusCode, value.body) ?? error;
|
|
831
|
+
}
|
|
832
|
+
function credentialResponseFailure(status, body) {
|
|
833
|
+
try {
|
|
834
|
+
const value = body;
|
|
835
|
+
const supported = {
|
|
836
|
+
VALIDATION_ERROR: {
|
|
837
|
+
status: 400,
|
|
838
|
+
action: "Supply the required credential fields with a valid email, password and signup name before submitting again."
|
|
839
|
+
},
|
|
840
|
+
PASSWORD_TOO_LONG: {
|
|
841
|
+
status: 400,
|
|
842
|
+
action: "Use a password within the configured maximum length before submitting again."
|
|
843
|
+
},
|
|
844
|
+
INVALID_EMAIL: {
|
|
845
|
+
status: 400,
|
|
846
|
+
action: "Supply a valid email address before submitting again."
|
|
847
|
+
},
|
|
848
|
+
PASSWORD_TOO_SHORT: {
|
|
849
|
+
status: 400,
|
|
850
|
+
action: "Use a password meeting the configured minimum length before submitting signup again."
|
|
851
|
+
},
|
|
852
|
+
INVALID_EMAIL_OR_PASSWORD: {
|
|
853
|
+
status: 401,
|
|
854
|
+
action: "Check the email/password, or use the configured password-reset flow before signing in again."
|
|
855
|
+
},
|
|
856
|
+
EMAIL_NOT_VERIFIED: {
|
|
857
|
+
status: 403,
|
|
858
|
+
action: "Complete the verification link sent to this email before signing in; request a new verification email only when needed."
|
|
859
|
+
},
|
|
860
|
+
USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: {
|
|
861
|
+
status: 422,
|
|
862
|
+
action: "Sign in to the existing account or use its configured password-reset flow; do not repeat signup for this email."
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
if (typeof value?.code !== "string" || !Object.hasOwn(supported, value.code))
|
|
866
|
+
return void 0;
|
|
867
|
+
const code = value.code;
|
|
868
|
+
const entry = supported[code];
|
|
869
|
+
if (status !== entry.status)
|
|
870
|
+
return void 0;
|
|
871
|
+
return new RuntimeDiagnosticError({
|
|
872
|
+
code,
|
|
873
|
+
stage: "request",
|
|
874
|
+
capability: "auth",
|
|
875
|
+
servingStarted: "unchanged",
|
|
876
|
+
// Trusted Better Auth hooks may have run before rejection. Do not infer rollback.
|
|
877
|
+
dataImpact: "unknown",
|
|
878
|
+
retryable: false,
|
|
879
|
+
retryPrecondition: entry.action,
|
|
880
|
+
nextAction: entry.action
|
|
881
|
+
});
|
|
882
|
+
} catch {
|
|
883
|
+
return void 0;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
function credentialRateLimitFailure(response, rejectedBeforeExecution) {
|
|
887
|
+
const value = response.headers.get("x-retry-after");
|
|
888
|
+
if (response.status !== 429)
|
|
889
|
+
return void 0;
|
|
890
|
+
const interval = value !== null && /^\d{1,10}$/u.test(value) ? Number(value) : void 0;
|
|
891
|
+
return new RuntimeDiagnosticError({
|
|
892
|
+
code: "RUNTIME_AUTH_RATE_LIMITED",
|
|
893
|
+
stage: "request",
|
|
894
|
+
capability: "auth",
|
|
895
|
+
servingStarted: "unchanged",
|
|
896
|
+
dataImpact: rejectedBeforeExecution ? "none" : "unknown",
|
|
897
|
+
retryable: false,
|
|
898
|
+
retryPrecondition: rejectedBeforeExecution ? interval !== void 0 ? `Wait at least ${interval} seconds for the configured SDK limit, then verify existing account/session state before submitting an intended auth operation.` : "Wait for the configured SDK rate-limit window to expire, then verify existing account/session state before submitting an intended auth operation." : (interval !== void 0 ? `Wait at least ${interval} seconds as specified by X-Retry-After` : "Wait for the configured SDK rate-limit window to expire") + ", then verify existing account/session state and configured auth hooks/plugins before submitting another operation; do not blindly repeat mutations.",
|
|
899
|
+
nextAction: rejectedBeforeExecution ? "Respect the SDK X-Retry-After header. Inspect existing account/session state using GET /api/auth/me; do not bypass the limit with another credential route." : "Respect the SDK X-Retry-After header. Inspect existing account/session state using GET /api/auth/me and verify configured auth hooks/plugins before retrying; the operation may already have changed data. Do not blindly repeat signup or sign-in."
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
function oauthResponseFailure(status, body) {
|
|
903
|
+
const value = body;
|
|
904
|
+
const known = {
|
|
905
|
+
VALIDATION_ERROR: {
|
|
906
|
+
status: 400,
|
|
907
|
+
code: "RUNTIME_AUTH_OAUTH_INPUT_INVALID",
|
|
908
|
+
action: "Use valid OAuth fields: scopes must be an array of strings, requestSignUp a boolean and idToken a valid token object before submitting again."
|
|
909
|
+
},
|
|
910
|
+
ID_TOKEN_NOT_SUPPORTED: {
|
|
911
|
+
status: 404,
|
|
912
|
+
code: "RUNTIME_AUTH_OAUTH_INPUT_INVALID",
|
|
913
|
+
action: "Use the browser redirect social sign-in flow; this provider does not support ID-token sign-in."
|
|
914
|
+
},
|
|
915
|
+
INVALID_TOKEN: {
|
|
916
|
+
status: 401,
|
|
917
|
+
code: "RUNTIME_AUTH_OAUTH_TOKEN_INVALID",
|
|
918
|
+
action: "Obtain a fresh valid provider ID token, or start a new browser redirect social sign-in before submitting again."
|
|
919
|
+
},
|
|
920
|
+
PROVIDER_NOT_FOUND: {
|
|
921
|
+
status: 404,
|
|
922
|
+
code: "RUNTIME_AUTH_OAUTH_PROVIDER_INVALID",
|
|
923
|
+
action: "Choose a provider listed by GET /api/auth/social-providers. Correct the effective Better Auth provider configuration and restart before signing in."
|
|
924
|
+
},
|
|
925
|
+
USER_EMAIL_NOT_FOUND: {
|
|
926
|
+
status: 401,
|
|
927
|
+
code: "RUNTIME_AUTH_OAUTH_IDENTITY_UNAVAILABLE",
|
|
928
|
+
action: "Use a provider account that supplies an email address and grant the configured email permission before starting a new social sign-in."
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
if (typeof value?.code !== "string" || !Object.hasOwn(known, value.code))
|
|
932
|
+
return void 0;
|
|
933
|
+
const entry = known[value.code];
|
|
934
|
+
if (status !== entry.status)
|
|
935
|
+
return void 0;
|
|
936
|
+
return new RuntimeDiagnosticError({
|
|
937
|
+
code: entry.code,
|
|
938
|
+
capability: "auth",
|
|
939
|
+
stage: "request",
|
|
940
|
+
servingStarted: "unchanged",
|
|
941
|
+
dataImpact: "unknown",
|
|
942
|
+
retryable: false,
|
|
943
|
+
retryPrecondition: entry.action,
|
|
944
|
+
nextAction: entry.action
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
function authTransportFailure(code, maxBodyBytes) {
|
|
948
|
+
const action = code === "RUNTIME_AUTH_REQUEST_BODY_TOO_LARGE" ? `Reduce the encoded auth payload to at most ${maxBodyBytes} bytes before submitting a fresh request. Use the storage upload API for files; the auth payload limit is separate.` : "Use a frontend origin admitted by the trusted bootstrap auth configuration. If this frontend is intended, correct that trusted origin configuration and restart the generation before submitting a fresh request; do not disable origin protection.";
|
|
949
|
+
return new RuntimeDiagnosticError({
|
|
950
|
+
code,
|
|
951
|
+
stage: "request",
|
|
952
|
+
capability: "auth",
|
|
953
|
+
servingStarted: "unchanged",
|
|
954
|
+
dataImpact: "none",
|
|
955
|
+
retryable: false,
|
|
956
|
+
retryPrecondition: action,
|
|
957
|
+
nextAction: `No auth operation ran. ${action}`
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
function renderAuthRequestFailure(error, logger, request) {
|
|
961
|
+
const known = runtimeDiagnostic(error);
|
|
962
|
+
const timeout = error instanceof RuntimeAuthSessionTimeoutError;
|
|
963
|
+
const diagnostic = known ?? {
|
|
964
|
+
code: timeout ? "RUNTIME_AUTH_SESSION_OBSERVATION_TIMEOUT" : "RUNTIME_AUTH_INITIALIZATION_FAILED",
|
|
965
|
+
stage: "request",
|
|
966
|
+
servingStarted: "unchanged",
|
|
967
|
+
dataImpact: "unknown",
|
|
968
|
+
retryable: false,
|
|
969
|
+
retryPrecondition: "Verify provider readiness and existing account/session state before repeating the auth operation.",
|
|
970
|
+
nextAction: "Inspect account/session state using GET /api/auth/me and verify Runtime readiness; do not blindly retry the auth operation.",
|
|
971
|
+
capability: "auth"
|
|
972
|
+
};
|
|
973
|
+
try {
|
|
974
|
+
logger.error("runtime.auth.request.failed", {
|
|
975
|
+
"runtime.public_code": diagnostic.code,
|
|
976
|
+
"runtime.stage": diagnostic.stage,
|
|
977
|
+
"runtime.serving_started": diagnostic.servingStarted,
|
|
978
|
+
"runtime.data_impact": diagnostic.dataImpact ?? "unknown",
|
|
979
|
+
"runtime.retryable": diagnostic.retryable,
|
|
980
|
+
"runtime.retry_precondition": diagnostic.retryPrecondition,
|
|
981
|
+
"runtime.next_action": diagnostic.nextAction,
|
|
982
|
+
"runtime.capability": diagnostic.capability ?? "auth",
|
|
983
|
+
"request.id": diagnostic.correlationId ?? runtimeRequestCorrelation(request)
|
|
984
|
+
});
|
|
985
|
+
} catch {
|
|
986
|
+
}
|
|
987
|
+
const rendered = known ? renderRuntimeError(error, "Request failed", request) : void 0;
|
|
988
|
+
const retryAfterSeconds = diagnostic.retryAfterSeconds;
|
|
989
|
+
return Response.json(rendered?.body ?? {
|
|
990
|
+
error: "Runtime auth execution is unavailable.",
|
|
991
|
+
...diagnostic,
|
|
992
|
+
correlationId: runtimeRequestCorrelation(request)
|
|
993
|
+
}, {
|
|
994
|
+
status: timeout ? 503 : rendered?.status ?? 503,
|
|
995
|
+
headers: {
|
|
996
|
+
"cache-control": "no-store",
|
|
997
|
+
...retryAfterSeconds !== void 0 ? { "retry-after": String(retryAfterSeconds) } : {}
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// ../runtime/dist/adapters/auth/better-auth/completion-notifications.js
|
|
1003
|
+
async function observeAuthCompletion(event, request, logger, notify) {
|
|
1004
|
+
try {
|
|
1005
|
+
await notify();
|
|
1006
|
+
} catch {
|
|
1007
|
+
try {
|
|
1008
|
+
const reset = event === "password-reset";
|
|
1009
|
+
logger.error("runtime.auth.completion.notification.failed", {
|
|
1010
|
+
"runtime.public_code": reset ? "RUNTIME_AUTH_AFTER_PASSWORD_RESET_FAILED" : "RUNTIME_AUTH_AFTER_EMAIL_VERIFICATION_FAILED",
|
|
1011
|
+
"runtime.stage": "request",
|
|
1012
|
+
"runtime.capability": "auth",
|
|
1013
|
+
"runtime.serving_started": "unchanged",
|
|
1014
|
+
"runtime.data_impact": "committed",
|
|
1015
|
+
"runtime.retryable": false,
|
|
1016
|
+
"runtime.retry_precondition": "Do not repeat the successful auth operation to retry its notification.",
|
|
1017
|
+
"runtime.next_action": reset ? "Password update succeeded. Inspect the configured onPasswordReset notification; allow SDK session finalization to complete." : "Email verification succeeded. Inspect the configured afterEmailVerification notification; do not repeat verification to retry it.",
|
|
1018
|
+
...request instanceof Request ? { "request.id": runtimeRequestCorrelation(request) } : {}
|
|
1019
|
+
});
|
|
1020
|
+
} catch {
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// ../runtime/dist/adapters/auth/better-auth/verification-gate.js
|
|
1026
|
+
var RuntimeVerificationGateTimeout = class extends Error {
|
|
1027
|
+
};
|
|
1028
|
+
var RuntimeVerificationGateInterrupted = class extends Error {
|
|
1029
|
+
};
|
|
1030
|
+
async function runRuntimeVerificationGate(hook, signal) {
|
|
1031
|
+
if (signal?.aborted)
|
|
1032
|
+
throw new RuntimeVerificationGateInterrupted();
|
|
1033
|
+
const deadline = performance.now() + 8e3;
|
|
1034
|
+
let timer;
|
|
1035
|
+
let onAbort;
|
|
1036
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
1037
|
+
timer = setTimeout(() => reject(new RuntimeVerificationGateTimeout()), 8e3);
|
|
1038
|
+
});
|
|
1039
|
+
const interrupted = new Promise((_resolve, reject) => {
|
|
1040
|
+
onAbort = () => reject(new RuntimeVerificationGateInterrupted());
|
|
1041
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1042
|
+
});
|
|
1043
|
+
try {
|
|
1044
|
+
await Promise.race([Promise.resolve().then(hook), timeout, interrupted]);
|
|
1045
|
+
if (signal?.aborted)
|
|
1046
|
+
throw new RuntimeVerificationGateInterrupted();
|
|
1047
|
+
if (performance.now() >= deadline)
|
|
1048
|
+
throw new RuntimeVerificationGateTimeout();
|
|
1049
|
+
} catch (error) {
|
|
1050
|
+
if (signal?.aborted)
|
|
1051
|
+
throw new RuntimeVerificationGateInterrupted();
|
|
1052
|
+
if (performance.now() >= deadline)
|
|
1053
|
+
throw new RuntimeVerificationGateTimeout();
|
|
1054
|
+
throw error;
|
|
1055
|
+
} finally {
|
|
1056
|
+
if (timer)
|
|
1057
|
+
clearTimeout(timer);
|
|
1058
|
+
if (signal && onAbort)
|
|
1059
|
+
signal.removeEventListener("abort", onAbort);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// ../runtime/dist/adapters/auth/better-auth/options.js
|
|
1064
|
+
function additionalFields(config) {
|
|
1065
|
+
const fields = config.user?.additionalFields;
|
|
1066
|
+
if (!fields || Object.keys(fields).length === 0)
|
|
1067
|
+
return void 0;
|
|
1068
|
+
return Object.fromEntries(Object.entries(fields).map(([name, field]) => [
|
|
1069
|
+
name,
|
|
1070
|
+
{
|
|
1071
|
+
type: field.type === "boolean" ? "boolean" : field.type === "integer" || field.type === "number" ? "number" : field.type === "timestamp" ? "date" : "string",
|
|
1072
|
+
required: field.nullable !== true,
|
|
1073
|
+
...field.default !== void 0 ? { defaultValue: field.default } : {},
|
|
1074
|
+
...field.columnName ? { fieldName: field.columnName } : {},
|
|
1075
|
+
input: field.input === true
|
|
1076
|
+
}
|
|
1077
|
+
]));
|
|
1078
|
+
}
|
|
1079
|
+
function authUser(user) {
|
|
1080
|
+
return {
|
|
1081
|
+
id: typeof user.id === "string" ? user.id : void 0,
|
|
1082
|
+
email: typeof user.email === "string" ? user.email : "",
|
|
1083
|
+
name: typeof user.name === "string" ? user.name : void 0,
|
|
1084
|
+
emailVerified: user.emailVerified === true,
|
|
1085
|
+
createdAt: user.createdAt,
|
|
1086
|
+
updatedAt: user.updatedAt
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
function buildRuntimeBetterAuthOptions(input) {
|
|
1090
|
+
const config = input.authConfig;
|
|
1091
|
+
const defaults = {
|
|
1092
|
+
database: input.database,
|
|
1093
|
+
secret: input.secret,
|
|
1094
|
+
baseURL: input.origin,
|
|
1095
|
+
basePath: "/api/auth",
|
|
1096
|
+
trustedOrigins: input.trustedOrigins,
|
|
1097
|
+
plugins: input.plugins,
|
|
1098
|
+
...additionalFields(config) ? { user: { additionalFields: additionalFields(config) } } : {},
|
|
1099
|
+
emailAndPassword: {
|
|
1100
|
+
enabled: true,
|
|
1101
|
+
...config.emailVerification ? {
|
|
1102
|
+
requireEmailVerification: config.emailVerification.requireEmailVerification ?? true,
|
|
1103
|
+
autoSignIn: false
|
|
1104
|
+
} : {},
|
|
1105
|
+
...config.passwordReset ? {
|
|
1106
|
+
resetPasswordTokenExpiresIn: config.passwordReset.resetPasswordTokenExpiresIn,
|
|
1107
|
+
sendResetPassword: async ({ user, url, token }, request) => config.passwordReset.sendResetPassword({ user: authUser(user), url, token }, { request }),
|
|
1108
|
+
onPasswordReset: config.passwordReset.onPasswordReset ? async ({ user }, request) => observeAuthCompletion("password-reset", request, input.logger ?? runtimeNullLogger, () => config.passwordReset.onPasswordReset({ user: authUser(user) }, { request })) : void 0
|
|
1109
|
+
} : {}
|
|
1110
|
+
},
|
|
1111
|
+
...config.emailVerification ? {
|
|
1112
|
+
emailVerification: {
|
|
1113
|
+
sendOnSignUp: config.emailVerification.sendOnSignUp ?? true,
|
|
1114
|
+
autoSignInAfterVerification: config.emailVerification.autoSignInAfterVerification ?? true,
|
|
1115
|
+
sendVerificationEmail: async ({ user, url, token }, request) => config.emailVerification.sendVerificationEmail({ user: authUser(user), url, token }, { request }),
|
|
1116
|
+
beforeEmailVerification: config.emailVerification.beforeEmailVerification ? async (user, request) => {
|
|
1117
|
+
try {
|
|
1118
|
+
await runRuntimeVerificationGate(() => {
|
|
1119
|
+
const hook = () => config.emailVerification.beforeEmailVerification(authUser(user), { request });
|
|
1120
|
+
return input.trackVerificationGate ? input.trackVerificationGate(hook) : hook();
|
|
1121
|
+
}, request instanceof Request ? request.signal : void 0);
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
if (error instanceof RuntimeVerificationGateTimeout || error instanceof RuntimeVerificationGateInterrupted)
|
|
1124
|
+
throw new RuntimeDiagnosticError({
|
|
1125
|
+
code: error instanceof RuntimeVerificationGateTimeout ? "AUTH_EMAIL_VERIFICATION_GATE_TIMEOUT" : "AUTH_EMAIL_VERIFICATION_INTERRUPTED",
|
|
1126
|
+
stage: "request",
|
|
1127
|
+
capability: "auth",
|
|
1128
|
+
servingStarted: "unchanged",
|
|
1129
|
+
dataImpact: "unknown",
|
|
1130
|
+
retryable: false,
|
|
1131
|
+
retryPrecondition: "Check the current verification state and correct any stalled verification gate before starting another flow.",
|
|
1132
|
+
nextAction: "Check whether your email is verified, then follow the normal verification flow if needed. Earlier hook effects may remain."
|
|
1133
|
+
});
|
|
1134
|
+
throw new RuntimeDiagnosticError({
|
|
1135
|
+
code: "AUTH_EMAIL_VERIFICATION_GATE_REJECTED",
|
|
1136
|
+
stage: "request",
|
|
1137
|
+
capability: "auth",
|
|
1138
|
+
servingStarted: "unchanged",
|
|
1139
|
+
dataImpact: "unknown",
|
|
1140
|
+
retryable: false,
|
|
1141
|
+
retryPrecondition: "The application developer must correct the verification gate first.",
|
|
1142
|
+
nextAction: "After the application developer corrects the gate, follow the normal verification flow. Earlier hook effects may remain."
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
if (request instanceof Request && request.signal.aborted)
|
|
1146
|
+
throw new RuntimeDiagnosticError({
|
|
1147
|
+
code: "AUTH_EMAIL_VERIFICATION_INTERRUPTED",
|
|
1148
|
+
stage: "request",
|
|
1149
|
+
capability: "auth",
|
|
1150
|
+
servingStarted: "unchanged",
|
|
1151
|
+
dataImpact: "unknown",
|
|
1152
|
+
retryable: false,
|
|
1153
|
+
retryPrecondition: "Check the current verification state before starting another verification flow.",
|
|
1154
|
+
nextAction: "Check whether your email is verified, then follow the normal verification flow if needed. Earlier hook effects may remain."
|
|
1155
|
+
});
|
|
1156
|
+
} : void 0,
|
|
1157
|
+
afterEmailVerification: config.emailVerification.afterEmailVerification ? async (user, request) => observeAuthCompletion("email-verification", request, input.logger ?? runtimeNullLogger, () => config.emailVerification.afterEmailVerification(authUser(user), { request })) : void 0
|
|
1158
|
+
}
|
|
1159
|
+
} : {},
|
|
1160
|
+
session: { expiresIn: 60 * 60 * 24 * 7, updateAge: 60 * 60 * 24 },
|
|
1161
|
+
account: { encryptOAuthTokens: true },
|
|
1162
|
+
socialProviders: input.socialProviders
|
|
1163
|
+
};
|
|
1164
|
+
const overridden = typeof config.betterAuth === "function" ? config.betterAuth(defaults) : defaults;
|
|
1165
|
+
const plugins = [...input.plugins];
|
|
1166
|
+
if (Array.isArray(overridden.plugins)) {
|
|
1167
|
+
for (const plugin of overridden.plugins)
|
|
1168
|
+
if (!plugins.includes(plugin))
|
|
1169
|
+
plugins.push(plugin);
|
|
1170
|
+
}
|
|
1171
|
+
const policy = input.rateLimit ?? resolveAuthRateLimitPolicy(config, {});
|
|
1172
|
+
const { ipAddress: _appIp, ...advanced } = overridden.advanced ?? {};
|
|
1173
|
+
const { context: _context, ipAddress, ...rateLimit } = policy;
|
|
1174
|
+
return {
|
|
1175
|
+
...overridden,
|
|
1176
|
+
rateLimit,
|
|
1177
|
+
advanced: { ...advanced, ...ipAddress ? { ipAddress } : {} },
|
|
1178
|
+
database: input.database,
|
|
1179
|
+
secret: input.secret,
|
|
1180
|
+
baseURL: input.origin,
|
|
1181
|
+
basePath: "/api/auth",
|
|
1182
|
+
trustedOrigins: input.trustedOrigins,
|
|
1183
|
+
plugins,
|
|
1184
|
+
emailAndPassword: { ...overridden.emailAndPassword, enabled: true },
|
|
1185
|
+
session: { ...overridden.session, expiresIn: 60 * 60 * 24 * 7, updateAge: 60 * 60 * 24 },
|
|
1186
|
+
account: { ...overridden.account, encryptOAuthTokens: true }
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// ../runtime/dist/adapters/auth/better-auth/social.js
|
|
1191
|
+
function copyProviderData(value) {
|
|
1192
|
+
if (Array.isArray(value))
|
|
1193
|
+
return Object.freeze(value.map(copyProviderData));
|
|
1194
|
+
if (value && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null))
|
|
1195
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyProviderData(item)])));
|
|
1196
|
+
return value;
|
|
1197
|
+
}
|
|
1198
|
+
async function captureRuntimeNativeProviders(value) {
|
|
1199
|
+
if (value == null)
|
|
1200
|
+
return {};
|
|
1201
|
+
if (typeof value !== "object" || Array.isArray(value))
|
|
1202
|
+
throw new Error("Invalid social providers");
|
|
1203
|
+
const providers = {};
|
|
1204
|
+
for (const [id, original] of Object.entries(value)) {
|
|
1205
|
+
const provider = typeof original === "function" ? await original() : original;
|
|
1206
|
+
if (provider == null || provider.enabled === false)
|
|
1207
|
+
continue;
|
|
1208
|
+
if (typeof provider !== "object")
|
|
1209
|
+
throw new Error("Invalid social provider");
|
|
1210
|
+
providers[id] = copyProviderData(provider);
|
|
1211
|
+
}
|
|
1212
|
+
return Object.freeze(providers);
|
|
1213
|
+
}
|
|
1214
|
+
function captureRuntimeGenericProviders(plugins, createPlugin, origin) {
|
|
1215
|
+
const providers = /* @__PURE__ */ new Map();
|
|
1216
|
+
const retained = [];
|
|
1217
|
+
let genericIndex;
|
|
1218
|
+
for (const plugin of plugins) {
|
|
1219
|
+
const value = plugin;
|
|
1220
|
+
if (value?.id !== "generic-oauth") {
|
|
1221
|
+
retained.push(plugin);
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
genericIndex ??= retained.length;
|
|
1225
|
+
if (!Array.isArray(value.options?.config))
|
|
1226
|
+
throw new Error("Invalid generic OAuth options");
|
|
1227
|
+
for (const config of value.options.config) {
|
|
1228
|
+
if (!config || typeof config !== "object" || Array.isArray(config) || typeof config.providerId !== "string" || !config.providerId || typeof config.clientId !== "string")
|
|
1229
|
+
throw new Error("Invalid generic OAuth provider");
|
|
1230
|
+
const captured = { ...config };
|
|
1231
|
+
if (captured.redirectURI === void 0 && origin !== void 0)
|
|
1232
|
+
captured.redirectURI = new URL(`/api/auth/oauth2/callback/${encodeURIComponent(config.providerId)}`, origin).href;
|
|
1233
|
+
providers.set(config.providerId, copyProviderData(captured));
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
if (genericIndex !== void 0) {
|
|
1237
|
+
retained.splice(genericIndex, 0, createPlugin({ config: [...providers.values()] }));
|
|
1238
|
+
}
|
|
1239
|
+
return { plugins: retained, providerIds: [...providers.keys()] };
|
|
1240
|
+
}
|
|
1241
|
+
var builtInProviders = {
|
|
1242
|
+
kakao: {
|
|
1243
|
+
authorizationUrl: "https://kauth.kakao.com/oauth/authorize",
|
|
1244
|
+
tokenUrl: "https://kauth.kakao.com/oauth/token",
|
|
1245
|
+
userInfoUrl: "https://kapi.kakao.com/v2/user/me",
|
|
1246
|
+
scopes: ["profile_nickname", "profile_image", "account_email"],
|
|
1247
|
+
accountSubject: ({ profile }) => {
|
|
1248
|
+
const id = profile.id;
|
|
1249
|
+
if (typeof id === "string" && id.length > 0)
|
|
1250
|
+
return id;
|
|
1251
|
+
if (typeof id === "number" && Number.isFinite(id))
|
|
1252
|
+
return String(id);
|
|
1253
|
+
throw new Error("OAuth provider did not return a valid account subject.");
|
|
1254
|
+
},
|
|
1255
|
+
mapProfileToUser: (profile) => {
|
|
1256
|
+
const account = profile.kakao_account;
|
|
1257
|
+
const value = account?.profile;
|
|
1258
|
+
return {
|
|
1259
|
+
email: typeof account?.email === "string" ? account.email : void 0,
|
|
1260
|
+
name: typeof value?.nickname === "string" ? value.nickname : void 0,
|
|
1261
|
+
image: typeof value?.profile_image_url === "string" ? value.profile_image_url : void 0
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
},
|
|
1265
|
+
naver: {
|
|
1266
|
+
authorizationUrl: "https://nid.naver.com/oauth2.0/authorize",
|
|
1267
|
+
tokenUrl: "https://nid.naver.com/oauth2.0/token",
|
|
1268
|
+
userInfoUrl: "https://openapi.naver.com/v1/nid/me",
|
|
1269
|
+
scopes: ["name", "email", "profile_image"],
|
|
1270
|
+
accountSubject: ({ profile }) => {
|
|
1271
|
+
const value = profile.response;
|
|
1272
|
+
if (typeof value?.id === "string" && value.id.length > 0)
|
|
1273
|
+
return value.id;
|
|
1274
|
+
throw new Error("OAuth provider did not return a valid account subject.");
|
|
1275
|
+
},
|
|
1276
|
+
mapProfileToUser: (profile) => {
|
|
1277
|
+
const value = profile.response;
|
|
1278
|
+
return {
|
|
1279
|
+
email: typeof value?.email === "string" ? value.email : void 0,
|
|
1280
|
+
name: typeof value?.name === "string" ? value.name : void 0,
|
|
1281
|
+
image: typeof value?.profile_image === "string" ? value.profile_image : void 0
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
function resolveRuntimeSocialAuth(config) {
|
|
1287
|
+
const socialProviders = {};
|
|
1288
|
+
const customOAuthConfig = [];
|
|
1289
|
+
for (const [providerId, provider] of Object.entries(config ?? {})) {
|
|
1290
|
+
if (!provider || typeof provider.clientId !== "string" || !provider.clientId)
|
|
1291
|
+
continue;
|
|
1292
|
+
if (providerId === "google" || providerId === "apple") {
|
|
1293
|
+
if (typeof provider.clientSecret !== "string" || !provider.clientSecret)
|
|
1294
|
+
continue;
|
|
1295
|
+
socialProviders[providerId] = provider;
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
const merged = { ...builtInProviders[providerId], ...provider };
|
|
1299
|
+
if (!merged.authorizationUrl || !merged.tokenUrl || !merged.userInfoUrl)
|
|
1300
|
+
continue;
|
|
1301
|
+
customOAuthConfig.push({ ...merged, providerId, clientId: provider.clientId });
|
|
1302
|
+
}
|
|
1303
|
+
return { socialProviders, customOAuthConfig };
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth-exchange.js
|
|
1307
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
1308
|
+
import { and as and2, eq as eq2, getTableColumns as getTableColumns2, gt as gt2 } from "drizzle-orm";
|
|
1309
|
+
var legacyIvLength = 12;
|
|
1310
|
+
var boundIvLength = 16;
|
|
1311
|
+
function parseBinding(value) {
|
|
1312
|
+
const receipt = JSON.parse(value);
|
|
1313
|
+
if (!receipt || receipt.transport !== "cookie" && receipt.transport !== "bearer" || typeof receipt.token !== "string" || !receipt.token || typeof receipt.userId !== "string" || !receipt.userId)
|
|
1314
|
+
return null;
|
|
1315
|
+
return { transport: receipt.transport, userId: receipt.userId, token: receipt.token };
|
|
1316
|
+
}
|
|
1317
|
+
function seal(key, aad, value, ivLength) {
|
|
1318
|
+
const iv = randomBytes(ivLength);
|
|
1319
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv).setAAD(Buffer.from(aad));
|
|
1320
|
+
const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
1321
|
+
return [iv, cipher.getAuthTag(), encrypted].map((part) => part.toString("base64url")).join(".");
|
|
1322
|
+
}
|
|
1323
|
+
function open(key, aad, parts) {
|
|
1324
|
+
const [iv, tag, ciphertext] = parts.map((part) => Buffer.from(part, "base64url"));
|
|
1325
|
+
if (!iv || !tag || !ciphertext || tag.length !== 16)
|
|
1326
|
+
throw new Error("Invalid OAuth receipt");
|
|
1327
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv).setAAD(Buffer.from(aad)).setAuthTag(tag);
|
|
1328
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
1329
|
+
}
|
|
1330
|
+
function createOAuthExchangeStore(database, verification, key, origin) {
|
|
1331
|
+
const table = verification;
|
|
1332
|
+
const columns = getTableColumns2(table);
|
|
1333
|
+
const identifier = (code) => `gencow-oauth-exchange:v1:${createHmac("sha256", key).update(`${origin}\0${code}`).digest("hex")}`;
|
|
1334
|
+
return {
|
|
1335
|
+
async create({ value, ...binding }) {
|
|
1336
|
+
const code = randomBytes(32).toString("base64url");
|
|
1337
|
+
const id = identifier(code);
|
|
1338
|
+
const credential = seal(key, id, value, boundIvLength);
|
|
1339
|
+
const metadata = seal(key, `${id}:binding:${credential}`, JSON.stringify(binding), legacyIvLength);
|
|
1340
|
+
const now = /* @__PURE__ */ new Date();
|
|
1341
|
+
await database.drizzle.insert(table).values({
|
|
1342
|
+
id: randomUUID(),
|
|
1343
|
+
identifier: id,
|
|
1344
|
+
value: `${credential}.${metadata}`,
|
|
1345
|
+
expiresAt: new Date(now.getTime() + 5 * 6e4),
|
|
1346
|
+
createdAt: now,
|
|
1347
|
+
updatedAt: now
|
|
1348
|
+
});
|
|
1349
|
+
return code;
|
|
1350
|
+
},
|
|
1351
|
+
async consume(code) {
|
|
1352
|
+
if (!/^[A-Za-z0-9_-]{43}$/u.test(code))
|
|
1353
|
+
return null;
|
|
1354
|
+
const id = identifier(code);
|
|
1355
|
+
const [row] = await database.drizzle.delete(table).where(and2(eq2(columns.identifier, id), gt2(columns.expiresAt, /* @__PURE__ */ new Date()))).returning({ value: columns.value });
|
|
1356
|
+
if (!row || typeof row.value !== "string")
|
|
1357
|
+
return null;
|
|
1358
|
+
try {
|
|
1359
|
+
const parts = row.value.split(".");
|
|
1360
|
+
const ivLength = Buffer.from(parts[0] ?? "", "base64url").length;
|
|
1361
|
+
if (ivLength === legacyIvLength && parts.length === 3) {
|
|
1362
|
+
const value2 = open(key, id, parts);
|
|
1363
|
+
return value2 ? { value: value2 } : null;
|
|
1364
|
+
}
|
|
1365
|
+
if (ivLength !== boundIvLength || parts.length !== 6)
|
|
1366
|
+
return null;
|
|
1367
|
+
const credential = parts.slice(0, 3);
|
|
1368
|
+
const value = open(key, id, credential);
|
|
1369
|
+
const binding = parseBinding(open(key, `${id}:binding:${credential.join(".")}`, parts.slice(3)));
|
|
1370
|
+
return value && binding ? { value, ...binding } : null;
|
|
1371
|
+
} catch {
|
|
1372
|
+
return null;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth-exchange-failure.js
|
|
1379
|
+
var databaseStates = /* @__PURE__ */ new Set([
|
|
1380
|
+
"08000",
|
|
1381
|
+
"08001",
|
|
1382
|
+
"08003",
|
|
1383
|
+
"08004",
|
|
1384
|
+
"08006",
|
|
1385
|
+
"08P01",
|
|
1386
|
+
"40001",
|
|
1387
|
+
"40P01",
|
|
1388
|
+
"53300",
|
|
1389
|
+
"55P03",
|
|
1390
|
+
"57P01",
|
|
1391
|
+
"57P02",
|
|
1392
|
+
"57P03"
|
|
1393
|
+
]);
|
|
1394
|
+
function isTransientDatabaseFailure(error) {
|
|
1395
|
+
let cause = error;
|
|
1396
|
+
for (let depth = 0; cause && typeof cause === "object" && depth < 5; depth += 1) {
|
|
1397
|
+
const { code, errno, cause: next } = cause;
|
|
1398
|
+
if (databaseStates.has(code ?? "") || databaseStates.has(errno ?? ""))
|
|
1399
|
+
return true;
|
|
1400
|
+
cause = next;
|
|
1401
|
+
}
|
|
1402
|
+
return false;
|
|
1403
|
+
}
|
|
1404
|
+
function oauthExchangeFailure(error, request, logger) {
|
|
1405
|
+
const diagnostic = runtimeDiagnostic(error);
|
|
1406
|
+
const sdkFailure = error;
|
|
1407
|
+
const rateLimit = diagnostic?.code === "RUNTIME_AUTH_RATE_LIMIT_STORAGE_UNAVAILABLE";
|
|
1408
|
+
const correction = diagnostic?.code === "RUNTIME_AUTH_DATABASE_QUERY_FAILED" ? { diagnostic, response: renderRuntimeError(error, "Authentication could not be verified.", request) } : null;
|
|
1409
|
+
if (!correction && !rateLimit && diagnostic?.code !== "RUNTIME_AUTH_DATABASE_UNAVAILABLE" && diagnostic?.code !== "RUNTIME_DATABASE_UNAVAILABLE" && diagnostic?.code !== "RUNTIME_AUTH_SESSION_OBSERVATION_TIMEOUT" && !(sdkFailure?.statusCode === 500 && sdkFailure.body?.code === "FAILED_TO_GET_SESSION") && !isTransientDatabaseFailure(error))
|
|
1410
|
+
return null;
|
|
1411
|
+
const code = correction?.diagnostic.code ?? (rateLimit ? diagnostic.code : "AUTH_STORE_TEMPORARILY_UNAVAILABLE");
|
|
1412
|
+
const correlationId = diagnostic?.correlationId ?? runtimeRequestCorrelation(request);
|
|
1413
|
+
const stage = rateLimit ? "auth-rate-limit-store" : "auth-store";
|
|
1414
|
+
const nextAction = correction ? `${correction.diagnostic.nextAction} Then start a new social sign-in; do not reuse this exchange code.` : rateLimit ? "After rate-limit storage recovers, start a new social sign-in. Do not retry or reuse this exchange code." : "After authentication storage recovers, start a new social sign-in. Do not retry or reuse this exchange code.";
|
|
1415
|
+
const retryPrecondition = correction ? `${correction.diagnostic.retryPrecondition} This exchange code was consumed and cannot be reused.` : diagnostic?.retryAfterSeconds ? `Wait at least ${diagnostic.retryAfterSeconds} seconds and for the store to recover before starting a fresh social sign-in. This exchange code cannot be reused.` : "Wait for the original authentication work to settle and the store to recover before starting a fresh social sign-in. This exchange code cannot be reused.";
|
|
1416
|
+
try {
|
|
1417
|
+
logger.error("runtime.auth.oauth.exchange.failed", {
|
|
1418
|
+
"runtime.public_code": code,
|
|
1419
|
+
"runtime.stage": stage,
|
|
1420
|
+
"request.id": correlationId
|
|
1421
|
+
});
|
|
1422
|
+
} catch {
|
|
1423
|
+
}
|
|
1424
|
+
return Response.json({
|
|
1425
|
+
error: correction ? `${correction.response.body.error} After the configuration is corrected, start a new social sign-in.` : rateLimit ? "Authentication rate-limit storage is unavailable. After it recovers, start a new social sign-in." : "Authentication storage is temporarily unavailable. After it recovers, start a new social sign-in.",
|
|
1426
|
+
code,
|
|
1427
|
+
capability: "auth",
|
|
1428
|
+
stage,
|
|
1429
|
+
servingStarted: "unchanged",
|
|
1430
|
+
dataImpact: diagnostic?.dataImpact ?? "none",
|
|
1431
|
+
exchangeCodeConsumed: true,
|
|
1432
|
+
stateImpact: "OAuth exchange code consumed; no credentials issued",
|
|
1433
|
+
retryable: false,
|
|
1434
|
+
retryPrecondition,
|
|
1435
|
+
nextAction,
|
|
1436
|
+
correlationId
|
|
1437
|
+
}, { status: correction?.response.status ?? 503, headers: { "cache-control": "no-store" } });
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth.js
|
|
1441
|
+
var guidance = {
|
|
1442
|
+
RUNTIME_AUTH_OAUTH_CALLBACK_INVALID: "Use an HTTP(S) callbackURL, errorCallbackURL and newUserCallbackURL on a configured trusted auth origin; correct trusted bootstrap configuration and restart if necessary.",
|
|
1443
|
+
RUNTIME_AUTH_OAUTH_MODE_INVALID: "Omit oauthReturnMode (or handoff mode) for the token default, or use exactly token or cookie as admitted by auth.oauth.allowedReturnModes. Restart after changing trusted auth configuration.",
|
|
1444
|
+
RUNTIME_AUTH_OAUTH_PROVIDER_INVALID: "Choose a provider listed by GET /api/auth/social-providers. Configure its credentials and restart before starting social sign-in.",
|
|
1445
|
+
RUNTIME_AUTH_OAUTH_INPUT_INVALID: "Supply the social provider or exchange code required by this route. Use an array of strings for scopes and valid OAuth fields before submitting a fresh request.",
|
|
1446
|
+
RUNTIME_AUTH_OAUTH_CODE_INVALID: "The exchange code is invalid, expired or already used. Inspect GET /api/auth/me, then start a new social sign-in when needed; do not repeat this exchange code.",
|
|
1447
|
+
RUNTIME_AUTH_OAUTH_SESSION_UNAVAILABLE: "The OAuth session is no longer valid. Inspect GET /api/auth/me, then start a new social sign-in when needed.",
|
|
1448
|
+
RUNTIME_AUTH_OAUTH_START_FAILED: "Verify the provider credentials and endpoints, callback registration and Runtime readiness before starting a new social sign-in."
|
|
1449
|
+
};
|
|
1450
|
+
function failure(code, dataImpact = "none") {
|
|
1451
|
+
return new RuntimeDiagnosticError({
|
|
1452
|
+
code,
|
|
1453
|
+
capability: "auth",
|
|
1454
|
+
stage: "request",
|
|
1455
|
+
servingStarted: "unchanged",
|
|
1456
|
+
dataImpact,
|
|
1457
|
+
retryable: false,
|
|
1458
|
+
retryPrecondition: guidance[code],
|
|
1459
|
+
nextAction: guidance[code]
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
function redirect(url, sdkHeaders) {
|
|
1463
|
+
const headers = new Headers(sdkHeaders);
|
|
1464
|
+
headers.delete("content-length");
|
|
1465
|
+
headers.delete("content-type");
|
|
1466
|
+
headers.set("location", url.href);
|
|
1467
|
+
headers.set("cache-control", "no-store");
|
|
1468
|
+
return new Response(null, { status: 302, headers });
|
|
1469
|
+
}
|
|
1470
|
+
function createOAuthFacade(input) {
|
|
1471
|
+
const { config } = input;
|
|
1472
|
+
const store = createOAuthExchangeStore(input.database, config.authSchema.verification, input.key, config.originPolicy.origin);
|
|
1473
|
+
function callback(value) {
|
|
1474
|
+
if (value !== void 0 && value !== null && typeof value !== "string")
|
|
1475
|
+
throw failure("RUNTIME_AUTH_OAUTH_CALLBACK_INVALID");
|
|
1476
|
+
const requested = typeof value === "string" ? value.trim() : "";
|
|
1477
|
+
try {
|
|
1478
|
+
const url = new URL(requested || config.authConfig.oauth?.callbackURL || "/auth/callback", config.originPolicy.origin);
|
|
1479
|
+
if (url.username || url.password || !isRuntimeOriginAllowed(url.origin, config.originPolicy.trustedOrigins))
|
|
1480
|
+
throw Error();
|
|
1481
|
+
return url;
|
|
1482
|
+
} catch {
|
|
1483
|
+
throw failure("RUNTIME_AUTH_OAUTH_CALLBACK_INVALID");
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
function mode(value) {
|
|
1487
|
+
if (value !== void 0 && value !== "token" && value !== "cookie")
|
|
1488
|
+
throw failure("RUNTIME_AUTH_OAUTH_MODE_INVALID");
|
|
1489
|
+
const result = value ?? "token";
|
|
1490
|
+
if (!(config.authConfig.oauth?.allowedReturnModes ?? ["token"]).includes(result))
|
|
1491
|
+
throw failure("RUNTIME_AUTH_OAUTH_MODE_INVALID");
|
|
1492
|
+
return result;
|
|
1493
|
+
}
|
|
1494
|
+
function handoff(target, returnMode) {
|
|
1495
|
+
const url = new URL("/api/auth/oauth/handoff", config.originPolicy.origin);
|
|
1496
|
+
url.searchParams.set("callbackURL", target.href);
|
|
1497
|
+
url.searchParams.set("mode", returnMode);
|
|
1498
|
+
return url.href;
|
|
1499
|
+
}
|
|
1500
|
+
async function verifiedSession2(request) {
|
|
1501
|
+
const explicitBearer = request.headers.get("authorization")?.startsWith("Bearer ");
|
|
1502
|
+
const bearer = explicitBearer ? candidateSessionToken(request) : null;
|
|
1503
|
+
const tokens = explicitBearer ? bearer ? [bearer] : [] : extractSessionTokens(request.headers.get("cookie"));
|
|
1504
|
+
const transport = explicitBearer ? "bearer" : "cookie";
|
|
1505
|
+
const sessions = await Promise.all(tokens.map(async (token, index) => {
|
|
1506
|
+
const credential = { value: token, transport };
|
|
1507
|
+
const session = await input.getOAuthSession(request.headers, credential).catch((error) => {
|
|
1508
|
+
if (error instanceof RuntimeAuthSessionTimeoutError)
|
|
1509
|
+
throw error;
|
|
1510
|
+
throw sessionLookupFailure(error);
|
|
1511
|
+
});
|
|
1512
|
+
const identity = session?.user ? toRuntimeIdentity(session.user) : null;
|
|
1513
|
+
return session && identity ? { session, identity, credential, index } : null;
|
|
1514
|
+
}));
|
|
1515
|
+
return sessions.filter((value) => value !== null).sort((a, b) => sessionCreatedAtMs(b.session) - sessionCreatedAtMs(a.session) || a.index - b.index)[0] ?? null;
|
|
1516
|
+
}
|
|
1517
|
+
return async (request, path) => {
|
|
1518
|
+
const url = new URL(request.url);
|
|
1519
|
+
if (path === "/api/auth/sign-in/social/redirect" && request.method === "GET" || path === "/api/auth/sign-in/social" && request.method === "POST") {
|
|
1520
|
+
const isRedirect = request.method === "GET";
|
|
1521
|
+
const body = isRedirect ? {
|
|
1522
|
+
provider: url.searchParams.get("provider"),
|
|
1523
|
+
callbackURL: url.searchParams.get("callbackURL"),
|
|
1524
|
+
oauthReturnMode: url.searchParams.get("oauthReturnMode") ?? void 0,
|
|
1525
|
+
errorCallbackURL: url.searchParams.get("errorCallbackURL"),
|
|
1526
|
+
newUserCallbackURL: url.searchParams.get("newUserCallbackURL"),
|
|
1527
|
+
scopes: url.searchParams.getAll("scope"),
|
|
1528
|
+
...url.searchParams.has("requestSignUp") ? { requestSignUp: url.searchParams.get("requestSignUp") === "true" } : {}
|
|
1529
|
+
} : await request.json().catch(() => null);
|
|
1530
|
+
if (!body || typeof body.provider !== "string" || !body.provider)
|
|
1531
|
+
throw failure("RUNTIME_AUTH_OAUTH_INPUT_INVALID");
|
|
1532
|
+
const selection = await input.providerSelection();
|
|
1533
|
+
if (!selection.providers.includes(body.provider))
|
|
1534
|
+
throw failure("RUNTIME_AUTH_OAUTH_PROVIDER_INVALID");
|
|
1535
|
+
const target = callback(body.callbackURL);
|
|
1536
|
+
const newUser = body.newUserCallbackURL ? callback(body.newUserCallbackURL) : target;
|
|
1537
|
+
const error = body.errorCallbackURL ? callback(body.errorCallbackURL) : void 0;
|
|
1538
|
+
const returnMode = mode(body.oauthReturnMode);
|
|
1539
|
+
const sdkURL = new URL("/api/auth/sign-in/social", config.originPolicy.origin);
|
|
1540
|
+
const headers = new Headers(request.headers);
|
|
1541
|
+
headers.delete("content-length");
|
|
1542
|
+
headers.set("content-type", "application/json");
|
|
1543
|
+
const sdk = await (await input.ensure()).handler(new Request(sdkURL, {
|
|
1544
|
+
method: "POST",
|
|
1545
|
+
headers,
|
|
1546
|
+
signal: request.signal,
|
|
1547
|
+
body: JSON.stringify({
|
|
1548
|
+
provider: body.provider,
|
|
1549
|
+
callbackURL: handoff(target, returnMode),
|
|
1550
|
+
newUserCallbackURL: handoff(newUser, returnMode),
|
|
1551
|
+
errorCallbackURL: error?.href,
|
|
1552
|
+
scopes: body.scopes,
|
|
1553
|
+
requestSignUp: body.requestSignUp,
|
|
1554
|
+
...!isRedirect ? { idToken: body.idToken, loginHint: body.loginHint, additionalData: body.additionalData } : {}
|
|
1555
|
+
})
|
|
1556
|
+
}));
|
|
1557
|
+
if (!sdk.ok) {
|
|
1558
|
+
const limited = credentialRateLimitFailure(sdk, false);
|
|
1559
|
+
if (limited) {
|
|
1560
|
+
const safe = renderAuthRequestFailure(limited, input.logger, request);
|
|
1561
|
+
const headers2 = new Headers(sdk.headers);
|
|
1562
|
+
headers2.delete("content-length");
|
|
1563
|
+
headers2.set("content-type", "application/json");
|
|
1564
|
+
headers2.set("cache-control", "no-store");
|
|
1565
|
+
return new Response(await safe.text(), { status: safe.status, headers: headers2 });
|
|
1566
|
+
}
|
|
1567
|
+
const diagnosis = oauthResponseFailure(sdk.status, await sdk.json().catch(() => null));
|
|
1568
|
+
if (diagnosis)
|
|
1569
|
+
throw diagnosis;
|
|
1570
|
+
throw failure("RUNTIME_AUTH_OAUTH_START_FAILED", "unknown");
|
|
1571
|
+
}
|
|
1572
|
+
if (!isRedirect)
|
|
1573
|
+
return sdk;
|
|
1574
|
+
const result = await sdk.json().catch(() => null);
|
|
1575
|
+
try {
|
|
1576
|
+
if (typeof result?.url !== "string")
|
|
1577
|
+
throw Error();
|
|
1578
|
+
const authorization = new URL(result.url);
|
|
1579
|
+
if (!/^https?:$/u.test(authorization.protocol) || authorization.username || authorization.password)
|
|
1580
|
+
throw Error();
|
|
1581
|
+
return redirect(authorization, sdk.headers);
|
|
1582
|
+
} catch {
|
|
1583
|
+
throw failure("RUNTIME_AUTH_OAUTH_START_FAILED", "unknown");
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
if (path === "/api/auth/oauth/handoff" && request.method === "GET") {
|
|
1587
|
+
const target = callback(url.searchParams.get("callbackURL"));
|
|
1588
|
+
const returnMode = mode(url.searchParams.get("mode") ?? void 0);
|
|
1589
|
+
const session = await verifiedSession2(request);
|
|
1590
|
+
for (const name of ["code", "oauth", "error"])
|
|
1591
|
+
target.searchParams.delete(name);
|
|
1592
|
+
if (!session)
|
|
1593
|
+
target.searchParams.set("error", "oauth_session_missing");
|
|
1594
|
+
else if (returnMode === "cookie")
|
|
1595
|
+
target.searchParams.set("oauth", "success");
|
|
1596
|
+
else
|
|
1597
|
+
target.searchParams.set("code", await store.create({
|
|
1598
|
+
value: session.credential.value,
|
|
1599
|
+
transport: session.credential.transport,
|
|
1600
|
+
userId: session.identity.id,
|
|
1601
|
+
token: session.session.session.token
|
|
1602
|
+
}));
|
|
1603
|
+
return redirect(target);
|
|
1604
|
+
}
|
|
1605
|
+
if (path === "/api/auth/oauth/exchange" && request.method === "POST") {
|
|
1606
|
+
mode("token");
|
|
1607
|
+
const body = await request.json().catch(() => null);
|
|
1608
|
+
if (typeof body?.code !== "string" || !body.code)
|
|
1609
|
+
throw failure("RUNTIME_AUTH_OAUTH_INPUT_INVALID");
|
|
1610
|
+
const credential = await store.consume(body.code);
|
|
1611
|
+
if (!credential)
|
|
1612
|
+
throw failure("RUNTIME_AUTH_OAUTH_CODE_INVALID");
|
|
1613
|
+
try {
|
|
1614
|
+
const session = await input.getOAuthSession(request.headers, credential);
|
|
1615
|
+
const identity = session?.user ? toRuntimeIdentity(session.user) : null;
|
|
1616
|
+
const sessionToken = session?.session.token;
|
|
1617
|
+
if (!identity || !sessionToken || "transport" in credential && (credential.userId !== identity.id || credential.token !== sessionToken))
|
|
1618
|
+
throw failure("RUNTIME_AUTH_OAUTH_SESSION_UNAVAILABLE", "unknown");
|
|
1619
|
+
const jwt = await issueAccessToken(identity, input.key);
|
|
1620
|
+
const active = await input.getOAuthSession(request.headers, credential);
|
|
1621
|
+
if (active?.user.id !== identity.id || active.session.token !== sessionToken)
|
|
1622
|
+
throw failure("RUNTIME_AUTH_OAUTH_SESSION_UNAVAILABLE", "unknown");
|
|
1623
|
+
return Response.json({ user: identity, sessionToken, ...jwt }, { headers: { "cache-control": "no-store" } });
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
const recovery = oauthExchangeFailure(error, request, input.logger);
|
|
1626
|
+
if (recovery)
|
|
1627
|
+
return recovery;
|
|
1628
|
+
throw error;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
return null;
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth-session.js
|
|
1636
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
1637
|
+
|
|
1638
|
+
// ../runtime/dist/adapters/auth/better-auth/read-recovery.js
|
|
1639
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
1640
|
+
|
|
1641
|
+
// ../runtime/dist/adapters/auth/better-auth/read-recovery-circuit.js
|
|
1642
|
+
var WINDOW_MS = 6e4;
|
|
1643
|
+
var OPEN_MS = 1e4;
|
|
1644
|
+
var FAILURE_THRESHOLD = 3;
|
|
1645
|
+
function createAuthReadCircuit(now = () => performance.now()) {
|
|
1646
|
+
let failures = [];
|
|
1647
|
+
let openedUntil;
|
|
1648
|
+
let epoch = 0;
|
|
1649
|
+
let activeProbe;
|
|
1650
|
+
const owners = /* @__PURE__ */ new WeakMap();
|
|
1651
|
+
const retryAfter = (remainingMs) => Math.max(1, Math.min(60, Math.ceil(remainingMs / 1e3)));
|
|
1652
|
+
function admit() {
|
|
1653
|
+
const time = now();
|
|
1654
|
+
failures = failures.filter((failure2) => time - failure2 < WINDOW_MS);
|
|
1655
|
+
if (activeProbe)
|
|
1656
|
+
return { allowed: false, probeInProgress: true };
|
|
1657
|
+
if (openedUntil !== void 0 && time < openedUntil)
|
|
1658
|
+
return { allowed: false, retryAfterSeconds: retryAfter(openedUntil - time) };
|
|
1659
|
+
const permit = Object.freeze({
|
|
1660
|
+
allowed: true,
|
|
1661
|
+
halfOpen: openedUntil !== void 0
|
|
1662
|
+
});
|
|
1663
|
+
owners.set(permit, { epoch, observing: false, settled: false });
|
|
1664
|
+
if (permit.halfOpen)
|
|
1665
|
+
activeProbe = permit;
|
|
1666
|
+
return permit;
|
|
1667
|
+
}
|
|
1668
|
+
function openCircuit(time = now()) {
|
|
1669
|
+
openedUntil = time + OPEN_MS;
|
|
1670
|
+
return retryAfter(OPEN_MS);
|
|
1671
|
+
}
|
|
1672
|
+
function settle(permit, reason, settlement) {
|
|
1673
|
+
const owner = owners.get(permit);
|
|
1674
|
+
if (!owner || owner.settled || owner.observing || owner.epoch !== epoch)
|
|
1675
|
+
return void 0;
|
|
1676
|
+
if (permit.halfOpen) {
|
|
1677
|
+
if (activeProbe !== permit)
|
|
1678
|
+
return void 0;
|
|
1679
|
+
if (reason === "observation_timeout") {
|
|
1680
|
+
if (settlement) {
|
|
1681
|
+
owner.observing = true;
|
|
1682
|
+
const complete = (result) => {
|
|
1683
|
+
owner.observing = false;
|
|
1684
|
+
settle(permit, result === "transient" ? "settled_transient_exhausted" : result);
|
|
1685
|
+
};
|
|
1686
|
+
void settlement.then(complete, () => complete("other"));
|
|
1687
|
+
}
|
|
1688
|
+
return void 0;
|
|
1689
|
+
}
|
|
1690
|
+
owner.settled = true;
|
|
1691
|
+
activeProbe = void 0;
|
|
1692
|
+
epoch++;
|
|
1693
|
+
if (reason === "settled_transient_exhausted")
|
|
1694
|
+
return openCircuit();
|
|
1695
|
+
failures = [];
|
|
1696
|
+
openedUntil = void 0;
|
|
1697
|
+
return void 0;
|
|
1698
|
+
}
|
|
1699
|
+
owner.settled = true;
|
|
1700
|
+
if (reason !== "settled_transient_exhausted")
|
|
1701
|
+
return void 0;
|
|
1702
|
+
const time = now();
|
|
1703
|
+
failures = failures.filter((failure2) => time - failure2 < WINDOW_MS);
|
|
1704
|
+
failures.push(time);
|
|
1705
|
+
return !activeProbe && failures.length >= FAILURE_THRESHOLD ? openCircuit(time) : void 0;
|
|
1706
|
+
}
|
|
1707
|
+
return Object.freeze({ admit, settle });
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// ../runtime/dist/adapters/auth/better-auth/read-recovery-vetting.js
|
|
1711
|
+
import { getTableColumns as getTableColumns3 } from "drizzle-orm";
|
|
1712
|
+
import { is as isDrizzleType } from "drizzle-orm";
|
|
1713
|
+
import { PgBigInt53, PgBoolean, PgInteger, PgTable, PgText, PgTimestamp, pgTable, timestamp as timestamp2 } from "drizzle-orm/pg-core";
|
|
1714
|
+
var replaySafeColumnPrototypes = /* @__PURE__ */ new Map([
|
|
1715
|
+
[PgText.prototype, "identity"],
|
|
1716
|
+
[PgBoolean.prototype, "identity"],
|
|
1717
|
+
[PgInteger.prototype, "identity"],
|
|
1718
|
+
[PgBigInt53.prototype, "identity"],
|
|
1719
|
+
[PgTimestamp.prototype, "timestamp"]
|
|
1720
|
+
]);
|
|
1721
|
+
var dateGetTime = Date.prototype.getTime;
|
|
1722
|
+
var dateToISOString = Date.prototype.toISOString;
|
|
1723
|
+
var functionToString = Function.prototype.toString;
|
|
1724
|
+
var builtinTimestampEncoder = getTableColumns3(pgTable("runtime_auth_replay_timestamp", { value: timestamp2("value") })).value.mapToDriverValue;
|
|
1725
|
+
var builtinTimestampEncoderSource = Reflect.apply(functionToString, builtinTimestampEncoder, []);
|
|
1726
|
+
var approvedTimestampEncoderSource = `(value) => {
|
|
1727
|
+
if (typeof value === "string")
|
|
1728
|
+
return value;
|
|
1729
|
+
return value.toISOString();
|
|
1730
|
+
}`;
|
|
1731
|
+
function plainRecord(value) {
|
|
1732
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1733
|
+
}
|
|
1734
|
+
function dataRecord(value, allowed) {
|
|
1735
|
+
const record7 = plainRecord(value);
|
|
1736
|
+
if (!record7)
|
|
1737
|
+
return void 0;
|
|
1738
|
+
try {
|
|
1739
|
+
const prototype = Object.getPrototypeOf(record7);
|
|
1740
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
1741
|
+
return void 0;
|
|
1742
|
+
for (const key of Reflect.ownKeys(record7)) {
|
|
1743
|
+
if (typeof key !== "string" || allowed && !allowed.includes(key))
|
|
1744
|
+
return void 0;
|
|
1745
|
+
const descriptor = Object.getOwnPropertyDescriptor(record7, key);
|
|
1746
|
+
if (!descriptor || !("value" in descriptor))
|
|
1747
|
+
return void 0;
|
|
1748
|
+
}
|
|
1749
|
+
return record7;
|
|
1750
|
+
} catch {
|
|
1751
|
+
return void 0;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
function denseDataArray(value, maximumLength) {
|
|
1755
|
+
if (!Array.isArray(value) || value.length > maximumLength)
|
|
1756
|
+
return void 0;
|
|
1757
|
+
try {
|
|
1758
|
+
if (Object.getPrototypeOf(value) !== Array.prototype)
|
|
1759
|
+
return void 0;
|
|
1760
|
+
const keys = Reflect.ownKeys(value);
|
|
1761
|
+
if (keys.length !== value.length + 1 || !keys.includes("length"))
|
|
1762
|
+
return void 0;
|
|
1763
|
+
const entries = [];
|
|
1764
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1765
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
1766
|
+
if (!descriptor || !("value" in descriptor))
|
|
1767
|
+
return void 0;
|
|
1768
|
+
entries.push(descriptor.value);
|
|
1769
|
+
}
|
|
1770
|
+
return entries;
|
|
1771
|
+
} catch {
|
|
1772
|
+
return void 0;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
function pristineDate(value) {
|
|
1776
|
+
if (typeof value !== "object" || value === null)
|
|
1777
|
+
return false;
|
|
1778
|
+
try {
|
|
1779
|
+
const dateMethodsArePristine = Object.getOwnPropertyDescriptor(Date.prototype, "getTime")?.value === dateGetTime && Object.getOwnPropertyDescriptor(Date.prototype, "toISOString")?.value === dateToISOString;
|
|
1780
|
+
return Object.getPrototypeOf(value) === Date.prototype && dateMethodsArePristine && Reflect.ownKeys(value).length === 0 && Number.isFinite(Reflect.apply(dateGetTime, value, []));
|
|
1781
|
+
} catch {
|
|
1782
|
+
return false;
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
function safePrimitive(value) {
|
|
1786
|
+
if (value === null || value === void 0)
|
|
1787
|
+
return true;
|
|
1788
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint")
|
|
1789
|
+
return typeof value !== "number" || Number.isFinite(value);
|
|
1790
|
+
const array = denseDataArray(value, 256);
|
|
1791
|
+
if (array)
|
|
1792
|
+
return array.every((entry) => safePrimitive(entry) && !Array.isArray(entry));
|
|
1793
|
+
return false;
|
|
1794
|
+
}
|
|
1795
|
+
function safeTimestampValue(value) {
|
|
1796
|
+
if (value === null || value === void 0 || typeof value === "string")
|
|
1797
|
+
return true;
|
|
1798
|
+
if (pristineDate(value))
|
|
1799
|
+
return true;
|
|
1800
|
+
const array = denseDataArray(value, 256);
|
|
1801
|
+
return !!array && array.every((entry) => entry === null || typeof entry === "string" || pristineDate(entry));
|
|
1802
|
+
}
|
|
1803
|
+
function hasOwnNoopFlag(value) {
|
|
1804
|
+
if (typeof value !== "function")
|
|
1805
|
+
return false;
|
|
1806
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, "isNoop");
|
|
1807
|
+
return !!descriptor && "value" in descriptor && descriptor.value === true;
|
|
1808
|
+
}
|
|
1809
|
+
function safeBoundValue(field, value, operator, selectedTable) {
|
|
1810
|
+
try {
|
|
1811
|
+
const column = getTableColumns3(selectedTable)[field];
|
|
1812
|
+
if (!column)
|
|
1813
|
+
return false;
|
|
1814
|
+
if (replaySafeColumnPrototypes.get(Object.getPrototypeOf(column)) !== "timestamp")
|
|
1815
|
+
return safePrimitive(value);
|
|
1816
|
+
return (!Array.isArray(value) || operator === "in" || operator === "not_in") && safeTimestampValue(value);
|
|
1817
|
+
} catch {
|
|
1818
|
+
return false;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
function hasSelectedField(field, table, selectedTable) {
|
|
1822
|
+
if (Object.hasOwn(table?.fields ?? {}, field))
|
|
1823
|
+
return true;
|
|
1824
|
+
if (field !== "id" || !selectedTable)
|
|
1825
|
+
return false;
|
|
1826
|
+
try {
|
|
1827
|
+
return Object.hasOwn(getTableColumns3(selectedTable), "id");
|
|
1828
|
+
} catch {
|
|
1829
|
+
return false;
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
function safeWhere(value, table, selectedTable) {
|
|
1833
|
+
if (value === void 0)
|
|
1834
|
+
return true;
|
|
1835
|
+
const entries = denseDataArray(value, 100);
|
|
1836
|
+
if (!entries)
|
|
1837
|
+
return false;
|
|
1838
|
+
const fields = new Set(Object.keys(table?.fields ?? {}));
|
|
1839
|
+
const operators = /* @__PURE__ */ new Set([
|
|
1840
|
+
"eq",
|
|
1841
|
+
"ne",
|
|
1842
|
+
"in",
|
|
1843
|
+
"not_in",
|
|
1844
|
+
"contains",
|
|
1845
|
+
"starts_with",
|
|
1846
|
+
"ends_with",
|
|
1847
|
+
"lt",
|
|
1848
|
+
"lte",
|
|
1849
|
+
"gt",
|
|
1850
|
+
"gte"
|
|
1851
|
+
]);
|
|
1852
|
+
return entries.every((entry) => {
|
|
1853
|
+
const item = dataRecord(entry, ["field", "value", "operator", "connector", "mode"]);
|
|
1854
|
+
if (!item || typeof item.field !== "string" || !fields.has(item.field) && !hasSelectedField(item.field, table, selectedTable))
|
|
1855
|
+
return false;
|
|
1856
|
+
if (item.operator !== void 0 && (typeof item.operator !== "string" || !operators.has(item.operator)))
|
|
1857
|
+
return false;
|
|
1858
|
+
if (item.connector !== void 0 && item.connector !== "AND" && item.connector !== "OR")
|
|
1859
|
+
return false;
|
|
1860
|
+
if (item.mode !== void 0 && item.mode !== "sensitive" && item.mode !== "insensitive")
|
|
1861
|
+
return false;
|
|
1862
|
+
return safeBoundValue(item.field, item.value, item.operator, selectedTable);
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
function safeReadArguments(input, method, model, table, selectedTable) {
|
|
1866
|
+
const allowed = method === "findOne" ? ["model", "where", "join", "select"] : method === "findMany" ? ["model", "where", "join", "select", "limit", "offset", "sortBy"] : ["model", "where"];
|
|
1867
|
+
if (!dataRecord(input, allowed) || !safeWhere(input.where, table, selectedTable))
|
|
1868
|
+
return false;
|
|
1869
|
+
if (input.select !== void 0) {
|
|
1870
|
+
const selectedFields = denseDataArray(input.select, 256);
|
|
1871
|
+
if (!selectedFields || selectedFields.some((field) => typeof field !== "string" || !hasSelectedField(field, table, selectedTable)))
|
|
1872
|
+
return false;
|
|
1873
|
+
}
|
|
1874
|
+
for (const key of ["limit", "offset"]) {
|
|
1875
|
+
const value = input[key];
|
|
1876
|
+
if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0 || value > 1e4))
|
|
1877
|
+
return false;
|
|
1878
|
+
}
|
|
1879
|
+
if (input.sortBy !== void 0) {
|
|
1880
|
+
const sort = dataRecord(input.sortBy, ["field", "direction"]);
|
|
1881
|
+
if (!sort || typeof sort.field !== "string" || !hasSelectedField(sort.field, table, selectedTable) || sort.direction !== "asc" && sort.direction !== "desc")
|
|
1882
|
+
return false;
|
|
1883
|
+
}
|
|
1884
|
+
return input.model === model;
|
|
1885
|
+
}
|
|
1886
|
+
function hasCustomTransform(table) {
|
|
1887
|
+
if (!table?.fields)
|
|
1888
|
+
return true;
|
|
1889
|
+
for (const field of Object.values(table.fields)) {
|
|
1890
|
+
if (field === null || typeof field !== "object")
|
|
1891
|
+
return true;
|
|
1892
|
+
try {
|
|
1893
|
+
const descriptor = Object.getOwnPropertyDescriptor(field, "transform");
|
|
1894
|
+
if (descriptor)
|
|
1895
|
+
return true;
|
|
1896
|
+
const prototype = Object.getPrototypeOf(field);
|
|
1897
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
1898
|
+
return true;
|
|
1899
|
+
} catch {
|
|
1900
|
+
return true;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
return false;
|
|
1904
|
+
}
|
|
1905
|
+
function safeTable(table) {
|
|
1906
|
+
try {
|
|
1907
|
+
if (!isDrizzleType(table, PgTable))
|
|
1908
|
+
return false;
|
|
1909
|
+
const columns = Object.values(getTableColumns3(table));
|
|
1910
|
+
return columns.every((column) => {
|
|
1911
|
+
const prototype = Object.getPrototypeOf(column);
|
|
1912
|
+
const kind = replaySafeColumnPrototypes.get(prototype);
|
|
1913
|
+
const decoder = Object.getOwnPropertyDescriptor(column, "mapFromDriverValue");
|
|
1914
|
+
const encoder = Object.getOwnPropertyDescriptor(column, "mapToDriverValue");
|
|
1915
|
+
if (!kind || !decoder || !("value" in decoder) || !encoder || !("value" in encoder))
|
|
1916
|
+
return false;
|
|
1917
|
+
const decoderFunction = decoder.value;
|
|
1918
|
+
const encoderFunction = encoder.value;
|
|
1919
|
+
const encoderIsSafe = typeof encoderFunction === "function" && (kind === "timestamp" ? builtinTimestampEncoderSource === approvedTimestampEncoderSource && Reflect.apply(functionToString, encoderFunction, []) === approvedTimestampEncoderSource : hasOwnNoopFlag(encoderFunction));
|
|
1920
|
+
return typeof decoderFunction === "function" && hasOwnNoopFlag(decoderFunction) && encoderIsSafe;
|
|
1921
|
+
});
|
|
1922
|
+
} catch {
|
|
1923
|
+
return false;
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
function standardSessionUserJoin(input, schema, tables) {
|
|
1927
|
+
const join = dataRecord(input.join, ["user"]);
|
|
1928
|
+
if (!join || Object.keys(join).length !== 1 || join.user !== true)
|
|
1929
|
+
return false;
|
|
1930
|
+
const session = tables.session;
|
|
1931
|
+
const reference = plainRecord(plainRecord(session?.fields?.userId)?.references);
|
|
1932
|
+
const user = tables.user;
|
|
1933
|
+
try {
|
|
1934
|
+
const sessionColumns = getTableColumns3(schema.session);
|
|
1935
|
+
const userColumns = getTableColumns3(schema.user);
|
|
1936
|
+
return reference?.model === "user" && reference.field === "id" && user?.modelName === "user" && !!sessionColumns.userId && !!userColumns.id;
|
|
1937
|
+
} catch {
|
|
1938
|
+
return false;
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
function noRequestedJoin(value) {
|
|
1942
|
+
return value === void 0 || !!dataRecord(value, []);
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// ../runtime/dist/adapters/auth/better-auth/read-recovery.js
|
|
1946
|
+
var models = /* @__PURE__ */ new Set(["user", "session", "account", "verification", "rateLimit"]);
|
|
1947
|
+
var builderChains = /* @__PURE__ */ new Set(["from", "where", "limit", "offset", "orderBy"]);
|
|
1948
|
+
var SDK_AUTH_READ_FAILURE = Object.freeze({
|
|
1949
|
+
name: "RuntimeDatabaseReadFailure",
|
|
1950
|
+
message: "The selected authentication database read failed."
|
|
1951
|
+
});
|
|
1952
|
+
function safeAuthDiagnostic(reason, retryAfterSeconds, dataImpact = "unknown") {
|
|
1953
|
+
const retryable = reason === "settled_transient_exhausted" && retryAfterSeconds === void 0 && dataImpact === "none";
|
|
1954
|
+
const guidance2 = retryAfterSeconds !== void 0 ? {
|
|
1955
|
+
retryPrecondition: `Wait at least ${retryAfterSeconds} seconds for the selected authentication database recovery circuit, then make a new eligible read.`,
|
|
1956
|
+
nextAction: "Wait for the stated recovery interval, then make a new session or identity read. Do not repeat signup, sign-in, or another mutation blindly."
|
|
1957
|
+
} : reason === "settled_transient_exhausted" ? {
|
|
1958
|
+
retryPrecondition: "Retry only the failed non-effectful session or identity read after the selected database is ready; do not repeat credential mutations or the whole request.",
|
|
1959
|
+
nextAction: "Verify any earlier credential-operation effects, then retry only the session or identity read after database readiness is restored."
|
|
1960
|
+
} : reason === "observation_timeout" ? {
|
|
1961
|
+
retryPrecondition: "Do not retry while the original database query remains unsettled; its connection and result are still owned by this Runtime generation.",
|
|
1962
|
+
nextAction: "Wait for the in-flight database read to settle before making another request; do not start an overlapping retry."
|
|
1963
|
+
} : reason === "budget_exhausted" ? {
|
|
1964
|
+
retryPrecondition: "This logical read's captured time budget has expired; start a new eligible read only after prior database work settles.",
|
|
1965
|
+
nextAction: "Allow in-flight database work to settle, then begin a fresh read if it is still needed; do not extend this expired operation."
|
|
1966
|
+
} : reason === "owner_closing" ? {
|
|
1967
|
+
retryPrecondition: "Retry only after a replacement Runtime generation is ready and its database admission is open.",
|
|
1968
|
+
nextAction: "Wait for the Runtime generation to finish draining and for its replacement to become ready; do not retry against the closing database owner."
|
|
1969
|
+
} : reason === "unreplayed_connection_failure" ? {
|
|
1970
|
+
retryPrecondition: "Do not repeat this authentication operation; wait for the selected database connection to recover and verify any effects before making a new request.",
|
|
1971
|
+
nextAction: "Wait for selected database readiness, inspect any earlier account, session, hook, or provider effects, and start a new request only when it is safe to do so."
|
|
1972
|
+
} : reason === "probe_in_progress" ? {
|
|
1973
|
+
retryPrecondition: "Wait for the already-running recovery probe to settle before starting another eligible read.",
|
|
1974
|
+
nextAction: "Wait for the in-flight database recovery probe to settle, then make a new session or identity read if needed."
|
|
1975
|
+
} : {
|
|
1976
|
+
retryPrecondition: "Wait for the selected authentication database recovery interval, then issue a new eligible read.",
|
|
1977
|
+
nextAction: "Wait for the stated recovery interval, then make a new session or identity read; verify credential-operation effects before repeating mutations."
|
|
1978
|
+
};
|
|
1979
|
+
const error = new RuntimeDiagnosticError({
|
|
1980
|
+
code: "RUNTIME_AUTH_DATABASE_UNAVAILABLE",
|
|
1981
|
+
stage: "request",
|
|
1982
|
+
capability: "auth",
|
|
1983
|
+
servingStarted: "unchanged",
|
|
1984
|
+
dataImpact,
|
|
1985
|
+
retryable,
|
|
1986
|
+
...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {},
|
|
1987
|
+
...guidance2
|
|
1988
|
+
});
|
|
1989
|
+
Reflect.deleteProperty(error, "stack");
|
|
1990
|
+
return error;
|
|
1991
|
+
}
|
|
1992
|
+
function rateLimitDiagnostic(retryAfterSeconds, dataImpact) {
|
|
1993
|
+
const retryPrecondition = retryAfterSeconds === void 0 ? "Wait for the selected rate-limit database to recover before a new request; never bypass the configured limit." : `Wait at least ${retryAfterSeconds} seconds for the selected rate-limit database recovery circuit before making a new request.`;
|
|
1994
|
+
const error = new RuntimeDiagnosticError({
|
|
1995
|
+
code: "RUNTIME_AUTH_RATE_LIMIT_STORAGE_UNAVAILABLE",
|
|
1996
|
+
stage: "request",
|
|
1997
|
+
capability: "auth",
|
|
1998
|
+
servingStarted: "unchanged",
|
|
1999
|
+
dataImpact,
|
|
2000
|
+
retryable: false,
|
|
2001
|
+
...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {},
|
|
2002
|
+
retryPrecondition,
|
|
2003
|
+
nextAction: "Wait for the selected database-backed rate limiter to recover, then make a new request. Runtime will not disable the limit or switch to memory."
|
|
2004
|
+
});
|
|
2005
|
+
Reflect.deleteProperty(error, "stack");
|
|
2006
|
+
return error;
|
|
2007
|
+
}
|
|
2008
|
+
function selectedAuthQueryFailure(model) {
|
|
2009
|
+
const error = new RuntimeDiagnosticError({
|
|
2010
|
+
code: model === "rateLimit" ? "RUNTIME_AUTH_RATE_LIMIT_STORAGE_UNAVAILABLE" : "RUNTIME_AUTH_DATABASE_QUERY_FAILED",
|
|
2011
|
+
stage: "request",
|
|
2012
|
+
capability: "database",
|
|
2013
|
+
servingStarted: "unchanged",
|
|
2014
|
+
dataImpact: "unknown",
|
|
2015
|
+
retryable: false,
|
|
2016
|
+
retryPrecondition: model === "rateLimit" ? "Correct the selected rate-limit database schema, privileges, or trusted binding before another request; do not bypass the configured limit." : "Correct the selected authentication database schema, privileges, or trusted binding, then deliberately verify the session again; do not repeat a credential mutation blindly.",
|
|
2017
|
+
nextAction: model === "rateLimit" ? "Have the Runtime configuration owner verify the selected rate-limit table and permissions, apply the supported correction, and retry only after confirming any earlier effects. Runtime will not disable the limit or switch to memory." : "Have the Runtime configuration owner verify the selected auth database schema and permissions, apply the supported correction, and start a new deliberate session check after confirming any earlier effects."
|
|
2018
|
+
});
|
|
2019
|
+
Reflect.deleteProperty(error, "stack");
|
|
2020
|
+
return error;
|
|
2021
|
+
}
|
|
2022
|
+
function widenHandlerFailure(error) {
|
|
2023
|
+
const diagnostic = runtimeDiagnostic(error);
|
|
2024
|
+
if (!diagnostic)
|
|
2025
|
+
return error;
|
|
2026
|
+
const effectNote = " Earlier account, session, rate-limit, hook, or provider effects may exist; verify them before starting a new request.";
|
|
2027
|
+
const widened = new RuntimeDiagnosticError({
|
|
2028
|
+
...diagnostic,
|
|
2029
|
+
dataImpact: "unknown",
|
|
2030
|
+
retryable: false,
|
|
2031
|
+
retryPrecondition: `${diagnostic.retryPrecondition}${effectNote}`,
|
|
2032
|
+
nextAction: `${diagnostic.nextAction}${effectNote}`
|
|
2033
|
+
});
|
|
2034
|
+
Reflect.deleteProperty(widened, "stack");
|
|
2035
|
+
return widened;
|
|
2036
|
+
}
|
|
2037
|
+
function createAuthDatabaseReadRecovery(input) {
|
|
2038
|
+
const { borrowed, schema } = input;
|
|
2039
|
+
const runRead = borrowed[runtimeVettedAuthRead];
|
|
2040
|
+
const withReadScope = borrowed[runtimeVettedAuthReadScope];
|
|
2041
|
+
const executionScope = borrowed[runtimeDatabaseExecutionScope];
|
|
2042
|
+
const ownerAvailable = !!runRead && !!withReadScope && !!executionScope;
|
|
2043
|
+
const circuit = createAuthReadCircuit(input.now);
|
|
2044
|
+
const explicitDeadlines = new AsyncLocalStorage2();
|
|
2045
|
+
const operations = new AsyncLocalStorage2();
|
|
2046
|
+
const readContexts = new AsyncLocalStorage2();
|
|
2047
|
+
function withReadDeadline(deadlineAt, operation) {
|
|
2048
|
+
const scoped = () => explicitDeadlines.run(deadlineAt, operation);
|
|
2049
|
+
return executionScope ? executionScope(() => {
|
|
2050
|
+
}, scoped) : scoped();
|
|
2051
|
+
}
|
|
2052
|
+
async function withOperation(kind, operation) {
|
|
2053
|
+
const state = { kind };
|
|
2054
|
+
return operations.run(state, async () => {
|
|
2055
|
+
try {
|
|
2056
|
+
const result = await operation();
|
|
2057
|
+
if (state.terminal)
|
|
2058
|
+
throw state.terminal;
|
|
2059
|
+
return result;
|
|
2060
|
+
} catch (error) {
|
|
2061
|
+
if (state.terminal)
|
|
2062
|
+
throw state.terminal;
|
|
2063
|
+
throw error;
|
|
2064
|
+
}
|
|
2065
|
+
}).catch((error) => {
|
|
2066
|
+
if (kind !== "handler" || state.terminal !== error || !(error instanceof Error))
|
|
2067
|
+
throw error;
|
|
2068
|
+
throw widenHandlerFailure(error);
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
function admitCircuit() {
|
|
2072
|
+
const admission = circuit.admit();
|
|
2073
|
+
if (!admission.allowed)
|
|
2074
|
+
return {
|
|
2075
|
+
denied: {
|
|
2076
|
+
reason: admission.probeInProgress ? "probe_in_progress" : "circuit_open",
|
|
2077
|
+
...admission.retryAfterSeconds !== void 0 ? { retryAfterSeconds: admission.retryAfterSeconds } : {}
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
return {
|
|
2081
|
+
read: {
|
|
2082
|
+
admission,
|
|
2083
|
+
ownerReads: /* @__PURE__ */ new Set(),
|
|
2084
|
+
failureReasons: [],
|
|
2085
|
+
pendingSettlements: /* @__PURE__ */ new Set(),
|
|
2086
|
+
settlementOutcomes: []
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
function settleCircuitRead(state) {
|
|
2091
|
+
if (!state.completionRequested)
|
|
2092
|
+
return void 0;
|
|
2093
|
+
if (state.settled)
|
|
2094
|
+
return state.retryAfterSeconds;
|
|
2095
|
+
if (state.ownerReads.size || state.pendingSettlements.size) {
|
|
2096
|
+
if (!state.settlementScheduled) {
|
|
2097
|
+
state.settlementScheduled = true;
|
|
2098
|
+
const ownerReads = [...state.ownerReads];
|
|
2099
|
+
const settlements = [...state.pendingSettlements];
|
|
2100
|
+
void Promise.all([Promise.allSettled(ownerReads), Promise.allSettled(settlements)]).then(([, settlementResults]) => {
|
|
2101
|
+
for (const [index, promise] of settlements.entries()) {
|
|
2102
|
+
state.pendingSettlements.delete(promise);
|
|
2103
|
+
const result = settlementResults[index];
|
|
2104
|
+
state.settlementOutcomes.push(result?.status === "fulfilled" && (result.value === "success" || result.value === "transient" || result.value === "other") ? result.value : "other");
|
|
2105
|
+
}
|
|
2106
|
+
state.settlementScheduled = false;
|
|
2107
|
+
settleCircuitRead(state);
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
return void 0;
|
|
2111
|
+
}
|
|
2112
|
+
state.settled = true;
|
|
2113
|
+
const firstFailure = state.failureReasons[0];
|
|
2114
|
+
const halfOpenTimedOut = state.admission.halfOpen && firstFailure === "observation_timeout";
|
|
2115
|
+
const anyTransientOutcome = state.failureReasons.includes("settled_transient_exhausted") || state.settlementOutcomes.includes("transient");
|
|
2116
|
+
const reason = firstFailure === "settled_transient_exhausted" || halfOpenTimedOut && anyTransientOutcome ? "settled_transient_exhausted" : firstFailure ? "other" : "success";
|
|
2117
|
+
state.retryAfterSeconds = circuit.settle(state.admission, reason);
|
|
2118
|
+
return state.retryAfterSeconds;
|
|
2119
|
+
}
|
|
2120
|
+
function settleFailedCircuitRead(operation, model, state) {
|
|
2121
|
+
state.completionRequested = true;
|
|
2122
|
+
const retryAfterSeconds = settleCircuitRead(state);
|
|
2123
|
+
if (retryAfterSeconds === void 0 || state.failureReasons[0] !== "settled_transient_exhausted")
|
|
2124
|
+
return;
|
|
2125
|
+
operation.terminal = model === "rateLimit" ? rateLimitDiagnostic(retryAfterSeconds, "unknown") : safeAuthDiagnostic("circuit_open", retryAfterSeconds, "unknown");
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
2128
|
+
function recordTerminal(state, reason, settlement) {
|
|
2129
|
+
if (!state)
|
|
2130
|
+
return;
|
|
2131
|
+
state.failureReasons.push(reason);
|
|
2132
|
+
if (settlement)
|
|
2133
|
+
state.pendingSettlements.add(settlement);
|
|
2134
|
+
}
|
|
2135
|
+
function latchTerminal(operation, terminal) {
|
|
2136
|
+
if (!operation)
|
|
2137
|
+
return terminal;
|
|
2138
|
+
if (!operation.terminal)
|
|
2139
|
+
operation.terminal = terminal;
|
|
2140
|
+
return SDK_AUTH_READ_FAILURE;
|
|
2141
|
+
}
|
|
2142
|
+
function sanitizedTerminal(error, model, circuitRead) {
|
|
2143
|
+
const operation = operations.getStore();
|
|
2144
|
+
const record7 = runtimeDatabaseFailureRecord(error);
|
|
2145
|
+
if (record7) {
|
|
2146
|
+
recordTerminal(circuitRead, record7.reason, record7.settlement);
|
|
2147
|
+
const rateLimit = model === "rateLimit";
|
|
2148
|
+
const diagnostic = safeAuthDiagnostic(record7.reason, void 0, "unknown");
|
|
2149
|
+
const safe2 = rateLimit ? rateLimitDiagnostic(void 0, "unknown") : diagnostic;
|
|
2150
|
+
return latchTerminal(operation, safe2);
|
|
2151
|
+
}
|
|
2152
|
+
const login = error && typeof error === "object" ? ownedPostgresLoginDiagnostic(error) : void 0;
|
|
2153
|
+
if (login) {
|
|
2154
|
+
recordTerminal(circuitRead, "other");
|
|
2155
|
+
const safe2 = new RuntimeDiagnosticError(login);
|
|
2156
|
+
Reflect.deleteProperty(safe2, "stack");
|
|
2157
|
+
return latchTerminal(operation, safe2);
|
|
2158
|
+
}
|
|
2159
|
+
if (error && typeof error === "object" && ownedPostgresQueryFailure(error)) {
|
|
2160
|
+
recordTerminal(circuitRead, "other");
|
|
2161
|
+
const safe2 = safeAuthDiagnostic("unreplayed_connection_failure", void 0, "unknown");
|
|
2162
|
+
return latchTerminal(operation, safe2);
|
|
2163
|
+
}
|
|
2164
|
+
if (operation?.kind === "oauth-read" && model !== "rateLimit" && ownedPostgresQuerySqlStateInCause(error) === "55P03") {
|
|
2165
|
+
recordTerminal(circuitRead, "other");
|
|
2166
|
+
return latchTerminal(operation, safeAuthDiagnostic("budget_exhausted"));
|
|
2167
|
+
}
|
|
2168
|
+
if (error && typeof error === "object" && ownedPostgresQueryRejection(error)) {
|
|
2169
|
+
recordTerminal(circuitRead, "other");
|
|
2170
|
+
const safe2 = selectedAuthQueryFailure(model);
|
|
2171
|
+
return latchTerminal(operation, safe2);
|
|
2172
|
+
}
|
|
2173
|
+
const existing = runtimeDiagnostic(error);
|
|
2174
|
+
if (existing && error instanceof Error) {
|
|
2175
|
+
recordTerminal(circuitRead, "other");
|
|
2176
|
+
const safe2 = new RuntimeDiagnosticError(existing);
|
|
2177
|
+
Reflect.deleteProperty(safe2, "stack");
|
|
2178
|
+
return latchTerminal(operation, safe2);
|
|
2179
|
+
}
|
|
2180
|
+
const safe = new Error("The selected authentication database read failed.");
|
|
2181
|
+
Reflect.deleteProperty(safe, "stack");
|
|
2182
|
+
recordTerminal(circuitRead, "other");
|
|
2183
|
+
return latchTerminal(operation, safe);
|
|
2184
|
+
}
|
|
2185
|
+
function executeOnce(target, receiver, args) {
|
|
2186
|
+
const execute = Reflect.get(target, "execute", receiver);
|
|
2187
|
+
if (typeof execute !== "function")
|
|
2188
|
+
return Promise.reject(new Error("Selected auth read is unavailable."));
|
|
2189
|
+
try {
|
|
2190
|
+
return Promise.resolve(Reflect.apply(execute, receiver, args));
|
|
2191
|
+
} catch (error) {
|
|
2192
|
+
return Promise.reject(error);
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
function wrapBuilder(builder, relation2) {
|
|
2196
|
+
return new Proxy(builder, {
|
|
2197
|
+
get(target, key, receiver) {
|
|
2198
|
+
const member = Reflect.get(target, key, receiver);
|
|
2199
|
+
if (key === "execute" && typeof member === "function")
|
|
2200
|
+
return (...args) => {
|
|
2201
|
+
const context = readContexts.getStore();
|
|
2202
|
+
const model = context?.observedTables.get(relation2);
|
|
2203
|
+
if (!context || !model)
|
|
2204
|
+
return Reflect.apply(member, target, args);
|
|
2205
|
+
if (!context.safe || !context.replayModels.has(model)) {
|
|
2206
|
+
return executeOnce(target, receiver, args).catch((error) => {
|
|
2207
|
+
if (!(error && typeof error === "object" && ownedPostgresQueryRejection(error)) && !(error && typeof error === "object" && ownedPostgresLoginDiagnostic(error)))
|
|
2208
|
+
throw error;
|
|
2209
|
+
throw sanitizedTerminal(error, model, context.circuitRead);
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
const run = async () => {
|
|
2213
|
+
const query = () => executeOnce(target, receiver, args);
|
|
2214
|
+
return runRead(context.method, query, {
|
|
2215
|
+
retryDelayMs: 25,
|
|
2216
|
+
retryAttemptTimeoutMs: 4e3,
|
|
2217
|
+
deadlineAt: explicitDeadlines.getStore()
|
|
2218
|
+
});
|
|
2219
|
+
};
|
|
2220
|
+
const attempt = Promise.resolve(run()).catch((error) => {
|
|
2221
|
+
throw sanitizedTerminal(error, model ?? "user", context.circuitRead);
|
|
2222
|
+
});
|
|
2223
|
+
const ownerReads = context.circuitRead?.ownerReads;
|
|
2224
|
+
ownerReads?.add(attempt);
|
|
2225
|
+
if (ownerReads)
|
|
2226
|
+
void attempt.then(() => ownerReads.delete(attempt), () => ownerReads.delete(attempt));
|
|
2227
|
+
return attempt;
|
|
2228
|
+
};
|
|
2229
|
+
if (key === "then")
|
|
2230
|
+
return (fulfilled, rejected) => Promise.resolve(Reflect.get(receiver, "execute", receiver)()).then(fulfilled, rejected);
|
|
2231
|
+
if (key === "catch")
|
|
2232
|
+
return (rejected) => Promise.resolve(Reflect.get(receiver, "then", receiver)(void 0, rejected));
|
|
2233
|
+
if (key === "finally")
|
|
2234
|
+
return (callback) => Promise.resolve(Reflect.get(receiver, "execute", receiver)()).finally(callback);
|
|
2235
|
+
if (typeof member !== "function")
|
|
2236
|
+
return member;
|
|
2237
|
+
if (!builderChains.has(key))
|
|
2238
|
+
return (...args) => Reflect.apply(member, target, args);
|
|
2239
|
+
return (...args) => {
|
|
2240
|
+
const result = Reflect.apply(member, target, args);
|
|
2241
|
+
const nextRelation = key === "from" ? args[0] : relation2;
|
|
2242
|
+
return result && typeof result === "object" ? wrapBuilder(result, nextRelation) : result;
|
|
2243
|
+
};
|
|
2244
|
+
}
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
const drizzle = ownerAvailable ? new Proxy(borrowed.drizzle, {
|
|
2248
|
+
get(target, key, receiver) {
|
|
2249
|
+
const member = Reflect.get(target, key, receiver);
|
|
2250
|
+
if (key !== "select" || typeof member !== "function")
|
|
2251
|
+
return member;
|
|
2252
|
+
return (...args) => {
|
|
2253
|
+
const context = readContexts.getStore();
|
|
2254
|
+
if (!ownerAvailable || !context)
|
|
2255
|
+
return Reflect.apply(member, target, args);
|
|
2256
|
+
const result = Reflect.apply(member, target, args);
|
|
2257
|
+
return result && typeof result === "object" ? wrapBuilder(result) : result;
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
}) : borrowed.drizzle;
|
|
2261
|
+
function selectedRead(inputValue, method, options, tables) {
|
|
2262
|
+
const inputRecord = dataRecord(inputValue);
|
|
2263
|
+
const model = inputRecord?.model;
|
|
2264
|
+
const validModel = typeof model === "string" && models.has(model);
|
|
2265
|
+
const selectedModel = validModel ? model : void 0;
|
|
2266
|
+
const table = selectedModel ? schema[selectedModel] : void 0;
|
|
2267
|
+
const modelTable = tables[selectedModel ?? ""];
|
|
2268
|
+
const effectiveOptions = plainRecord(options);
|
|
2269
|
+
const experimentalValue = effectiveOptions?.experimental;
|
|
2270
|
+
const experimental = experimentalValue === void 0 ? void 0 : dataRecord(experimentalValue, ["joins"]);
|
|
2271
|
+
const joins = experimental?.joins;
|
|
2272
|
+
const joinsDisabled = effectiveOptions !== void 0 && (experimentalValue === void 0 || !!experimental && (joins === void 0 || joins === false));
|
|
2273
|
+
const plugins = Array.isArray(effectiveOptions?.plugins) ? effectiveOptions.plugins : [];
|
|
2274
|
+
const advanced = effectiveOptions?.advanced === void 0 ? {} : dataRecord(effectiveOptions.advanced);
|
|
2275
|
+
const databaseOptions = advanced?.database === void 0 ? {} : dataRecord(advanced.database);
|
|
2276
|
+
const configuredFindManyLimit = databaseOptions?.defaultFindManyLimit;
|
|
2277
|
+
const defaultFindManyLimit = configuredFindManyLimit === void 0 ? 100 : configuredFindManyLimit;
|
|
2278
|
+
const defaultFindManyLimitIsValid = advanced !== void 0 && databaseOptions !== void 0 && Number.isSafeInteger(defaultFindManyLimit) && typeof defaultFindManyLimit === "number" && defaultFindManyLimit >= 0;
|
|
2279
|
+
const findManyLimit = inputRecord?.limit ?? defaultFindManyLimit;
|
|
2280
|
+
const boundedSessionFindMany = method !== "findMany" || defaultFindManyLimitIsValid && Number.isSafeInteger(findManyLimit) && typeof findManyLimit === "number" && findManyLimit >= 0 && findManyLimit <= 100;
|
|
2281
|
+
const pluginOverrides = (modelName) => plugins.some((plugin) => {
|
|
2282
|
+
const pluginSchema = plainRecord(plainRecord(plugin)?.schema);
|
|
2283
|
+
return !!modelName && !!pluginSchema && Object.hasOwn(pluginSchema, modelName);
|
|
2284
|
+
});
|
|
2285
|
+
const noTransforms = !hasCustomTransform(modelTable) && !pluginOverrides(selectedModel);
|
|
2286
|
+
const modelIdentity = !!selectedModel && modelTable?.modelName === selectedModel && safeTable(table);
|
|
2287
|
+
const specialJoin = selectedModel === "session" && (method === "findOne" || method === "findMany") && boundedSessionFindMany && standardSessionUserJoin(inputRecord ?? {}, schema, tables) && safeTable(schema.user) && tables.user?.modelName === "user" && !hasCustomTransform(tables.user) && !pluginOverrides("user");
|
|
2288
|
+
const noJoin = noRequestedJoin(inputRecord?.join);
|
|
2289
|
+
const safe = !!inputRecord && validModel && boundedSessionFindMany && safeReadArguments(inputRecord, method, selectedModel, modelTable, table) && modelIdentity && joinsDisabled && noTransforms && (noJoin || specialJoin);
|
|
2290
|
+
const replayModels = /* @__PURE__ */ new Set();
|
|
2291
|
+
const observedTables = /* @__PURE__ */ new Map();
|
|
2292
|
+
const aliases = selectedModel || typeof model !== "string" ? [] : [...models].filter((key) => tables[key]?.modelName === model);
|
|
2293
|
+
const observedModel = selectedModel ?? (aliases.length === 1 ? aliases[0] : void 0);
|
|
2294
|
+
if (observedModel) {
|
|
2295
|
+
const alias = tables[observedModel]?.modelName;
|
|
2296
|
+
const relation2 = schema[typeof alias === "string" ? alias : observedModel];
|
|
2297
|
+
if (relation2 && typeof relation2 === "object")
|
|
2298
|
+
observedTables.set(relation2, observedModel);
|
|
2299
|
+
}
|
|
2300
|
+
if (standardSessionUserJoin(inputRecord ?? {}, schema, tables) && schema.user && !observedTables.has(schema.user)) {
|
|
2301
|
+
observedTables.set(schema.user, "user");
|
|
2302
|
+
}
|
|
2303
|
+
if (safe && selectedModel) {
|
|
2304
|
+
replayModels.add(selectedModel);
|
|
2305
|
+
if (specialJoin)
|
|
2306
|
+
replayModels.add("user");
|
|
2307
|
+
}
|
|
2308
|
+
return { method, replayModels, observedTables, safe };
|
|
2309
|
+
}
|
|
2310
|
+
function decorateFactory(factory) {
|
|
2311
|
+
if (!ownerAvailable)
|
|
2312
|
+
return factory;
|
|
2313
|
+
return (factoryOptions) => {
|
|
2314
|
+
const adapter = factory(factoryOptions);
|
|
2315
|
+
const tables = input.getAuthTables(factoryOptions);
|
|
2316
|
+
return new Proxy(adapter, {
|
|
2317
|
+
get(target, key, receiver) {
|
|
2318
|
+
const method = Reflect.get(target, key, receiver);
|
|
2319
|
+
if (key !== "findOne" && key !== "findMany" && key !== "count" || typeof method !== "function")
|
|
2320
|
+
return method;
|
|
2321
|
+
return (...args) => {
|
|
2322
|
+
const context = selectedRead(args[0], key, factoryOptions, tables);
|
|
2323
|
+
if (!context.safe || !runRead || !withReadScope || !executionScope) {
|
|
2324
|
+
const invoke = () => executionScope ? executionScope(() => {
|
|
2325
|
+
}, () => readContexts.run(context, () => Reflect.apply(method, target, args))) : readContexts.run(context, () => Reflect.apply(method, target, args));
|
|
2326
|
+
const current2 = operations.getStore();
|
|
2327
|
+
return current2 ? invoke() : withOperation("read", invoke);
|
|
2328
|
+
}
|
|
2329
|
+
const runSelected = async (operation) => {
|
|
2330
|
+
const inputRecord = dataRecord(args[0]);
|
|
2331
|
+
const selectedModel = inputRecord?.model;
|
|
2332
|
+
const circuitModel = typeof selectedModel === "string" && models.has(selectedModel) ? selectedModel : "user";
|
|
2333
|
+
const admitted = admitCircuit();
|
|
2334
|
+
if ("denied" in admitted) {
|
|
2335
|
+
const impact = "unknown";
|
|
2336
|
+
const denied = selectedModel === "rateLimit" ? rateLimitDiagnostic(admitted.denied.retryAfterSeconds, impact) : safeAuthDiagnostic(admitted.denied.reason, admitted.denied.retryAfterSeconds, impact);
|
|
2337
|
+
if (!operation.terminal)
|
|
2338
|
+
operation.terminal = denied;
|
|
2339
|
+
throw denied;
|
|
2340
|
+
}
|
|
2341
|
+
const readContext = { ...context, circuitRead: admitted.read };
|
|
2342
|
+
const execute2 = () => readContexts.run(readContext, () => Reflect.apply(method, target, args));
|
|
2343
|
+
try {
|
|
2344
|
+
const result = await withReadScope({ deadlineAt: explicitDeadlines.getStore() }, execute2);
|
|
2345
|
+
if (admitted.read.failureReasons.length)
|
|
2346
|
+
settleFailedCircuitRead(operation, circuitModel, admitted.read);
|
|
2347
|
+
else {
|
|
2348
|
+
admitted.read.completionRequested = true;
|
|
2349
|
+
settleCircuitRead(admitted.read);
|
|
2350
|
+
}
|
|
2351
|
+
return result;
|
|
2352
|
+
} catch (error) {
|
|
2353
|
+
if (!admitted.read.failureReasons.length)
|
|
2354
|
+
recordTerminal(admitted.read, "other");
|
|
2355
|
+
settleFailedCircuitRead(operation, circuitModel, admitted.read);
|
|
2356
|
+
throw error;
|
|
2357
|
+
}
|
|
2358
|
+
};
|
|
2359
|
+
const current = operations.getStore();
|
|
2360
|
+
const execute = (operation) => executionScope(() => {
|
|
2361
|
+
}, () => runSelected(operation));
|
|
2362
|
+
return current ? execute(current) : withOperation("read", () => execute(operations.getStore()));
|
|
2363
|
+
};
|
|
2364
|
+
}
|
|
2365
|
+
});
|
|
2366
|
+
};
|
|
2367
|
+
}
|
|
2368
|
+
return Object.freeze({
|
|
2369
|
+
drizzle,
|
|
2370
|
+
decorateFactory,
|
|
2371
|
+
withOperation,
|
|
2372
|
+
withReadDeadline,
|
|
2373
|
+
circuit
|
|
2374
|
+
});
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth-session.js
|
|
2378
|
+
var configurationSqlStates = /* @__PURE__ */ new Set(["42501", "42P01", "42703", "3F000"]);
|
|
2379
|
+
function isConfigurationFailure(error) {
|
|
2380
|
+
for (let depth = 0; error && typeof error === "object" && depth < 5; depth++) {
|
|
2381
|
+
const { code, errno, cause } = error;
|
|
2382
|
+
if (configurationSqlStates.has(code ?? "") || configurationSqlStates.has(errno ?? ""))
|
|
2383
|
+
return true;
|
|
2384
|
+
error = cause;
|
|
2385
|
+
}
|
|
2386
|
+
return false;
|
|
2387
|
+
}
|
|
2388
|
+
function createOAuthSessionObserver() {
|
|
2389
|
+
const lookups = new AsyncLocalStorage3();
|
|
2390
|
+
const observesLookup = ({ path }) => path === "/get-session" && lookups.getStore() !== void 0;
|
|
2391
|
+
return {
|
|
2392
|
+
plugin({ APIError, createAuthMiddleware }) {
|
|
2393
|
+
async function preserveStoreFailure(operation) {
|
|
2394
|
+
try {
|
|
2395
|
+
return await operation();
|
|
2396
|
+
} catch (error) {
|
|
2397
|
+
if (!isConfigurationFailure(error))
|
|
2398
|
+
throw error;
|
|
2399
|
+
const diagnosis = selectedAuthQueryFailure("session");
|
|
2400
|
+
const failure2 = new APIError("INTERNAL_SERVER_ERROR", {
|
|
2401
|
+
code: diagnosis.diagnostic.code,
|
|
2402
|
+
message: "Authentication storage configuration needs correction."
|
|
2403
|
+
});
|
|
2404
|
+
Object.defineProperty(failure2, "cause", { value: diagnosis });
|
|
2405
|
+
throw failure2;
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
return {
|
|
2409
|
+
id: "gencow-oauth-session-observer",
|
|
2410
|
+
hooks: {
|
|
2411
|
+
before: [
|
|
2412
|
+
{
|
|
2413
|
+
matcher: (context) => observesLookup(context) && Boolean(context.context.secondaryStorage),
|
|
2414
|
+
handler: createAuthMiddleware(async ({ context }) => {
|
|
2415
|
+
const adapter = context.internalAdapter;
|
|
2416
|
+
const internalAdapter = {
|
|
2417
|
+
...adapter,
|
|
2418
|
+
findSession: (token) => preserveStoreFailure(() => adapter.findSession(token)),
|
|
2419
|
+
deleteSession: (token) => preserveStoreFailure(() => adapter.deleteSession(token))
|
|
2420
|
+
};
|
|
2421
|
+
return { context: { context: { internalAdapter } } };
|
|
2422
|
+
})
|
|
2423
|
+
}
|
|
2424
|
+
],
|
|
2425
|
+
after: [
|
|
2426
|
+
{
|
|
2427
|
+
matcher: observesLookup,
|
|
2428
|
+
handler: createAuthMiddleware(async ({ context }) => {
|
|
2429
|
+
const observation = lookups.getStore();
|
|
2430
|
+
if (observation)
|
|
2431
|
+
observation.session = context.session?.session;
|
|
2432
|
+
})
|
|
2433
|
+
}
|
|
2434
|
+
]
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
},
|
|
2438
|
+
async read(api, requestHeaders, credential) {
|
|
2439
|
+
const transport = credential.transport ?? "cookie";
|
|
2440
|
+
const headers = new Headers(requestHeaders);
|
|
2441
|
+
headers.delete("authorization");
|
|
2442
|
+
headers.delete("cookie");
|
|
2443
|
+
if (transport === "cookie")
|
|
2444
|
+
headers.set("cookie", sessionTokenToCookieHeader(credential.value));
|
|
2445
|
+
else
|
|
2446
|
+
headers.set("authorization", `Bearer ${credential.value}`);
|
|
2447
|
+
const observation = {};
|
|
2448
|
+
return lookups.run(observation, async () => {
|
|
2449
|
+
const result = await api.getSession({
|
|
2450
|
+
headers,
|
|
2451
|
+
query: { disableCookieCache: true, disableRefresh: true }
|
|
2452
|
+
});
|
|
2453
|
+
const session = observation.session;
|
|
2454
|
+
const user = result?.user;
|
|
2455
|
+
return session?.token && user?.id === session.userId ? { user, session } : null;
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
|
|
2461
|
+
// ../runtime/dist/adapters/auth/better-auth/oauth-compatibility.js
|
|
2462
|
+
async function handleCompatibleOAuthRequest(request, handler, logger) {
|
|
2463
|
+
const url = new URL(request.url);
|
|
2464
|
+
const legacyStart = request.method === "POST" && url.pathname === "/api/auth/sign-in/oauth2";
|
|
2465
|
+
const callbackPath = url.pathname.replace(/^\/api\/auth\/oauth2\/callback\/([^/]+)$/u, "/api/auth/callback/$1");
|
|
2466
|
+
if (!legacyStart && callbackPath === url.pathname)
|
|
2467
|
+
return handler(request);
|
|
2468
|
+
let translated;
|
|
2469
|
+
if (legacyStart) {
|
|
2470
|
+
url.pathname = "/api/auth/sign-in/social";
|
|
2471
|
+
let body = await request.text();
|
|
2472
|
+
try {
|
|
2473
|
+
const value = JSON.parse(body);
|
|
2474
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
2475
|
+
const { providerId, ...fields } = value;
|
|
2476
|
+
body = JSON.stringify({ ...fields, provider: providerId });
|
|
2477
|
+
}
|
|
2478
|
+
} catch {
|
|
2479
|
+
}
|
|
2480
|
+
const headers = new Headers(request.headers);
|
|
2481
|
+
headers.delete("content-length");
|
|
2482
|
+
translated = new Request(url, { method: request.method, headers, body, signal: request.signal });
|
|
2483
|
+
} else {
|
|
2484
|
+
url.pathname = callbackPath;
|
|
2485
|
+
translated = new Request(url, request);
|
|
2486
|
+
}
|
|
2487
|
+
const response = await handler(translated);
|
|
2488
|
+
if (legacyStart && !response.ok) {
|
|
2489
|
+
const diagnosis = credentialRateLimitFailure(response, false) ?? oauthResponseFailure(response.status, await response.clone().json().catch(() => null));
|
|
2490
|
+
if (diagnosis) {
|
|
2491
|
+
const safe = renderAuthRequestFailure(diagnosis, logger, request);
|
|
2492
|
+
const headers = new Headers(response.headers);
|
|
2493
|
+
headers.delete("content-length");
|
|
2494
|
+
safe.headers.forEach((value, name) => headers.set(name, value));
|
|
2495
|
+
return new Response(safe.body, { status: safe.status, headers });
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
return response;
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
// ../runtime/dist/adapters/auth/better-auth/body-inspection.js
|
|
2502
|
+
var MAX_AUTH_BODY_BYTES = 1024 * 1024;
|
|
2503
|
+
function abortedInput() {
|
|
2504
|
+
return new RuntimeDiagnosticError({
|
|
2505
|
+
code: "RUNTIME_AUTH_REQUEST_ABORTED",
|
|
2506
|
+
stage: "request",
|
|
2507
|
+
servingStarted: "unchanged",
|
|
2508
|
+
dataImpact: "none",
|
|
2509
|
+
retryable: false,
|
|
2510
|
+
retryPrecondition: "Use a fresh request only if the auth operation is still intended and the generation is ready.",
|
|
2511
|
+
nextAction: "No auth operation ran. Check generation readiness before submitting a fresh request.",
|
|
2512
|
+
capability: "auth"
|
|
2513
|
+
});
|
|
2514
|
+
}
|
|
2515
|
+
function inspectAuthRequestBody(request, work) {
|
|
2516
|
+
return captureRequestBody(request, work, MAX_AUTH_BODY_BYTES, abortedInput);
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
// ../runtime/dist/adapters/auth/better-auth/request-observation.js
|
|
2520
|
+
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
|
|
2521
|
+
function createAuthRequestObservation() {
|
|
2522
|
+
const observations = new AsyncLocalStorage4();
|
|
2523
|
+
const plugin = {
|
|
2524
|
+
id: "gencow-request-observation",
|
|
2525
|
+
// In the pinned SDK the native limiter runs before the first onRequest
|
|
2526
|
+
// plugin. Mark entry before application request plugins or credential hooks.
|
|
2527
|
+
// Native policy callbacks can run earlier; the caller assesses them
|
|
2528
|
+
// separately. The SDK returns early on quota denial.
|
|
2529
|
+
async onRequest() {
|
|
2530
|
+
const observation = observations.getStore();
|
|
2531
|
+
if (observation)
|
|
2532
|
+
observation.entered = true;
|
|
2533
|
+
}
|
|
2534
|
+
};
|
|
2535
|
+
return {
|
|
2536
|
+
plugin,
|
|
2537
|
+
dispose: () => observations.disable(),
|
|
2538
|
+
async run(execute) {
|
|
2539
|
+
const observation = { entered: false };
|
|
2540
|
+
return observations.run(observation, async () => ({
|
|
2541
|
+
response: await execute(),
|
|
2542
|
+
rejectedBeforeExecution: !observation.entered
|
|
2543
|
+
}));
|
|
2544
|
+
}
|
|
2545
|
+
};
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
// ../runtime/dist/adapters/auth/better-auth/background-work.js
|
|
2549
|
+
function createAuthBackgroundWork(observe) {
|
|
2550
|
+
const wrapped = /* @__PURE__ */ new WeakSet();
|
|
2551
|
+
function wrap(context) {
|
|
2552
|
+
if (!wrapped.has(context.runInBackground)) {
|
|
2553
|
+
const run = context.runInBackground;
|
|
2554
|
+
context.runInBackground = function(promise) {
|
|
2555
|
+
observe(() => promise);
|
|
2556
|
+
return run.call(this, promise);
|
|
2557
|
+
};
|
|
2558
|
+
wrapped.add(context.runInBackground);
|
|
2559
|
+
}
|
|
2560
|
+
if (!wrapped.has(context.runInBackgroundOrAwait)) {
|
|
2561
|
+
const runOrAwait = context.runInBackgroundOrAwait;
|
|
2562
|
+
context.runInBackgroundOrAwait = function(promise) {
|
|
2563
|
+
if (promise)
|
|
2564
|
+
observe(() => promise);
|
|
2565
|
+
return runOrAwait.call(this, promise);
|
|
2566
|
+
};
|
|
2567
|
+
wrapped.add(context.runInBackgroundOrAwait);
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
const plugin = {
|
|
2571
|
+
id: "gencow-background-work-observation",
|
|
2572
|
+
init: wrap
|
|
2573
|
+
};
|
|
2574
|
+
return { plugin, wrap };
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
// ../runtime/dist/adapters/auth/better-auth/data-protection.js
|
|
2578
|
+
import { is } from "drizzle-orm";
|
|
2579
|
+
import { PgTable as PgTable2, getTableConfig } from "drizzle-orm/pg-core";
|
|
2580
|
+
function unavailable() {
|
|
2581
|
+
throw new RuntimeDiagnosticError({
|
|
2582
|
+
code: "RUNTIME_AUTH_DATA_PROTECTION_UNAVAILABLE",
|
|
2583
|
+
stage: "request",
|
|
2584
|
+
capability: "auth",
|
|
2585
|
+
servingStarted: "unchanged",
|
|
2586
|
+
dataImpact: "none",
|
|
2587
|
+
retryable: false,
|
|
2588
|
+
retryPrecondition: "Use an Auth configuration whose selected model mappings can be protected safely before generic Data access.",
|
|
2589
|
+
nextAction: "Inspect selected Auth model/schema configuration and restart after correcting the mapping. Other supported capabilities remain available; generic Auth-table SQL is never a fallback."
|
|
2590
|
+
});
|
|
2591
|
+
}
|
|
2592
|
+
function relation(table) {
|
|
2593
|
+
if (!is(table, PgTable2))
|
|
2594
|
+
unavailable();
|
|
2595
|
+
const config = getTableConfig(table);
|
|
2596
|
+
return Object.freeze({ schema: config.schema ?? "public", name: config.name });
|
|
2597
|
+
}
|
|
2598
|
+
function declaredAuthRelations(schema) {
|
|
2599
|
+
return Object.freeze(["user", "session", "account", "verification"].map((key) => relation(schema[key])));
|
|
2600
|
+
}
|
|
2601
|
+
function captureAuthDataProtection(models2, schema) {
|
|
2602
|
+
if (!models2 || typeof models2 !== "object" || Array.isArray(models2))
|
|
2603
|
+
unavailable();
|
|
2604
|
+
const entries = Object.values(models2);
|
|
2605
|
+
if (entries.length < 4)
|
|
2606
|
+
unavailable();
|
|
2607
|
+
const relations = entries.map((model) => {
|
|
2608
|
+
if (!model || typeof model !== "object" || !("modelName" in model) || typeof model.modelName !== "string")
|
|
2609
|
+
unavailable();
|
|
2610
|
+
return relation(schema[model.modelName]);
|
|
2611
|
+
});
|
|
2612
|
+
return Object.freeze([
|
|
2613
|
+
...new Map(relations.map((value) => [`${value.schema}\0${value.name}`, value])).values()
|
|
2614
|
+
]);
|
|
2615
|
+
}
|
|
2616
|
+
function createAuthDataProtectionReader(ensure, schema, admit) {
|
|
2617
|
+
let snapshot;
|
|
2618
|
+
return () => admit(() => snapshot ??= (async () => captureAuthDataProtection((await (await ensure()).$context)?.tables, schema))());
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
// ../runtime/dist/adapters/auth/better-auth/administration-transaction.js
|
|
2622
|
+
function createAuthAdministrationTransaction(sdk, database, schema) {
|
|
2623
|
+
const scoped = sdk.drizzleAdapter(database.drizzle, { provider: "pg", schema, transaction: true });
|
|
2624
|
+
return async (options, operation) => await sdk.runWithTransaction(scoped(options), operation);
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
// ../runtime/dist/adapters/auth/better-auth/response-policy.js
|
|
2628
|
+
function finalizeAuthResponses(app) {
|
|
2629
|
+
app.use("/api/auth/*", async (context, next) => {
|
|
2630
|
+
await next();
|
|
2631
|
+
if (context.res.headers.get("cache-control") !== "no-store")
|
|
2632
|
+
context.header("Cache-Control", "no-store");
|
|
2633
|
+
});
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
// ../runtime/dist/adapters/auth/better-auth/adapter.js
|
|
2637
|
+
var SESSION_TIMEOUT_MS = 8e3;
|
|
2638
|
+
function withTimeout(operation) {
|
|
2639
|
+
return new Promise((resolve, reject) => {
|
|
2640
|
+
const timer = setTimeout(() => reject(new RuntimeAuthSessionTimeoutError()), SESSION_TIMEOUT_MS);
|
|
2641
|
+
void operation.then((value) => {
|
|
2642
|
+
clearTimeout(timer);
|
|
2643
|
+
resolve(value);
|
|
2644
|
+
}, (error) => {
|
|
2645
|
+
clearTimeout(timer);
|
|
2646
|
+
reject(error);
|
|
2647
|
+
});
|
|
2648
|
+
});
|
|
2649
|
+
}
|
|
2650
|
+
function authResponse(body, status = 200, sdkHeaders) {
|
|
2651
|
+
const headers = new Headers(sdkHeaders);
|
|
2652
|
+
headers.delete("content-length");
|
|
2653
|
+
headers.delete("content-type");
|
|
2654
|
+
headers.set("cache-control", "no-store");
|
|
2655
|
+
return Response.json(body, { status, headers });
|
|
2656
|
+
}
|
|
2657
|
+
function createBetterAuthAdapter(config, dependencies, initializeOverride) {
|
|
2658
|
+
const accessTokenKey = new Uint8Array(config.accessTokenKey);
|
|
2659
|
+
const social = resolveRuntimeSocialAuth(config.authConfig.socialProviders);
|
|
2660
|
+
const administrationUpdates = createAuthProfileUpdateOperation();
|
|
2661
|
+
const administrationDeletes = createAuthProfileDeleteOperation();
|
|
2662
|
+
let disposed = false;
|
|
2663
|
+
let initialization;
|
|
2664
|
+
let databaseReadRecovery;
|
|
2665
|
+
let disposal;
|
|
2666
|
+
const pending = /* @__PURE__ */ new Set();
|
|
2667
|
+
const requestObservation = createAuthRequestObservation();
|
|
2668
|
+
const oauthSessionObserver = createOAuthSessionObserver();
|
|
2669
|
+
const backgroundWork = createAuthBackgroundWork(observe);
|
|
2670
|
+
let hasApplicationRateLimitCode = true;
|
|
2671
|
+
let isSdkApiError = () => false;
|
|
2672
|
+
let signupRequiresVerification = config.authConfig.emailVerification ? config.authConfig.emailVerification.requireEmailVerification ?? true : false;
|
|
2673
|
+
const signupEvents = createSignupEvents(config.authConfig, dependencies.database, dependencies.logger);
|
|
2674
|
+
function observe(operation) {
|
|
2675
|
+
const work = dependencies.work.track(Promise.resolve().then(operation));
|
|
2676
|
+
pending.add(work);
|
|
2677
|
+
const settled = () => {
|
|
2678
|
+
pending.delete(work);
|
|
2679
|
+
};
|
|
2680
|
+
void work.then(settled, settled);
|
|
2681
|
+
return work;
|
|
2682
|
+
}
|
|
2683
|
+
function admit(operation) {
|
|
2684
|
+
if (disposed) {
|
|
2685
|
+
return Promise.reject(authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Create a new Runtime application before using auth."));
|
|
2686
|
+
}
|
|
2687
|
+
return observe(operation);
|
|
2688
|
+
}
|
|
2689
|
+
let preparation;
|
|
2690
|
+
const prepare = () => preparation ??= (async () => {
|
|
2691
|
+
try {
|
|
2692
|
+
const sdk = await loadBetterAuthSdk();
|
|
2693
|
+
const { bearer, genericOAuth, drizzleAdapter, isAPIError } = sdk;
|
|
2694
|
+
isSdkApiError = isAPIError;
|
|
2695
|
+
databaseReadRecovery = createAuthDatabaseReadRecovery({
|
|
2696
|
+
borrowed: dependencies.database,
|
|
2697
|
+
schema: config.authSchema,
|
|
2698
|
+
getAuthTables: sdk.getAuthTables
|
|
2699
|
+
});
|
|
2700
|
+
const generatedFactory = drizzleAdapter(databaseReadRecovery.drizzle, {
|
|
2701
|
+
provider: "pg",
|
|
2702
|
+
schema: config.authSchema
|
|
2703
|
+
});
|
|
2704
|
+
const database = protectRateLimitDatabase(databaseReadRecovery.decorateFactory(generatedFactory), dependencies.database, config.authSchema, () => hasApplicationRateLimitCode ? "unknown" : "none");
|
|
2705
|
+
const options = buildRuntimeBetterAuthOptions({
|
|
2706
|
+
authConfig: config.authConfig,
|
|
2707
|
+
rateLimit: config.rateLimit,
|
|
2708
|
+
logger: dependencies.logger,
|
|
2709
|
+
trackVerificationGate: observe,
|
|
2710
|
+
database,
|
|
2711
|
+
secret: config.secret,
|
|
2712
|
+
origin: config.originPolicy.origin,
|
|
2713
|
+
trustedOrigins: config.originPolicy.trustedOrigins,
|
|
2714
|
+
plugins: [
|
|
2715
|
+
bearer(),
|
|
2716
|
+
...social.customOAuthConfig.length ? [genericOAuth({ config: social.customOAuthConfig })] : []
|
|
2717
|
+
],
|
|
2718
|
+
socialProviders: social.socialProviders
|
|
2719
|
+
});
|
|
2720
|
+
const nativeProviders = await captureRuntimeNativeProviders(options.socialProviders);
|
|
2721
|
+
options.socialProviders = nativeProviders;
|
|
2722
|
+
const generic = captureRuntimeGenericProviders(options.plugins, genericOAuth, config.originPolicy.origin);
|
|
2723
|
+
options.plugins = generic.plugins;
|
|
2724
|
+
const customProviders = generic.providerIds;
|
|
2725
|
+
return {
|
|
2726
|
+
sdk,
|
|
2727
|
+
options,
|
|
2728
|
+
customProviders,
|
|
2729
|
+
providers: [.../* @__PURE__ */ new Set([...Object.keys(nativeProviders), ...customProviders])]
|
|
2730
|
+
};
|
|
2731
|
+
} catch (error) {
|
|
2732
|
+
if (runtimeDiagnostic(error))
|
|
2733
|
+
throw error;
|
|
2734
|
+
throw authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Correct Better Auth configuration and database schema before restarting.");
|
|
2735
|
+
}
|
|
2736
|
+
})();
|
|
2737
|
+
const ensure = () => {
|
|
2738
|
+
if (disposed)
|
|
2739
|
+
return Promise.reject(authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Create a new Runtime application before using auth."));
|
|
2740
|
+
if (!initialization) {
|
|
2741
|
+
initialization = (initializeOverride ?? (async () => {
|
|
2742
|
+
try {
|
|
2743
|
+
const { sdk, options } = await prepare();
|
|
2744
|
+
const { betterAuth } = sdk;
|
|
2745
|
+
const administrationTransaction = createAuthAdministrationTransaction(sdk, dependencies.database, config.authSchema);
|
|
2746
|
+
signupRequiresVerification = options.emailAndPassword.requireEmailVerification === true;
|
|
2747
|
+
const plugins = options.plugins;
|
|
2748
|
+
hasApplicationRateLimitCode = Boolean(config.rateLimit.customStorage) || Object.values(config.rateLimit.customRules).some((rule) => typeof rule === "function") || plugins.some((plugin) => (plugin.rateLimit?.length ?? 0) > 0);
|
|
2749
|
+
const initialized = betterAuth({
|
|
2750
|
+
...options,
|
|
2751
|
+
plugins: [
|
|
2752
|
+
requestObservation.plugin,
|
|
2753
|
+
backgroundWork.plugin,
|
|
2754
|
+
...plugins,
|
|
2755
|
+
oauthSessionObserver.plugin(sdk),
|
|
2756
|
+
administrationUpdates.plugin(sdk, administrationTransaction),
|
|
2757
|
+
administrationDeletes.plugin(sdk, administrationTransaction)
|
|
2758
|
+
],
|
|
2759
|
+
...config.rateLimit.customStorage ? {
|
|
2760
|
+
rateLimit: {
|
|
2761
|
+
...options.rateLimit,
|
|
2762
|
+
customStorage: protectCustomRateLimitStorage(config.rateLimit.customStorage)
|
|
2763
|
+
}
|
|
2764
|
+
} : {},
|
|
2765
|
+
databaseHooks: signupEvents.databaseHooks(options.databaseHooks),
|
|
2766
|
+
// Never let SDK logging leak provider/config secrets. Runtime
|
|
2767
|
+
// emits classified codes through its protected logger instead.
|
|
2768
|
+
logger: { disabled: true },
|
|
2769
|
+
// Better Call otherwise absorbs non-API errors and prints raw stacks.
|
|
2770
|
+
// API errors/redirects retain SDK HTTP rendering under this policy.
|
|
2771
|
+
onAPIError: { throw: true }
|
|
2772
|
+
});
|
|
2773
|
+
backgroundWork.wrap(await initialized.$context);
|
|
2774
|
+
admitAuthRateLimit(config.rateLimit, dependencies.appId ?? config.originPolicy.origin, dependencies.logger);
|
|
2775
|
+
return initialized;
|
|
2776
|
+
} catch (error) {
|
|
2777
|
+
initialization = void 0;
|
|
2778
|
+
if (runtimeDiagnostic(error))
|
|
2779
|
+
throw error;
|
|
2780
|
+
throw authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Correct Better Auth configuration and database schema before restarting.");
|
|
2781
|
+
}
|
|
2782
|
+
}))().catch((error) => {
|
|
2783
|
+
initialization = void 0;
|
|
2784
|
+
throw error;
|
|
2785
|
+
});
|
|
2786
|
+
}
|
|
2787
|
+
return initialization;
|
|
2788
|
+
};
|
|
2789
|
+
const observeSession = (operation, kind = "read") => {
|
|
2790
|
+
const deadlineAt = performance.now() + SESSION_TIMEOUT_MS;
|
|
2791
|
+
const lookup = () => withTimeout(observe(operation));
|
|
2792
|
+
return databaseReadRecovery ? databaseReadRecovery.withOperation(kind, () => databaseReadRecovery.withReadDeadline(deadlineAt, lookup)) : lookup();
|
|
2793
|
+
};
|
|
2794
|
+
const getSession = async (request, token) => {
|
|
2795
|
+
try {
|
|
2796
|
+
const auth = await ensure();
|
|
2797
|
+
const headers = new Headers(request.headers);
|
|
2798
|
+
if (token)
|
|
2799
|
+
headers.set("cookie", sessionTokenToCookieHeader(token));
|
|
2800
|
+
const deletion = selectedAuthDeletionEnabled(await auth.$context);
|
|
2801
|
+
return await observeSession(() => auth.api.getSession({ headers, ...deletion ? { query: { disableCookieCache: true } } : {} }));
|
|
2802
|
+
} catch (error) {
|
|
2803
|
+
if (error instanceof RuntimeAuthSessionTimeoutError)
|
|
2804
|
+
throw error;
|
|
2805
|
+
throw sessionLookupFailure(error);
|
|
2806
|
+
}
|
|
2807
|
+
};
|
|
2808
|
+
const resolveAuthentication = createAuthIdentityResolver({
|
|
2809
|
+
key: accessTokenKey,
|
|
2810
|
+
requireSelectedUser: initializeOverride === void 0,
|
|
2811
|
+
ensure,
|
|
2812
|
+
getSession,
|
|
2813
|
+
observe: observeSession
|
|
2814
|
+
});
|
|
2815
|
+
const resolveTrustedAuthentication = async (request) => {
|
|
2816
|
+
const resolved = await resolveAuthentication(request);
|
|
2817
|
+
const credential = classifyBetterAuthCredential(request);
|
|
2818
|
+
if (resolved.method !== "anonymous")
|
|
2819
|
+
return Object.freeze({ ...resolved, credentialStatus: "verified" });
|
|
2820
|
+
return Object.freeze({
|
|
2821
|
+
...resolved,
|
|
2822
|
+
credentialStatus: credential === "absent" ? "absent" : "invalid"
|
|
2823
|
+
});
|
|
2824
|
+
};
|
|
2825
|
+
const oauthFacade = createOAuthFacade({
|
|
2826
|
+
config,
|
|
2827
|
+
database: dependencies.database,
|
|
2828
|
+
key: accessTokenKey,
|
|
2829
|
+
providerSelection: prepare,
|
|
2830
|
+
logger: dependencies.logger,
|
|
2831
|
+
ensure,
|
|
2832
|
+
getOAuthSession: async (headers, credential) => {
|
|
2833
|
+
const { api } = await ensure();
|
|
2834
|
+
return observeSession(() => oauthSessionObserver.read(api, headers, credential), "oauth-read").catch((error) => {
|
|
2835
|
+
if (isSdkApiError(error)) {
|
|
2836
|
+
const status = error.statusCode;
|
|
2837
|
+
if (status === 401 || status === 403)
|
|
2838
|
+
return null;
|
|
2839
|
+
}
|
|
2840
|
+
throw error;
|
|
2841
|
+
});
|
|
2842
|
+
}
|
|
2843
|
+
});
|
|
2844
|
+
const facade = async (request, path) => {
|
|
2845
|
+
if (path === "/api/auth/social-providers" && request.method === "GET") {
|
|
2846
|
+
return authResponse({ providers: (await prepare()).providers });
|
|
2847
|
+
}
|
|
2848
|
+
const oauthResponse = await oauthFacade(request, path);
|
|
2849
|
+
if (oauthResponse)
|
|
2850
|
+
return oauthResponse;
|
|
2851
|
+
if (path === "/api/auth/token" && request.method === "POST") {
|
|
2852
|
+
const session = await getSession(request, candidateSessionToken(request));
|
|
2853
|
+
const identity = session?.user ? toRuntimeIdentity(session.user) : null;
|
|
2854
|
+
return identity ? authResponse(await issueAccessToken(identity, accessTokenKey)) : authResponse({ code: "UNAUTHORIZED" }, 401);
|
|
2855
|
+
}
|
|
2856
|
+
if (path === "/api/auth/me" && request.method === "GET") {
|
|
2857
|
+
const session = await getSession(request, candidateSessionToken(request));
|
|
2858
|
+
const identity = session?.user ? toRuntimeIdentity(session.user) : null;
|
|
2859
|
+
return identity ? authResponse({ user: identity, session: session?.session ?? null }) : authResponse({ code: "UNAUTHORIZED" }, 401);
|
|
2860
|
+
}
|
|
2861
|
+
if ((path === "/api/auth/sign-in" || path === "/api/auth/sign-up") && request.method === "POST") {
|
|
2862
|
+
const body = await request.json().catch(() => null);
|
|
2863
|
+
if (!body)
|
|
2864
|
+
throw credentialResponseFailure(400, { code: "VALIDATION_ERROR" });
|
|
2865
|
+
const auth = await ensure();
|
|
2866
|
+
const url = new URL(request.url);
|
|
2867
|
+
url.pathname = path.endsWith("sign-in") ? "/api/auth/sign-in/email" : "/api/auth/sign-up/email";
|
|
2868
|
+
const headers = new Headers(request.headers);
|
|
2869
|
+
headers.delete("content-length");
|
|
2870
|
+
headers.set("content-type", "application/json");
|
|
2871
|
+
const runHandler = () => requestObservation.run(() => auth.handler(new Request(url, {
|
|
2872
|
+
method: "POST",
|
|
2873
|
+
headers,
|
|
2874
|
+
body: JSON.stringify(body),
|
|
2875
|
+
signal: request.signal
|
|
2876
|
+
})));
|
|
2877
|
+
const { response: sdkResponse, rejectedBeforeExecution } = databaseReadRecovery ? await databaseReadRecovery.withOperation("handler", runHandler) : await runHandler();
|
|
2878
|
+
if (!sdkResponse.ok) {
|
|
2879
|
+
const limited = credentialRateLimitFailure(sdkResponse, rejectedBeforeExecution && !hasApplicationRateLimitCode && !initializeOverride);
|
|
2880
|
+
if (limited) {
|
|
2881
|
+
const safe = renderAuthRequestFailure(limited, dependencies.logger, request);
|
|
2882
|
+
return authResponse({ ...await safe.json(), message: "Too many requests. Please try again later." }, 429, sdkResponse.headers);
|
|
2883
|
+
}
|
|
2884
|
+
const diagnosis = credentialResponseFailure(sdkResponse.status, await sdkResponse.clone().json().catch(() => null));
|
|
2885
|
+
if (diagnosis)
|
|
2886
|
+
throw diagnosis;
|
|
2887
|
+
return sdkResponse;
|
|
2888
|
+
}
|
|
2889
|
+
const result = await sdkResponse.json();
|
|
2890
|
+
const user = result && typeof result.user === "object" && result.user ? toRuntimeIdentity(result.user) : null;
|
|
2891
|
+
if (!user) {
|
|
2892
|
+
if (result && result.requiresVerification === true)
|
|
2893
|
+
return authResponse({ requiresVerification: true, email: body.email }, 200, sdkResponse.headers);
|
|
2894
|
+
return authResponse({ code: "UNAUTHORIZED" }, 401);
|
|
2895
|
+
}
|
|
2896
|
+
const sessionToken = typeof result?.token === "string" ? result.token : void 0;
|
|
2897
|
+
if (!sessionToken) {
|
|
2898
|
+
const requiresVerification = signupRequiresVerification && result.user.emailVerified !== true;
|
|
2899
|
+
return path.endsWith("sign-up") ? authResponse({
|
|
2900
|
+
requiresVerification,
|
|
2901
|
+
requiresSignIn: !requiresVerification,
|
|
2902
|
+
email: body.email,
|
|
2903
|
+
user,
|
|
2904
|
+
correlationId: runtimeRequestCorrelation(request),
|
|
2905
|
+
nextAction: requiresVerification ? "Signup accepted. Complete the email verification step before signing in; do not repeat signup." : "Signup accepted. Use sign in with these credentials; do not repeat signup."
|
|
2906
|
+
}, 200, sdkResponse.headers) : authResponse({ code: "UNAUTHORIZED" }, 401);
|
|
2907
|
+
}
|
|
2908
|
+
return authResponse({
|
|
2909
|
+
user,
|
|
2910
|
+
...sessionToken ? { sessionToken } : {},
|
|
2911
|
+
...await issueAccessToken(user, accessTokenKey)
|
|
2912
|
+
}, 200, sdkResponse.headers);
|
|
2913
|
+
}
|
|
2914
|
+
return null;
|
|
2915
|
+
};
|
|
2916
|
+
return {
|
|
2917
|
+
administration: createAuthAdministrationInspection(ensure, admit, administrationUpdates, administrationDeletes),
|
|
2918
|
+
dataProtection: createAuthDataProtectionReader(ensure, config.authSchema, admit),
|
|
2919
|
+
async initialize() {
|
|
2920
|
+
await admit(async () => {
|
|
2921
|
+
await ensure();
|
|
2922
|
+
});
|
|
2923
|
+
},
|
|
2924
|
+
async resolveAuthentication(request) {
|
|
2925
|
+
return admit(() => resolveTrustedAuthentication(request)).catch((error) => {
|
|
2926
|
+
throw sessionLookupFailure(error);
|
|
2927
|
+
});
|
|
2928
|
+
},
|
|
2929
|
+
mapIdentityToRls({ identity }) {
|
|
2930
|
+
const mapper = config.authConfig.rls?.mapSessionToContext;
|
|
2931
|
+
return mapper ? mapper({ user: identity }) : defaultRlsSessionContext(identity?.id ?? "");
|
|
2932
|
+
},
|
|
2933
|
+
configureHttpApp(app) {
|
|
2934
|
+
finalizeAuthResponses(app);
|
|
2935
|
+
app.all("/api/auth/*", async (context) => {
|
|
2936
|
+
try {
|
|
2937
|
+
return await admit(async () => {
|
|
2938
|
+
const request = await inspectAuthRequestBody(context.req.raw, dependencies.work);
|
|
2939
|
+
if (!request)
|
|
2940
|
+
throw authTransportFailure("RUNTIME_AUTH_REQUEST_BODY_TOO_LARGE", MAX_AUTH_BODY_BYTES);
|
|
2941
|
+
const origin = request.headers.get("origin");
|
|
2942
|
+
if (origin && !isRuntimeOriginAllowed(origin, config.originPolicy.trustedOrigins))
|
|
2943
|
+
throw authTransportFailure("RUNTIME_AUTH_ORIGIN_INVALID", MAX_AUTH_BODY_BYTES);
|
|
2944
|
+
return signupEvents.run(request, async () => {
|
|
2945
|
+
const response = await facade(request, new URL(context.req.url).pathname);
|
|
2946
|
+
if (response)
|
|
2947
|
+
return response;
|
|
2948
|
+
const runSdkHandler = () => handleCompatibleOAuthRequest(request, async (translated) => (await ensure()).handler(translated), dependencies.logger);
|
|
2949
|
+
return databaseReadRecovery ? await databaseReadRecovery.withOperation("handler", runSdkHandler) : await runSdkHandler();
|
|
2950
|
+
});
|
|
2951
|
+
});
|
|
2952
|
+
} catch (error) {
|
|
2953
|
+
return renderAuthRequestFailure(credentialFailure(error, isSdkApiError), dependencies.logger, context.req.raw);
|
|
2954
|
+
}
|
|
2955
|
+
});
|
|
2956
|
+
},
|
|
2957
|
+
dispose() {
|
|
2958
|
+
disposed = true;
|
|
2959
|
+
disposal ??= (async () => {
|
|
2960
|
+
while (pending.size > 0)
|
|
2961
|
+
await Promise.allSettled([...pending]);
|
|
2962
|
+
await initialization?.catch(() => {
|
|
2963
|
+
});
|
|
2964
|
+
initialization = void 0;
|
|
2965
|
+
requestObservation.dispose();
|
|
2966
|
+
})();
|
|
2967
|
+
return disposal;
|
|
2968
|
+
}
|
|
2969
|
+
};
|
|
2970
|
+
}
|
|
2971
|
+
|
|
2972
|
+
// ../runtime/dist/adapters/auth/better-auth/rate-limit-readiness.js
|
|
2973
|
+
import { getTableColumns as getTableColumns4, getTableName, sql as sql2 } from "drizzle-orm";
|
|
2974
|
+
import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
|
|
2975
|
+
function unavailable2(context) {
|
|
2976
|
+
throw authStartupError("RUNTIME_AUTH_RATE_LIMIT_SCHEMA_UNAVAILABLE", context === "local" ? "Run gencow db:generate and gencow db:push --local for the selected app database, then restart. Preserve applied migrations; add a forward migration if needed." : "Generate and apply the app's forward auth migration through its app-scoped cloud migration flow, then redeploy. Preserve applied migrations.");
|
|
2977
|
+
}
|
|
2978
|
+
function rows(result) {
|
|
2979
|
+
const value = result && typeof result === "object" && "rows" in result ? result.rows : result;
|
|
2980
|
+
return Array.isArray(value) ? value : [];
|
|
2981
|
+
}
|
|
2982
|
+
async function preflightAuthRateLimit(options, database) {
|
|
2983
|
+
const policy = options.rateLimit;
|
|
2984
|
+
if (!policy.enabled || policy.customStorage || policy.storage !== "database")
|
|
2985
|
+
return;
|
|
2986
|
+
if (!options.authSchema.rateLimit)
|
|
2987
|
+
unavailable2(policy.context);
|
|
2988
|
+
try {
|
|
2989
|
+
const table = options.authSchema.rateLimit;
|
|
2990
|
+
const { columns, config } = (() => {
|
|
2991
|
+
try {
|
|
2992
|
+
const columns2 = getTableColumns4(table);
|
|
2993
|
+
const config2 = getTableConfig2(table);
|
|
2994
|
+
if (!columns2)
|
|
2995
|
+
unavailable2(policy.context);
|
|
2996
|
+
return { columns: columns2, config: config2 };
|
|
2997
|
+
} catch {
|
|
2998
|
+
unavailable2(policy.context);
|
|
2999
|
+
}
|
|
3000
|
+
})();
|
|
3001
|
+
const expected = { id: "text", key: "text", count: "integer", lastRequest: "bigint" };
|
|
3002
|
+
if (Object.entries(expected).some(([name, type]) => !columns[name] || columns[name].getSQLType() !== type || !columns[name].notNull) || !columns.id.hasDefault)
|
|
3003
|
+
unavailable2(policy.context);
|
|
3004
|
+
const quote = (value) => '"' + value.replaceAll('"', '""') + '"';
|
|
3005
|
+
const relation2 = [config.schema ?? "public", getTableName(table)].map(quote).join(".");
|
|
3006
|
+
await database.drizzle.transaction(async (transaction) => {
|
|
3007
|
+
await transaction.execute(sql2`select set_config('statement_timeout', '10000', true)`);
|
|
3008
|
+
const attributes = rows(await transaction.execute(sql2`
|
|
3009
|
+
select a.attname as name, format_type(a.atttypid, a.atttypmod) as type,
|
|
3010
|
+
a.attnotnull as required, a.atthasdef as has_default,
|
|
3011
|
+
exists(select 1 from pg_catalog.pg_index i where i.indrelid = a.attrelid
|
|
3012
|
+
and i.indisunique and i.indisvalid and i.indisready and i.indnkeyatts = 1
|
|
3013
|
+
and i.indkey[0] = a.attnum and i.indpred is null and i.indexprs is null) as unique_key
|
|
3014
|
+
from pg_catalog.pg_attribute a
|
|
3015
|
+
where a.attrelid = pg_catalog.to_regclass(${relation2}) and a.attnum > 0 and not a.attisdropped`));
|
|
3016
|
+
for (const [field, type] of Object.entries(expected)) {
|
|
3017
|
+
const column = columns[field];
|
|
3018
|
+
const attribute = attributes.find((value) => value.name === column.name);
|
|
3019
|
+
if (!attribute || attribute.type !== type || attribute.required !== true || field === "id" && (attribute.has_default !== true || attribute.unique_key !== true) || field === "key" && attribute.unique_key !== true)
|
|
3020
|
+
unavailable2(policy.context);
|
|
3021
|
+
}
|
|
3022
|
+
const permissions = rows(await transaction.execute(sql2`
|
|
3023
|
+
select (has_table_privilege(pg_catalog.to_regclass(${relation2}), 'SELECT')
|
|
3024
|
+
and has_table_privilege(pg_catalog.to_regclass(${relation2}), 'INSERT')
|
|
3025
|
+
and has_table_privilege(pg_catalog.to_regclass(${relation2}), 'UPDATE')
|
|
3026
|
+
and has_table_privilege(pg_catalog.to_regclass(${relation2}), 'DELETE')) as usable`));
|
|
3027
|
+
if (permissions[0]?.usable !== true)
|
|
3028
|
+
unavailable2(policy.context);
|
|
3029
|
+
await transaction.execute(sql2`select ${columns.id}, ${columns.key}, ${columns.count}, ${columns.lastRequest} from ${table} limit 0`);
|
|
3030
|
+
});
|
|
3031
|
+
} catch (error) {
|
|
3032
|
+
if (runtimeDiagnostic(error))
|
|
3033
|
+
throw error;
|
|
3034
|
+
let cause = error;
|
|
3035
|
+
for (let depth = 0; depth < 4 && cause && typeof cause === "object"; depth++) {
|
|
3036
|
+
if ("code" in cause && ["42P01", "42703", "42501"].includes(String(cause.code)))
|
|
3037
|
+
unavailable2(policy.context);
|
|
3038
|
+
cause = cause instanceof Error ? cause.cause : void 0;
|
|
3039
|
+
}
|
|
3040
|
+
throw authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Restore the selected rate-limit database's readiness and resolve schema-lock contention before restarting; no auth handler ran.", "Restart only after the selected database is available; do not alter applied migrations or retry mutations.");
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
// ../runtime/dist/adapters/auth/better-auth/preflight.js
|
|
3045
|
+
import { sql as sql3 } from "drizzle-orm";
|
|
3046
|
+
async function preflightBetterAuthAdapter(input, relations = ["user", "session", "account", "verification"].map((name) => ({ schema: "public", name }))) {
|
|
3047
|
+
const database = input.drizzle;
|
|
3048
|
+
if (typeof database.execute !== "function") {
|
|
3049
|
+
throw authStartupError("RUNTIME_AUTH_SCHEMA_INVALID", "Use a Runtime database adapter that provides the private auth database handle.");
|
|
3050
|
+
}
|
|
3051
|
+
try {
|
|
3052
|
+
await database.transaction(async (transaction) => {
|
|
3053
|
+
await transaction.execute(sql3`select set_config('statement_timeout', '10000', true)`);
|
|
3054
|
+
await transaction.execute(sql3`select 1`);
|
|
3055
|
+
for (const relation2 of relations)
|
|
3056
|
+
await transaction.execute(sql3`select 1 from ${sql3.identifier(relation2.schema)}.${sql3.identifier(relation2.name)} limit 1`);
|
|
3057
|
+
});
|
|
3058
|
+
} catch (error) {
|
|
3059
|
+
if (!missingSchema(error)) {
|
|
3060
|
+
throw authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Restore database readiness and resolve schema-lock contention before restarting Runtime; do not alter applied migrations or retry mutations.", "Restart only after database readiness and schema-lock availability are restored; no auth handler ran.");
|
|
3061
|
+
}
|
|
3062
|
+
throw authStartupError("RUNTIME_AUTH_SCHEMA_INVALID", "Apply the declared Better Auth schema migration to the configured database before restarting Runtime.");
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
function missingSchema(error) {
|
|
3066
|
+
const trusted = trustedRuntimeQuerySqlState(error);
|
|
3067
|
+
if (trusted === "42P01" || trusted === "42703")
|
|
3068
|
+
return true;
|
|
3069
|
+
let current = error;
|
|
3070
|
+
for (let depth = 0; depth < 4; depth++) {
|
|
3071
|
+
if (!current || typeof current !== "object")
|
|
3072
|
+
return false;
|
|
3073
|
+
if ("code" in current && (current.code === "42P01" || current.code === "42703"))
|
|
3074
|
+
return true;
|
|
3075
|
+
current = current instanceof Error ? current.cause : void 0;
|
|
3076
|
+
}
|
|
3077
|
+
return false;
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
// ../runtime/dist/adapters/auth/better-auth/ready.js
|
|
3081
|
+
async function createReadyBetterAuthAdapter(options, dependencies, initializeOverride) {
|
|
3082
|
+
await preflightAuthRateLimit(options, dependencies.database);
|
|
3083
|
+
await preflightBetterAuthAdapter(dependencies.database, declaredAuthRelations(options.authSchema));
|
|
3084
|
+
const adapter = createBetterAuthAdapter(options, dependencies, initializeOverride);
|
|
3085
|
+
try {
|
|
3086
|
+
await adapter.initialize();
|
|
3087
|
+
return adapter;
|
|
3088
|
+
} catch (error) {
|
|
3089
|
+
await Promise.resolve().then(() => adapter.dispose?.()).catch(() => {
|
|
3090
|
+
});
|
|
3091
|
+
try {
|
|
3092
|
+
dependencies.logger.error("runtime.component.preflight.failed", {
|
|
3093
|
+
"runtime.public_code": runtimeDiagnostic(error)?.code ?? "RUNTIME_AUTH_INITIALIZATION_FAILED"
|
|
3094
|
+
});
|
|
3095
|
+
} catch {
|
|
3096
|
+
}
|
|
3097
|
+
if (runtimeDiagnostic(error))
|
|
3098
|
+
throw error;
|
|
3099
|
+
throw authStartupError("RUNTIME_AUTH_INITIALIZATION_FAILED", "Correct Better Auth configuration before restarting.");
|
|
3100
|
+
}
|
|
3101
|
+
}
|
|
3102
|
+
export {
|
|
3103
|
+
createReadyBetterAuthAdapter
|
|
3104
|
+
};
|