@protobase/server 0.26.9 → 0.28.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/dist/admin-options.d.ts +2 -2
- package/dist/api-cors.js +14 -3
- package/dist/app-identity.d.ts +12 -0
- package/dist/app-name.d.ts +4 -0
- package/dist/app-name.js +4 -2
- package/dist/better-auth/create-auth.d.ts +6 -5
- package/dist/better-auth/create-auth.js +7 -7
- package/dist/better-auth/origins.js +6 -1
- package/dist/better-auth/passkey-plugin.js +5 -5
- package/dist/create-admin.d.ts +13 -1
- package/dist/create-admin.js +6 -5
- package/dist/gotrue/provider-flows.js +42 -0
- package/dist/gotrue/provider-routes.js +39 -25
- package/dist/index.d.ts +5 -1
- package/dist/index.js +3 -1
- package/dist/meta.js +2 -1
- package/dist/mobile-config.d.ts +9 -0
- package/dist/mobile-config.js +8 -0
- package/dist/project-config.d.ts +6 -0
- package/dist/project-config.js +6 -2
- package/dist/web-app/app-icons.d.ts +31 -0
- package/dist/web-app/app-icons.js +26 -0
- package/dist/web-app/web-manifest-route.js +2 -2
- package/dist/web-app/web-manifest.js +22 -3
- package/package.json +4 -4
package/dist/admin-options.d.ts
CHANGED
|
@@ -55,8 +55,8 @@ export type AdminOptions = {
|
|
|
55
55
|
/**
|
|
56
56
|
* The websites whose browser code may call the API (`/api/*` but `/api/auth/*`) besides the app's own origins (see
|
|
57
57
|
* `createAuth`'s `origins`): a list of origins, or `*` for any. Defaults to the one the platform passes in
|
|
58
|
-
* `PROTOBASE_CORS_ORIGINS` (`*` or comma separated), when set.
|
|
59
|
-
* CORS headers.
|
|
58
|
+
* `PROTOBASE_CORS_ORIGINS` (`*` or comma separated), when set. A `mobile` section adds the app's Capacitor origins
|
|
59
|
+
* (`capacitor://localhost`, `https://localhost`). With none of these nor other origins, the API sends no CORS headers.
|
|
60
60
|
*/
|
|
61
61
|
cors?: CorsOrigins;
|
|
62
62
|
/** The runtime updates endpoint behind the top bar's update button (see `RuntimeOptions`); `false` turns it off. */
|
package/dist/api-cors.js
CHANGED
|
@@ -1,17 +1,28 @@
|
|
|
1
1
|
import { readList } from "./better-auth/origins.js";
|
|
2
|
+
import { capacitorOrigins } from "./mobile-config.js";
|
|
2
3
|
import { cors } from "hono/cors";
|
|
3
4
|
//#region src/api-cors.ts
|
|
4
5
|
const corsOriginsVariable = "PROTOBASE_CORS_ORIGINS";
|
|
5
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* The origins in `PROTOBASE_CORS_ORIGINS`, `*` or comma separated; `undefined` when it is unset. One that is not an
|
|
8
|
+
* http or https URL stops the server at startup: another scheme, such as `capacitor:`, has the origin `null`.
|
|
9
|
+
*/
|
|
6
10
|
const readCorsOrigins = (env) => {
|
|
7
11
|
const value = env[corsOriginsVariable]?.trim();
|
|
8
12
|
if (!value) return void 0;
|
|
9
13
|
if (value === "*") return "*";
|
|
10
14
|
return readList(value).map((origin) => {
|
|
11
15
|
if (!URL.canParse(origin)) throw new Error(`${corsOriginsVariable} lists "${origin}", which is not a URL such as https://shop.com`);
|
|
12
|
-
|
|
16
|
+
const url = new URL(origin);
|
|
17
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${corsOriginsVariable} lists "${origin}", but it takes http and https origins only; a mobile section in protobase.config.ts allows the app's Capacitor origins`);
|
|
18
|
+
return url.origin;
|
|
13
19
|
});
|
|
14
20
|
};
|
|
21
|
+
/** The allowed origins plus the Capacitor ones when the app has a mobile section; `*` stays `*`. */
|
|
22
|
+
const withMobileOrigins = (allowed, mobile) => {
|
|
23
|
+
if (!mobile || allowed === "*") return allowed;
|
|
24
|
+
return [.../* @__PURE__ */ new Set([...allowed ?? [], ...capacitorOrigins])];
|
|
25
|
+
};
|
|
15
26
|
const allowHeaders = [
|
|
16
27
|
"authorization",
|
|
17
28
|
"content-type",
|
|
@@ -53,4 +64,4 @@ const apiCors = ({ own, allowed, skip }) => {
|
|
|
53
64
|
return (c, next) => skip(c.req.path) ? next() : handler(c, next);
|
|
54
65
|
};
|
|
55
66
|
//#endregion
|
|
56
|
-
export { apiCors, corsOriginsVariable, readCorsOrigins };
|
|
67
|
+
export { apiCors, corsOriginsVariable, readCorsOrigins, withMobileOrigins };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/app-identity.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The `app` section of `protobase.config.ts`: the colours the installed app shows, beside its name (`createAuth`'s
|
|
4
|
+
* `appName`) and its icons (`protobase.favicon.svg` and the PNGs beside it). Any CSS colour, such as `#0d9488`.
|
|
5
|
+
*/
|
|
6
|
+
export type AppIdentity = {
|
|
7
|
+
/** The colour of the installed app's title bar and of the browser's toolbar around it. */
|
|
8
|
+
themeColor?: string;
|
|
9
|
+
/** The colour of the screen an installed app shows while it starts. */
|
|
10
|
+
backgroundColor?: string;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
package/dist/app-name.js
CHANGED
|
@@ -4,8 +4,10 @@ const appNameVariable = "PROTOBASE_APP_NAME";
|
|
|
4
4
|
const defaultAppName = "Protobase";
|
|
5
5
|
/**
|
|
6
6
|
* The app's name the platform passes in `PROTOBASE_APP_NAME`, such as `Property Finder`; `undefined` when it is not
|
|
7
|
-
* set. Protobase names the app with it in sign-in prompts and in the mail it sends,
|
|
7
|
+
* set. Protobase names the app with it in sign-in prompts and in the mail it sends, over the name the app gives itself.
|
|
8
8
|
*/
|
|
9
9
|
const readAppName = (env) => env["PROTOBASE_APP_NAME"]?.trim() || void 0;
|
|
10
|
+
/** The name the app goes by: the platform's `PROTOBASE_APP_NAME`, which deployments rename it with, over its own `own`. */
|
|
11
|
+
const appNameOver = (env, own) => readAppName(env) ?? own;
|
|
10
12
|
//#endregion
|
|
11
|
-
export { appNameVariable, defaultAppName, readAppName };
|
|
13
|
+
export { appNameOver, appNameVariable, defaultAppName, readAppName };
|
|
@@ -34,8 +34,9 @@ export type CreateAuthOptions = {
|
|
|
34
34
|
passkeyDomain?: string;
|
|
35
35
|
/**
|
|
36
36
|
* The app's name: authenticator apps and passkey prompts show it, the auth emails name the app with it, and the
|
|
37
|
-
* default mailer sends them from it, as the sender's display name
|
|
38
|
-
* `PROTOBASE_APP_NAME`, when set,
|
|
37
|
+
* default mailer sends them from it, as the sender's display name; the tab titles, the sidebar's logo and the
|
|
38
|
+
* installed app show it too. The name the platform passes in `PROTOBASE_APP_NAME`, when set, overrides it; without
|
|
39
|
+
* either it is `Protobase` (without a sender's display name).
|
|
39
40
|
*/
|
|
40
41
|
appName?: string;
|
|
41
42
|
/** Signs cookies and encrypts the JWT private keys. Generate with `openssl rand -base64 32`. */
|
|
@@ -1294,7 +1295,7 @@ export declare const createAuth: (options: CreateAuthOptions) => import("better-
|
|
|
1294
1295
|
email: string;
|
|
1295
1296
|
emailVerified: boolean;
|
|
1296
1297
|
name: string;
|
|
1297
|
-
image
|
|
1298
|
+
image? /** Signs cookies and encrypts the JWT private keys. Generate with `openssl rand -base64 32`. */ : string | null | undefined;
|
|
1298
1299
|
};
|
|
1299
1300
|
};
|
|
1300
1301
|
}>>[];
|
|
@@ -1347,7 +1348,7 @@ export declare const createAuth: (options: CreateAuthOptions) => import("better-
|
|
|
1347
1348
|
$Infer: {
|
|
1348
1349
|
body: {
|
|
1349
1350
|
token: string;
|
|
1350
|
-
issuer
|
|
1351
|
+
issuer?: string;
|
|
1351
1352
|
};
|
|
1352
1353
|
response: {
|
|
1353
1354
|
payload: {
|
|
@@ -5971,7 +5972,7 @@ export declare const createAuth: (options: CreateAuthOptions) => import("better-
|
|
|
5971
5972
|
/** The app keeps each user's metadata, in the column `users.metadata` names. */
|
|
5972
5973
|
userMetadata: boolean;
|
|
5973
5974
|
socialProviders: string[];
|
|
5974
|
-
/** The app's name it signs in and mails as: `
|
|
5975
|
+
/** The app's name it signs in and mails as: `PROTOBASE_APP_NAME`, else `appName`, else `Protobase`. */
|
|
5975
5976
|
appName: string;
|
|
5976
5977
|
operator: string | undefined;
|
|
5977
5978
|
platformSignIn: {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { multiHostBaseURL, readOrigins, resolveOrigins } from "./origins.js";
|
|
2
|
-
import {
|
|
1
|
+
import { appOrigins, multiHostBaseURL, readOrigins, resolveOrigins } from "./origins.js";
|
|
2
|
+
import { appNameOver, defaultAppName } from "../app-name.js";
|
|
3
3
|
import { goTrueIssuer, goTrueKeyPair } from "../gotrue/keys.js";
|
|
4
4
|
import { roleDefinitions } from "./organizations/role-definitions.js";
|
|
5
5
|
import { narrowClaims } from "./roles/active-role.js";
|
|
@@ -38,7 +38,6 @@ const platformOperator = () => readOperatorSettings(globalThis.process?.env ?? {
|
|
|
38
38
|
const platformSignInSettings = () => readPlatformSignIn(globalThis.process?.env ?? {});
|
|
39
39
|
const platformOrigins = () => readOrigins(globalThis.process?.env ?? {});
|
|
40
40
|
const platformPasskeyDomain = () => readPasskeyDomain(globalThis.process?.env ?? {});
|
|
41
|
-
const platformAppName = () => readAppName(globalThis.process?.env ?? {});
|
|
42
41
|
const tokenLifetime = "15m";
|
|
43
42
|
/**
|
|
44
43
|
* Better Auth for a single-tenant admin: sign-in with a password, an emailed code or a passkey, two-factor
|
|
@@ -148,7 +147,8 @@ const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, defini
|
|
|
148
147
|
passkeyPlugin({
|
|
149
148
|
domain: passkeyDomain ?? hosts[0],
|
|
150
149
|
hosts,
|
|
151
|
-
formerDomain: hosts[0]
|
|
150
|
+
formerDomain: hosts[0],
|
|
151
|
+
origins: appOrigins(options.baseURL, origins)
|
|
152
152
|
}),
|
|
153
153
|
...mail ? [emailOTP(emailCodeOptions(mail))] : [],
|
|
154
154
|
...mail && signUpRole ? [signUpPlugin({
|
|
@@ -275,7 +275,7 @@ const createAuth = (options) => {
|
|
|
275
275
|
const signUpRole = options.signUp && checkSignUpRole(options.signUp.role, roles);
|
|
276
276
|
const others = roles.filter((role) => role !== "admin");
|
|
277
277
|
const defaultRole = options.defaultRole ?? (options.organizations ? "user" : others.length === 1 ? others[0] : void 0);
|
|
278
|
-
const appName =
|
|
278
|
+
const appName = appNameOver(globalThis.process?.env ?? {}, options.appName);
|
|
279
279
|
const mailer = options.mailer === void 0 ? platformMailer(void 0, appName) : options.mailer || void 0;
|
|
280
280
|
const provider = options.operator === void 0 ? platformOperator() : options.operator || void 0;
|
|
281
281
|
const operator = provider && resolveOperator(provider);
|
|
@@ -310,7 +310,7 @@ const createAuth = (options) => {
|
|
|
310
310
|
/** Issuer and audience of the tokens: `baseURL`, on every origin. */
|
|
311
311
|
issuer: options.baseURL,
|
|
312
312
|
/** Every origin the app is served on, `baseURL`'s first. */
|
|
313
|
-
origins:
|
|
313
|
+
origins: appOrigins(options.baseURL, origins),
|
|
314
314
|
/** The RP ID of new passkeys. */
|
|
315
315
|
passkeyDomain,
|
|
316
316
|
roles,
|
|
@@ -328,7 +328,7 @@ const createAuth = (options) => {
|
|
|
328
328
|
/** The app keeps each user's metadata, in the column `users.metadata` names. */
|
|
329
329
|
userMetadata: Boolean(options.users?.metadata),
|
|
330
330
|
socialProviders,
|
|
331
|
-
/** The app's name it signs in and mails as: `
|
|
331
|
+
/** The app's name it signs in and mails as: `PROTOBASE_APP_NAME`, else `appName`, else `Protobase`. */
|
|
332
332
|
appName: appName ?? "Protobase",
|
|
333
333
|
operator: operator?.name,
|
|
334
334
|
platformSignIn: platformSignIn && {
|
|
@@ -24,6 +24,11 @@ const resolveOrigins = (baseURL, origins) => {
|
|
|
24
24
|
return [...new Set(resolved)].filter((origin) => origin !== base.origin);
|
|
25
25
|
};
|
|
26
26
|
/**
|
|
27
|
+
* Every origin the app is served on: `baseURL`'s, then the others from `resolveOrigins`. The only origins a passkey's
|
|
28
|
+
* answer may name, and the list `/.well-known/webauthn` serves; never empty.
|
|
29
|
+
*/
|
|
30
|
+
const appOrigins = (baseURL, origins) => [new URL(baseURL).origin, ...origins];
|
|
31
|
+
/**
|
|
27
32
|
* Better Auth's `baseURL` for an app on several origins: each request is answered for its own host when that is one of
|
|
28
33
|
* them (its links, such as a password reset, and its passkey and sign-in callbacks then stay on that host), and for
|
|
29
34
|
* `baseURL` otherwise. With no other origins it is `baseURL` itself.
|
|
@@ -40,4 +45,4 @@ const multiHostBaseURL = (baseURL, origins) => {
|
|
|
40
45
|
/** Where browsers read which origins may use the app's passkeys (WebAuthn Related Origin Requests). */
|
|
41
46
|
const webauthnPath = "/.well-known/webauthn";
|
|
42
47
|
//#endregion
|
|
43
|
-
export { multiHostBaseURL, originsVariable, readList, readOrigins, resolveOrigins, webauthnPath };
|
|
48
|
+
export { appOrigins, multiHostBaseURL, originsVariable, readList, readOrigins, resolveOrigins, webauthnPath };
|
|
@@ -18,11 +18,13 @@ const decodeBase64 = (value) => Uint8Array.from(atob(value), (char) => char.char
|
|
|
18
18
|
* RP ID it was made with, so changing the passkey domain breaks none. A sign-in asks the browser for passkeys of one RP
|
|
19
19
|
* ID, `?rpId=` or the passkey domain, and checks the passkey it gets against its own. On an app with several origins,
|
|
20
20
|
* browsers let each origin use the passkeys of the others through `/.well-known/webauthn` (Related Origin Requests).
|
|
21
|
+
* Adding a passkey and signing in with one both accept only an answer that names one of the app's own origins.
|
|
21
22
|
*/
|
|
22
|
-
const passkeyPlugin = ({ domain, hosts, formerDomain }) => {
|
|
23
|
+
const passkeyPlugin = ({ domain, hosts, formerDomain, origins }) => {
|
|
23
24
|
const base = passkey({
|
|
24
25
|
schema: pluginNames.passkey,
|
|
25
|
-
rpID: domain
|
|
26
|
+
rpID: domain,
|
|
27
|
+
origin: origins
|
|
26
28
|
});
|
|
27
29
|
const rpIDOf = (stored) => stored.rpID ?? formerDomain;
|
|
28
30
|
/** `GET /passkey/generate-authenticate-options?rpId=`: what the browser needs to ask for a passkey of that RP ID. */
|
|
@@ -70,8 +72,6 @@ const passkeyPlugin = ({ domain, hosts, formerDomain }) => {
|
|
|
70
72
|
method: "POST",
|
|
71
73
|
body: z$1.object({ response: z$1.record(z$1.any(), z$1.any()) })
|
|
72
74
|
}, async (ctx) => {
|
|
73
|
-
const origin = ctx.headers?.get("origin");
|
|
74
|
-
if (!origin) throw new APIError("BAD_REQUEST", { message: "origin missing" });
|
|
75
75
|
const response = ctx.body.response;
|
|
76
76
|
const cookie = ctx.context.createAuthCookie(challengeCookie);
|
|
77
77
|
const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
@@ -91,7 +91,7 @@ const passkeyPlugin = ({ domain, hosts, formerDomain }) => {
|
|
|
91
91
|
const verification = await verifyAuthenticationResponse({
|
|
92
92
|
response,
|
|
93
93
|
expectedChallenge,
|
|
94
|
-
expectedOrigin:
|
|
94
|
+
expectedOrigin: origins,
|
|
95
95
|
expectedRPID: rpIDOf(stored),
|
|
96
96
|
credential: {
|
|
97
97
|
id: stored.credentialID,
|
package/dist/create-admin.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { MobileConfig } from "./mobile-config.js";
|
|
2
|
+
import { AppIdentity } from "./app-identity.js";
|
|
3
|
+
import { AppIcons } from "./web-app/app-icons.js";
|
|
1
4
|
import { AdminAuth } from "./better-auth/create-auth.js";
|
|
2
5
|
import { EventsOptions } from "./changes/events-options.js";
|
|
3
6
|
import { JobDefinition } from "./jobs/job-types.js";
|
|
@@ -43,6 +46,15 @@ export type CreateAdminInput = {
|
|
|
43
46
|
subscriptions?: SubscriptionDefinition[];
|
|
44
47
|
/** Webhook subscriptions made in the admin app, from `extends: [webhooks()]` (see `WebhooksOptions`). */
|
|
45
48
|
webhooks?: WebhooksOptions;
|
|
49
|
+
/** The app's iOS and Android build (see `MobileConfig`): the API answers its Capacitor origins through CORS. */
|
|
50
|
+
mobile?: MobileConfig;
|
|
51
|
+
/** The app's colours, which its web manifest carries (see `AppIdentity`). */
|
|
52
|
+
app?: AppIdentity;
|
|
53
|
+
/**
|
|
54
|
+
* The icons the project has of its own, as `protobase build` and `protobase dev` find them beside its favicon: the
|
|
55
|
+
* web manifest names its PNGs, and `/meta` the favicon when it is the project's, which the sidebar's logo draws.
|
|
56
|
+
*/
|
|
57
|
+
icons?: AppIcons;
|
|
46
58
|
/**
|
|
47
59
|
* The plugins the app's bundle carries, as `protobase build` writes them: its protobase.ui.tsx and its extensions'
|
|
48
60
|
* UI configs, each a plugin.json path on the app's origin. `/meta` names them to everyone, before any other plugin,
|
|
@@ -69,5 +81,5 @@ export type CreateAdminInput = {
|
|
|
69
81
|
upgradeWebSocket?: UpgradeWebSocket;
|
|
70
82
|
};
|
|
71
83
|
/** The admin REST API as a Hono app. It uses only Web APIs, so it runs on Node, Workers and anywhere else Hono does. */
|
|
72
|
-
export declare const createAdmin: ({ resources: appResources, views: appViews, pages, userMenu, bottomBars, db, authenticate, auth, functions, files: filesOptions, events, history: historyOptions, jobs, subscriptions, webhooks: webhooksOptions, bundlePlugins, fieldTypes, options, formsDifficulty, commentUsers: givenCommentUsers, verifyToken, upgradeWebSocket }: CreateAdminInput) => Admin;
|
|
84
|
+
export declare const createAdmin: ({ resources: appResources, views: appViews, pages, userMenu, bottomBars, db, authenticate, auth, functions, files: filesOptions, events, history: historyOptions, jobs, subscriptions, webhooks: webhooksOptions, mobile, app: identity, icons, bundlePlugins, fieldTypes, options, formsDifficulty, commentUsers: givenCommentUsers, verifyToken, upgradeWebSocket }: CreateAdminInput) => Admin;
|
|
73
85
|
//#endregion
|
package/dist/create-admin.js
CHANGED
|
@@ -10,7 +10,7 @@ import { assistantSettings } from "./assistant/assistant-settings.js";
|
|
|
10
10
|
import { builtInAssistant } from "./assistant/built-in-assistant.js";
|
|
11
11
|
import { consoleAuditQueue } from "./audit/console-queue.js";
|
|
12
12
|
import { webauthnPath } from "./better-auth/origins.js";
|
|
13
|
-
import { apiCors, readCorsOrigins } from "./api-cors.js";
|
|
13
|
+
import { apiCors, readCorsOrigins, withMobileOrigins } from "./api-cors.js";
|
|
14
14
|
import { apiKeySettings } from "./api-keys/api-key-settings.js";
|
|
15
15
|
import { apiKeyCaller } from "./api-keys/resolve-caller.js";
|
|
16
16
|
import { jwtVerifier } from "./auth/jwt.js";
|
|
@@ -63,6 +63,7 @@ import { batchRoute } from "./routes/batch.js";
|
|
|
63
63
|
import { collectionRoutes } from "./routes/collection.js";
|
|
64
64
|
import { docsRoutes } from "./routes/docs.js";
|
|
65
65
|
import { metaRoutes } from "./routes/meta.js";
|
|
66
|
+
import { faviconPath } from "./web-app/web-manifest.js";
|
|
66
67
|
import { webManifestRoute } from "./web-app/web-manifest-route.js";
|
|
67
68
|
import { recordRoutes } from "./routes/record.js";
|
|
68
69
|
import { createScanGuard } from "./scan-guard.js";
|
|
@@ -75,7 +76,7 @@ const declaredRoles = (auth, roles) => {
|
|
|
75
76
|
return names.length > 0 ? [...new Set(names)] : void 0;
|
|
76
77
|
};
|
|
77
78
|
/** The admin REST API as a Hono app. It uses only Web APIs, so it runs on Node, Workers and anywhere else Hono does. */
|
|
78
|
-
const createAdmin = ({ resources: appResources, views: appViews = [], pages = [], userMenu, bottomBars = [], db, authenticate, auth, functions = {}, files: filesOptions, events, history: historyOptions, jobs = [], subscriptions = [], webhooks: webhooksOptions, bundlePlugins = [], fieldTypes = {}, options = {}, formsDifficulty, commentUsers: givenCommentUsers, verifyToken, upgradeWebSocket }) => {
|
|
79
|
+
const createAdmin = ({ resources: appResources, views: appViews = [], pages = [], userMenu, bottomBars = [], db, authenticate, auth, functions = {}, files: filesOptions, events, history: historyOptions, jobs = [], subscriptions = [], webhooks: webhooksOptions, mobile, app: identity, icons, bundlePlugins = [], fieldTypes = {}, options = {}, formsDifficulty, commentUsers: givenCommentUsers, verifyToken, upgradeWebSocket }) => {
|
|
79
80
|
const basePath = options.basePath ?? "/api/v1";
|
|
80
81
|
const appModels = appResources.map((resource) => resource.toModel());
|
|
81
82
|
const withComments = appModels.some((model) => model.comments);
|
|
@@ -191,7 +192,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], pages = []
|
|
|
191
192
|
} }
|
|
192
193
|
};
|
|
193
194
|
const appName = auth?.appName ?? readAppName(globalThis.process?.env ?? {}) ?? "Protobase";
|
|
194
|
-
const meta = createMeta(deps, appName);
|
|
195
|
+
const meta = createMeta(deps, appName, icons?.favicon ? faviconPath : void 0);
|
|
195
196
|
const onError = createErrorHandler(options.onUnhandledError);
|
|
196
197
|
const guarded = (routes, caller = authenticate) => {
|
|
197
198
|
const app = new Hono();
|
|
@@ -219,7 +220,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], pages = []
|
|
|
219
220
|
}, withAnonymous(authenticate, options.roles));
|
|
220
221
|
const app = new Hono();
|
|
221
222
|
app.onError(onError);
|
|
222
|
-
const corsOrigins = options.cors ?? readCorsOrigins(globalThis.process?.env ?? {});
|
|
223
|
+
const corsOrigins = withMobileOrigins(options.cors ?? readCorsOrigins(globalThis.process?.env ?? {}), Boolean(mobile));
|
|
223
224
|
const ownOrigins = auth?.origins ?? [];
|
|
224
225
|
if (corsOrigins !== void 0 || ownOrigins.length > 1) {
|
|
225
226
|
const answering = [authBasePath, ...Object.entries(apiFunctions).filter(([, fn]) => fn.options.cors).map(([name]) => `${systemPath}/functions/${name}`)];
|
|
@@ -301,7 +302,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], pages = []
|
|
|
301
302
|
}
|
|
302
303
|
app.route(basePath, api);
|
|
303
304
|
app.route(`${deps.systemPath}/meta`, metaApp);
|
|
304
|
-
app.route(systemPath || "/", webManifestRoute(appName));
|
|
305
|
+
app.route(systemPath || "/", webManifestRoute(appName, identity, icons));
|
|
305
306
|
app.route(deps.systemPath || "/", system);
|
|
306
307
|
const webhooks = createWebhooks({
|
|
307
308
|
deps,
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { goTruePath } from "./keys.js";
|
|
2
|
+
import { hashOf } from "../better-auth/sign-up/sign-up-code.js";
|
|
3
|
+
import { generateRandomString } from "better-auth/crypto";
|
|
4
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
5
|
+
//#region src/gotrue/provider-flows.ts
|
|
6
|
+
const flowSeconds = 600;
|
|
7
|
+
const flowCookie = (context) => context.createAuthCookie("gotrue_flow", {
|
|
8
|
+
maxAge: flowSeconds,
|
|
9
|
+
path: `${goTruePath}/callback`
|
|
10
|
+
});
|
|
11
|
+
const identifierOf = async (id) => `gotrue-provider-flow-${await hashOf(id)}`;
|
|
12
|
+
/** Keeps `flow` and gives the browser its id; answers the flow's hand-off secret. */
|
|
13
|
+
const startFlow = async (c, context, flow) => {
|
|
14
|
+
const id = generateRandomString(32);
|
|
15
|
+
const secret = generateRandomString(32);
|
|
16
|
+
const stored = {
|
|
17
|
+
...flow,
|
|
18
|
+
handOff: await hashOf(secret)
|
|
19
|
+
};
|
|
20
|
+
await context.internalAdapter.createVerificationValue({
|
|
21
|
+
identifier: await identifierOf(id),
|
|
22
|
+
value: JSON.stringify(stored),
|
|
23
|
+
expiresAt: new Date(Date.now() + flowSeconds * 1e3)
|
|
24
|
+
});
|
|
25
|
+
const { name, attributes } = flowCookie(context);
|
|
26
|
+
setCookie(c, name, id, attributes);
|
|
27
|
+
return secret;
|
|
28
|
+
};
|
|
29
|
+
/** Takes the flow of the browser's cookie, so it works once, and clears the cookie; nothing when there is none. */
|
|
30
|
+
const takeFlow = async (c, context) => {
|
|
31
|
+
const { name, attributes } = flowCookie(context);
|
|
32
|
+
const id = getCookie(c, name);
|
|
33
|
+
if (!id) return void 0;
|
|
34
|
+
deleteCookie(c, name, attributes);
|
|
35
|
+
const consumed = await context.internalAdapter.consumeVerificationValue(await identifierOf(id));
|
|
36
|
+
if (!consumed || new Date(consumed.expiresAt) < /* @__PURE__ */ new Date()) return void 0;
|
|
37
|
+
return JSON.parse(consumed.value);
|
|
38
|
+
};
|
|
39
|
+
/** Whether `secret` is the flow's hand-off secret. */
|
|
40
|
+
const isHandOff = async (flow, secret) => !!secret && await hashOf(secret) === flow.handOff;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { isHandOff, startFlow, takeFlow };
|
|
@@ -2,6 +2,7 @@ import { goTruePath } from "./keys.js";
|
|
|
2
2
|
import { GoTrueError } from "./errors.js";
|
|
3
3
|
import { callBetterAuth } from "./forward.js";
|
|
4
4
|
import { issueAuthCode } from "./auth-codes.js";
|
|
5
|
+
import { isHandOff, startFlow, takeFlow } from "./provider-flows.js";
|
|
5
6
|
import { Hono } from "hono";
|
|
6
7
|
//#region src/gotrue/provider-routes.ts
|
|
7
8
|
const challengeOf = (query) => {
|
|
@@ -27,52 +28,65 @@ const providerRoutes = ({ auth, context, sessionOf }) => {
|
|
|
27
28
|
if (requested && URL.canParse(requested) && (await context()).isTrustedOrigin(requested)) return requested;
|
|
28
29
|
return own;
|
|
29
30
|
};
|
|
31
|
+
const implicitFragment = async (userId) => {
|
|
32
|
+
const session = await sessionOf((await (await context()).internalAdapter.createSession(userId)).token);
|
|
33
|
+
return {
|
|
34
|
+
access_token: session.access_token,
|
|
35
|
+
token_type: "bearer",
|
|
36
|
+
expires_in: String(session.expires_in),
|
|
37
|
+
expires_at: String(session.expires_at),
|
|
38
|
+
refresh_token: session.refresh_token
|
|
39
|
+
};
|
|
40
|
+
};
|
|
30
41
|
return new Hono().get("/authorize", async (c) => {
|
|
31
42
|
const query = c.req.query();
|
|
32
43
|
const provider = query.provider ?? "";
|
|
33
44
|
if (!auth.socialProviders.includes(provider)) throw new GoTrueError(400, "validation_failed", `Unsupported provider: ${provider || "none"} is not one of this app's`);
|
|
34
45
|
const challenge = challengeOf(query);
|
|
46
|
+
const redirectTo = await destination(query.redirect_to, c.req.raw);
|
|
47
|
+
if (!challenge && new URL(redirectTo).protocol !== "https:") throw new GoTrueError(400, "validation_failed", "A redirect_to that is not https needs a code_challenge");
|
|
48
|
+
const before = await auth.api.getSession({ headers: c.req.raw.headers });
|
|
49
|
+
const secret = await startFlow(c, await context(), {
|
|
50
|
+
redirectTo,
|
|
51
|
+
challenge,
|
|
52
|
+
sessionBefore: before?.session.id
|
|
53
|
+
});
|
|
35
54
|
const callback = new URL(`${goTruePath}/callback`, c.req.url);
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
callback.searchParams.set("code_challenge", challenge.challenge);
|
|
39
|
-
callback.searchParams.set("code_challenge_method", challenge.method);
|
|
40
|
-
}
|
|
55
|
+
const success = new URL(callback);
|
|
56
|
+
success.searchParams.set("flow", secret);
|
|
41
57
|
const { json, headers } = await callBetterAuth(auth, c.req.raw, "/sign-in/social", {
|
|
42
58
|
provider,
|
|
43
|
-
callbackURL:
|
|
59
|
+
callbackURL: success.toString(),
|
|
44
60
|
errorCallbackURL: callback.toString(),
|
|
45
61
|
disableRedirect: true,
|
|
46
62
|
...query.scopes && { scopes: query.scopes.split(/[\s,]+/).filter(Boolean) }
|
|
47
63
|
});
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
return response;
|
|
64
|
+
for (const cookie of headers.getSetCookie()) c.header("set-cookie", cookie, { append: true });
|
|
65
|
+
return c.redirect(String(json.url), 302);
|
|
51
66
|
}).get("/callback", async (c) => {
|
|
52
67
|
const query = c.req.query();
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
if (!
|
|
68
|
+
const ctx = await context();
|
|
69
|
+
const flow = await takeFlow(c, ctx);
|
|
70
|
+
const signedIn = flow && !query.error && await isHandOff(flow, query.flow) && await auth.api.getSession({ headers: c.req.raw.headers });
|
|
71
|
+
const made = signedIn && signedIn.session.id !== flow.sessionBefore ? signedIn : void 0;
|
|
72
|
+
if (!flow || !made) {
|
|
58
73
|
const error = query.error ?? "access_denied";
|
|
74
|
+
const target = flow?.redirectTo ?? await destination(query.redirect_to, c.req.raw);
|
|
75
|
+
const where = (flow ? flow.challenge : query.code_challenge) ? "search" : "hash";
|
|
59
76
|
return c.redirect(withParams(target, {
|
|
60
77
|
error,
|
|
61
78
|
error_code: error,
|
|
62
79
|
error_description: query.error_description ?? "The sign-in with the provider did not complete"
|
|
63
80
|
}, where), 302);
|
|
64
81
|
}
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
refresh_token: session.refresh_token
|
|
74
|
-
};
|
|
75
|
-
return c.redirect(withParams(target, fragment, "hash"), 302);
|
|
82
|
+
const { redirectTo, challenge } = flow;
|
|
83
|
+
const handOff = challenge ? withParams(redirectTo, { code: await issueAuthCode(ctx, made.user.id, challenge) }, "search") : withParams(redirectTo, await implicitFragment(made.user.id), "hash");
|
|
84
|
+
const { headers } = await auth.api.signOut({
|
|
85
|
+
headers: c.req.raw.headers,
|
|
86
|
+
returnHeaders: true
|
|
87
|
+
});
|
|
88
|
+
for (const cookie of headers.getSetCookie()) c.header("set-cookie", cookie, { append: true });
|
|
89
|
+
return c.redirect(handOff, 302);
|
|
76
90
|
});
|
|
77
91
|
};
|
|
78
92
|
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { MobileConfig } from "./mobile-config.js";
|
|
2
|
+
import { AppIdentity } from "./app-identity.js";
|
|
3
|
+
import { AppIcons, PngIcon, pngIcons } from "./web-app/app-icons.js";
|
|
1
4
|
import { SignInPolicy, SignInRule, StaffAccessRule, defaultSignInPolicy, signInPolicyMethods } from "./better-auth/sign-in-policy.js";
|
|
2
5
|
import { StaffSignIn } from "./better-auth/staff-log.js";
|
|
3
6
|
import { MailMessage, Mailer } from "./mail/smtp-mailer.js";
|
|
@@ -55,6 +58,7 @@ import { parseRoles } from "./better-auth/parse-roles.js";
|
|
|
55
58
|
import { LinkedAccount, NewUser, StoredUser, createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned, setUserRole } from "./better-auth/users.js";
|
|
56
59
|
import { IssueTokenOptions, issueToken, maxTokenTtlSeconds } from "./better-auth/tokens.js";
|
|
57
60
|
import { webauthnPath } from "./better-auth/origins.js";
|
|
61
|
+
import { defaultAppName } from "./app-name.js";
|
|
58
62
|
import { authSchemaMigration, checkAuthSchema } from "./better-auth/auth-schema.js";
|
|
59
63
|
import { changesMigration, checkChanges, migrationCommand } from "./changes/capture-schema.js";
|
|
60
64
|
import { checkComputed, computedMigration } from "./computed/computed-schema.js";
|
|
@@ -96,4 +100,4 @@ import { isSchedule } from "./jobs/schedule.js";
|
|
|
96
100
|
import { DrainResult, JobsRuntime, StartJobsOptions, startJobs } from "./jobs/runtime.js";
|
|
97
101
|
import { jobsDrainApp } from "./jobs/drain-route.js";
|
|
98
102
|
import { checkJobsSchema, jobsSchema, jobsSchemaMigration } from "./jobs/schema.js";
|
|
99
|
-
export { type Admin, type AdminAuth, type AdminOptions, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApprovalAnswer, type ApprovalRequest, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type Authenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentUsers, type Completion, type CompletionOptions, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSource, type HistoryOptions, HttpProblem, type IssueTokenOptions, type JobContext, type JobDefinition, type JobOptions, type JobsRuntime, type JwtOptions, type JwtVerifyOptions, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, type Mailer, type MapLayer, type MapOptions, type MapSettings, type MemberInput, MissingCredentials, ModelError, type ModelSettings, type NewOrganization, type NewUser, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type ProjectConfig, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type QueryOptions, type QueryResult, type ReasoningDetail, type ReasoningEffort, type RecordKeyInput, type RecordPage, type RenderedEmail, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StoreFileInput, type StoredMember, type StoredObject, type StoredOrganization, type StoredUser, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolCall, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type User, type UserCreatedHook, type ViewSource, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, beforeSignInPluginsVariable, betterAuthAuthenticator, betterAuthTokens, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createFileCleanup, createOrganization, createUser, defaultSignInPolicy, defineConfig, defineEmail, defineFunction, defineJob, defineTool, deleteUser, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, handleDroppedConnections, hasUsers, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listUsers, localFileStore, localFiles, mapSettings, mapStyleUrl, mapStyleVariable, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, migrationCommand, newWebhookSecret, normalizeRoles, notFound, parseColumns, parseRoles, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, processor, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readWriteQueryTool, recordOf, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, s3Files, seesAssistant, seesRuntime, setMemberRoles, setUserBanned, setUserRole, signInPolicyMethods, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storeFile, streamChatCompletion, subscription, thumbHash, unauthorized, variantPath, verifySignature, verifyStandardWebhook, webauthnPath, webhooks, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps };
|
|
103
|
+
export { type Admin, type AdminAuth, type AdminOptions, type ApiFunction, type ApiKeys, type ApiKeysOptions, type AppIcons, type AppIdentity, type ApprovalAnswer, type ApprovalRequest, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type Authenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentUsers, type Completion, type CompletionOptions, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSource, type HistoryOptions, HttpProblem, type IssueTokenOptions, type JobContext, type JobDefinition, type JobOptions, type JobsRuntime, type JwtOptions, type JwtVerifyOptions, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, type Mailer, type MapLayer, type MapOptions, type MapSettings, type MemberInput, MissingCredentials, type MobileConfig, ModelError, type ModelSettings, type NewOrganization, type NewUser, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type PngIcon, type ProjectConfig, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type QueryOptions, type QueryResult, type ReasoningDetail, type ReasoningEffort, type RecordKeyInput, type RecordPage, type RenderedEmail, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StoreFileInput, type StoredMember, type StoredObject, type StoredOrganization, type StoredUser, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolCall, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type User, type UserCreatedHook, type ViewSource, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, beforeSignInPluginsVariable, betterAuthAuthenticator, betterAuthTokens, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createFileCleanup, createOrganization, createUser, defaultAppName, defaultSignInPolicy, defineConfig, defineEmail, defineFunction, defineJob, defineTool, deleteUser, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, handleDroppedConnections, hasUsers, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listUsers, localFileStore, localFiles, mapSettings, mapStyleUrl, mapStyleVariable, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, migrationCommand, newWebhookSecret, normalizeRoles, notFound, parseColumns, parseRoles, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, processor, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readWriteQueryTool, recordOf, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, s3Files, seesAssistant, seesRuntime, setMemberRoles, setUserBanned, setUserRole, signInPolicyMethods, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storeFile, streamChatCompletion, subscription, thumbHash, unauthorized, variantPath, verifySignature, verifyStandardWebhook, webauthnPath, webhooks, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps };
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,7 @@ import { webauthnPath } from "./better-auth/origins.js";
|
|
|
21
21
|
import { apiKeySettings, apiKeyVariables } from "./api-keys/api-key-settings.js";
|
|
22
22
|
import { apiKeyCaller } from "./api-keys/resolve-caller.js";
|
|
23
23
|
import { jwtAuthenticator, jwtVerifier } from "./auth/jwt.js";
|
|
24
|
+
import { defaultAppName } from "./app-name.js";
|
|
24
25
|
import { defaultSignInPolicy, signInPolicyMethods } from "./better-auth/sign-in-policy.js";
|
|
25
26
|
import { parseRoles } from "./better-auth/parse-roles.js";
|
|
26
27
|
import { readOperatorSettings } from "./better-auth/operator-provider.js";
|
|
@@ -48,6 +49,7 @@ import { beforeSignInPluginsVariable, pluginOptions, pluginsBeforeSignIn, plugin
|
|
|
48
49
|
import { runtimeUrl, runtimeVariable, seesRuntime } from "./runtime/runtime-settings.js";
|
|
49
50
|
import { checkSourceNames, sourceOptions, sourcesFor, sourcesVariable } from "./sources/source-settings.js";
|
|
50
51
|
import { renderVariant, thumbHash } from "./files/images.js";
|
|
52
|
+
import { pngIcons } from "./web-app/app-icons.js";
|
|
51
53
|
import { createAdmin } from "./create-admin.js";
|
|
52
54
|
import { handleDroppedConnections } from "./dropped-connections.js";
|
|
53
55
|
import { configExports } from "./resource-source.js";
|
|
@@ -73,4 +75,4 @@ import { aspectRatio, fileSize, fileType, imageSize, processor } from "./files/p
|
|
|
73
75
|
import { defineEmail } from "./mail/define-email.js";
|
|
74
76
|
import { startJobs } from "./jobs/runtime.js";
|
|
75
77
|
import { jobsDrainApp } from "./jobs/drain-route.js";
|
|
76
|
-
export { FatalJobError, HttpProblem, MissingCredentials, ModelError, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, beforeSignInPluginsVariable, betterAuthAuthenticator, betterAuthTokens, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createFileCleanup, createOrganization, createUser, defaultSignInPolicy, defineConfig, defineEmail, defineFunction, defineJob, defineTool, deleteUser, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, handleDroppedConnections, hasUsers, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listUsers, localFileStore, localFiles, mapSettings, mapStyleUrl, mapStyleVariable, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, migrationCommand, newWebhookSecret, normalizeRoles, notFound, parseColumns, parseRoles, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, processor, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readWriteQueryTool, recordOf, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, s3Files, seesAssistant, seesRuntime, setMemberRoles, setUserBanned, setUserRole, signInPolicyMethods, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storeFile, streamChatCompletion, subscription, thumbHash, unauthorized, variantPath, verifySignature, verifyStandardWebhook, webauthnPath, webhooks, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps };
|
|
78
|
+
export { FatalJobError, HttpProblem, MissingCredentials, ModelError, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, beforeSignInPluginsVariable, betterAuthAuthenticator, betterAuthTokens, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createFileCleanup, createOrganization, createUser, defaultAppName, defaultSignInPolicy, defineConfig, defineEmail, defineFunction, defineJob, defineTool, deleteUser, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, handleDroppedConnections, hasUsers, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listUsers, localFileStore, localFiles, mapSettings, mapStyleUrl, mapStyleVariable, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, migrationCommand, newWebhookSecret, normalizeRoles, notFound, parseColumns, parseRoles, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, processor, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readWriteQueryTool, recordOf, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, s3Files, seesAssistant, seesRuntime, setMemberRoles, setUserBanned, setUserRole, signInPolicyMethods, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storeFile, streamChatCompletion, subscription, thumbHash, unauthorized, variantPath, verifySignature, verifyStandardWebhook, webauthnPath, webhooks, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps };
|
package/dist/meta.js
CHANGED
|
@@ -28,7 +28,7 @@ const modelsHash = (deps) => sha256Hex(stableJson(deps.registry.entries.map((ent
|
|
|
28
28
|
* they could use once signed in, which keep their place in the bottom bar and the user menu.
|
|
29
29
|
* The ETag hashes all of it, so it differs per user and per roles.
|
|
30
30
|
*/
|
|
31
|
-
const createMeta = (deps, appName) => {
|
|
31
|
+
const createMeta = (deps, appName, appIcon) => {
|
|
32
32
|
const base = modelsHash(deps);
|
|
33
33
|
const forCaller = async (session) => {
|
|
34
34
|
const accesses = await Promise.all(deps.registry.entries.map((entry) => requestAccess(deps, entry, session)));
|
|
@@ -62,6 +62,7 @@ const createMeta = (deps, appName) => {
|
|
|
62
62
|
const sources = sourcesFor(deps.sources, session.user.roles);
|
|
63
63
|
const body = {
|
|
64
64
|
appName,
|
|
65
|
+
...appIcon && { appIcon },
|
|
65
66
|
resources: visible.map((access) => access.readable),
|
|
66
67
|
views,
|
|
67
68
|
pages,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/mobile-config.d.ts
|
|
2
|
+
/** The `mobile` section of `protobase.config.ts`: with it, `protobase mobile` builds the app for iOS and Android. */
|
|
3
|
+
export type MobileConfig = {
|
|
4
|
+
/** The app's id in reverse-DNS form, such as `com.example.shop`. */
|
|
5
|
+
appId: string;
|
|
6
|
+
/** Extra native Capacitor plugins the app needs, as npm name → version range, such as `{ '@capacitor/camera': '^8.0.0' }`. */
|
|
7
|
+
plugins?: Record<string, string>;
|
|
8
|
+
};
|
|
9
|
+
//#endregion
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/mobile-config.ts
|
|
2
|
+
/**
|
|
3
|
+
* The origins Capacitor's WebView serves the app's files on: `capacitor://localhost` on iOS, `https://localhost` on
|
|
4
|
+
* Android. They hold because `protobase mobile` never sets Capacitor's `server.hostname` or schemes.
|
|
5
|
+
*/
|
|
6
|
+
const capacitorOrigins = ["capacitor://localhost", "https://localhost"];
|
|
7
|
+
//#endregion
|
|
8
|
+
export { capacitorOrigins };
|
package/dist/project-config.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { MobileConfig } from "./mobile-config.js";
|
|
2
|
+
import { AppIdentity } from "./app-identity.js";
|
|
1
3
|
import { AdminAuth } from "./better-auth/create-auth.js";
|
|
2
4
|
import { EventsOptions } from "./changes/events-options.js";
|
|
3
5
|
import { Authenticator } from "./types.js";
|
|
@@ -32,6 +34,10 @@ export type ProjectConfig = {
|
|
|
32
34
|
webhooks?: WebhooksOptions;
|
|
33
35
|
/** The module of the app's jobs, e.g. `import * as jobs from './config/jobs'`: every `defineJob` it exports. */
|
|
34
36
|
jobs?: Record<string, unknown>;
|
|
37
|
+
/** The app's iOS and Android build (see `MobileConfig`): `protobase mobile` needs it, and the API answers the app's origins. */
|
|
38
|
+
mobile?: MobileConfig;
|
|
39
|
+
/** The installed app's colours (see `AppIdentity`), which its web manifest carries. */
|
|
40
|
+
app?: AppIdentity;
|
|
35
41
|
options?: AdminOptions;
|
|
36
42
|
};
|
|
37
43
|
/** Typed identity, for `export default defineConfig({ extends: [...], config, auth, ... })` in `protobase.config.ts`. */
|
package/dist/project-config.js
CHANGED
|
@@ -143,13 +143,15 @@ const mergedOptions = (named) => {
|
|
|
143
143
|
*/
|
|
144
144
|
const mergeConfig = (...configs) => {
|
|
145
145
|
const named = configs.flatMap((config, index) => flatten(config, config.name ?? `config ${index + 1}`));
|
|
146
|
-
const { db, authenticate, auth, events, history, webhooks } = lastSet(named.map(({ config }) => ({
|
|
146
|
+
const { db, authenticate, auth, events, history, webhooks, mobile, app } = lastSet(named.map(({ config }) => ({
|
|
147
147
|
db: config.db,
|
|
148
148
|
authenticate: config.authenticate,
|
|
149
149
|
auth: config.auth,
|
|
150
150
|
events: config.events,
|
|
151
151
|
history: config.history,
|
|
152
|
-
webhooks: config.webhooks
|
|
152
|
+
webhooks: config.webhooks,
|
|
153
|
+
mobile: config.mobile,
|
|
154
|
+
app: config.app
|
|
153
155
|
})));
|
|
154
156
|
const module = mergedModule(named);
|
|
155
157
|
const functions = mergedFunctions(named);
|
|
@@ -169,6 +171,8 @@ const mergeConfig = (...configs) => {
|
|
|
169
171
|
...history && { history },
|
|
170
172
|
...webhooks && { webhooks },
|
|
171
173
|
...jobs && { jobs },
|
|
174
|
+
...mobile && { mobile },
|
|
175
|
+
...app && { app },
|
|
172
176
|
...options && { options }
|
|
173
177
|
};
|
|
174
178
|
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/web-app/app-icons.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The PNG icons a project may put beside its `protobase.favicon.svg`, for platforms that take no SVG, each square at
|
|
4
|
+
* `size` pixels and answered on the app's own origin at `/<file>`: Android's 192 and 512 pixel icons, a 512 pixel
|
|
5
|
+
* maskable one whose mark keeps to the middle 80%, and the 180 pixel Apple touch icon an iPhone home screen shows.
|
|
6
|
+
*/
|
|
7
|
+
export declare const pngIcons: {
|
|
8
|
+
readonly icon192: {
|
|
9
|
+
readonly file: "protobase.icon-192.png";
|
|
10
|
+
readonly size: 192;
|
|
11
|
+
};
|
|
12
|
+
readonly icon512: {
|
|
13
|
+
readonly file: "protobase.icon-512.png";
|
|
14
|
+
readonly size: 512;
|
|
15
|
+
};
|
|
16
|
+
readonly maskable: {
|
|
17
|
+
readonly file: "protobase.icon-maskable.png";
|
|
18
|
+
readonly size: 512;
|
|
19
|
+
};
|
|
20
|
+
readonly appleTouch: {
|
|
21
|
+
readonly file: "protobase.apple-touch-icon.png";
|
|
22
|
+
readonly size: 180;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
export type PngIcon = keyof typeof pngIcons;
|
|
26
|
+
/** The icons a project has of its own: `favicon` when the favicon is its own rather than Protobase's, and its PNGs. */
|
|
27
|
+
export type AppIcons = {
|
|
28
|
+
favicon: boolean;
|
|
29
|
+
png: PngIcon[];
|
|
30
|
+
};
|
|
31
|
+
//#endregion
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/web-app/app-icons.ts
|
|
2
|
+
/**
|
|
3
|
+
* The PNG icons a project may put beside its `protobase.favicon.svg`, for platforms that take no SVG, each square at
|
|
4
|
+
* `size` pixels and answered on the app's own origin at `/<file>`: Android's 192 and 512 pixel icons, a 512 pixel
|
|
5
|
+
* maskable one whose mark keeps to the middle 80%, and the 180 pixel Apple touch icon an iPhone home screen shows.
|
|
6
|
+
*/
|
|
7
|
+
const pngIcons = {
|
|
8
|
+
icon192: {
|
|
9
|
+
file: "protobase.icon-192.png",
|
|
10
|
+
size: 192
|
|
11
|
+
},
|
|
12
|
+
icon512: {
|
|
13
|
+
file: "protobase.icon-512.png",
|
|
14
|
+
size: 512
|
|
15
|
+
},
|
|
16
|
+
maskable: {
|
|
17
|
+
file: "protobase.icon-maskable.png",
|
|
18
|
+
size: 512
|
|
19
|
+
},
|
|
20
|
+
appleTouch: {
|
|
21
|
+
file: "protobase.apple-touch-icon.png",
|
|
22
|
+
size: 180
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { pngIcons };
|
|
@@ -4,9 +4,9 @@ import { Hono } from "hono";
|
|
|
4
4
|
/** The path under the system path (`/api`) the admin app's page links its manifest at. */
|
|
5
5
|
const webManifestPath = "/manifest.webmanifest";
|
|
6
6
|
/** Answers the web app manifest to anyone: the browser fetches it without the user's token, before they sign in. */
|
|
7
|
-
const webManifestRoute = (appName) => {
|
|
7
|
+
const webManifestRoute = (appName, identity, icons) => {
|
|
8
8
|
const app = new Hono();
|
|
9
|
-
const body = JSON.stringify(webManifest(appName));
|
|
9
|
+
const body = JSON.stringify(webManifest(appName, identity, icons));
|
|
10
10
|
app.get(webManifestPath, () => new Response(body, { headers: {
|
|
11
11
|
"content-type": "application/manifest+json",
|
|
12
12
|
"cache-control": "no-cache"
|
|
@@ -1,22 +1,41 @@
|
|
|
1
|
+
import { pngIcons } from "./app-icons.js";
|
|
1
2
|
//#region src/web-app/web-manifest.ts
|
|
2
3
|
/** Where the app's favicon is on its own origin, which `protobase build` and `protobase dev` always answer. */
|
|
3
4
|
const faviconPath = "/protobase.favicon.svg";
|
|
5
|
+
const manifestIcons = {
|
|
6
|
+
icon192: "any",
|
|
7
|
+
icon512: "any",
|
|
8
|
+
maskable: "maskable"
|
|
9
|
+
};
|
|
10
|
+
const isManifestIcon = (icon) => icon in manifestIcons;
|
|
11
|
+
const manifestIcon = (icon) => {
|
|
12
|
+
const { file, size } = pngIcons[icon];
|
|
13
|
+
return {
|
|
14
|
+
src: `/${file}`,
|
|
15
|
+
sizes: `${size}x${size}`,
|
|
16
|
+
type: "image/png",
|
|
17
|
+
...manifestIcons[icon] === "maskable" && { purpose: "maskable" }
|
|
18
|
+
};
|
|
19
|
+
};
|
|
4
20
|
/**
|
|
5
21
|
* The web app manifest that makes the admin app installable: named for the app, opening at its home page in a window
|
|
6
|
-
* of its own, with the favicon as its icon
|
|
22
|
+
* of its own, with the favicon as its icon, the project's PNGs beside it and its colours when it has them. An SVG with
|
|
23
|
+
* `sizes: "any"` meets Chrome's 192 and 512 pixel icon sizes; Safari and some Android launchers take only PNGs.
|
|
7
24
|
*/
|
|
8
|
-
const webManifest = (appName) => ({
|
|
25
|
+
const webManifest = (appName, { themeColor, backgroundColor } = {}, icons) => ({
|
|
9
26
|
name: appName,
|
|
10
27
|
short_name: appName,
|
|
11
28
|
id: "/",
|
|
12
29
|
start_url: "/",
|
|
13
30
|
scope: "/",
|
|
14
31
|
display: "standalone",
|
|
32
|
+
...themeColor && { theme_color: themeColor },
|
|
33
|
+
...backgroundColor && { background_color: backgroundColor },
|
|
15
34
|
icons: [{
|
|
16
35
|
src: faviconPath,
|
|
17
36
|
sizes: "any",
|
|
18
37
|
type: "image/svg+xml"
|
|
19
|
-
}]
|
|
38
|
+
}, ...(icons?.png ?? []).filter(isManifestIcon).map(manifestIcon)]
|
|
20
39
|
});
|
|
21
40
|
//#endregion
|
|
22
41
|
export { faviconPath, webManifest };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -32,9 +32,9 @@
|
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@better-auth/passkey": "^1.7.7",
|
|
34
34
|
"@better-auth/sso": "^1.7.7",
|
|
35
|
-
"@protobase/layout": "0.
|
|
36
|
-
"@protobase/query": "0.
|
|
37
|
-
"@protobase/schema": "0.
|
|
35
|
+
"@protobase/layout": "0.28.0",
|
|
36
|
+
"@protobase/query": "0.28.0",
|
|
37
|
+
"@protobase/schema": "0.28.0",
|
|
38
38
|
"@react-email/render": "^2.1.0",
|
|
39
39
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
40
40
|
"@sentry/core": "^11.7.0",
|