@gadicc/loom 1.26.0 → 1.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_MAX_BODY_BYTES = exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_ENV = void 0;
4
+ exports.isBetterAuthLocalTestLoginEnabled = isBetterAuthLocalTestLoginEnabled;
5
+ exports.safeBetterAuthLocalTestCallbackURL = safeBetterAuthLocalTestCallbackURL;
6
+ exports.normalizeBetterAuthLocalTestCallbackURL = normalizeBetterAuthLocalTestCallbackURL;
7
+ exports.createBetterAuthLocalTestLoginHandler = createBetterAuthLocalTestLoginHandler;
8
+ exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_ENV = "LOOM_LOCAL_TEST_LOGIN";
9
+ exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_MAX_BODY_BYTES = 8 * 1024;
10
+ /**
11
+ * Returns whether developer UI login is explicitly enabled for this process.
12
+ *
13
+ * The helper deliberately rejects production/test modes and every Vercel
14
+ * runtime. Tests should pass an explicit development-shaped environment and
15
+ * exercise the handler with loopback requests.
16
+ */
17
+ function isBetterAuthLocalTestLoginEnabled(env, optInEnvName = exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_ENV) {
18
+ return env.NODE_ENV === "development" &&
19
+ env[optInEnvName] === "1" &&
20
+ !Object.entries(env).some(([name, value]) => name.startsWith("VERCEL") && Boolean(value));
21
+ }
22
+ function randomLocalPassword() {
23
+ return `${crypto.randomUUID()}${crypto.randomUUID()}`;
24
+ }
25
+ function isLoopbackHostname(hostname) {
26
+ const normalized = hostname.toLowerCase();
27
+ return normalized === "localhost" ||
28
+ normalized === "127.0.0.1" ||
29
+ normalized === "[::1]" ||
30
+ normalized === "::1";
31
+ }
32
+ function hasControlCharacters(value) {
33
+ return [...value].some((character) => {
34
+ const code = character.charCodeAt(0);
35
+ return code <= 0x1f || code === 0x7f;
36
+ });
37
+ }
38
+ function parseHttpOrigin(value) {
39
+ try {
40
+ const origin = new URL(value);
41
+ if (origin.protocol !== "http:" ||
42
+ origin.origin !== value ||
43
+ !isLoopbackHostname(origin.hostname)) {
44
+ return null;
45
+ }
46
+ return origin;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function parseLoopbackHost(value) {
53
+ if (!value || /[\\/?#@]/.test(value) || hasControlCharacters(value)) {
54
+ return null;
55
+ }
56
+ try {
57
+ const parsed = new URL(`http://${value}`);
58
+ if (!isLoopbackHostname(parsed.hostname))
59
+ return null;
60
+ return parsed.host;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ function commaSeparatedValues(value) {
67
+ if (value === null)
68
+ return [];
69
+ const values = value.split(",").map((entry) => entry.trim());
70
+ return values.every(Boolean) ? values : [];
71
+ }
72
+ function requestLoopbackOrigin(request) {
73
+ const requestOrigin = parseHttpOrigin(new URL(request.url).origin);
74
+ const origin = request.headers.get("origin");
75
+ const parsedOrigin = origin ? parseHttpOrigin(origin) : null;
76
+ const host = request.headers.get("host");
77
+ const parsedHost = host ? parseLoopbackHost(host) : null;
78
+ if (!requestOrigin || !parsedOrigin || !parsedHost)
79
+ return null;
80
+ const forwardedHosts = commaSeparatedValues(request.headers.get("x-forwarded-host"));
81
+ if (request.headers.has("x-forwarded-host") &&
82
+ (forwardedHosts.length !== 1 || !parseLoopbackHost(forwardedHosts[0]))) {
83
+ return null;
84
+ }
85
+ const forwardedProtocols = commaSeparatedValues(request.headers.get("x-forwarded-proto"));
86
+ if (request.headers.has("x-forwarded-proto") &&
87
+ (forwardedProtocols.length !== 1 ||
88
+ forwardedProtocols[0].toLowerCase() !== "http")) {
89
+ return null;
90
+ }
91
+ const effectivePublicHost = forwardedHosts.length
92
+ ? parseLoopbackHost(forwardedHosts[0])
93
+ : parsedHost;
94
+ if (parsedOrigin.host !== effectivePublicHost)
95
+ return null;
96
+ return parsedOrigin;
97
+ }
98
+ /** Keep a callback on an application page of the current origin. */
99
+ function safeBetterAuthLocalTestCallbackURL(value, fallback = "/") {
100
+ const safeFallback = normalizeBetterAuthLocalTestCallbackURL(fallback);
101
+ if (!safeFallback) {
102
+ throw new Error("Invalid local test login fallback callback URL");
103
+ }
104
+ return normalizeBetterAuthLocalTestCallbackURL(value) ?? safeFallback;
105
+ }
106
+ /** Return a safe same-origin application callback path, or null. */
107
+ function normalizeBetterAuthLocalTestCallbackURL(value) {
108
+ if (typeof value !== "string" ||
109
+ !value.startsWith("/") ||
110
+ value.length > 4096) {
111
+ return null;
112
+ }
113
+ try {
114
+ const decoded = decodeURIComponent(value);
115
+ if (decoded.startsWith("//") || decoded.includes("\\") ||
116
+ hasControlCharacters(decoded)) {
117
+ return null;
118
+ }
119
+ const url = new URL(value, "https://local-test.invalid");
120
+ if (url.origin !== "https://local-test.invalid" ||
121
+ /^\/api(?:\/|$)/.test(decodeURIComponent(url.pathname))) {
122
+ return null;
123
+ }
124
+ return url.pathname + url.search + url.hash;
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ function contentLengthIsAllowed(request, maxBodyBytes) {
131
+ const value = request.headers.get("content-length");
132
+ if (value === null)
133
+ return true;
134
+ if (!/^(0|[1-9]\d*)$/.test(value))
135
+ return false;
136
+ return Number(value) <= maxBodyBytes;
137
+ }
138
+ async function readBoundedBody(request, maxBodyBytes) {
139
+ if (!request.body)
140
+ return "";
141
+ const reader = request.body.getReader();
142
+ const chunks = [];
143
+ let size = 0;
144
+ try {
145
+ while (true) {
146
+ const { done, value } = await reader.read();
147
+ if (done)
148
+ break;
149
+ size += value.byteLength;
150
+ if (size > maxBodyBytes) {
151
+ try {
152
+ await reader.cancel();
153
+ }
154
+ catch {
155
+ // The request is already rejected; a broken producer cannot escape.
156
+ }
157
+ return null;
158
+ }
159
+ chunks.push(value);
160
+ }
161
+ }
162
+ catch {
163
+ try {
164
+ await reader.cancel();
165
+ }
166
+ catch {
167
+ // The request is already rejected; a broken producer cannot escape.
168
+ }
169
+ return null;
170
+ }
171
+ finally {
172
+ try {
173
+ reader.releaseLock();
174
+ }
175
+ catch {
176
+ // A failed stream read is handled as invalid input below.
177
+ }
178
+ }
179
+ const body = new Uint8Array(size);
180
+ let offset = 0;
181
+ for (const chunk of chunks) {
182
+ body.set(chunk, offset);
183
+ offset += chunk.byteLength;
184
+ }
185
+ try {
186
+ return new TextDecoder("utf-8", { fatal: true }).decode(body);
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ function notFoundResponse() {
193
+ return new Response("Not found", { status: 404 });
194
+ }
195
+ function getSetCookieValues(headers) {
196
+ const getSetCookie = headers.getSetCookie;
197
+ if (getSetCookie)
198
+ return getSetCookie.call(headers);
199
+ const value = headers.get("set-cookie");
200
+ return value ? [value] : [];
201
+ }
202
+ /**
203
+ * Creates a POST-only, loopback-only Better Auth developer-login handler.
204
+ *
205
+ * All request/deployment guards run before the body is read, Better Auth hashes
206
+ * a credential, or the app provisioning callback can reach its database.
207
+ */
208
+ function createBetterAuthLocalTestLoginHandler(options) {
209
+ const enabled = isBetterAuthLocalTestLoginEnabled(options.env, options.optInEnvName);
210
+ const authBasePath = options.authBasePath ?? "/api/auth";
211
+ const maxBodyBytes = options.maxBodyBytes ??
212
+ exports.DEFAULT_BETTER_AUTH_LOCAL_TEST_LOGIN_MAX_BODY_BYTES;
213
+ if (!/^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(authBasePath)) {
214
+ throw new Error("Invalid Better Auth base path");
215
+ }
216
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) {
217
+ throw new Error("Invalid local test login body limit");
218
+ }
219
+ const passwords = new Map();
220
+ return async function localTestLogin(request) {
221
+ if (!enabled || request.method !== "POST")
222
+ return notFoundResponse();
223
+ const publicOrigin = requestLoopbackOrigin(request);
224
+ if (!publicOrigin)
225
+ return notFoundResponse();
226
+ const contentType = request.headers.get("content-type")?.split(";", 1)[0]
227
+ .trim().toLowerCase();
228
+ if (contentType !== "application/x-www-form-urlencoded" ||
229
+ !contentLengthIsAllowed(request, maxBodyBytes)) {
230
+ return new Response("Invalid request", { status: 400 });
231
+ }
232
+ const body = await readBoundedBody(request, maxBodyBytes);
233
+ if (body === null)
234
+ return new Response("Invalid request", { status: 400 });
235
+ const fields = new URLSearchParams(body);
236
+ const allowedFields = new Set(["identity", "callbackURL"]);
237
+ if ([...fields.keys()].some((key) => !allowedFields.has(key))) {
238
+ return new Response("Invalid request", { status: 400 });
239
+ }
240
+ const identityKeys = fields.getAll("identity");
241
+ const callbackValues = fields.getAll("callbackURL");
242
+ if (identityKeys.length !== 1 || callbackValues.length > 1) {
243
+ return new Response("Invalid request", { status: 400 });
244
+ }
245
+ const key = identityKeys[0];
246
+ if (!Object.prototype.hasOwnProperty.call(options.identities, key)) {
247
+ return new Response("Invalid request", { status: 400 });
248
+ }
249
+ const identity = options.identities[key];
250
+ const callbackURL = safeBetterAuthLocalTestCallbackURL(callbackValues[0], identity.defaultCallbackURL);
251
+ let password = passwords.get(key);
252
+ if (!password) {
253
+ password = identity.password?.trim() || randomLocalPassword();
254
+ passwords.set(key, password);
255
+ }
256
+ const context = await options.auth.$context;
257
+ const passwordHash = await context.password.hash(password);
258
+ await options.provisionIdentity({
259
+ identity,
260
+ key,
261
+ password,
262
+ passwordHash,
263
+ });
264
+ const signInHeaders = new Headers({
265
+ "content-type": "application/json",
266
+ origin: publicOrigin.origin,
267
+ });
268
+ const userAgent = request.headers.get("user-agent");
269
+ if (userAgent)
270
+ signInHeaders.set("user-agent", userAgent);
271
+ const signInResponse = await options.auth.handler(new Request(new URL(`${authBasePath}/sign-in/email`, publicOrigin), {
272
+ body: JSON.stringify({
273
+ email: identity.email,
274
+ password,
275
+ rememberMe: true,
276
+ }),
277
+ headers: signInHeaders,
278
+ method: "POST",
279
+ }));
280
+ if (!signInResponse.ok)
281
+ return signInResponse;
282
+ const responseHeaders = new Headers({ location: callbackURL });
283
+ for (const cookie of getSetCookieValues(signInResponse.headers)) {
284
+ responseHeaders.append("set-cookie", cookie);
285
+ }
286
+ return new Response(null, {
287
+ headers: responseHeaders,
288
+ status: 303,
289
+ });
290
+ };
291
+ }
@@ -1,3 +1,4 @@
1
1
  export * from "./config.js";
2
+ export * from "./localTestLogin.js";
2
3
  export * from "./server.js";
3
4
  //# sourceMappingURL=mod.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../../src/src/next/auth/mod.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC"}
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../../src/src/next/auth/mod.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC"}
@@ -15,4 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./config.js"), exports);
18
+ __exportStar(require("./localTestLogin.js"), exports);
18
19
  __exportStar(require("./server.js"), exports);
@@ -75,7 +75,9 @@ from the consumer's working directory.
75
75
  versions may write either an empty value or a redaction sentinel.
76
76
  - For external prebuilds, query Vercel env metadata, preserve usable pulled
77
77
  values, add unique build-only placeholders only for confirmed Sensitive
78
- entries, and reject an artifact containing any placeholder marker. Preserve an
78
+ entries, and reject any marker across the complete deployable artifact graph,
79
+ including contained symlinks and function `filePathMap` content. Prefer
80
+ `vercel build --standalone` for local prebuilt deployments. Preserve an
79
81
  untouched pull snapshot for migrations; once database variables are Sensitive,
80
82
  overlay a separately governed GitHub `MIGRATION_DATABASE_URL_UNPOOLED` secret
81
83
  only for migration validation and the migration command. Readable pulled URLs
@@ -102,6 +102,31 @@ The helper accepts only loopback hosts and origins by default. Do not spread it
102
102
  into production configuration or enable trusted proxy headers when requests can
103
103
  bypass or spoof the intended proxy boundary.
104
104
 
105
+ ## Local test login
106
+
107
+ Developer UI login is distinct from a production-build E2E auth harness. Use
108
+ `createBetterAuthLocalTestLoginHandler` only for a small app-owned POST route,
109
+ and use `isBetterAuthLocalTestLoginEnabled(process.env)` for both the Better
110
+ Auth email/password switch and server-rendered UI visibility.
111
+
112
+ The shared enablement helper requires `LOOM_LOCAL_TEST_LOGIN=1`, Next
113
+ development mode, and no Vercel runtime marker. Do not add the opt-in to
114
+ deployed environment settings. The handler separately requires the request URL,
115
+ Host, Origin, and any forwarded host/protocol values to be loopback-only, with
116
+ Origin matching the effective public Host. It accepts only a fixed identity key
117
+ and a same-origin application callback from a bounded URL-encoded body; email,
118
+ name, password, and grants must never come from request data.
119
+
120
+ Keep identity persistence and application authorization in the consumer's
121
+ `provisionIdentity` callback or a separate explicit fixture. The callback must
122
+ be idempotent and should update the credential record transactionally. A label
123
+ such as `admin` is not permission: preserve the app's existing grant boundary,
124
+ including separate grant/restore fixtures where they already exist.
125
+
126
+ Better Auth 1.7's `testUtils` can support production-build E2E through a
127
+ separate test-only auth instance without adding HTTP endpoints to the deployed
128
+ app. Keep that harness independent from this developer route.
129
+
105
130
  ## Verification
106
131
 
107
132
  - Run `loom check` and the consumer's typecheck/tests.
@@ -91,7 +91,11 @@ Use this skill when working on the shared DB stack from a consuming app.
91
91
  Sensitive values, and scan `.vercel/output` for those markers before uploading
92
92
  the prebuilt artifact. Prefer `loom db release prepare-build-env` and
93
93
  `loom db release verify-build-env`; keep only the declarative requirements
94
- policy app-local.
94
+ policy app-local. Prefer `vercel build --standalone` for local prebuilt
95
+ deployments so FileFsRef content is materialized inside the output. Loom also
96
+ scans contained symlinks and function `filePathMap` targets; pass the Vercel
97
+ deployment root as the optional third `verify-build-env` argument when a
98
+ monorepo's mappings are relative to a root above the app.
95
99
  - Use
96
100
  `loom db migrations verify-env --connect --env-file
97
101
  "$RUNNER_TEMP/vercel-production.env"`