@lowdefy/api 7.1.0 → 7.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.
Files changed (119) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +95 -21
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +163 -92
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -0,0 +1,303 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { timingSafeEqual } from 'node:crypto';
16
+ import { APIError } from 'better-auth/api';
17
+ import { type } from '@lowdefy/helpers';
18
+ import createMobileAuthPageResponse from './createMobileAuthPageResponse.js';
19
+ import createMobileSignInCsrfToken from './createMobileSignInCsrfToken.js';
20
+ import createPhoneSession from './createPhoneSession.js';
21
+ import escapeHtml from './escapeHtml.js';
22
+ import getMobileSignInReturnUrl from './getMobileSignInReturnUrl.js';
23
+ import isSameOriginRequest from '../../../context/isSameOriginRequest.js';
24
+ import mintOneTimeToken from './mintOneTimeToken.js';
25
+ import readMobileSignInParams from './readMobileSignInParams.js';
26
+ // Set when a signed-out person is sent from /auth/mobile to sign in, to the
27
+ // time they were sent. A browser session created after it was created inside
28
+ // this sign-in, for the phone, and is ended once the phone has its own.
29
+ const STARTED_COOKIE = 'lowdefy_mobile_sign_in_started';
30
+ const STARTED_COOKIE_MAX_AGE = 15 * 60;
31
+ // A confirmation form posts a CSRF token and a decision; anything larger is
32
+ // not one.
33
+ const MAX_BODY_LENGTH = 4096;
34
+ const NO_STORE_HEADERS = {
35
+ 'cache-control': 'no-store',
36
+ // The redirect target carries the one-time token; no Referer may echo it.
37
+ 'referrer-policy': 'no-referrer'
38
+ };
39
+ function textResponse({ message, status }) {
40
+ return new Response(message, {
41
+ status,
42
+ headers: {
43
+ ...NO_STORE_HEADERS,
44
+ 'content-type': 'text/plain; charset=utf-8'
45
+ }
46
+ });
47
+ }
48
+ function redirect({ location, status = 302, cookie }) {
49
+ const headers = new Headers({
50
+ ...NO_STORE_HEADERS,
51
+ location
52
+ });
53
+ if (!type.isNone(cookie)) {
54
+ headers.append('set-cookie', cookie);
55
+ }
56
+ return new Response(null, {
57
+ status,
58
+ headers
59
+ });
60
+ }
61
+ function startedCookie({ url, value, maxAge }) {
62
+ const secure = url.protocol === 'https:' ? '; Secure' : '';
63
+ return `${STARTED_COOKIE}=${value}; Path=${url.pathname}; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure}`;
64
+ }
65
+ function readStartedAt({ request }) {
66
+ const pair = (request.headers.get('cookie') ?? '').split(';').map((part)=>part.trim()).find((part)=>part.startsWith(`${STARTED_COOKIE}=`));
67
+ if (type.isNone(pair)) {
68
+ return null;
69
+ }
70
+ const startedAt = Number(pair.slice(STARTED_COOKIE.length + 1));
71
+ return Number.isFinite(startedAt) ? startedAt : null;
72
+ }
73
+ function tokensMatch(expected, received) {
74
+ if (!type.isString(received)) {
75
+ return false;
76
+ }
77
+ const expectedBuffer = Buffer.from(expected);
78
+ const receivedBuffer = Buffer.from(received);
79
+ return expectedBuffer.length === receivedBuffer.length && timingSafeEqual(expectedBuffer, receivedBuffer);
80
+ }
81
+ function renderConfirmation({ appName, csrfToken, params, primaryColor, session, url }) {
82
+ const app = escapeHtml(appName);
83
+ const account = session.user.email ?? session.user.name;
84
+ const asAccount = type.isNone(account) ? '' : ` as ${escapeHtml(account)}`;
85
+ return createMobileAuthPageResponse({
86
+ title: `Sign in to ${app}`,
87
+ primaryColor,
88
+ // Its url carries no secret (the shell, state and code challenge), and
89
+ // the Continue post must carry the page's real Origin.
90
+ referrerPolicy: 'same-origin',
91
+ content: `<h1>Sign in to ${app} on this device?</h1>
92
+ <p>The ${escapeHtml(params.shell.id)} app is asking to sign in${asAccount}. Continue only if you opened this from that app.</p>
93
+ <form method="post" action="${escapeHtml(`${url.pathname}${url.search}`)}">
94
+ <input type="hidden" name="csrf_token" value="${escapeHtml(csrfToken)}" />
95
+ <button class="primary" type="submit" name="decision" value="continue">Continue</button>
96
+ <button class="secondary" type="submit" name="decision" value="cancel">Cancel</button>
97
+ </form>`
98
+ });
99
+ }
100
+ // POST /auth/mobile - the confirmation page's Continue or Cancel. Only a
101
+ // same-origin post from that page, shown to this browser session for this
102
+ // sign-in, is accepted: the Origin (and Sec-Fetch-Site) must be the app's own
103
+ // (the request's host, or the pinned canonical origin behind a proxy that
104
+ // rewrites Host), and the CSRF token must be the page's. The session cookie is SameSite, so a
105
+ // cross-site post carries none.
106
+ //
107
+ // Continue creates a new session for the phone (createPhoneSession), mints the
108
+ // one-time token for it, bound to the shell's code challenge, and returns it
109
+ // to the shell. A browser session created inside this sign-in is then ended;
110
+ // the person's existing browser session is left as it is. Cancel returns
111
+ // error=cancelled.
112
+ async function confirmMobileSignIn({ auth, authJson, params, request, session, url }) {
113
+ const sameOrigin = isSameOriginRequest({
114
+ getHeader: (name)=>request.headers.get(name),
115
+ publicOrigins: type.isString(auth.options?.baseURL) ? [
116
+ auth.options.baseURL
117
+ ] : []
118
+ });
119
+ if (!sameOrigin) {
120
+ return textResponse({
121
+ message: 'Forbidden.',
122
+ status: 403
123
+ });
124
+ }
125
+ const body = await request.text();
126
+ if (body.length > MAX_BODY_LENGTH) {
127
+ return textResponse({
128
+ message: 'Request too large.',
129
+ status: 413
130
+ });
131
+ }
132
+ const form = new URLSearchParams(body);
133
+ const { secret, adapter } = await auth.$context;
134
+ const csrfToken = createMobileSignInCsrfToken({
135
+ params,
136
+ secret,
137
+ sessionId: session.session.id
138
+ });
139
+ if (!tokensMatch(csrfToken, form.get('csrf_token'))) {
140
+ return textResponse({
141
+ message: 'Forbidden.',
142
+ status: 403
143
+ });
144
+ }
145
+ const clearStarted = startedCookie({
146
+ url,
147
+ value: '',
148
+ maxAge: 0
149
+ });
150
+ if (form.get('decision') !== 'continue') {
151
+ const query = new URLSearchParams({
152
+ error: 'cancelled',
153
+ state: params.state
154
+ });
155
+ return redirect({
156
+ location: getMobileSignInReturnUrl({
157
+ auth,
158
+ params,
159
+ query,
160
+ url
161
+ }),
162
+ status: 303,
163
+ cookie: clearStarted
164
+ });
165
+ }
166
+ let phoneSession;
167
+ try {
168
+ phoneSession = await createPhoneSession({
169
+ auth,
170
+ authJson,
171
+ browserSession: session,
172
+ request
173
+ });
174
+ } catch (error) {
175
+ // The organization policy refused the person (or could not decide). Logged and answered as
176
+ // BetterAuth's own routes answer an APIError: through onAPIError.onError (createOnAPIError),
177
+ // one warn line for a refusal, an error line for anything else, with the error's status.
178
+ if (error instanceof APIError) {
179
+ auth.options.onAPIError.onError(error);
180
+ return textResponse({
181
+ message: error.message,
182
+ status: error.statusCode
183
+ });
184
+ }
185
+ throw error;
186
+ }
187
+ const token = await mintOneTimeToken({
188
+ auth,
189
+ codeChallenge: params.codeChallenge,
190
+ sessionToken: phoneSession.token
191
+ });
192
+ const startedAt = readStartedAt({
193
+ request
194
+ });
195
+ if (!type.isNone(startedAt) && new Date(session.session.createdAt).getTime() >= startedAt) {
196
+ await adapter.delete({
197
+ model: 'session',
198
+ where: [
199
+ {
200
+ field: 'id',
201
+ value: session.session.id
202
+ }
203
+ ]
204
+ });
205
+ }
206
+ const query = new URLSearchParams({
207
+ token,
208
+ state: params.state
209
+ });
210
+ return redirect({
211
+ location: getMobileSignInReturnUrl({
212
+ auth,
213
+ params,
214
+ query,
215
+ url
216
+ }),
217
+ status: 303,
218
+ cookie: clearStarted
219
+ });
220
+ }
221
+ // /auth/mobile?shell=<id>&state=<s>&code_challenge=<c>&code_challenge_method=S256&platform=<p>
222
+ // - the page a phone shell opens in a system sign-in sheet for every sign-in
223
+ // method the app offers (passkeys, SSO, magic links, a second factor). The
224
+ // query is checked first (readMobileSignInParams); a bad one answers 400.
225
+ //
226
+ // - GET, signed out: redirect to the app's sign-in page, whose callbackUrl
227
+ // brings the person back here once they are, and note when they were sent.
228
+ // - GET, signed in: a confirmation page, "Sign in to <app> on this device?",
229
+ // naming the shell and the account, with Continue and Cancel. A GET never
230
+ // mints a token, so an app that opens this page itself can not take a
231
+ // session silently: the person sees which app is asking and can cancel.
232
+ // - POST: the confirmation (confirmMobileSignIn).
233
+ //
234
+ // The session is read from the database, not the cookie cache, so a session
235
+ // ended a moment ago is never used.
236
+ async function handleMobileSignIn({ auth, authJson, basePath, primaryColor, request }) {
237
+ if (type.isNone(auth)) {
238
+ return textResponse({
239
+ message: 'Auth is not configured.',
240
+ status: 404
241
+ });
242
+ }
243
+ const url = new URL(request.url);
244
+ const { error, params } = readMobileSignInParams({
245
+ authJson,
246
+ url,
247
+ userAgent: request.headers.get('user-agent') ?? ''
248
+ });
249
+ if (!type.isNone(error)) {
250
+ return textResponse({
251
+ message: error,
252
+ status: 400
253
+ });
254
+ }
255
+ const { headers } = request;
256
+ const session = await auth.api.getSession({
257
+ headers,
258
+ query: {
259
+ disableCookieCache: true
260
+ }
261
+ });
262
+ if (request.method === 'POST') {
263
+ if (type.isNone(session)) {
264
+ return textResponse({
265
+ message: 'Sign in again from the app.',
266
+ status: 403
267
+ });
268
+ }
269
+ return confirmMobileSignIn({
270
+ auth,
271
+ authJson,
272
+ params,
273
+ request,
274
+ session,
275
+ url
276
+ });
277
+ }
278
+ if (type.isNone(session)) {
279
+ const callbackUrl = `${url.pathname}${url.search}`;
280
+ return redirect({
281
+ location: `${basePath}${authJson.authPages.signIn}?callbackUrl=${encodeURIComponent(callbackUrl)}`,
282
+ cookie: startedCookie({
283
+ url,
284
+ value: Date.now(),
285
+ maxAge: STARTED_COOKIE_MAX_AGE
286
+ })
287
+ });
288
+ }
289
+ const { secret } = await auth.$context;
290
+ return renderConfirmation({
291
+ appName: auth.options?.appName ?? 'this app',
292
+ csrfToken: createMobileSignInCsrfToken({
293
+ params,
294
+ secret,
295
+ sessionId: session.session.id
296
+ }),
297
+ params,
298
+ primaryColor,
299
+ session,
300
+ url
301
+ });
302
+ }
303
+ export default handleMobileSignIn;
@@ -0,0 +1,30 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import createMobileAuthPageResponse from './createMobileAuthPageResponse.js';
16
+ // GET /auth/mobile/callback - the Android app link the sign-in sheet returns
17
+ // to (getMobileSignInReturnUrl). Android opens it in the shell when the link
18
+ // is verified (assetlinks.json), so this page shows only when it is not: it
19
+ // asks the person to go back to the app. It never shows the query, and its
20
+ // script takes the one-time token out of the address bar and history.
21
+ function handleMobileSignInCallback({ primaryColor }) {
22
+ return createMobileAuthPageResponse({
23
+ title: 'Return to the app',
24
+ primaryColor,
25
+ script: 'history.replaceState(null, "", location.pathname);',
26
+ content: `<h1>Return to the app</h1>
27
+ <p>Go back to the app to finish signing in.</p>`
28
+ });
29
+ }
30
+ export default handleMobileSignInCallback;
@@ -0,0 +1,33 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // A request from a phone shell's own code: an HTTP request that names the shell
17
+ // (x-lowdefy-shell, sent on every shell call by withShellHeader) and carries
18
+ // no Origin, Cookie or Sec-Fetch-Mode header. A browser sends Origin on every
19
+ // fetch that can change state, but not on a same-origin GET, and page script
20
+ // can leave cookies off with `credentials: 'omit'`; Sec-Fetch-Mode it sends on
21
+ // every request and script cannot remove, so a browser's script never counts
22
+ // as native. A phone's HTTP stack sends none of the three.
23
+ // A top-level navigation (a magic link opened in a browser with no cookies for
24
+ // the site) sends neither either, but cannot add a header, so it never counts.
25
+ // Shells keep no cookie jar (they send the session as a bearer), so their
26
+ // requests carry no Cookie.
27
+ function isNativeAuthRequest({ request }) {
28
+ if (type.isNone(request)) {
29
+ return false;
30
+ }
31
+ return request.headers.has('x-lowdefy-shell') && !request.headers.has('origin') && !request.headers.has('cookie') && !request.headers.has('sec-fetch-mode');
32
+ }
33
+ export default isNativeAuthRequest;
@@ -0,0 +1,29 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import sha256Base64Url from './sha256Base64Url.js';
17
+ // RFC 7636 section 4.1: 43 to 128 unreserved characters.
18
+ const CODE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
19
+ // Whether a PKCE code verifier is the one an S256 code challenge was made from.
20
+ function matchesCodeChallenge({ codeChallenge, codeVerifier }) {
21
+ if (!type.isString(codeChallenge) || !type.isString(codeVerifier)) {
22
+ return false;
23
+ }
24
+ if (!CODE_VERIFIER.test(codeVerifier)) {
25
+ return false;
26
+ }
27
+ return sha256Base64Url(codeVerifier) === codeChallenge;
28
+ }
29
+ export default matchesCodeChallenge;
@@ -0,0 +1,41 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { generateRandomString } from 'better-auth/crypto';
16
+ import getOneTimeTokenIdentifiers from './getOneTimeTokenIdentifiers.js';
17
+ import storeCodeChallenge from './storeCodeChallenge.js';
18
+ // Mints the one-time token for the phone's session, the record BetterAuth's
19
+ // one-time-token plugin verifies at /one-time-token/verify: the session token
20
+ // under the hashed one-time token (storeToken: 'hashed'), for one minute. The
21
+ // plugin's own generate endpoint mints for the caller's session, which is the
22
+ // browser's; the phone gets a session of its own (createPhoneSession). The
23
+ // token is bound to the shell's PKCE code challenge.
24
+ async function mintOneTimeToken({ auth, codeChallenge, sessionToken }) {
25
+ const { internalAdapter } = await auth.$context;
26
+ const token = generateRandomString(32);
27
+ await internalAdapter.createVerificationValue({
28
+ identifier: getOneTimeTokenIdentifiers({
29
+ token
30
+ }).token,
31
+ value: sessionToken,
32
+ expiresAt: new Date(Date.now() + 60 * 1000)
33
+ });
34
+ await storeCodeChallenge({
35
+ auth,
36
+ codeChallenge,
37
+ token
38
+ });
39
+ return token;
40
+ }
41
+ export default mintOneTimeToken;
@@ -0,0 +1,34 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import isNativeAuthRequest from './isNativeAuthRequest.js';
16
+ import sha256Base64Url from './sha256Base64Url.js';
17
+ const DEVICE_KEY = /^[A-Za-z0-9_-]{32,128}$/;
18
+ // The SHA-256 of the per-phone device key a shell sends on its email-code calls
19
+ // (x-lowdefy-device-key), or null when the request is not a shell's own or carries
20
+ // no well-formed key. The key is a secret only that phone holds, so the server
21
+ // keeps only its hash.
22
+ function readDeviceKeyHash({ request }) {
23
+ if (!isNativeAuthRequest({
24
+ request
25
+ })) {
26
+ return null;
27
+ }
28
+ const key = request.headers.get('x-lowdefy-device-key');
29
+ if (key === null || !DEVICE_KEY.test(key)) {
30
+ return null;
31
+ }
32
+ return sha256Base64Url(key);
33
+ }
34
+ export default readDeviceKeyHash;
@@ -0,0 +1,90 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // A state longer than this is not a shell's: shells send a short random value.
17
+ const STATE_MAX_LENGTH = 512;
18
+ // An S256 code challenge (RFC 7636): base64url(SHA-256(verifier)), unpadded.
19
+ const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
20
+ const PLATFORMS = new Set([
21
+ 'android',
22
+ 'ios'
23
+ ]);
24
+ // The query a phone shell opens /auth/mobile with:
25
+ // ?shell=<id>&state=<s>&code_challenge=<c>&code_challenge_method=S256&platform=ios|android
26
+ //
27
+ // - The shell must be one listed in mobile.shells, so the token only ever goes
28
+ // to that shell's scheme or app link.
29
+ // - The shell must send a PKCE S256 code challenge. The challenge is stored
30
+ // with the one-time token, and the exchange needs its verifier
31
+ // (createCodeVerifierCheck).
32
+ // - platform picks the return: iOS's ASWebAuthenticationSession hands the
33
+ // shell's scheme only to the app that opened it, while on Android any app can
34
+ // register a scheme, so an Android shell gets the token by its verified app
35
+ // link and must have one (an android package and sha256 in mobile.shells).
36
+ // The query is the caller's to choose, so an Android browser asking for the
37
+ // iOS (scheme) return is refused: an app on Android could otherwise open a
38
+ // Custom Tab, which shares the browser's session, and take the token by the
39
+ // shell's scheme. A Custom Tab's user agent is the browser's own, which the
40
+ // app cannot set.
41
+ //
42
+ // Returns { params } or { error } (the 400 message).
43
+ function readMobileSignInParams({ authJson, url, userAgent = '' }) {
44
+ const { searchParams } = url;
45
+ const shellId = searchParams.get('shell');
46
+ const state = searchParams.get('state');
47
+ const codeChallenge = searchParams.get('code_challenge');
48
+ const codeChallengeMethod = searchParams.get('code_challenge_method');
49
+ const platform = searchParams.get('platform');
50
+ const shell = (authJson.mobile?.shells ?? []).find((each)=>each.id === shellId);
51
+ if (type.isNone(shell)) {
52
+ return {
53
+ error: 'Unknown shell.'
54
+ };
55
+ }
56
+ if (!type.isString(state) || state.length === 0 || state.length > STATE_MAX_LENGTH) {
57
+ return {
58
+ error: 'The shell must send a state.'
59
+ };
60
+ }
61
+ if (codeChallengeMethod !== 'S256' || !CODE_CHALLENGE.test(codeChallenge ?? '')) {
62
+ return {
63
+ error: 'The shell must send an S256 code_challenge (PKCE).'
64
+ };
65
+ }
66
+ if (!PLATFORMS.has(platform)) {
67
+ return {
68
+ error: 'The shell must send its platform, ios or android.'
69
+ };
70
+ }
71
+ if (platform === 'ios' && /\bAndroid\b/i.test(userAgent)) {
72
+ return {
73
+ error: 'An Android browser must ask for the android return.'
74
+ };
75
+ }
76
+ if (platform === 'android' && shell.androidAppLink !== true) {
77
+ return {
78
+ error: `Shell "${shell.id}" has no Android app link. Set its android package and sha256 in mobile.shells.`
79
+ };
80
+ }
81
+ return {
82
+ params: {
83
+ codeChallenge,
84
+ platform,
85
+ shell,
86
+ state
87
+ }
88
+ };
89
+ }
90
+ export default readMobileSignInParams;
@@ -0,0 +1,22 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { createHash } from 'node:crypto';
16
+ // base64url(SHA-256(value)), unpadded: a PKCE S256 code challenge for a
17
+ // verifier (RFC 7636), and the key BetterAuth's one-time-token plugin stores a
18
+ // hashed token under (its defaultKeyHasher).
19
+ function sha256Base64Url(value) {
20
+ return createHash('sha256').update(value).digest('base64url');
21
+ }
22
+ export default sha256Base64Url;
@@ -0,0 +1,29 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import getOneTimeTokenIdentifiers from './getOneTimeTokenIdentifiers.js';
16
+ // Binds a one-time token to the shell's PKCE code challenge, for the code
17
+ // verifier check on /one-time-token/verify (createCodeVerifierCheck). It
18
+ // expires with the token, a minute after minting (buildOneTimeTokenPlugin).
19
+ async function storeCodeChallenge({ auth, codeChallenge, token }) {
20
+ const { internalAdapter } = await auth.$context;
21
+ await internalAdapter.createVerificationValue({
22
+ identifier: getOneTimeTokenIdentifiers({
23
+ token
24
+ }).challenge,
25
+ value: codeChallenge,
26
+ expiresAt: new Date(Date.now() + 60 * 1000)
27
+ });
28
+ }
29
+ export default storeCodeChallenge;