Add instance settings and mail delivery through PocketBase
Superadmins can now change signup rules (on/off and the domain allow-list) and branding at runtime; the environment variables only seed the defaults. Mail and S3 storage settings pass through to PocketBase's own settings, and docwell-server sends its own emails through a PocketBase hook so there is a single SMTP configuration. The boot hook no longer wipes SMTP settings that were not set from the environment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ba394b8fac
commit
e33a99241e
21 files changed
+1714
-25
No files matched your search
@@ -16,27 +16,64 @@ routerAdd(
|
||||
$apis.requireAuth("users"),
|
||||
);
|
||||
|
||||
// Instance settings come from the environment and are applied on every start,
|
||||
// so changing an env var and restarting is enough.
|
||||
// Sends one email through PocketBase's SMTP settings, so docwell-server's own
|
||||
// emails (invites, test mails) use the same mail configuration as the auth
|
||||
// emails PocketBase sends itself.
|
||||
routerAdd(
|
||||
"POST",
|
||||
"/api/docwell/mail",
|
||||
(e) => {
|
||||
const body = e.requestInfo().body;
|
||||
const to = String(body.to || "").trim();
|
||||
const subject = String(body.subject || "").trim();
|
||||
if (!to || !subject) {
|
||||
throw new BadRequestError("to and subject are required");
|
||||
}
|
||||
const meta = e.app.settings().meta;
|
||||
const message = new MailerMessage({
|
||||
from: { address: meta.senderAddress, name: meta.senderName },
|
||||
to: [{ address: to }],
|
||||
subject: subject,
|
||||
html: String(body.html || ""),
|
||||
text: String(body.text || ""),
|
||||
});
|
||||
e.app.newMailClient().send(message);
|
||||
return e.noContent(204);
|
||||
},
|
||||
$apis.requireSuperuserAuth(),
|
||||
);
|
||||
|
||||
// Settings that come from the environment are applied on every start, so
|
||||
// changing an env var and restarting is enough. Settings without an env var
|
||||
// are left alone: the admin panel manages them.
|
||||
onBootstrap((e) => {
|
||||
e.next();
|
||||
|
||||
const env = (key, def) => $os.getenv(key) || def;
|
||||
const env = (key) => $os.getenv(key) || "";
|
||||
const settings = e.app.settings();
|
||||
|
||||
settings.meta.appName = env("DOCWELL_APP_NAME", "Docwell");
|
||||
settings.meta.appURL = env("DOCWELL_WEB_URL", "http://localhost:3000");
|
||||
if (env("DOCWELL_APP_NAME")) {
|
||||
settings.meta.appName = env("DOCWELL_APP_NAME");
|
||||
} else if (settings.meta.appName === "Acme") {
|
||||
// PocketBase's placeholder name on a fresh database.
|
||||
settings.meta.appName = "Docwell";
|
||||
}
|
||||
settings.meta.appURL = env("DOCWELL_WEB_URL") || "http://localhost:3000";
|
||||
settings.meta.senderName = settings.meta.appName;
|
||||
settings.meta.senderAddress = env("DOCWELL_MAIL_FROM", "no-reply@docwell.localhost");
|
||||
if (env("DOCWELL_MAIL_FROM")) {
|
||||
settings.meta.senderAddress = env("DOCWELL_MAIL_FROM");
|
||||
} else if (settings.meta.senderAddress === "support@example.com") {
|
||||
settings.meta.senderAddress = "no-reply@docwell.localhost";
|
||||
}
|
||||
|
||||
const smtpHost = env("DOCWELL_SMTP_HOST", "");
|
||||
settings.smtp.enabled = smtpHost !== "";
|
||||
const smtpHost = env("DOCWELL_SMTP_HOST");
|
||||
if (smtpHost) {
|
||||
settings.smtp.enabled = true;
|
||||
settings.smtp.host = smtpHost;
|
||||
settings.smtp.port = parseInt(env("DOCWELL_SMTP_PORT", "587"), 10);
|
||||
settings.smtp.username = env("DOCWELL_SMTP_USERNAME", "");
|
||||
settings.smtp.password = env("DOCWELL_SMTP_PASSWORD", "");
|
||||
settings.smtp.tls = env("DOCWELL_SMTP_TLS", "false") === "true";
|
||||
settings.smtp.port = parseInt(env("DOCWELL_SMTP_PORT") || "587", 10);
|
||||
settings.smtp.username = env("DOCWELL_SMTP_USERNAME");
|
||||
settings.smtp.password = env("DOCWELL_SMTP_PASSWORD");
|
||||
settings.smtp.tls = env("DOCWELL_SMTP_TLS") === "true";
|
||||
}
|
||||
|
||||
e.app.save(settings);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Instance settings the admin panel edits (signup rules, branding), one record
|
||||
// per key. Mail and file storage settings live in PocketBase's own settings,
|
||||
// which docwell-server patches directly.
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const settings = new Collection({
|
||||
type: "base",
|
||||
name: "instance_settings",
|
||||
fields: [
|
||||
{ name: "key", type: "text", required: true, max: 64, pattern: "^[a-z0-9_]+$" },
|
||||
{ name: "value", type: "json", maxSize: 1048576 },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
indexes: ["CREATE UNIQUE INDEX idx_instance_settings_key ON instance_settings (key)"],
|
||||
});
|
||||
app.save(settings);
|
||||
},
|
||||
(app) => {
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId("instance_settings"));
|
||||
} catch (_) {}
|
||||
},
|
||||
);
|
||||
@@ -39,7 +39,9 @@ services:
|
||||
DOCWELL_PB_EMAIL: ${PB_ADMIN_EMAIL}
|
||||
DOCWELL_PB_PASSWORD: ${PB_ADMIN_PASSWORD}
|
||||
DOCWELL_PUBLIC_URL: ${DOCWELL_PUBLIC_URL:-http://localhost:8080}
|
||||
DOCWELL_WEB_URL: ${DOCWELL_WEB_URL:-http://localhost:3000}
|
||||
DOCWELL_CORS_ORIGINS: ${DOCWELL_WEB_URL:-http://localhost:3000}
|
||||
# Defaults until a superadmin saves signup rules in the admin panel.
|
||||
DOCWELL_SIGNUP_ENABLED: ${DOCWELL_SIGNUP_ENABLED:-true}
|
||||
DOCWELL_SIGNUP_DOMAINS: ${DOCWELL_SIGNUP_DOMAINS:-}
|
||||
ports:
|
||||
|
||||
@@ -29,6 +29,9 @@ export type Page = Schemas["Page"];
|
||||
export type TrashedPage = Schemas["TrashedPage"];
|
||||
export type PageContent = Schemas["PageContent"];
|
||||
export type PageVersion = Schemas["PageVersion"];
|
||||
export type PublicSettings = Schemas["PublicSettings"];
|
||||
export type InstanceSettings = Schemas["InstanceSettings"];
|
||||
export type InstanceSettingsUpdate = Schemas["InstanceSettingsUpdate"];
|
||||
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
|
||||
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
|
||||
|
||||
@@ -116,6 +119,14 @@ export function createClient(opts: ClientOptions) {
|
||||
confirmVerification: (token: string) => post("/api/v1/auth/verification/confirm", { token }),
|
||||
},
|
||||
|
||||
settings: {
|
||||
public: () => request<PublicSettings>("GET", "/api/v1/settings/public"),
|
||||
get: () => request<InstanceSettings>("GET", "/api/v1/admin/settings"),
|
||||
update: (patch: InstanceSettingsUpdate) => request<InstanceSettings>("PATCH", "/api/v1/admin/settings", patch),
|
||||
testEmail: (to: string) => post("/api/v1/admin/settings/test-email", { to }),
|
||||
testStorage: () => post("/api/v1/admin/settings/test-storage"),
|
||||
},
|
||||
|
||||
users: {
|
||||
list: (params: { page?: number; perPage?: number; q?: string; organization?: string } = {}) =>
|
||||
request<UserList>("GET", `/api/v1/users${query(params)}`),
|
||||
|
||||
Vendored
+242
@@ -657,6 +657,78 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/settings/public": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** Branding and signup availability, for signed-out pages */
|
||||
get: operations["getPublicSettings"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/admin/settings": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** Every instance setting (superadmin) */
|
||||
get: operations["getInstanceSettings"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
/**
|
||||
* Change the sections that are present (superadmin)
|
||||
* @description Mail and storage settings are PocketBase's own. Passwords and secrets are write-only: leave them out to keep the stored value. Environment variables such as DOCWELL_SMTP_HOST are applied again when docwell-db starts.
|
||||
*/
|
||||
patch: operations["updateInstanceSettings"];
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/admin/settings/test-email": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Send a test email with the saved mail settings (superadmin) */
|
||||
post: operations["sendTestEmail"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/admin/settings/test-storage": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Check that the configured S3 bucket is reachable (superadmin) */
|
||||
post: operations["testStorage"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
@@ -869,6 +941,62 @@ export interface components {
|
||||
name: string;
|
||||
version: string;
|
||||
};
|
||||
PublicSettings: {
|
||||
appName: string;
|
||||
/** @description #rrggbb, or empty for the default */
|
||||
accentColor: string;
|
||||
/** @description A data URL */
|
||||
logo: string;
|
||||
/** @description Self-service signup is open */
|
||||
signup: boolean;
|
||||
};
|
||||
SignupSettings: {
|
||||
enabled: boolean;
|
||||
/** @description Allowed email domains; empty allows all */
|
||||
domains: string[];
|
||||
};
|
||||
BrandingSettings: {
|
||||
appName: string;
|
||||
accentColor: string;
|
||||
/** @description data:image/(png|jpeg|webp|svg+xml);base64,..., at most 256 KB */
|
||||
logo: string;
|
||||
};
|
||||
SmtpSettings: {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
/** @description Leave out to keep the stored password */
|
||||
password?: string;
|
||||
readonly passwordSet: boolean;
|
||||
tls: boolean;
|
||||
senderName: string;
|
||||
senderAddress: string;
|
||||
};
|
||||
StorageSettings: {
|
||||
/** @description false stores files on docwell-db's disk */
|
||||
s3: boolean;
|
||||
bucket: string;
|
||||
region: string;
|
||||
endpoint: string;
|
||||
accessKey: string;
|
||||
/** @description Leave out to keep the stored secret */
|
||||
secret?: string;
|
||||
readonly secretSet: boolean;
|
||||
forcePathStyle: boolean;
|
||||
};
|
||||
InstanceSettings: {
|
||||
signup: components["schemas"]["SignupSettings"];
|
||||
branding: components["schemas"]["BrandingSettings"];
|
||||
smtp: components["schemas"]["SmtpSettings"];
|
||||
storage: components["schemas"]["StorageSettings"];
|
||||
};
|
||||
InstanceSettingsUpdate: {
|
||||
signup?: components["schemas"]["SignupSettings"];
|
||||
branding?: components["schemas"]["BrandingSettings"];
|
||||
smtp?: components["schemas"]["SmtpSettings"];
|
||||
storage?: components["schemas"]["StorageSettings"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Signed in */
|
||||
@@ -2145,4 +2273,118 @@ export interface operations {
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getPublicSettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PublicSettings"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getInstanceSettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["InstanceSettings"];
|
||||
};
|
||||
};
|
||||
403: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
updateInstanceSettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["InstanceSettingsUpdate"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Saved */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["InstanceSettings"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
sendTestEmail: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** Format: email */
|
||||
to: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Sent */
|
||||
204: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
testStorage: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Reachable */
|
||||
204: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -963,3 +963,273 @@ class Version {
|
||||
|
||||
Map<String, dynamic> toJson() => {'name': name, 'version': version};
|
||||
}
|
||||
|
||||
class PublicSettings {
|
||||
const PublicSettings({
|
||||
required this.appName,
|
||||
required this.accentColor,
|
||||
required this.logo,
|
||||
required this.signup,
|
||||
});
|
||||
|
||||
factory PublicSettings.fromJson(Map<String, dynamic> json) => PublicSettings(
|
||||
appName: json['appName'] as String,
|
||||
accentColor: json['accentColor'] as String,
|
||||
logo: json['logo'] as String,
|
||||
signup: json['signup'] as bool,
|
||||
);
|
||||
|
||||
final String appName;
|
||||
|
||||
/// #rrggbb, or empty for the default
|
||||
final String accentColor;
|
||||
|
||||
/// A data URL
|
||||
final String logo;
|
||||
|
||||
/// Self-service signup is open
|
||||
final bool signup;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'appName': appName,
|
||||
'accentColor': accentColor,
|
||||
'logo': logo,
|
||||
'signup': signup,
|
||||
};
|
||||
}
|
||||
|
||||
class SignupSettings {
|
||||
const SignupSettings({required this.enabled, required this.domains});
|
||||
|
||||
factory SignupSettings.fromJson(Map<String, dynamic> json) => SignupSettings(
|
||||
enabled: json['enabled'] as bool,
|
||||
domains: (json['domains'] as List).map((e) => e as String).toList(),
|
||||
);
|
||||
|
||||
final bool enabled;
|
||||
|
||||
/// Allowed email domains; empty allows all
|
||||
final List<String> domains;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'enabled': enabled,
|
||||
'domains': domains.map((e) => e).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
class BrandingSettings {
|
||||
const BrandingSettings({
|
||||
required this.appName,
|
||||
required this.accentColor,
|
||||
required this.logo,
|
||||
});
|
||||
|
||||
factory BrandingSettings.fromJson(Map<String, dynamic> json) =>
|
||||
BrandingSettings(
|
||||
appName: json['appName'] as String,
|
||||
accentColor: json['accentColor'] as String,
|
||||
logo: json['logo'] as String,
|
||||
);
|
||||
|
||||
final String appName;
|
||||
|
||||
final String accentColor;
|
||||
|
||||
/// data:image/(png|jpeg|webp|svg+xml);base64,..., at most 256 KB
|
||||
final String logo;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'appName': appName,
|
||||
'accentColor': accentColor,
|
||||
'logo': logo,
|
||||
};
|
||||
}
|
||||
|
||||
class SmtpSettings {
|
||||
const SmtpSettings({
|
||||
required this.enabled,
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.username,
|
||||
this.password,
|
||||
required this.passwordSet,
|
||||
required this.tls,
|
||||
required this.senderName,
|
||||
required this.senderAddress,
|
||||
});
|
||||
|
||||
factory SmtpSettings.fromJson(Map<String, dynamic> json) => SmtpSettings(
|
||||
enabled: json['enabled'] as bool,
|
||||
host: json['host'] as String,
|
||||
port: (json['port'] as num).toInt(),
|
||||
username: json['username'] as String,
|
||||
password: json['password'] == null ? null : json['password'] as String,
|
||||
passwordSet: json['passwordSet'] as bool,
|
||||
tls: json['tls'] as bool,
|
||||
senderName: json['senderName'] as String,
|
||||
senderAddress: json['senderAddress'] as String,
|
||||
);
|
||||
|
||||
final bool enabled;
|
||||
|
||||
final String host;
|
||||
|
||||
final int port;
|
||||
|
||||
final String username;
|
||||
|
||||
/// Leave out to keep the stored password
|
||||
final String? password;
|
||||
|
||||
final bool passwordSet;
|
||||
|
||||
final bool tls;
|
||||
|
||||
final String senderName;
|
||||
|
||||
final String senderAddress;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'enabled': enabled,
|
||||
'host': host,
|
||||
'port': port,
|
||||
'username': username,
|
||||
'password': ?password,
|
||||
'passwordSet': passwordSet,
|
||||
'tls': tls,
|
||||
'senderName': senderName,
|
||||
'senderAddress': senderAddress,
|
||||
};
|
||||
}
|
||||
|
||||
class StorageSettings {
|
||||
const StorageSettings({
|
||||
required this.s3,
|
||||
required this.bucket,
|
||||
required this.region,
|
||||
required this.endpoint,
|
||||
required this.accessKey,
|
||||
this.secret,
|
||||
required this.secretSet,
|
||||
required this.forcePathStyle,
|
||||
});
|
||||
|
||||
factory StorageSettings.fromJson(Map<String, dynamic> json) =>
|
||||
StorageSettings(
|
||||
s3: json['s3'] as bool,
|
||||
bucket: json['bucket'] as String,
|
||||
region: json['region'] as String,
|
||||
endpoint: json['endpoint'] as String,
|
||||
accessKey: json['accessKey'] as String,
|
||||
secret: json['secret'] == null ? null : json['secret'] as String,
|
||||
secretSet: json['secretSet'] as bool,
|
||||
forcePathStyle: json['forcePathStyle'] as bool,
|
||||
);
|
||||
|
||||
/// false stores files on docwell-db's disk
|
||||
final bool s3;
|
||||
|
||||
final String bucket;
|
||||
|
||||
final String region;
|
||||
|
||||
final String endpoint;
|
||||
|
||||
final String accessKey;
|
||||
|
||||
/// Leave out to keep the stored secret
|
||||
final String? secret;
|
||||
|
||||
final bool secretSet;
|
||||
|
||||
final bool forcePathStyle;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
's3': s3,
|
||||
'bucket': bucket,
|
||||
'region': region,
|
||||
'endpoint': endpoint,
|
||||
'accessKey': accessKey,
|
||||
'secret': ?secret,
|
||||
'secretSet': secretSet,
|
||||
'forcePathStyle': forcePathStyle,
|
||||
};
|
||||
}
|
||||
|
||||
class InstanceSettings {
|
||||
const InstanceSettings({
|
||||
required this.signup,
|
||||
required this.branding,
|
||||
required this.smtp,
|
||||
required this.storage,
|
||||
});
|
||||
|
||||
factory InstanceSettings.fromJson(Map<String, dynamic> json) =>
|
||||
InstanceSettings(
|
||||
signup: SignupSettings.fromJson(json['signup'] as Map<String, dynamic>),
|
||||
branding: BrandingSettings.fromJson(
|
||||
json['branding'] as Map<String, dynamic>,
|
||||
),
|
||||
smtp: SmtpSettings.fromJson(json['smtp'] as Map<String, dynamic>),
|
||||
storage: StorageSettings.fromJson(
|
||||
json['storage'] as Map<String, dynamic>,
|
||||
),
|
||||
);
|
||||
|
||||
final SignupSettings signup;
|
||||
|
||||
final BrandingSettings branding;
|
||||
|
||||
final SmtpSettings smtp;
|
||||
|
||||
final StorageSettings storage;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'signup': signup.toJson(),
|
||||
'branding': branding.toJson(),
|
||||
'smtp': smtp.toJson(),
|
||||
'storage': storage.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
class InstanceSettingsUpdate {
|
||||
const InstanceSettingsUpdate({
|
||||
this.signup,
|
||||
this.branding,
|
||||
this.smtp,
|
||||
this.storage,
|
||||
});
|
||||
|
||||
factory InstanceSettingsUpdate.fromJson(Map<String, dynamic> json) =>
|
||||
InstanceSettingsUpdate(
|
||||
signup: json['signup'] == null
|
||||
? null
|
||||
: SignupSettings.fromJson(json['signup'] as Map<String, dynamic>),
|
||||
branding: json['branding'] == null
|
||||
? null
|
||||
: BrandingSettings.fromJson(
|
||||
json['branding'] as Map<String, dynamic>,
|
||||
),
|
||||
smtp: json['smtp'] == null
|
||||
? null
|
||||
: SmtpSettings.fromJson(json['smtp'] as Map<String, dynamic>),
|
||||
storage: json['storage'] == null
|
||||
? null
|
||||
: StorageSettings.fromJson(json['storage'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
final SignupSettings? signup;
|
||||
|
||||
final BrandingSettings? branding;
|
||||
|
||||
final SmtpSettings? smtp;
|
||||
|
||||
final StorageSettings? storage;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'signup': ?signup?.toJson(),
|
||||
'branding': ?branding?.toJson(),
|
||||
'smtp': ?smtp?.toJson(),
|
||||
'storage': ?storage?.toJson(),
|
||||
};
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
"docwell/server/internal/config"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/httpapi"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/settings"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
"docwell/server/internal/ycrdt"
|
||||
)
|
||||
@@ -43,7 +45,12 @@ func run(log *slog.Logger) error {
|
||||
}
|
||||
|
||||
db := pocketbase.New(cfg.PocketBaseURL, cfg.PocketBaseEmail, cfg.PocketBasePassword)
|
||||
authSvc := auth.NewService(db, auth.Options{SignupEnabled: cfg.SignupEnabled, SignupDomains: cfg.SignupDomains})
|
||||
mailer := mail.PBSender{PB: db}
|
||||
settingsSvc := settings.New(db, settings.Signup{Enabled: cfg.SignupEnabled, Domains: cfg.SignupDomains}, mailer)
|
||||
authSvc := auth.NewService(db, auth.Options{Rules: func(ctx context.Context) (bool, []string, error) {
|
||||
rules, err := settingsSvc.Signup(ctx)
|
||||
return rules.Enabled, rules.Domains, err
|
||||
}})
|
||||
|
||||
// yrs.wasm compiles once; the cache makes later starts fast (ADR-3).
|
||||
cacheDir, _ := os.UserCacheDir()
|
||||
@@ -67,6 +74,7 @@ func run(log *slog.Logger) error {
|
||||
DB: db,
|
||||
Auth: authSvc,
|
||||
Directory: dirSvc,
|
||||
Settings: settingsSvc,
|
||||
Collab: hub,
|
||||
Admin: admin.Handler("/admin"),
|
||||
Log: log,
|
||||
|
||||
@@ -52,6 +52,17 @@ func NormalizeRole(role string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ---- Instance --------------------------------------------------------------
|
||||
|
||||
// ManageInstance checks changing instance-wide settings (signup rules,
|
||||
// branding, mail, storage, backups): superadmins only.
|
||||
func ManageInstance(c Caller) error {
|
||||
if !c.IsSuperadmin() {
|
||||
return apperr.Forbidden("superadmin role required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- Users -----------------------------------------------------------------
|
||||
|
||||
// UserScope says which users a manager may list: all of them, or one org.
|
||||
|
||||
@@ -184,6 +184,15 @@ type AuthMethods struct {
|
||||
Signup bool `json:"signup"`
|
||||
}
|
||||
|
||||
// BrandingSettings defines model for BrandingSettings.
|
||||
type BrandingSettings struct {
|
||||
AccentColor string `json:"accentColor"`
|
||||
AppName string `json:"appName"`
|
||||
|
||||
// Logo data:image/(png|jpeg|webp|svg+xml);base64,..., at most 256 KB
|
||||
Logo string `json:"logo"`
|
||||
}
|
||||
|
||||
// CreateUserRequest defines model for CreateUserRequest.
|
||||
type CreateUserRequest struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
@@ -213,6 +222,22 @@ type Error struct {
|
||||
MfaId *string `json:"mfaId,omitempty"`
|
||||
}
|
||||
|
||||
// InstanceSettings defines model for InstanceSettings.
|
||||
type InstanceSettings struct {
|
||||
Branding BrandingSettings `json:"branding"`
|
||||
Signup SignupSettings `json:"signup"`
|
||||
Smtp SmtpSettings `json:"smtp"`
|
||||
Storage StorageSettings `json:"storage"`
|
||||
}
|
||||
|
||||
// InstanceSettingsUpdate defines model for InstanceSettingsUpdate.
|
||||
type InstanceSettingsUpdate struct {
|
||||
Branding *BrandingSettings `json:"branding,omitempty"`
|
||||
Signup *SignupSettings `json:"signup,omitempty"`
|
||||
Smtp *SmtpSettings `json:"smtp,omitempty"`
|
||||
Storage *StorageSettings `json:"storage,omitempty"`
|
||||
}
|
||||
|
||||
// LoginRequest defines model for LoginRequest.
|
||||
type LoginRequest struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
@@ -292,6 +317,19 @@ type PageVersion struct {
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// PublicSettings defines model for PublicSettings.
|
||||
type PublicSettings struct {
|
||||
// AccentColor #rrggbb, or empty for the default
|
||||
AccentColor string `json:"accentColor"`
|
||||
AppName string `json:"appName"`
|
||||
|
||||
// Logo A data URL
|
||||
Logo string `json:"logo"`
|
||||
|
||||
// Signup Self-service signup is open
|
||||
Signup bool `json:"signup"`
|
||||
}
|
||||
|
||||
// Role Instance role. admin manages their own organization; superadmin manages everything.
|
||||
type Role string
|
||||
|
||||
@@ -308,6 +346,28 @@ type SignupRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// SignupSettings defines model for SignupSettings.
|
||||
type SignupSettings struct {
|
||||
// Domains Allowed email domains; empty allows all
|
||||
Domains []string `json:"domains"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// SmtpSettings defines model for SmtpSettings.
|
||||
type SmtpSettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
|
||||
// Password Leave out to keep the stored password
|
||||
Password *string `json:"password,omitempty"`
|
||||
PasswordSet *bool `json:"passwordSet,omitempty"`
|
||||
Port int `json:"port"`
|
||||
SenderAddress string `json:"senderAddress"`
|
||||
SenderName string `json:"senderName"`
|
||||
Tls bool `json:"tls"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Space defines model for Space.
|
||||
type Space struct {
|
||||
Created string `json:"created"`
|
||||
@@ -354,6 +414,22 @@ type Status struct {
|
||||
// StatusStatus defines model for Status.Status.
|
||||
type StatusStatus string
|
||||
|
||||
// StorageSettings defines model for StorageSettings.
|
||||
type StorageSettings struct {
|
||||
AccessKey string `json:"accessKey"`
|
||||
Bucket string `json:"bucket"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
ForcePathStyle bool `json:"forcePathStyle"`
|
||||
Region string `json:"region"`
|
||||
|
||||
// S3 false stores files on docwell-db's disk
|
||||
S3 bool `json:"s3"`
|
||||
|
||||
// Secret Leave out to keep the stored secret
|
||||
Secret *string `json:"secret,omitempty"`
|
||||
SecretSet *bool `json:"secretSet,omitempty"`
|
||||
}
|
||||
|
||||
// TrashedPage defines model for TrashedPage.
|
||||
type TrashedPage struct {
|
||||
DeletedAt string `json:"deletedAt"`
|
||||
@@ -441,6 +517,11 @@ type WorkspaceMember struct {
|
||||
// WorkspaceRole defines model for WorkspaceRole.
|
||||
type WorkspaceRole string
|
||||
|
||||
// SendTestEmailJSONBody defines parameters for SendTestEmail.
|
||||
type SendTestEmailJSONBody struct {
|
||||
To openapi_types.Email `json:"to"`
|
||||
}
|
||||
|
||||
// LoginWithOtpJSONBody defines parameters for LoginWithOtp.
|
||||
type LoginWithOtpJSONBody struct {
|
||||
Code string `json:"code"`
|
||||
@@ -547,6 +628,12 @@ type CreateSpaceJSONBody struct {
|
||||
Visibility *SpaceVisibility `json:"visibility,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateInstanceSettingsJSONRequestBody defines body for UpdateInstanceSettings for application/json ContentType.
|
||||
type UpdateInstanceSettingsJSONRequestBody = InstanceSettingsUpdate
|
||||
|
||||
// SendTestEmailJSONRequestBody defines body for SendTestEmail for application/json ContentType.
|
||||
type SendTestEmailJSONRequestBody SendTestEmailJSONBody
|
||||
|
||||
// LoginJSONRequestBody defines body for Login for application/json ContentType.
|
||||
type LoginJSONRequestBody = LoginRequest
|
||||
|
||||
|
||||
@@ -133,6 +133,9 @@ type Options struct {
|
||||
SignupEnabled bool
|
||||
// SignupDomains, if not empty, limits signup to these email domains.
|
||||
SignupDomains []string
|
||||
// Rules, when set, replaces SignupEnabled and SignupDomains with rules
|
||||
// read on every signup (the admin panel can change them at runtime).
|
||||
Rules func(ctx context.Context) (enabled bool, domains []string, err error)
|
||||
// CacheTTL is how long a verified token is trusted without asking
|
||||
// PocketBase again.
|
||||
CacheTTL time.Duration
|
||||
@@ -274,10 +277,14 @@ func (s *Service) Signup(ctx context.Context, in SignupInput) (Session, error) {
|
||||
}
|
||||
|
||||
if !first {
|
||||
if !s.opts.SignupEnabled {
|
||||
enabled, domains, err := s.signupRules(ctx)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
if !enabled {
|
||||
return Session{}, ErrSignupDisabled
|
||||
}
|
||||
if !s.domainAllowed(in.Email) {
|
||||
if !DomainAllowed(domains, in.Email) {
|
||||
return Session{}, ErrDomainNotAllowed
|
||||
}
|
||||
}
|
||||
@@ -301,16 +308,25 @@ func (s *Service) Signup(ctx context.Context, in SignupInput) (Session, error) {
|
||||
return s.Login(ctx, in.Email, in.Password, "")
|
||||
}
|
||||
|
||||
func (s *Service) domainAllowed(email string) bool {
|
||||
if len(s.opts.SignupDomains) == 0 {
|
||||
func (s *Service) signupRules(ctx context.Context) (bool, []string, error) {
|
||||
if s.opts.Rules != nil {
|
||||
return s.opts.Rules(ctx)
|
||||
}
|
||||
return s.opts.SignupEnabled, s.opts.SignupDomains, nil
|
||||
}
|
||||
|
||||
// DomainAllowed reports whether email's domain is on the allow-list; an empty
|
||||
// list allows every domain.
|
||||
func DomainAllowed(domains []string, email string) bool {
|
||||
if len(domains) == 0 {
|
||||
return true
|
||||
}
|
||||
at := strings.LastIndexByte(email, '@')
|
||||
if at < 0 {
|
||||
return false
|
||||
}
|
||||
domain := strings.ToLower(email[at+1:])
|
||||
for _, d := range s.opts.SignupDomains {
|
||||
domain := strings.ToLower(strings.TrimSpace(email[at+1:]))
|
||||
for _, d := range domains {
|
||||
if strings.EqualFold(d, domain) {
|
||||
return true
|
||||
}
|
||||
@@ -384,7 +400,11 @@ func (s *Service) Methods(ctx context.Context) (Methods, error) {
|
||||
if err := s.pb.DoAs(ctx, http.MethodGet, usersPath+"/auth-methods", "", nil, &res); err != nil {
|
||||
return Methods{}, mapError(err)
|
||||
}
|
||||
m := Methods{Password: res.Password.Enabled, OTP: res.OTP.Enabled, MFA: res.MFA.Enabled, OAuth2: []string{}, Signup: s.opts.SignupEnabled}
|
||||
signup, _, err := s.signupRules(ctx)
|
||||
if err != nil {
|
||||
return Methods{}, err
|
||||
}
|
||||
m := Methods{Password: res.Password.Enabled, OTP: res.OTP.Enabled, MFA: res.MFA.Enabled, OAuth2: []string{}, Signup: signup}
|
||||
if res.OAuth2.Enabled {
|
||||
for _, p := range res.OAuth2.Providers {
|
||||
m.OAuth2 = append(m.OAuth2, p.Name)
|
||||
|
||||
@@ -15,6 +15,8 @@ type Config struct {
|
||||
Addr string
|
||||
// PublicURL is the externally reachable base URL of the server.
|
||||
PublicURL string
|
||||
// WebURL is the base URL of docwell-web; links in emails open it.
|
||||
WebURL string
|
||||
// CORSOrigins lists origins allowed to call the API from a browser.
|
||||
CORSOrigins []string
|
||||
|
||||
@@ -46,6 +48,7 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
|
||||
cfg := Config{
|
||||
Addr: get("DOCWELL_ADDR", ":8080"),
|
||||
PublicURL: strings.TrimRight(get("DOCWELL_PUBLIC_URL", "http://localhost:8080"), "/"),
|
||||
WebURL: strings.TrimRight(get("DOCWELL_WEB_URL", "http://localhost:3000"), "/"),
|
||||
CORSOrigins: splitList(get("DOCWELL_CORS_ORIGINS", "http://localhost:5173,http://localhost:3000")),
|
||||
PocketBaseURL: strings.TrimRight(get("DOCWELL_PB_URL", "http://127.0.0.1:8090"), "/"),
|
||||
PocketBaseEmail: get("DOCWELL_PB_EMAIL", ""),
|
||||
|
||||
@@ -37,10 +37,11 @@ func CurrentUser(ctx context.Context) (auth.User, bool) {
|
||||
}
|
||||
|
||||
type api struct {
|
||||
auth AuthService
|
||||
dir DirectoryService
|
||||
collab CollabHub
|
||||
log *slog.Logger
|
||||
auth AuthService
|
||||
dir DirectoryService
|
||||
settings SettingsService
|
||||
collab CollabHub
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||
@@ -140,6 +141,7 @@ func (a *api) routes(mux *routeMux) {
|
||||
|
||||
a.directoryRoutes(mux)
|
||||
a.spaceRoutes(mux)
|
||||
a.settingsRoutes(mux)
|
||||
}
|
||||
|
||||
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
|
||||
@@ -23,6 +23,7 @@ type Deps struct {
|
||||
DB Pinger
|
||||
Auth AuthService
|
||||
Directory DirectoryService
|
||||
Settings SettingsService
|
||||
// Collab serves /collab; nil disables live editing.
|
||||
Collab CollabHub
|
||||
Admin http.Handler
|
||||
@@ -51,7 +52,7 @@ func NewRouter(d Deps) http.Handler {
|
||||
|
||||
func newMux(d Deps) *routeMux {
|
||||
mux := &routeMux{ServeMux: http.NewServeMux()}
|
||||
a := &api{auth: d.Auth, dir: d.Directory, collab: d.Collab, log: d.Log}
|
||||
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, collab: d.Collab, log: d.Log}
|
||||
a.routes(mux)
|
||||
a.collabRoute(mux, d.CORSOrigins)
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/settings"
|
||||
)
|
||||
|
||||
// SettingsService is the part of settings.Service the HTTP layer uses.
|
||||
type SettingsService interface {
|
||||
Public(ctx context.Context) (settings.Public, error)
|
||||
Get(ctx context.Context, c access.Caller) (settings.Instance, error)
|
||||
Apply(ctx context.Context, c access.Caller, in settings.Update) (settings.Instance, error)
|
||||
TestEmail(ctx context.Context, c access.Caller, to string) error
|
||||
TestStorage(ctx context.Context, c access.Caller) error
|
||||
}
|
||||
|
||||
func (a *api) settingsRoutes(mux *routeMux) {
|
||||
// Branding and signup availability, for the login and signup pages.
|
||||
mux.HandleFunc("GET /api/v1/settings/public", func(w http.ResponseWriter, r *http.Request) {
|
||||
p, err := a.settings.Public(r.Context())
|
||||
a.respond(w, p, err)
|
||||
})
|
||||
|
||||
// Instance settings (superadmins; the service checks the role).
|
||||
mux.HandleFunc("GET /api/v1/admin/settings", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
s, err := a.settings.Get(r.Context(), caller(r))
|
||||
a.respond(w, s, err)
|
||||
}))
|
||||
mux.HandleFunc("PATCH /api/v1/admin/settings", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in settings.Update
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
s, err := a.settings.Apply(r.Context(), caller(r), in)
|
||||
a.respond(w, s, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/admin/settings/test-email", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ To string }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
a.respondNoContent(w, a.settings.TestEmail(r.Context(), caller(r), in.To))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/admin/settings/test-storage", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.settings.TestStorage(r.Context(), caller(r)))
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package mail sends Docwell's own emails (invites, test mails). Delivery goes
|
||||
// through PocketBase (pb_hooks/docwell.pb.js), so every email uses the one SMTP
|
||||
// configuration the admin panel edits.
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
texttemplate "text/template"
|
||||
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// Message is one email. HTML and Text are alternative bodies.
|
||||
type Message struct {
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
HTML string `json:"html"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// Sender delivers a message.
|
||||
type Sender interface {
|
||||
Send(ctx context.Context, m Message) error
|
||||
}
|
||||
|
||||
// PBSender sends through PocketBase's mail hook.
|
||||
type PBSender struct{ PB *pocketbase.Client }
|
||||
|
||||
func (s PBSender) Send(ctx context.Context, m Message) error {
|
||||
return s.PB.Do(ctx, http.MethodPost, "/api/docwell/mail", m, nil)
|
||||
}
|
||||
|
||||
//go:embed templates
|
||||
var files embed.FS
|
||||
|
||||
var (
|
||||
htmlTemplates = template.Must(template.ParseFS(files, "templates/*.html"))
|
||||
textTemplates = texttemplate.Must(texttemplate.ParseFS(files, "templates/*.txt"))
|
||||
)
|
||||
|
||||
// Render builds a message from the templates named name.html and name.txt.
|
||||
// The first line of the text template is the subject.
|
||||
func Render(to, name string, data any) (Message, error) {
|
||||
var text, html bytes.Buffer
|
||||
if err := textTemplates.ExecuteTemplate(&text, name+".txt", data); err != nil {
|
||||
return Message{}, fmt.Errorf("mail: %s.txt: %w", name, err)
|
||||
}
|
||||
if err := htmlTemplates.ExecuteTemplate(&html, name+".html", data); err != nil {
|
||||
return Message{}, fmt.Errorf("mail: %s.html: %w", name, err)
|
||||
}
|
||||
subject, body, _ := strings.Cut(text.String(), "\n")
|
||||
return Message{To: to, Subject: strings.TrimSpace(subject), HTML: html.String(), Text: strings.TrimSpace(body) + "\n"}, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package mail
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRender(t *testing.T) {
|
||||
m, err := Render("a@b.test", "test", map[string]string{"AppName": "Acme <Wiki>"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.To != "a@b.test" || m.Subject != "Acme <Wiki> test email" {
|
||||
t.Errorf("to/subject = %q / %q", m.To, m.Subject)
|
||||
}
|
||||
if !strings.Contains(m.HTML, "Acme <Wiki>") {
|
||||
t.Errorf("html must escape the app name: %s", m.HTML)
|
||||
}
|
||||
if strings.Contains(m.Text, "test email\n") || !strings.HasPrefix(m.Text, "This is a test email") {
|
||||
t.Errorf("text must not repeat the subject: %q", m.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<p>This is a test email from {{.AppName}}.</p>
|
||||
<p>Mail delivery works.</p>
|
||||
@@ -0,0 +1,2 @@
|
||||
{{.AppName}} test email
|
||||
This is a test email from {{.AppName}}. Mail delivery works.
|
||||
@@ -0,0 +1,488 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package settings holds the instance settings superadmins edit in the admin
|
||||
// panel. Signup rules and branding are stored in the instance_settings
|
||||
// collection (environment variables only seed the defaults); mail and file
|
||||
// storage are PocketBase's own settings, patched through its settings API.
|
||||
package settings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// Signup controls self-service account creation.
|
||||
type Signup struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
// Domains limits signup to these email domains when not empty.
|
||||
Domains []string `json:"domains"`
|
||||
}
|
||||
|
||||
// Branding is how the instance presents itself in the apps and emails.
|
||||
type Branding struct {
|
||||
AppName string `json:"appName"`
|
||||
// AccentColor is "#rrggbb", or "" for the design system's default.
|
||||
AccentColor string `json:"accentColor"`
|
||||
// Logo is a data: URL (PNG, JPEG, WebP or SVG), or "" for the Docwell logo.
|
||||
Logo string `json:"logo"`
|
||||
}
|
||||
|
||||
// SMTP is the outgoing mail server. Password is write-only: reads leave it
|
||||
// empty and report PasswordSet instead.
|
||||
type SMTP struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password,omitempty"`
|
||||
PasswordSet bool `json:"passwordSet"`
|
||||
TLS bool `json:"tls"`
|
||||
SenderName string `json:"senderName"`
|
||||
SenderAddress string `json:"senderAddress"`
|
||||
}
|
||||
|
||||
// Storage selects where uploaded files live: PocketBase's local disk, or S3.
|
||||
// Secret is write-only like SMTP.Password.
|
||||
type Storage struct {
|
||||
S3 bool `json:"s3"`
|
||||
Bucket string `json:"bucket"`
|
||||
Region string `json:"region"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
Secret string `json:"secret,omitempty"`
|
||||
SecretSet bool `json:"secretSet"`
|
||||
ForcePathStyle bool `json:"forcePathStyle"`
|
||||
}
|
||||
|
||||
// Instance is every setting, as the admin panel shows it.
|
||||
type Instance struct {
|
||||
Signup Signup `json:"signup"`
|
||||
Branding Branding `json:"branding"`
|
||||
SMTP SMTP `json:"smtp"`
|
||||
Storage Storage `json:"storage"`
|
||||
}
|
||||
|
||||
// Update changes the sections that are set. A nil SMTP.Password or
|
||||
// Storage.Secret keeps the stored one.
|
||||
type Update struct {
|
||||
Signup *Signup `json:"signup"`
|
||||
Branding *Branding `json:"branding"`
|
||||
SMTP *struct {
|
||||
SMTP
|
||||
Password *string `json:"password"`
|
||||
} `json:"smtp"`
|
||||
Storage *struct {
|
||||
Storage
|
||||
Secret *string `json:"secret"`
|
||||
} `json:"storage"`
|
||||
}
|
||||
|
||||
// Public is what signed-out visitors may know (the login page needs it).
|
||||
type Public struct {
|
||||
AppName string `json:"appName"`
|
||||
AccentColor string `json:"accentColor"`
|
||||
Logo string `json:"logo"`
|
||||
Signup bool `json:"signup"`
|
||||
}
|
||||
|
||||
const (
|
||||
keySignup = "signup"
|
||||
keyBranding = "branding"
|
||||
cacheTTL = 30 * time.Second
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
pb *pocketbase.Client
|
||||
defaults Signup
|
||||
mail mail.Sender
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]cached
|
||||
}
|
||||
|
||||
type cached struct {
|
||||
raw json.RawMessage
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// New returns the settings service; defaults apply until a superadmin saves
|
||||
// signup rules of their own.
|
||||
func New(pb *pocketbase.Client, defaults Signup, sender mail.Sender) *Service {
|
||||
return &Service{pb: pb, defaults: defaults, mail: sender, now: time.Now, cache: map[string]cached{}}
|
||||
}
|
||||
|
||||
type kvRecord struct {
|
||||
ID string `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
}
|
||||
|
||||
// load reads one key into out; found is false when it was never saved.
|
||||
func (s *Service) load(ctx context.Context, key string, out any) (found bool, err error) {
|
||||
s.mu.Lock()
|
||||
c, ok := s.cache[key]
|
||||
s.mu.Unlock()
|
||||
if !ok || s.now().After(c.expires) {
|
||||
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
c = cached{expires: s.now().Add(cacheTTL)}
|
||||
if len(res.Items) > 0 {
|
||||
c.raw = res.Items[0].Value
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = c
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if len(c.raw) == 0 || string(c.raw) == "null" {
|
||||
return false, nil
|
||||
}
|
||||
return true, json.Unmarshal(c.raw, out)
|
||||
}
|
||||
|
||||
func (s *Service) save(ctx context.Context, key string, v any) error {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := map[string]any{"key": key, "value": json.RawMessage(raw)}
|
||||
if len(res.Items) > 0 {
|
||||
_, err = pocketbase.Update[kvRecord](ctx, s.pb, "instance_settings", res.Items[0].ID, body)
|
||||
} else {
|
||||
_, err = pocketbase.Create[kvRecord](ctx, s.pb, "instance_settings", body)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = cached{raw: raw, expires: s.now().Add(cacheTTL)}
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Signup returns the signup rules (the defaults until a superadmin saves some).
|
||||
func (s *Service) Signup(ctx context.Context) (Signup, error) {
|
||||
out := s.defaults
|
||||
if _, err := s.load(ctx, keySignup, &out); err != nil {
|
||||
return Signup{}, err
|
||||
}
|
||||
if out.Domains == nil {
|
||||
out.Domains = []string{}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Branding returns the instance branding; an unset name is "Docwell".
|
||||
func (s *Service) Branding(ctx context.Context) (Branding, error) {
|
||||
var out Branding
|
||||
if _, err := s.load(ctx, keyBranding, &out); err != nil {
|
||||
return Branding{}, err
|
||||
}
|
||||
if out.AppName == "" {
|
||||
out.AppName = "Docwell"
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Public returns the settings signed-out visitors may see.
|
||||
func (s *Service) Public(ctx context.Context) (Public, error) {
|
||||
b, err := s.Branding(ctx)
|
||||
if err != nil {
|
||||
return Public{}, err
|
||||
}
|
||||
su, err := s.Signup(ctx)
|
||||
if err != nil {
|
||||
return Public{}, err
|
||||
}
|
||||
return Public{AppName: b.AppName, AccentColor: b.AccentColor, Logo: b.Logo, Signup: su.Enabled}, nil
|
||||
}
|
||||
|
||||
// pbSettings is the part of PocketBase's /api/settings this package uses.
|
||||
// PocketBase never returns passwords or secrets.
|
||||
type pbSettings struct {
|
||||
Meta struct {
|
||||
AppName string `json:"appName"`
|
||||
SenderName string `json:"senderName"`
|
||||
SenderAddress string `json:"senderAddress"`
|
||||
} `json:"meta"`
|
||||
SMTP struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
TLS bool `json:"tls"`
|
||||
} `json:"smtp"`
|
||||
S3 struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Bucket string `json:"bucket"`
|
||||
Region string `json:"region"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
ForcePathStyle bool `json:"forcePathStyle"`
|
||||
} `json:"s3"`
|
||||
}
|
||||
|
||||
func (s *Service) pbSettings(ctx context.Context) (pbSettings, error) {
|
||||
var out pbSettings
|
||||
err := s.pb.Do(ctx, http.MethodGet, "/api/settings", nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Get returns every instance setting (superadmin).
|
||||
func (s *Service) Get(ctx context.Context, c access.Caller) (Instance, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
return s.get(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) get(ctx context.Context) (Instance, error) {
|
||||
su, err := s.Signup(ctx)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
b, err := s.Branding(ctx)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
pb, err := s.pbSettings(ctx)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
return Instance{
|
||||
Signup: su,
|
||||
Branding: b,
|
||||
SMTP: SMTP{
|
||||
Enabled: pb.SMTP.Enabled, Host: pb.SMTP.Host, Port: pb.SMTP.Port, Username: pb.SMTP.Username,
|
||||
// PocketBase hides the password; with a username set, assume one is stored.
|
||||
PasswordSet: pb.SMTP.Username != "", TLS: pb.SMTP.TLS,
|
||||
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
|
||||
},
|
||||
Storage: Storage{
|
||||
S3: pb.S3.Enabled, Bucket: pb.S3.Bucket, Region: pb.S3.Region, Endpoint: pb.S3.Endpoint,
|
||||
AccessKey: pb.S3.AccessKey, SecretSet: pb.S3.AccessKey != "", ForcePathStyle: pb.S3.ForcePathStyle,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
var (
|
||||
domainPattern = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`)
|
||||
colorPattern = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
||||
logoPattern = regexp.MustCompile(`^data:image/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$`)
|
||||
)
|
||||
|
||||
// maxLogo caps the logo data URL; it is sent with every public settings read.
|
||||
const maxLogo = 256 << 10
|
||||
|
||||
// CleanDomains normalizes an allow-list ("@Example.com " → "example.com").
|
||||
func CleanDomains(in []string) ([]string, error) {
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, d := range in {
|
||||
d = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(d), "@"))
|
||||
if d == "" || seen[d] {
|
||||
continue
|
||||
}
|
||||
if !domainPattern.MatchString(d) {
|
||||
return nil, apperr.InvalidFields(map[string]string{"signup.domains": fmt.Sprintf("%q is not a domain.", d)})
|
||||
}
|
||||
seen[d] = true
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func cleanBranding(b Branding) (Branding, error) {
|
||||
b.AppName = strings.TrimSpace(b.AppName)
|
||||
b.AccentColor = strings.TrimSpace(b.AccentColor)
|
||||
fields := map[string]string{}
|
||||
if b.AppName == "" {
|
||||
fields["branding.appName"] = "Name is required."
|
||||
} else if len(b.AppName) > 60 {
|
||||
fields["branding.appName"] = "Name is too long (max 60)."
|
||||
}
|
||||
if b.AccentColor != "" && !colorPattern.MatchString(b.AccentColor) {
|
||||
fields["branding.accentColor"] = "Colour must look like #2f7d6d."
|
||||
}
|
||||
if b.Logo != "" && (len(b.Logo) > maxLogo || !logoPattern.MatchString(b.Logo)) {
|
||||
fields["branding.logo"] = "Logo must be a PNG, JPEG, WebP or SVG image under 190 KB."
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
return Branding{}, apperr.InvalidFields(fields)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Apply saves the sections set in in (superadmin) and returns the result.
|
||||
func (s *Service) Apply(ctx context.Context, c access.Caller, in Update) (Instance, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
|
||||
patch := map[string]any{}
|
||||
meta := map[string]any{}
|
||||
var branding *Branding
|
||||
if in.Branding != nil {
|
||||
b, err := cleanBranding(*in.Branding)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
branding = &b
|
||||
// PocketBase signs its own emails (verification, reset) with this name.
|
||||
meta["appName"] = b.AppName
|
||||
meta["senderName"] = b.AppName
|
||||
if b.AccentColor != "" {
|
||||
meta["accentColor"] = b.AccentColor
|
||||
}
|
||||
}
|
||||
var signup *Signup
|
||||
if in.Signup != nil {
|
||||
domains, err := CleanDomains(in.Signup.Domains)
|
||||
if err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
signup = &Signup{Enabled: in.Signup.Enabled, Domains: domains}
|
||||
}
|
||||
if in.SMTP != nil {
|
||||
m := in.SMTP
|
||||
m.Host = strings.TrimSpace(m.Host)
|
||||
m.SenderAddress = strings.TrimSpace(m.SenderAddress)
|
||||
fields := map[string]string{}
|
||||
if m.Enabled && m.Host == "" {
|
||||
fields["smtp.host"] = "Host is required."
|
||||
}
|
||||
if m.Enabled && (m.Port < 1 || m.Port > 65535) {
|
||||
fields["smtp.port"] = "Port must be between 1 and 65535."
|
||||
}
|
||||
if !strings.Contains(m.SenderAddress, "@") {
|
||||
fields["smtp.senderAddress"] = "A valid sender address is required."
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
return Instance{}, apperr.InvalidFields(fields)
|
||||
}
|
||||
smtp := map[string]any{
|
||||
"enabled": m.Enabled, "host": m.Host, "port": m.Port, "username": strings.TrimSpace(m.Username), "tls": m.TLS,
|
||||
}
|
||||
if m.Password != nil {
|
||||
smtp["password"] = *m.Password
|
||||
}
|
||||
patch["smtp"] = smtp
|
||||
meta["senderAddress"] = m.SenderAddress
|
||||
if name := strings.TrimSpace(m.SenderName); name != "" {
|
||||
meta["senderName"] = name
|
||||
}
|
||||
}
|
||||
if in.Storage != nil {
|
||||
st := in.Storage
|
||||
if st.S3 && (strings.TrimSpace(st.Bucket) == "" || strings.TrimSpace(st.Endpoint) == "") {
|
||||
return Instance{}, apperr.InvalidFields(map[string]string{"storage.bucket": "Bucket and endpoint are required for S3."})
|
||||
}
|
||||
s3 := map[string]any{
|
||||
"enabled": st.S3, "bucket": strings.TrimSpace(st.Bucket), "region": strings.TrimSpace(st.Region),
|
||||
"endpoint": strings.TrimSpace(st.Endpoint), "accessKey": strings.TrimSpace(st.AccessKey), "forcePathStyle": st.ForcePathStyle,
|
||||
}
|
||||
if st.Secret != nil {
|
||||
s3["secret"] = *st.Secret
|
||||
}
|
||||
patch["s3"] = s3
|
||||
}
|
||||
if len(meta) > 0 {
|
||||
patch["meta"] = meta
|
||||
}
|
||||
|
||||
if len(patch) > 0 {
|
||||
if err := s.pb.Do(ctx, http.MethodPatch, "/api/settings", patch, nil); err != nil {
|
||||
return Instance{}, settingsError(err)
|
||||
}
|
||||
}
|
||||
if branding != nil {
|
||||
if err := s.save(ctx, keyBranding, branding); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
}
|
||||
if signup != nil {
|
||||
if err := s.save(ctx, keySignup, signup); err != nil {
|
||||
return Instance{}, err
|
||||
}
|
||||
}
|
||||
return s.get(ctx)
|
||||
}
|
||||
|
||||
// settingsError reports PocketBase's validation of mail and storage settings
|
||||
// as field errors ("smtp.host", "s3.bucket", ...).
|
||||
func settingsError(err error) error {
|
||||
var pbErr *pocketbase.Error
|
||||
if !errors.As(err, &pbErr) || pbErr.Status != http.StatusBadRequest {
|
||||
return err
|
||||
}
|
||||
fields := map[string]string{}
|
||||
for k, v := range pbErr.Data {
|
||||
fields[k] = v.Message
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
return apperr.Invalid(pbErr.Message)
|
||||
}
|
||||
return apperr.InvalidFields(fields)
|
||||
}
|
||||
|
||||
// TestEmail sends a test message to to (superadmin).
|
||||
func (s *Service) TestEmail(ctx context.Context, c access.Caller, to string) error {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return err
|
||||
}
|
||||
to = strings.TrimSpace(to)
|
||||
if !strings.Contains(to, "@") {
|
||||
return apperr.InvalidFields(map[string]string{"to": "A valid email is required."})
|
||||
}
|
||||
b, err := s.Branding(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := mail.Render(to, "test", map[string]string{"AppName": b.AppName})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.mail.Send(ctx, m); err != nil {
|
||||
var pbErr *pocketbase.Error
|
||||
if errors.As(err, &pbErr) {
|
||||
return apperr.Invalid("the mail server rejected the message: " + pbErr.Message)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestStorage checks that PocketBase can reach the configured S3 bucket (superadmin).
|
||||
func (s *Service) TestStorage(ctx context.Context, c access.Caller) error {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return err
|
||||
}
|
||||
err := s.pb.Do(ctx, http.MethodPost, "/api/settings/test/s3", map[string]string{"filesystem": "storage"}, nil)
|
||||
var pbErr *pocketbase.Error
|
||||
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest {
|
||||
return apperr.Invalid("storage test failed: " + pbErr.Message)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package settings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// fakePB stores instance_settings records and PocketBase settings in memory.
|
||||
type fakePB struct {
|
||||
mu sync.Mutex
|
||||
kv map[string]json.RawMessage
|
||||
settings map[string]map[string]any
|
||||
}
|
||||
|
||||
func newFake(t *testing.T) (*fakePB, *pocketbase.Client) {
|
||||
t.Helper()
|
||||
f := &fakePB{kv: map[string]json.RawMessage{}, settings: map[string]map[string]any{
|
||||
"meta": {"appName": "Docwell", "senderName": "Docwell", "senderAddress": "no-reply@x.test"},
|
||||
"smtp": {"enabled": false, "host": "", "port": 587, "username": "", "tls": false},
|
||||
"s3": {"enabled": false},
|
||||
}}
|
||||
reply := func(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, map[string]string{"token": "su"})
|
||||
})
|
||||
mux.HandleFunc("GET /api/collections/instance_settings/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
items := []kvRecord{}
|
||||
for k, v := range f.kv {
|
||||
if r.URL.Query().Get("filter") == "key = '"+k+"'" {
|
||||
items = append(items, kvRecord{ID: "id_" + k, Key: k, Value: v})
|
||||
}
|
||||
}
|
||||
reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1})
|
||||
})
|
||||
save := func(w http.ResponseWriter, r *http.Request) {
|
||||
var rec kvRecord
|
||||
_ = json.NewDecoder(r.Body).Decode(&rec)
|
||||
f.mu.Lock()
|
||||
f.kv[rec.Key] = rec.Value
|
||||
f.mu.Unlock()
|
||||
reply(w, rec)
|
||||
}
|
||||
mux.HandleFunc("POST /api/collections/instance_settings/records", save)
|
||||
mux.HandleFunc("PATCH /api/collections/instance_settings/records/{id}", save)
|
||||
mux.HandleFunc("GET /api/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
reply(w, f.settings)
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
var patch map[string]map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&patch)
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for section, values := range patch {
|
||||
for k, v := range values {
|
||||
f.settings[section][k] = v
|
||||
}
|
||||
}
|
||||
reply(w, f.settings)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return f, pocketbase.New(srv.URL, "su@x.test", "pw")
|
||||
}
|
||||
|
||||
type sentMail struct{ got []mail.Message }
|
||||
|
||||
func (s *sentMail) Send(_ context.Context, m mail.Message) error {
|
||||
s.got = append(s.got, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
super = access.Caller{ID: "s", Role: access.RoleSuperadmin}
|
||||
admin = access.Caller{ID: "a", Role: access.RoleAdmin, OrgID: "o"}
|
||||
)
|
||||
|
||||
func TestSignupDefaultsUntilSaved(t *testing.T) {
|
||||
_, pb := newFake(t)
|
||||
s := New(pb, Signup{Enabled: false, Domains: []string{"env.test"}}, &sentMail{})
|
||||
ctx := context.Background()
|
||||
|
||||
got, err := s.Signup(ctx)
|
||||
if err != nil || got.Enabled || len(got.Domains) != 1 {
|
||||
t.Fatalf("defaults = %+v, %v", got, err)
|
||||
}
|
||||
_, err = s.Apply(ctx, super, Update{Signup: &Signup{Enabled: true, Domains: []string{" @Example.COM", "example.com", "b.test"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = s.Signup(ctx)
|
||||
if !got.Enabled || len(got.Domains) != 2 || got.Domains[0] != "example.com" {
|
||||
t.Errorf("saved = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlySuperadmins(t *testing.T) {
|
||||
_, pb := newFake(t)
|
||||
s := New(pb, Signup{}, &sentMail{})
|
||||
ctx := context.Background()
|
||||
for name, err := range map[string]error{
|
||||
"get": func() error { _, err := s.Get(ctx, admin); return err }(),
|
||||
"apply": func() error { _, err := s.Apply(ctx, admin, Update{}); return err }(),
|
||||
"mail": s.TestEmail(ctx, admin, "x@y.test"),
|
||||
} {
|
||||
if e, ok := apperr.As(err); !ok || e.Kind != apperr.KindForbidden {
|
||||
t.Errorf("%s by an org admin = %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrandingAndSMTP(t *testing.T) {
|
||||
f, pb := newFake(t)
|
||||
s := New(pb, Signup{}, &sentMail{})
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := s.Apply(ctx, super, Update{Branding: &Branding{AppName: "Acme", AccentColor: "red"}})
|
||||
if e, ok := apperr.As(err); !ok || e.Fields["branding.accentColor"] == "" {
|
||||
t.Errorf("bad colour = %v", err)
|
||||
}
|
||||
|
||||
pw := "secret"
|
||||
up := Update{Branding: &Branding{AppName: " Acme Wiki ", AccentColor: "#112233"}}
|
||||
up.SMTP = &struct {
|
||||
SMTP
|
||||
Password *string `json:"password"`
|
||||
}{SMTP: SMTP{Enabled: true, Host: "smtp.x.test", Port: 465, Username: "me", TLS: true, SenderAddress: "wiki@x.test"}, Password: &pw}
|
||||
got, err := s.Apply(ctx, super, up)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Branding.AppName != "Acme Wiki" || !got.SMTP.Enabled || got.SMTP.Port != 465 || got.SMTP.Password != "" || !got.SMTP.PasswordSet {
|
||||
t.Errorf("after apply = %+v", got)
|
||||
}
|
||||
if f.settings["meta"]["appName"] != "Acme Wiki" || f.settings["smtp"]["password"] != "secret" {
|
||||
t.Errorf("pocketbase settings = %v", f.settings)
|
||||
}
|
||||
|
||||
// Leaving the password out keeps the stored one.
|
||||
up.SMTP.Password = nil
|
||||
if _, err := s.Apply(ctx, super, Update{SMTP: up.SMTP}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.settings["smtp"]["password"] != "secret" {
|
||||
t.Error("password must survive an update without one")
|
||||
}
|
||||
|
||||
pub, err := s.Public(ctx)
|
||||
if err != nil || pub.AppName != "Acme Wiki" || pub.AccentColor != "#112233" {
|
||||
t.Errorf("public = %+v, %v", pub, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestEmail(t *testing.T) {
|
||||
_, pb := newFake(t)
|
||||
sent := &sentMail{}
|
||||
s := New(pb, Signup{}, sent)
|
||||
if err := s.TestEmail(context.Background(), super, "nope"); err == nil {
|
||||
t.Error("invalid address must fail")
|
||||
}
|
||||
if err := s.TestEmail(context.Background(), super, "me@x.test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sent.got) != 1 || sent.got[0].To != "me@x.test" || sent.got[0].Subject != "Docwell test email" {
|
||||
t.Errorf("sent = %+v", sent.got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanDomains(t *testing.T) {
|
||||
if _, err := CleanDomains([]string{"not a domain"}); err == nil {
|
||||
t.Error("spaces must be rejected")
|
||||
}
|
||||
got, err := CleanDomains([]string{"", "A.b"})
|
||||
if err != nil || len(got) != 1 || got[0] != "a.b" {
|
||||
t.Errorf("got %v, %v", got, err)
|
||||
}
|
||||
var e *apperr.Error
|
||||
_, err = CleanDomains([]string{"x"})
|
||||
if !errors.As(err, &e) {
|
||||
t.Errorf("single label = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -850,6 +850,81 @@ paths:
|
||||
schema: { $ref: "#/components/schemas/Page" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/settings/public:
|
||||
get:
|
||||
operationId: getPublicSettings
|
||||
tags: [settings]
|
||||
summary: Branding and signup availability, for signed-out pages
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PublicSettings" }
|
||||
/api/v1/admin/settings:
|
||||
get:
|
||||
operationId: getInstanceSettings
|
||||
tags: [settings]
|
||||
summary: Every instance setting (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/InstanceSettings" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
patch:
|
||||
operationId: updateInstanceSettings
|
||||
tags: [settings]
|
||||
summary: Change the sections that are present (superadmin)
|
||||
description: >-
|
||||
Mail and storage settings are PocketBase's own. Passwords and secrets are write-only:
|
||||
leave them out to keep the stored value. Environment variables such as
|
||||
DOCWELL_SMTP_HOST are applied again when docwell-db starts.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/InstanceSettingsUpdate" }
|
||||
responses:
|
||||
"200":
|
||||
description: Saved
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/InstanceSettings" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/admin/settings/test-email:
|
||||
post:
|
||||
operationId: sendTestEmail
|
||||
tags: [settings]
|
||||
summary: Send a test email with the saved mail settings (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [to]
|
||||
properties:
|
||||
to: { type: string, format: email }
|
||||
responses:
|
||||
"204": { description: Sent }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/admin/settings/test-storage:
|
||||
post:
|
||||
operationId: testStorage
|
||||
tags: [settings]
|
||||
summary: Check that the configured S3 bucket is reachable (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"204": { description: Reachable }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
components:
|
||||
securitySchemes:
|
||||
bearer:
|
||||
@@ -1110,3 +1185,64 @@ components:
|
||||
properties:
|
||||
name: { type: string }
|
||||
version: { type: string }
|
||||
PublicSettings:
|
||||
type: object
|
||||
required: [appName, accentColor, logo, signup]
|
||||
properties:
|
||||
appName: { type: string }
|
||||
accentColor: { type: string, description: "#rrggbb, or empty for the default" }
|
||||
logo: { type: string, description: A data URL, or empty for the Docwell logo }
|
||||
signup: { type: boolean, description: Self-service signup is open }
|
||||
SignupSettings:
|
||||
type: object
|
||||
required: [enabled, domains]
|
||||
properties:
|
||||
enabled: { type: boolean }
|
||||
domains: { type: array, items: { type: string }, description: Allowed email domains; empty allows all }
|
||||
BrandingSettings:
|
||||
type: object
|
||||
required: [appName, accentColor, logo]
|
||||
properties:
|
||||
appName: { type: string, maxLength: 60 }
|
||||
accentColor: { type: string }
|
||||
logo: { type: string, description: "data:image/(png|jpeg|webp|svg+xml);base64,..., at most 256 KB" }
|
||||
SmtpSettings:
|
||||
type: object
|
||||
required: [enabled, host, port, username, passwordSet, tls, senderName, senderAddress]
|
||||
properties:
|
||||
enabled: { type: boolean }
|
||||
host: { type: string }
|
||||
port: { type: integer }
|
||||
username: { type: string }
|
||||
password: { type: string, writeOnly: true, description: Leave out to keep the stored password }
|
||||
passwordSet: { type: boolean, readOnly: true }
|
||||
tls: { type: boolean }
|
||||
senderName: { type: string }
|
||||
senderAddress: { type: string }
|
||||
StorageSettings:
|
||||
type: object
|
||||
required: [s3, bucket, region, endpoint, accessKey, secretSet, forcePathStyle]
|
||||
properties:
|
||||
s3: { type: boolean, description: false stores files on docwell-db's disk }
|
||||
bucket: { type: string }
|
||||
region: { type: string }
|
||||
endpoint: { type: string }
|
||||
accessKey: { type: string }
|
||||
secret: { type: string, writeOnly: true, description: Leave out to keep the stored secret }
|
||||
secretSet: { type: boolean, readOnly: true }
|
||||
forcePathStyle: { type: boolean }
|
||||
InstanceSettings:
|
||||
type: object
|
||||
required: [signup, branding, smtp, storage]
|
||||
properties:
|
||||
signup: { $ref: "#/components/schemas/SignupSettings" }
|
||||
branding: { $ref: "#/components/schemas/BrandingSettings" }
|
||||
smtp: { $ref: "#/components/schemas/SmtpSettings" }
|
||||
storage: { $ref: "#/components/schemas/StorageSettings" }
|
||||
InstanceSettingsUpdate:
|
||||
type: object
|
||||
properties:
|
||||
signup: { $ref: "#/components/schemas/SignupSettings" }
|
||||
branding: { $ref: "#/components/schemas/BrandingSettings" }
|
||||
smtp: { $ref: "#/components/schemas/SmtpSettings" }
|
||||
storage: { $ref: "#/components/schemas/StorageSettings" }
|
||||
Reference in new issue
Block a user