@midsummer-ai/sdk 0.1.0-staging.3608 → 0.1.0-staging.3620

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/auth/files.mjs ADDED
@@ -0,0 +1,231 @@
1
+ import { getAuthTables } from "better-auth/db";
2
+ //#region src/auth/files.ts
3
+ /** The Database's shape of a better-auth field. */
4
+ function shapeOf(field, tables) {
5
+ const type = field.type;
6
+ const base = field.references?.field === "id" ? `v.id(${JSON.stringify(tables[field.references.model] ?? field.references.model)})` : type === "string" ? "v.string()" : type === "number" || type === "date" ? "v.number()" : type === "boolean" ? "v.boolean()" : type === "string[]" ? "v.array(v.string())" : type === "number[]" ? "v.array(v.number())" : Array.isArray(type) ? `v.union(${type.map((one) => `v.literal(${JSON.stringify(one)})`).join(", ")})` : "v.any()";
7
+ return field.required === true ? base : `v.optional(${base})`;
8
+ }
9
+ /**
10
+ * The tables better-auth asks for under `options` (its plugins add theirs), as the Database keeps them. A
11
+ * field is looked up by an index when better-auth marks it unique or indexed, when it names another row, and
12
+ * for `expiresAt`, by which old rows are cleared.
13
+ */
14
+ function authTablesOf(options) {
15
+ const tables = getAuthTables(options);
16
+ const names = Object.fromEntries(Object.entries(tables).map(([key, table]) => [key, table.modelName]));
17
+ return Object.fromEntries(Object.values(tables).map((table) => {
18
+ const fields = {}, indexed = [], unique = [];
19
+ for (const [key, field] of Object.entries(table.fields)) {
20
+ const name = field.fieldName ?? key;
21
+ fields[name] = shapeOf(field, names);
22
+ if (field.unique && field.type === "string") unique.push(name);
23
+ else if (field.unique || field.index || field.references || name === "expiresAt") indexed.push(name);
24
+ }
25
+ return [table.modelName, {
26
+ fields,
27
+ indexed,
28
+ unique
29
+ }];
30
+ }));
31
+ }
32
+ /** `db/authTables.ts`: each table as `defineTable(...)` with its indexes, and the fields each is looked up by. */
33
+ function tablesFile(tables) {
34
+ const lines = Object.entries(tables).map(([name, table]) => {
35
+ return ` ${name}: defineTable({ ${Object.entries(table.fields).map(([field, shape]) => `${field}: ${shape}`).join(", ")} })${[...table.unique.map((field) => `.index("by_${field}", "${field}", { unique: true })`), ...table.indexed.map((field) => `.index("by_${field}", "${field}")`)].join("")},`;
36
+ });
37
+ const one = (field) => field === "key" || field === "token" ? 0 : 1;
38
+ const lookups = Object.entries(tables).map(([name, table]) => ` ${name}: ${JSON.stringify([...table.unique, ...[...table.indexed].sort((a, b) => one(a) - one(b))])},`);
39
+ return `// Written by \`midsummer auth init\` from the tables sign-in uses. Write it again with that command; don't edit it.
40
+ import { defineTable, v } from "@midsummer-ai/sdk/server"
41
+
42
+ /** Sign-in's tables. Name each in db/schema.ts: \`user: authTables.user\`. */
43
+ export const authTables = {
44
+ ${lines.join("\n")}
45
+ }
46
+
47
+ /** The fields each table is looked up by, each with its index \`by_<field>\`, those that find one row first. */
48
+ export const authLookups = {
49
+ ${lookups.join("\n")}
50
+ }
51
+ `;
52
+ }
53
+ /** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
54
+ function schemaLines(tables) {
55
+ return Object.keys(tables).map((name) => `${name}: authTables.${name},`).join(" ");
56
+ }
57
+ /**
58
+ * `db/auth.ts`: what `@midsummer-ai/sdk/auth` calls, `auth.create`, `auth.findOne`, `auth.findMany`,
59
+ * `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment` and `auth.consume`. A `where` is
60
+ * better-auth's: clauses of `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
61
+ * joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
62
+ * reads the table.
63
+ */
64
+ const FUNCTIONS_FILE = `// Written by \`midsummer auth init\`: what @midsummer-ai/sdk/auth keeps your app's users with. Write it again with that command; don't edit it.
65
+ import { mutation, query, v } from "./_generated/server"
66
+ import { authLookups } from "./authTables"
67
+
68
+ const where = v.optional(v.array(v.any()))
69
+
70
+ function server(ctx) {
71
+ if (!ctx.identity.server) throw new Error("Only the app's own server reads and writes sign-in's tables.")
72
+ }
73
+ function table(model) {
74
+ if (!Object.hasOwn(authLookups, model)) throw new Error(\`\${model} is not one of sign-in's tables\`)
75
+ return model
76
+ }
77
+ /** A row as better-auth takes it: its \`_id\` as \`id\`. */
78
+ function shown(doc) {
79
+ if (!doc) return null
80
+ const { _id, _creationTime, _version, ...fields } = doc
81
+ return { id: _id, ...fields }
82
+ }
83
+ const text = (value) => (typeof value === "string" ? value.toLowerCase() : value)
84
+ function holds(row, clause) {
85
+ const { field, value, operator = "eq", mode } = clause
86
+ const have = row[field], loose = mode === "insensitive"
87
+ const same = (a, b) => (loose ? text(a) === text(b) : a === b)
88
+ switch (operator) {
89
+ case "eq": return value === null ? have == null : same(have, value)
90
+ case "ne": return value === null ? have != null : !same(have, value)
91
+ case "in": return Array.isArray(value) && value.some((one) => same(have, one))
92
+ case "not_in": return Array.isArray(value) && !value.some((one) => same(have, one))
93
+ case "lt": return value != null && have != null && have < value
94
+ case "lte": return value != null && have != null && have <= value
95
+ case "gt": return value != null && have != null && have > value
96
+ case "gte": return value != null && have != null && have >= value
97
+ case "contains": return typeof have === "string" && typeof value === "string" && (loose ? text(have).includes(text(value)) : have.includes(value))
98
+ case "starts_with": return typeof have === "string" && typeof value === "string" && (loose ? text(have).startsWith(text(value)) : have.startsWith(value))
99
+ case "ends_with": return typeof have === "string" && typeof value === "string" && (loose ? text(have).endsWith(text(value)) : have.endsWith(value))
100
+ default: throw new Error(\`sign-in asked with an operator the Database's sign-in tables don't take: \${operator}\`)
101
+ }
102
+ }
103
+ /** Whether a row matches a where: its clauses in order, each joined to those before by its own connector. */
104
+ function matches(row, clauses) {
105
+ if (!clauses?.length) return true
106
+ let result = holds(row, clauses[0])
107
+ for (const clause of clauses.slice(1)) result = clause.connector === "OR" ? result || holds(row, clause) : result && holds(row, clause)
108
+ return result
109
+ }
110
+ const RANGE = { lt: "lt", lte: "lte", gt: "gt", gte: "gte" }
111
+ /** The rows of \`model\` a where can hold: by id, through the index of a field it asks for by value, or the whole table. */
112
+ async function candidates(ctx, model, clauses) {
113
+ const all = clauses ?? []
114
+ const ands = all.every((clause, index) => index === 0 || clause.connector !== "OR")
115
+ if (ands) {
116
+ const byId = all.find((clause) => clause.field === "id" && (clause.operator ?? "eq") === "eq")
117
+ if (byId) {
118
+ const id = typeof byId.value === "string" ? ctx.db.normalizeId(model, byId.value) : null
119
+ const doc = id ? await ctx.db.get(model, id) : null
120
+ return doc ? [doc] : []
121
+ }
122
+ const ids = all.find((clause) => clause.field === "id" && clause.operator === "in" && Array.isArray(clause.value))
123
+ if (ids) return (await Promise.all(ids.value.map((one) => (typeof one === "string" && ctx.db.normalizeId(model, one) ? ctx.db.get(model, one) : null)))).filter(Boolean)
124
+ const lookups = authLookups[model]
125
+ // Of the fields it asks for by value, the one listed first finds the fewest rows: a unique one, a key or a token.
126
+ const exact = all.filter((clause) => (clause.operator ?? "eq") === "eq" && clause.mode !== "insensitive" && clause.value !== null && lookups.includes(clause.field)).sort((a, b) => lookups.indexOf(a.field) - lookups.indexOf(b.field))[0]
127
+ if (exact) return ctx.db.query(model).withIndex(\`by_\${exact.field}\`, (q) => q.eq(exact.field, exact.value)).collect()
128
+ const ranged = all.find((clause) => RANGE[clause.operator] && clause.value != null && lookups.includes(clause.field))
129
+ if (ranged) return ctx.db.query(model).withIndex(\`by_\${ranged.field}\`, (q) => q[RANGE[ranged.operator]](ranged.field, ranged.value)).collect()
130
+ }
131
+ return ctx.db.query(model).collect()
132
+ }
133
+ async function found(ctx, model, clauses) {
134
+ return (await candidates(ctx, model, clauses)).map(shown).filter((row) => matches(row, clauses))
135
+ }
136
+ function ordered(rows, sortBy) {
137
+ if (!sortBy) return rows
138
+ const sign = sortBy.direction === "desc" ? -1 : 1
139
+ return [...rows].sort((a, b) => {
140
+ const x = a[sortBy.field], y = b[sortBy.field]
141
+ return x == null && y == null ? 0 : x == null ? -sign : y == null ? sign : x < y ? -sign : x > y ? sign : 0
142
+ })
143
+ }
144
+ /** A row's fields as written: better-auth's id is the Database's, and \`undefined\` takes a field out. */
145
+ const fieldsOf = (data) => Object.fromEntries(Object.entries(data ?? {}).filter(([field]) => field !== "id" && field !== "_id"))
146
+
147
+ export const create = mutation({
148
+ args: { model: v.string(), data: v.any() },
149
+ handler: async (ctx, { model, data }) => {
150
+ server(ctx)
151
+ const id = await ctx.db.insert(table(model), fieldsOf(data))
152
+ return shown(await ctx.db.get(model, id))
153
+ },
154
+ })
155
+ export const findOne = query({
156
+ args: { model: v.string(), where },
157
+ handler: async (ctx, { model, where }) => {
158
+ server(ctx)
159
+ return (await found(ctx, table(model), where))[0] ?? null
160
+ },
161
+ })
162
+ export const findMany = query({
163
+ args: { model: v.string(), where, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.any()) },
164
+ handler: async (ctx, { model, where, limit, offset, sortBy }) => {
165
+ server(ctx)
166
+ const rows = ordered(await found(ctx, table(model), where), sortBy)
167
+ return rows.slice(offset ?? 0, limit === undefined ? undefined : (offset ?? 0) + limit)
168
+ },
169
+ })
170
+ export const count = query({
171
+ args: { model: v.string(), where },
172
+ handler: async (ctx, { model, where }) => {
173
+ server(ctx)
174
+ return (await found(ctx, table(model), where)).length
175
+ },
176
+ })
177
+ export const update = mutation({
178
+ args: { model: v.string(), where, update: v.any() },
179
+ handler: async (ctx, { model, where, update }) => {
180
+ server(ctx)
181
+ const row = (await found(ctx, table(model), where))[0]
182
+ if (!row) return null
183
+ await ctx.db.patch(model, row.id, fieldsOf(update))
184
+ return shown(await ctx.db.get(model, row.id))
185
+ },
186
+ })
187
+ export const updateMany = mutation({
188
+ args: { model: v.string(), where, update: v.any() },
189
+ handler: async (ctx, { model, where, update }) => {
190
+ server(ctx)
191
+ const rows = await found(ctx, table(model), where)
192
+ await Promise.all(rows.map((row) => ctx.db.patch(model, row.id, fieldsOf(update))))
193
+ return rows.length
194
+ },
195
+ })
196
+ export const deleteMany = mutation({
197
+ args: { model: v.string(), where },
198
+ handler: async (ctx, { model, where }) => {
199
+ server(ctx)
200
+ const rows = await found(ctx, table(model), where)
201
+ await Promise.all(rows.map((row) => ctx.db.delete(model, row.id)))
202
+ return rows.length
203
+ },
204
+ })
205
+ /** Adds to a row's numbers and sets its fields in one step, returning the row, or null when the where finds none: a count is never passed by two at once. */
206
+ export const increment = mutation({
207
+ args: { model: v.string(), where, increment: v.any(), set: v.optional(v.any()) },
208
+ handler: async (ctx, { model, where, increment, set }) => {
209
+ server(ctx)
210
+ const row = (await found(ctx, table(model), where))[0]
211
+ if (!row) return null
212
+ const next = fieldsOf(set)
213
+ for (const [field, delta] of Object.entries(increment ?? {})) next[field] = (row[field] ?? 0) + delta
214
+ await ctx.db.patch(model, row.id, next)
215
+ return shown(await ctx.db.get(model, row.id))
216
+ },
217
+ })
218
+ /** Deletes the first row a where holds and returns it, in one step: a code or a link is used once. */
219
+ export const consume = mutation({
220
+ args: { model: v.string(), where },
221
+ handler: async (ctx, { model, where }) => {
222
+ server(ctx)
223
+ const row = (await found(ctx, table(model), where))[0]
224
+ if (!row) return null
225
+ await ctx.db.delete(model, row.id)
226
+ return row
227
+ },
228
+ })
229
+ `;
230
+ //#endregion
231
+ export { FUNCTIONS_FILE, authTablesOf, schemaLines, tablesFile };
@@ -0,0 +1,199 @@
1
+ import { n as databaseStore, t as AuthStore } from "../store-gCz6XVaG.mjs";
2
+ 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 };
package/auth/index.mjs ADDED
@@ -0,0 +1,3 @@
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";
2
+ import { checkSignInMail, signInWords } from "./mail.mjs";
3
+ export { AUTH_PATH, AuthError, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/key.d.mts ADDED
@@ -0,0 +1,19 @@
1
+ //#region src/auth/key.d.ts
2
+ /**
3
+ * An API key as `@midsummer-ai/sdk/auth` makes and checks one: `key_` and 64 random letters, kept only as its
4
+ * SHA-256 in unpadded base64url, with its first six characters beside it to tell it from another. The platform
5
+ * makes a key for a user with this, and the app's sign-in checks it as it checks its own.
6
+ */
7
+ /** What every API key starts with, so a bearer token that is one is told from an MCP client's. */
8
+ declare const KEY_PREFIX = "key_";
9
+ /** A key's hash, as its row keeps it. */
10
+ declare function keyHash(key: string): Promise<string>;
11
+ /** A new key: the key to show once, and what its row keeps. */
12
+ declare function newKey(): Promise<{
13
+ readonly key: string;
14
+ readonly hash: string;
15
+ readonly start: string;
16
+ readonly prefix: string;
17
+ }>;
18
+ //#endregion
19
+ export { KEY_PREFIX, keyHash, newKey };
package/auth/key.mjs ADDED
@@ -0,0 +1,28 @@
1
+ //#region src/auth/key.ts
2
+ /**
3
+ * An API key as `@midsummer-ai/sdk/auth` makes and checks one: `key_` and 64 random letters, kept only as its
4
+ * SHA-256 in unpadded base64url, with its first six characters beside it to tell it from another. The platform
5
+ * makes a key for a user with this, and the app's sign-in checks it as it checks its own.
6
+ */
7
+ /** What every API key starts with, so a bearer token that is one is told from an MCP client's. */
8
+ const KEY_PREFIX = "key_";
9
+ const LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
10
+ /** A key's hash, as its row keeps it. */
11
+ async function keyHash(key) {
12
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)));
13
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
14
+ }
15
+ /** A new key: the key to show once, and what its row keeps. */
16
+ async function newKey() {
17
+ let letters = "";
18
+ while (letters.length < 64) for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(96))) if (byte < 208 && letters.length < 64) letters += LETTERS[byte % 52];
19
+ const key = `${KEY_PREFIX}${letters}`;
20
+ return {
21
+ key,
22
+ hash: await keyHash(key),
23
+ start: key.slice(0, 6),
24
+ prefix: KEY_PREFIX
25
+ };
26
+ }
27
+ //#endregion
28
+ export { KEY_PREFIX, keyHash, newKey };
@@ -0,0 +1,31 @@
1
+ //#region src/auth/mail.d.ts
2
+ type SignInMailKind = "code" | "link" | "verify" | "reset" | "invite";
3
+ /** One sign-in mail: whom to, which kind, the app's name, and its code or its address. */
4
+ interface SignInMail {
5
+ readonly to: string;
6
+ readonly kind: SignInMailKind;
7
+ readonly app: string;
8
+ /** A code's digits, for `code`. */
9
+ readonly code?: string;
10
+ /** Where the mail's one link goes, for every kind but `code`: an https address, or http on the machine itself. */
11
+ readonly url?: string;
12
+ /** The organization an invitation is to, and who sent it. */
13
+ readonly organization?: string;
14
+ readonly inviter?: string;
15
+ }
16
+ /** A sign-in mail checked, as it comes from a Project's code; throws `EmailError("invalid")` saying what is wrong. */
17
+ declare function checkSignInMail(value: unknown): SignInMail;
18
+ /** A sign-in mail's subject, text and HTML. */
19
+ declare function signInWords(mail: SignInMail): {
20
+ readonly subject: string;
21
+ readonly text: string;
22
+ readonly html: string;
23
+ };
24
+ /**
25
+ * Sends a sign-in mail where the code runs: from `AUTH_EMAIL_FROM` when it is set, else from the shared
26
+ * sign-in sender. Under `midsummer dev`, with no deployment to send from, its words are printed instead,
27
+ * so the code or the link is there to use. Throws `EmailError` when Email refuses it.
28
+ */
29
+ declare function sendSignInMail(mail: SignInMail, env?: Readonly<Record<string, string | undefined>>): Promise<void>;
30
+ //#endregion
31
+ export { SignInMail, SignInMailKind, checkSignInMail, sendSignInMail, signInWords };
package/auth/mail.mjs ADDED
@@ -0,0 +1,138 @@
1
+ import { r as processEnv, t as here } from "../here-1plIxb0D.mjs";
2
+ import { l as email, t as EmailError } from "../email-ynNo0HqT.mjs";
3
+ //#region src/auth/mail.ts
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`
7
+ * names, on a domain of the Team's, as any Message; without one, from Midsummer's shared sign-in sender,
8
+ * which reaches anyone, a few times an hour an address and a few hundred times an hour a Team. Only these
9
+ * words go from the shared sender, so it carries no one's own mail.
10
+ */
11
+ const KINDS = [
12
+ "code",
13
+ "link",
14
+ "verify",
15
+ "reset",
16
+ "invite"
17
+ ];
18
+ 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
+ const LOCAL = /^(?:localhost|127\.0\.0\.1|\[::1\]|[a-z0-9-]+\.localhost)$/i;
20
+ const NAME = /^[^\r\n<>]{1,80}$/;
21
+ /** A sign-in mail checked, as it comes from a Project's code; throws `EmailError("invalid")` saying what is wrong. */
22
+ function checkSignInMail(value) {
23
+ const given = typeof value === "object" && value !== null ? value : {};
24
+ const invalid = (why) => new EmailError("invalid", why);
25
+ if (typeof given.to !== "string" || !ADDRESS.test(given.to) || given.to.length > 254) throw invalid("a sign-in mail goes to one email address");
26
+ if (!KINDS.includes(given.kind)) throw invalid(`a sign-in mail is one of ${KINDS.join(", ")}`);
27
+ if (typeof given.app !== "string" || !NAME.test(given.app.trim())) throw invalid("a sign-in mail names its app in 1 to 80 characters on one line");
28
+ const kind = given.kind;
29
+ if (kind === "code") {
30
+ 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
+ const url = typeof given.url === "string" ? URL.parse(given.url) : null;
33
+ 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
+ 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`);
36
+ return {
37
+ to: given.to.toLowerCase(),
38
+ kind,
39
+ app: given.app.trim(),
40
+ ...kind === "code" ? { code: given.code } : { url: given.url },
41
+ ...typeof given.organization === "string" ? { organization: given.organization } : {},
42
+ ...typeof given.inviter === "string" ? { inviter: given.inviter } : {}
43
+ };
44
+ }
45
+ const escape = (text) => text.replace(/[&<>"']/g, (c) => ({
46
+ "&": "&amp;",
47
+ "<": "&lt;",
48
+ ">": "&gt;",
49
+ "\"": "&quot;",
50
+ "'": "&#39;"
51
+ })[c]);
52
+ /** A sign-in mail's subject, text and HTML. */
53
+ function signInWords(mail) {
54
+ 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
+ ];
77
+ const parts = [
78
+ lead,
79
+ ...mail.url ? [mail.url] : [],
80
+ ...after ? [after] : [],
81
+ ignore
82
+ ];
83
+ 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>`
88
+ ].join("\n");
89
+ return {
90
+ subject,
91
+ text: `${parts.join("\n\n")}\n`,
92
+ html
93
+ };
94
+ }
95
+ /** A key a mail is sent once under: the same code or link asked twice is one Message. */
96
+ async function keyOf(mail) {
97
+ return `sign-in-${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
98
+ mail.kind,
99
+ mail.to,
100
+ mail.code ?? mail.url ?? ""
101
+ ])))).slice(0, 12)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
102
+ }
103
+ /**
104
+ * Sends a sign-in mail where the code runs: from `AUTH_EMAIL_FROM` when it is set, else from the shared
105
+ * sign-in sender. Under `midsummer dev`, with no deployment to send from, its words are printed instead,
106
+ * so the code or the link is there to use. Throws `EmailError` when Email refuses it.
107
+ */
108
+ async function sendSignInMail(mail, env = processEnv()) {
109
+ const checked = checkSignInMail(mail);
110
+ const from = env.AUTH_EMAIL_FROM;
111
+ const handle = here()?.email;
112
+ if (from && handle) {
113
+ await email().send({
114
+ from,
115
+ to: checked.to,
116
+ ...signInWords(checked),
117
+ key: await keyOf(checked),
118
+ tag: "sign-in"
119
+ });
120
+ return;
121
+ }
122
+ if (handle) {
123
+ const answer = await handle.send({
124
+ signIn: checked,
125
+ key: await keyOf(checked)
126
+ });
127
+ if (answer?.error) throw new EmailError(answer.error.code, answer.error.message);
128
+ return;
129
+ }
130
+ if (env.MIDSUMMER_DEV === "1") {
131
+ const words = signInWords(checked);
132
+ console.log(`[sign-in] mail to ${checked.to}: ${words.subject}\n${words.text}`);
133
+ return;
134
+ }
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 }).");
136
+ }
137
+ //#endregion
138
+ export { checkSignInMail, sendSignInMail, signInWords };
@@ -0,0 +1,2 @@
1
+ import { hashPassword, verifyPassword } from "better-auth/crypto";
2
+ export { hashPassword, verifyPassword };
@@ -0,0 +1,2 @@
1
+ import { hashPassword, verifyPassword } from "better-auth/crypto";
2
+ export { hashPassword, verifyPassword };