@midsummer-ai/sdk 0.1.0-staging.3650 → 0.1.0-staging.3656

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/THIRD-PARTY-NOTICES +1279 -0
  2. package/auth/client.d.mts +222 -18
  3. package/auth/client.mjs +321 -40
  4. package/auth/contract.d.mts +10 -1
  5. package/auth/contract.mjs +347 -30
  6. package/auth/files.d.mts +2 -28
  7. package/auth/files.mjs +2 -231
  8. package/auth/impersonate.d.mts +33 -0
  9. package/auth/impersonate.mjs +42 -0
  10. package/auth/import.d.mts +71 -0
  11. package/auth/import.mjs +195 -0
  12. package/auth/index.d.mts +5 -198
  13. package/auth/index.mjs +3 -2
  14. package/auth/mail.d.mts +23 -5
  15. package/auth/mail.mjs +93 -39
  16. package/auth/password.d.mts +10 -2
  17. package/auth/password.mjs +14 -2
  18. package/auth/react.d.mts +86 -0
  19. package/auth/react.mjs +865 -0
  20. package/auth/stand-in.d.mts +14 -3
  21. package/auth/stand-in.mjs +162 -29
  22. package/auth-CND9RW17.mjs +1819 -0
  23. package/authorize-BzDrbYtI-0gOzDrp2.mjs +18783 -0
  24. package/{client-C7QtAX5u.mjs → connection-C_JSWUrt.mjs} +3 -668
  25. package/database/client.mjs +665 -1
  26. package/dist-DXtY-DJA.mjs +343 -0
  27. package/engine-BhA0XgI7.mjs +48423 -0
  28. package/esm-E3EvzsGX.mjs +1518 -0
  29. package/factory-9jfDGyc1.mjs +1138 -0
  30. package/files-C-FvBxT4.d.mts +75 -0
  31. package/files-DAFOuID_.mjs +692 -0
  32. package/get-id-field-vhOArqXN.mjs +1455 -0
  33. package/index-CsgQ_ouh.d.mts +246 -0
  34. package/package.json +24 -7
  35. package/qr-C1mfuCT9.mjs +1163 -0
  36. package/request-state-BaLB2Hrt.mjs +85 -0
  37. package/rolldown-runtime-CL6CfywC.mjs +36 -0
  38. package/schemas-DTJTcCdK.mjs +6046 -0
  39. package/settings-si8iBtwc.d.mts +47 -0
  40. package/store-CeIGY-xT.d.mts +16 -0
  41. package/{store-dsVD9VnM.mjs → store-CsBhnabU.mjs} +1 -1
  42. package/{tabs-C85sXTwS.mjs → tabs-gHJHkhm2.mjs} +1 -1
  43. package/auth-BM6vB3XD.mjs +0 -754
  44. package/store-gCz6XVaG.d.mts +0 -15
package/auth/index.d.mts CHANGED
@@ -1,199 +1,6 @@
1
- import { n as databaseStore, t as AuthStore } from "../store-gCz6XVaG.mjs";
1
+ import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-CeIGY-xT.mjs";
2
+ import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-si8iBtwc.mjs";
2
3
  import { SignInMail, SignInMailKind, checkSignInMail, signInWords } from "./mail.mjs";
3
- import { BetterAuthPlugin } from "better-auth";
4
- //#region src/auth/index.d.ts
5
- type AuthErrorCode = "invalid" | "forbidden" | "unavailable";
6
- declare class AuthError extends Error {
7
- readonly code: AuthErrorCode;
8
- /** The scope an agent lacked, when that is why it was refused. */
9
- readonly scope?: string;
10
- constructor(code: AuthErrorCode, message: string, scope?: string);
11
- }
12
- /** Where sign-in is served, under every address of the app. */
13
- declare const AUTH_PATH = "/api/auth";
14
- /** How long a session is kept in its cookie before its row is read again, in seconds. */
15
- declare const SESSION_CACHE_S: number;
16
- interface AuthOptions {
17
- /** The app's name, as its mail and passkeys show it. `APP_NAME`, or "your app", when left out. */
18
- readonly appName?: string;
19
- /** The name the environment binds the Database under. `main` when left out. */
20
- readonly database?: string;
21
- /** Where rows are kept instead of the Project's Database: the Stand-in's `store` in tests. */
22
- readonly store?: AuthStore;
23
- /** Sends a sign-in mail instead of Email: the Stand-in's `mail` in tests. */
24
- readonly mail?: (mail: SignInMail) => Promise<void>;
25
- /** Where an invitation's link goes, from its id: `<origin>/accept-invitation/<id>` when left out. */
26
- readonly invitationUrl?: (origin: string, id: string) => string;
27
- /** The values it reads; the process's environment when left out. */
28
- readonly env?: Readonly<Record<string, string | undefined>>;
29
- /** More of better-auth's plugins, after Midsummer's. */
30
- readonly plugins?: ReadonlyArray<BetterAuthPlugin>;
31
- /**
32
- * What agents may do in the app, declared once: each scope with what it lets an agent do, in the words the
33
- * person who lets one in reads, such as `{ "notes:read": "Read your notes" }`. API keys and MCP clients carry a
34
- * subset. With none, no key can be made and no client can register.
35
- */
36
- readonly scopes?: Readonly<Record<string, string>>;
37
- /** The path of the app's MCP server, which MCP clients' tokens are bound to. `/mcp` when left out. */
38
- readonly mcpPath?: string;
39
- /** The app's sign-in page, where a person signs in before letting an MCP client in. `/sign-in` when left out. */
40
- readonly signInPage?: string;
41
- /** The app's own page that asks the person whether to let a client in; sign-in's own page when left out. */
42
- readonly consentPage?: string;
43
- }
44
- /** One of the app's users. */
45
- interface AuthUser {
46
- readonly id: string;
47
- readonly email: string;
48
- readonly name: string;
49
- readonly emailVerified: boolean;
50
- readonly image?: string | null;
51
- readonly role?: string | null;
52
- readonly banned?: boolean | null;
53
- readonly [field: string]: unknown;
54
- }
55
- /** A signed-in person: who they are and the session they are signed in with. */
56
- interface SignedIn {
57
- readonly via: "session";
58
- readonly user: AuthUser;
59
- readonly session: {
60
- readonly id: string;
61
- readonly userId: string;
62
- readonly expiresAt: Date;
63
- readonly activeOrganizationId?: string | null;
64
- readonly [field: string]: unknown;
65
- };
66
- }
67
- /** An agent acting for one of the app's users: through an API key, or as an MCP client they let in. */
68
- interface SignedInAgent {
69
- readonly via: "key" | "client";
70
- /** Who it acts for. */
71
- readonly user: AuthUser;
72
- /** What it may do: the scopes its key was made with, or the person granted its client. */
73
- readonly scopes: ReadonlyArray<string>;
74
- /** The key's id and name, or the client's id. */
75
- readonly agent: {
76
- readonly id: string;
77
- readonly name?: string;
78
- };
79
- }
80
- /** An API key as its owner sees it: never the key itself, which is shown once as it is made. */
81
- interface AgentKey {
82
- readonly id: string;
83
- readonly name: string | null;
84
- readonly start: string | null;
85
- readonly scopes: ReadonlyArray<string>;
86
- readonly createdAt: Date;
87
- readonly expiresAt: Date | null;
88
- readonly lastUsedAt: Date | null;
89
- }
90
- /** An MCP client a person let in, and what they let it do. */
91
- interface AgentGrant {
92
- readonly id: string;
93
- readonly clientId: string;
94
- readonly client: string | null;
95
- readonly scopes: ReadonlyArray<string>;
96
- readonly createdAt: Date;
97
- }
98
- interface Auth {
99
- /** Serves every request under `/api/auth` from better-auth's clients. */
100
- handler(request: Request): Promise<Response>;
101
- /**
102
- * Who a request is signed in as, or null; read from its cookie while that is fresh, else from its session's row.
103
- * With `scope`, the route also takes agents: a request with an API key or an MCP client's token is whoever
104
- * it acts for, when it carries that scope, and throws `AuthError` `forbidden` naming the scope when it doesn't.
105
- * A person signed in themselves may do everything. Without `scope`, a key or a token signs no one in.
106
- */
107
- session(request: Request): Promise<SignedIn | null>;
108
- session(request: Request, options: {
109
- readonly scope: string;
110
- }): Promise<SignedIn | SignedInAgent | null>;
111
- /**
112
- * A route for agents and people alike, such as the app's MCP server: `handler` runs for whoever is signed in
113
- * with `scope`. Anyone else gets what an MCP client needs to sign in (401, with where to find the app's sign-in)
114
- * or to ask for more (403, naming the scope).
115
- */
116
- protect(scope: string, handler: (request: Request, signedIn: SignedIn | SignedInAgent) => Response | Promise<Response>): (request: Request) => Promise<Response>;
117
- /** The signed-in person's API keys. Each call takes the request of the person themselves, never an agent's. */
118
- readonly keys: {
119
- /** Makes a key for an agent, with some of the app's scopes, good for `expiresIn` seconds (for good when left out). `key` is shown this once. */
120
- create(request: Request, input: {
121
- readonly name: string;
122
- readonly scopes: ReadonlyArray<string>;
123
- readonly expiresIn?: number;
124
- }): Promise<AgentKey & {
125
- readonly key: string;
126
- }>;
127
- list(request: Request): Promise<ReadonlyArray<AgentKey>>;
128
- /** Ends a key: it signs no one in within 30 seconds. */
129
- revoke(request: Request, id: string): Promise<void>;
130
- };
131
- /** The MCP clients the signed-in person let in. */
132
- readonly grants: {
133
- list(request: Request): Promise<ReadonlyArray<AgentGrant>>;
134
- /** Takes a client's access away: it can't renew its token, which ends within five minutes. */
135
- revoke(request: Request, id: string): Promise<void>;
136
- };
137
- /**
138
- * better-auth itself, for the address `origin` serves (`https://shop.acme.dev`): its `api` calls each of
139
- * its endpoints from the server, such as `api.signUpEmail({ body })`.
140
- */
141
- at(origin: string): BetterAuth;
142
- }
143
- /** better-auth as Midsummer sets it up for one address. */
144
- type BetterAuth = ReturnType<typeof instanceFor>;
145
- /** better-auth as Midsummer sets it up, for one origin. */
146
- declare function instanceFor(origin: string, options: AuthOptions, store: AuthStore, env: Readonly<Record<string, string | undefined>>): import("better-auth").Auth<{
147
- appName: string;
148
- baseURL: string;
149
- basePath: string;
150
- secret: string;
151
- database: AuthStore;
152
- trustedOrigins: string[];
153
- emailAndPassword: {
154
- enabled: true;
155
- sendResetPassword: ({ user, url }: {
156
- user: import("better-auth").User;
157
- url: string;
158
- token: string;
159
- }) => Promise<void>;
160
- };
161
- emailVerification: {
162
- sendOnSignUp: true;
163
- autoSignInAfterVerification: true;
164
- sendVerificationEmail: ({ user, url }: {
165
- user: import("better-auth").User;
166
- url: string;
167
- token: string;
168
- }) => Promise<void>;
169
- };
170
- socialProviders: import("better-auth").SocialProviders;
171
- session: {
172
- cookieCache: {
173
- enabled: true;
174
- maxAge: number;
175
- };
176
- };
177
- telemetry: {
178
- enabled: false;
179
- };
180
- plugins: BetterAuthPlugin[];
181
- }>;
182
- /** Sign-in over `options`: nothing is made until the first request, which may be at a module's top. */
183
- declare function createAuth(options?: AuthOptions): Auth;
184
- /** Sign-in for this deployment, set up from its environment. */
185
- declare const auth: Auth;
186
- /**
187
- * The `db/` files sign-in keeps its rows with, by name in `db/`, as `midsummer auth init` writes them, and what
188
- * `db/schema.ts` takes its tables in with: an import, and an entry for each table inside `defineSchema({ ... })`.
189
- * `plugins` are the ones given `createAuth`, whose tables are made too.
190
- */
191
- declare function authFiles(options?: Pick<AuthOptions, "plugins">): {
192
- readonly files: Readonly<Record<string, string>>;
193
- readonly schema: {
194
- readonly import: string;
195
- readonly tables: string;
196
- };
197
- };
198
- //#endregion
199
- export { AUTH_PATH, AgentGrant, AgentKey, Auth, AuthError, AuthErrorCode, AuthOptions, type AuthStore, AuthUser, BetterAuth, SESSION_CACHE_S, type SignInMail, type SignInMailKind, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
4
+ import { _ as AuthEventBatch, a as AuthError, c as AuthUser, d as SESSION_CACHE_S, f as SignedIn, g as AuthEvent, h as createAuth, i as Auth, l as AuthUserRecord, m as auth, n as AgentGrant, o as AuthErrorCode, p as SignedInAgent, r as AgentKey, s as AuthOptions, t as AUTH_PATH, u as IMPERSONATION_S, v as AuthEventType, y as EventSend } from "../index-CsgQ_ouh.mjs";
5
+ import { i as authFiles } from "../files-C-FvBxT4.mjs";
6
+ export { AUTH_PATH, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
- import { a as authFiles, i as auth, n as AuthError, o as createAuth, r as SESSION_CACHE_S, s as databaseStore, t as AUTH_PATH } from "../auth-BM6vB3XD.mjs";
1
+ import { a as auth, i as SESSION_CACHE_S, n as AuthError, o as createAuth, r as IMPERSONATION_S, t as AUTH_PATH, u as databaseStore } from "../auth-CND9RW17.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
- export { AUTH_PATH, AuthError, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
3
+ import { n as authFiles } from "../files-DAFOuID_.mjs";
4
+ export { AUTH_PATH, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/mail.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region src/auth/mail.d.ts
2
- type SignInMailKind = "code" | "link" | "verify" | "reset" | "invite";
2
+ type SignInMailKind = "code" | "link" | "verify" | "reset" | "invite" | "device";
3
3
  /** One sign-in mail: whom to, which kind, the app's name, and its code or its address. */
4
4
  interface SignInMail {
5
5
  readonly to: string;
@@ -12,20 +12,38 @@ interface SignInMail {
12
12
  /** The organization an invitation is to, and who sent it. */
13
13
  readonly organization?: string;
14
14
  readonly inviter?: string;
15
+ /** For `device`: what signed in, as its browser names itself ("Firefox on Linux"). */
16
+ readonly device?: string;
17
+ /** The app's logo (an https address) and colour (`#rrggbb`), from its settings. */
18
+ readonly brand?: {
19
+ readonly logo?: string;
20
+ readonly color?: string;
21
+ };
15
22
  }
16
23
  /** A sign-in mail checked, as it comes from a Project's code; throws `EmailError("invalid")` saying what is wrong. */
17
24
  declare function checkSignInMail(value: unknown): SignInMail;
18
- /** A sign-in mail's subject, text and HTML. */
25
+ /** A sign-in mail's subject, text and HTML: plain words first, then a page any mail app shows, in the app's colour. */
19
26
  declare function signInWords(mail: SignInMail): {
20
27
  readonly subject: string;
21
28
  readonly text: string;
22
29
  readonly html: string;
23
30
  };
24
31
  /**
25
- * Sends a sign-in mail where the code runs: from `AUTH_EMAIL_FROM` when it is set, else from the shared
32
+ * Sends a sign-in mail where the code runs: from `sender` (the settings' address) or `AUTH_EMAIL_FROM` when one is set, else from the shared
26
33
  * sign-in sender. Under `midsummer dev`, with no deployment to send from, its words are printed instead,
27
34
  * so the code or the link is there to use. Throws `EmailError` when Email refuses it.
28
35
  */
29
- declare function sendSignInMail(mail: SignInMail, env?: Readonly<Record<string, string | undefined>>): Promise<void>;
36
+ declare function sendSignInMail(mail: SignInMail, env?: Readonly<Record<string, string | undefined>>, sender?: string | null, remote?: RemoteMail): Promise<void>;
37
+ /** Where a sign-in mail goes from outside Midsummer: the platform's mail Action, with the database's key or a run's workload token. */
38
+ interface RemoteMail {
39
+ readonly url: string;
40
+ readonly proof: {
41
+ readonly key: string;
42
+ } | {
43
+ readonly workload: string;
44
+ readonly binding: string;
45
+ };
46
+ readonly fetch?: typeof fetch;
47
+ }
30
48
  //#endregion
31
- export { SignInMail, SignInMailKind, checkSignInMail, sendSignInMail, signInWords };
49
+ export { RemoteMail, SignInMail, SignInMailKind, checkSignInMail, sendSignInMail, signInWords };
package/auth/mail.mjs CHANGED
@@ -2,8 +2,8 @@ import { r as processEnv, t as here } from "../here-1plIxb0D.mjs";
2
2
  import { l as email, t as EmailError } from "../email-ynNo0HqT.mjs";
3
3
  //#region src/auth/mail.ts
4
4
  /**
5
- * The mail sign-in sends: a code, a sign-in link, an email check, a password reset or an invitation, each
6
- * in fixed words that name the app. A Deployment sends it through Email: from the address `AUTH_EMAIL_FROM`
5
+ * The mail sign-in sends: a code, a sign-in link, an email check, a password reset, an invitation or a sign-in from
6
+ * a new device, each in fixed words that name the app, with its logo and colour when its settings give them. A Deployment sends it through Email: from the address `AUTH_EMAIL_FROM`
7
7
  * names, on a domain of the Team's, as any Message; without one, from Midsummer's shared sign-in sender,
8
8
  * which reaches anyone, a few times an hour an address and a few hundred times an hour a Team. Only these
9
9
  * words go from the shared sender, so it carries no one's own mail.
@@ -13,7 +13,8 @@ const KINDS = [
13
13
  "link",
14
14
  "verify",
15
15
  "reset",
16
- "invite"
16
+ "invite",
17
+ "device"
17
18
  ];
18
19
  const ADDRESS = /^[^\s@<>()",;:]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;
19
20
  const LOCAL = /^(?:localhost|127\.0\.0\.1|\[::1\]|[a-z0-9-]+\.localhost)$/i;
@@ -28,18 +29,27 @@ function checkSignInMail(value) {
28
29
  const kind = given.kind;
29
30
  if (kind === "code") {
30
31
  if (typeof given.code !== "string" || !/^[A-Za-z0-9-]{4,16}$/.test(given.code)) throw invalid("a sign-in code is 4 to 16 letters or digits");
31
- } else {
32
+ } else if (kind !== "device" || given.url !== void 0) {
32
33
  const url = typeof given.url === "string" ? URL.parse(given.url) : null;
33
34
  if (!url || !(url.protocol === "https:" || url.protocol === "http:" && LOCAL.test(url.hostname)) || given.url.length > 2048) throw invalid("a sign-in link is an https address of at most 2048 characters");
34
35
  }
35
36
  for (const field of ["organization", "inviter"]) if (given[field] !== void 0 && (typeof given[field] !== "string" || !NAME.test(given[field]))) throw invalid(`a sign-in mail's ${field} is 1 to 80 characters on one line`);
37
+ if (given.device !== void 0 && (typeof given.device !== "string" || !/^[^\r\n<>]{1,120}$/.test(given.device))) throw invalid("a sign-in mail's device is 1 to 120 characters on one line");
38
+ const brand = typeof given.brand === "object" && given.brand !== null ? given.brand : {};
39
+ if (brand.logo !== void 0 && (typeof brand.logo !== "string" || URL.parse(brand.logo)?.protocol !== "https:" || brand.logo.length > 2048)) throw invalid("a sign-in mail's logo is an https address");
40
+ if (brand.color !== void 0 && (typeof brand.color !== "string" || !/^#[0-9a-f]{6}$/i.test(brand.color))) throw invalid("a sign-in mail's colour is #rrggbb");
36
41
  return {
37
42
  to: given.to.toLowerCase(),
38
43
  kind,
39
44
  app: given.app.trim(),
40
- ...kind === "code" ? { code: given.code } : { url: given.url },
45
+ ...kind === "code" ? { code: given.code } : typeof given.url === "string" ? { url: given.url } : {},
41
46
  ...typeof given.organization === "string" ? { organization: given.organization } : {},
42
- ...typeof given.inviter === "string" ? { inviter: given.inviter } : {}
47
+ ...typeof given.inviter === "string" ? { inviter: given.inviter } : {},
48
+ ...typeof given.device === "string" ? { device: given.device } : {},
49
+ ...brand.logo !== void 0 || brand.color !== void 0 ? { brand: {
50
+ ...typeof brand.logo === "string" ? { logo: brand.logo } : {},
51
+ ...typeof brand.color === "string" ? { color: brand.color.toLowerCase() } : {}
52
+ } } : {}
43
53
  };
44
54
  }
45
55
  const escape = (text) => text.replace(/[&<>"']/g, (c) => ({
@@ -49,42 +59,67 @@ const escape = (text) => text.replace(/[&<>"']/g, (c) => ({
49
59
  "\"": "&quot;",
50
60
  "'": "&#39;"
51
61
  })[c]);
52
- /** A sign-in mail's subject, text and HTML. */
53
- function signInWords(mail) {
62
+ /** Each kind's subject, its first line, its button's words, and what follows, in the app's name. */
63
+ function wordsOf(mail) {
54
64
  const { app } = mail;
55
- const ignore = "If you didn't ask for this, you can ignore this email.";
56
- const [subject, lead, after] = mail.kind === "code" ? [
57
- `Your ${app} code: ${mail.code}`,
58
- `Your code for ${app} is ${mail.code}.`,
59
- "It works once, for a few minutes."
60
- ] : mail.kind === "link" ? [
61
- `Sign in to ${app}`,
62
- `Sign in to ${app} with this link:`,
63
- "It works once, for a few minutes."
64
- ] : mail.kind === "verify" ? [
65
- `Confirm your email for ${app}`,
66
- `Confirm this is your email for ${app}:`,
67
- ""
68
- ] : mail.kind === "reset" ? [
69
- `Reset your ${app} password`,
70
- `Reset your password for ${app} with this link:`,
71
- "It works once, for an hour."
72
- ] : [
73
- `Join ${mail.organization ?? app} on ${app}`,
74
- `${mail.inviter ?? "Someone"} invited you to ${mail.organization ?? "their organization"} on ${app}:`,
75
- ""
76
- ];
65
+ switch (mail.kind) {
66
+ case "code": return {
67
+ subject: `Your ${app} code: ${mail.code}`,
68
+ lead: `Your code for ${app} is ${mail.code}.`,
69
+ after: "It works once, for a few minutes."
70
+ };
71
+ case "link": return {
72
+ subject: `Sign in to ${app}`,
73
+ lead: `Sign in to ${app} with this link:`,
74
+ button: "Sign in",
75
+ after: "It works once, for a few minutes."
76
+ };
77
+ case "verify": return {
78
+ subject: `Confirm your email for ${app}`,
79
+ lead: `Confirm this is your email for ${app}:`,
80
+ button: "Confirm email",
81
+ after: ""
82
+ };
83
+ case "reset": return {
84
+ subject: `Reset your ${app} password`,
85
+ lead: `Reset your password for ${app} with this link:`,
86
+ button: "Reset password",
87
+ after: "It works once, for an hour."
88
+ };
89
+ case "invite": return {
90
+ subject: `Join ${mail.organization ?? app} on ${app}`,
91
+ lead: `${mail.inviter ?? "Someone"} invited you to ${mail.organization ?? "their organization"} on ${app}:`,
92
+ button: "Accept invitation",
93
+ after: ""
94
+ };
95
+ case "device": return {
96
+ subject: `A new sign-in to ${app}`,
97
+ lead: `You signed in to ${app}${mail.device ? ` from ${mail.device}` : ""}, on a device you haven't used before.`,
98
+ after: "If this was you, there's nothing to do. If it wasn't, change your password and sign out of your other sessions in your account."
99
+ };
100
+ }
101
+ }
102
+ /** A sign-in mail's subject, text and HTML: plain words first, then a page any mail app shows, in the app's colour. */
103
+ function signInWords(mail) {
104
+ const { subject, lead, button, after } = wordsOf(mail);
105
+ const ignore = mail.kind === "device" ? "" : "If you didn't ask for this, you can ignore this email.";
77
106
  const parts = [
78
107
  lead,
79
108
  ...mail.url ? [mail.url] : [],
80
109
  ...after ? [after] : [],
81
- ignore
110
+ ...ignore ? [ignore] : []
82
111
  ];
112
+ const color = mail.brand?.color ?? "#111111";
113
+ const paragraph = (text) => `<p style="margin:0 0 16px;font-size:16px;line-height:1.5">${escape(text)}</p>`;
83
114
  const html = [
84
- `<p>${escape(lead)}</p>`,
85
- ...mail.url ? [`<p><a href="${escape(mail.url)}">${escape(mail.url)}</a></p>`] : [],
86
- ...after ? [`<p>${escape(after)}</p>`] : [],
87
- `<p>${escape(ignore)}</p>`
115
+ `<div style="font-family:system-ui,-apple-system,sans-serif;color:#111111;max-width:480px;margin:0 auto;padding:24px">`,
116
+ ...mail.brand?.logo ? [`<img src="${escape(mail.brand.logo)}" alt="${escape(mail.app)}" height="32" style="display:block;height:32px;margin:0 0 24px">`] : [],
117
+ paragraph(mail.kind === "code" ? `Your code for ${mail.app}:` : lead),
118
+ ...mail.kind === "code" && mail.code ? [`<p style="margin:0 0 16px;font-size:28px;font-weight:600;letter-spacing:4px">${escape(mail.code)}</p>`] : [],
119
+ ...mail.url && button ? [`<p style="margin:0 0 16px"><a href="${escape(mail.url)}" style="display:inline-block;background:${color};color:#ffffff;text-decoration:none;font-weight:600;padding:10px 18px;border-radius:8px">${escape(button)}</a></p>`, `<p style="margin:0 0 16px;font-size:13px;color:#555555;word-break:break-all">${escape(mail.url)}</p>`] : mail.url ? [paragraph(mail.url)] : [],
120
+ ...after ? [paragraph(after)] : [],
121
+ ...ignore ? [`<p style="margin:0;font-size:13px;color:#555555">${escape(ignore)}</p>`] : [],
122
+ `</div>`
88
123
  ].join("\n");
89
124
  return {
90
125
  subject,
@@ -101,13 +136,13 @@ async function keyOf(mail) {
101
136
  ])))).slice(0, 12)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
102
137
  }
103
138
  /**
104
- * Sends a sign-in mail where the code runs: from `AUTH_EMAIL_FROM` when it is set, else from the shared
139
+ * Sends a sign-in mail where the code runs: from `sender` (the settings' address) or `AUTH_EMAIL_FROM` when one is set, else from the shared
105
140
  * sign-in sender. Under `midsummer dev`, with no deployment to send from, its words are printed instead,
106
141
  * so the code or the link is there to use. Throws `EmailError` when Email refuses it.
107
142
  */
108
- async function sendSignInMail(mail, env = processEnv()) {
143
+ async function sendSignInMail(mail, env = processEnv(), sender, remote) {
109
144
  const checked = checkSignInMail(mail);
110
- const from = env.AUTH_EMAIL_FROM;
145
+ const from = sender || env.AUTH_EMAIL_FROM;
111
146
  const handle = here()?.email;
112
147
  if (from && handle) {
113
148
  await email().send({
@@ -127,12 +162,31 @@ async function sendSignInMail(mail, env = processEnv()) {
127
162
  if (answer?.error) throw new EmailError(answer.error.code, answer.error.message);
128
163
  return;
129
164
  }
165
+ if (remote) {
166
+ const response = await (remote.fetch ?? fetch)(remote.url, {
167
+ method: "POST",
168
+ headers: { "content-type": "application/json" },
169
+ body: JSON.stringify({
170
+ ...remote.proof,
171
+ mail: checked,
172
+ ...from ? { from } : {},
173
+ tag: await keyOf(checked)
174
+ })
175
+ }).catch(() => null);
176
+ if (!response) throw new EmailError("unavailable", "Midsummer couldn't be reached to send a sign-in mail.");
177
+ if (!response.ok) {
178
+ const refused = await response.json().catch(() => ({}));
179
+ const error = typeof refused.error === "string" ? { message: refused.error } : refused.error;
180
+ throw new EmailError(response.status === 401 || response.status === 403 ? "forbidden" : response.status === 400 ? "invalid" : "unavailable", error?.message ?? `Midsummer returned ${response.status} for a sign-in mail.`);
181
+ }
182
+ return;
183
+ }
130
184
  if (env.MIDSUMMER_DEV === "1") {
131
185
  const words = signInWords(checked);
132
186
  console.log(`[sign-in] mail to ${checked.to}: ${words.subject}\n${words.text}`);
133
187
  return;
134
188
  }
135
- throw new EmailError("forbidden", "This code runs outside a deployment, so sign-in has nowhere to send mail. In tests, give createAuth a mail function: createAuth({ mail }).");
189
+ throw new EmailError("forbidden", "This code runs outside a deployment, so sign-in has nowhere to send mail: set DATABASE_KEY. In tests, give createAuth a mail function: createAuth({ mail }).");
136
190
  }
137
191
  //#endregion
138
192
  export { checkSignInMail, sendSignInMail, signInWords };
@@ -1,2 +1,10 @@
1
- import { hashPassword, verifyPassword } from "better-auth/crypto";
2
- export { hashPassword, verifyPassword };
1
+ //#region src/auth/password.d.ts
2
+ declare const hashPassword: (password: string) => Promise<string>;
3
+ declare const verifyPassword: (input: {
4
+ readonly hash: string;
5
+ readonly password: string;
6
+ }) => Promise<boolean>;
7
+ /** Whether a hash is bcrypt's, as an import brings it. */
8
+ declare const isBcrypt: (hash: string) => boolean;
9
+ //#endregion
10
+ export { hashPassword, isBcrypt, verifyPassword };
package/auth/password.mjs CHANGED
@@ -1,2 +1,14 @@
1
- import { hashPassword, verifyPassword } from "better-auth/crypto";
2
- export { hashPassword, verifyPassword };
1
+ import { i as hashPassword$1, o as verifyPassword$1 } from "../engine-BhA0XgI7.mjs";
2
+ import { isBcrypt as isBcrypt$1 } from "./import.mjs";
3
+ //#region src/auth/password.ts
4
+ /**
5
+ * A password's hash as `@midsummer-ai/sdk/auth` makes and checks it: scrypt (N 16384, r 16, p 1, 64 bytes, a salt
6
+ * of 16 random bytes), written `<salt>:<key>` in hex. `verifyPassword` also takes the bcrypt hashes an import brings,
7
+ * which sign-in writes again in its own hash at that person's first sign-in.
8
+ */
9
+ const hashPassword = hashPassword$1;
10
+ const verifyPassword = verifyPassword$1;
11
+ /** Whether a hash is bcrypt's, as an import brings it. */
12
+ const isBcrypt = isBcrypt$1;
13
+ //#endregion
14
+ export { hashPassword, isBcrypt, verifyPassword };
@@ -0,0 +1,86 @@
1
+ import { AuthClient, ClientSession, ClientSettings, ClientUser } from "./client.mjs";
2
+ import { ReactNode } from "react";
3
+ //#region src/auth/react.d.ts
4
+ interface AuthState {
5
+ readonly client: AuthClient;
6
+ /** Who is signed in, or null; undefined until the first look. */
7
+ readonly signedIn: {
8
+ readonly user: ClientUser;
9
+ readonly session: ClientSession;
10
+ } | null | undefined;
11
+ readonly settings: ClientSettings | undefined;
12
+ /** Reads who is signed in again. */
13
+ refresh(): Promise<void>;
14
+ }
15
+ /** Gives the screens inside it the client and who is signed in; `baseURL` when the app's server is on another address. */
16
+ declare function AuthProvider(props: {
17
+ readonly children?: ReactNode;
18
+ readonly client?: AuthClient;
19
+ readonly baseURL?: string;
20
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<AuthState | null>>;
21
+ /** Who is signed in, the client and the app's settings: inside an `AuthProvider`. */
22
+ declare function useAuth(): AuthState;
23
+ /** Sign-in: a password, a code or a link by mail, a passkey, Google or GitHub, as the app's settings turn them on. */
24
+ declare function SignIn(props: {
25
+ readonly redirectTo?: string;
26
+ readonly signUpUrl?: string;
27
+ readonly resetUrl?: string;
28
+ }): import("react").FunctionComponentElement<{
29
+ readonly title: string;
30
+ readonly lead?: string;
31
+ readonly wide?: boolean;
32
+ readonly children?: ReactNode;
33
+ }> | null;
34
+ /** Sign-up with a name, an email and a password; under a waitlist, joining it. */
35
+ declare function SignUp(props: {
36
+ readonly redirectTo?: string;
37
+ readonly signInUrl?: string;
38
+ }): import("react").FunctionComponentElement<{
39
+ readonly title: string;
40
+ readonly lead?: string;
41
+ readonly wide?: boolean;
42
+ readonly children?: ReactNode;
43
+ }> | null;
44
+ /** The signed-in person's picture or initial, opening a menu: their account, and signing out. */
45
+ declare function UserButton(props: {
46
+ readonly accountUrl?: string;
47
+ readonly afterSignOut?: string;
48
+ }): import("react").DetailedReactHTMLElement<{
49
+ className: string;
50
+ onKeyDown: (event: {
51
+ key: string;
52
+ preventDefault(): void;
53
+ }) => void;
54
+ onBlur: (event: {
55
+ relatedTarget: unknown;
56
+ currentTarget: {
57
+ contains(node: unknown): boolean;
58
+ };
59
+ }) => void;
60
+ }, HTMLElement> | null;
61
+ /** The signed-in person's account: profile, password, two-step sign-in, passkeys, sessions, keys and apps. */
62
+ declare function UserProfile(): import("react").FunctionComponentElement<{
63
+ readonly title: string;
64
+ readonly lead?: string;
65
+ readonly wide?: boolean;
66
+ readonly children?: ReactNode;
67
+ }> | null;
68
+ /** Which organization the person works in, or their personal account; and making a new one. */
69
+ declare function OrganizationSwitcher(): import("react").DetailedReactHTMLElement<{
70
+ className: string;
71
+ style: {
72
+ display: "grid";
73
+ gap: number;
74
+ };
75
+ }, HTMLElement> | null;
76
+ /** One organization: its name, its members and their roles, and its invitations. The active one unless `organizationId` names another. */
77
+ declare function OrganizationProfile(props: {
78
+ readonly organizationId?: string;
79
+ }): import("react").FunctionComponentElement<{
80
+ readonly title: string;
81
+ readonly lead?: string;
82
+ readonly wide?: boolean;
83
+ readonly children?: ReactNode;
84
+ }> | null;
85
+ //#endregion
86
+ export { AuthProvider, AuthState, OrganizationProfile, OrganizationSwitcher, SignIn, SignUp, UserButton, UserProfile, useAuth };