@midsummer-ai/sdk 0.1.0-staging.3611 → 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/client.d.mts +23 -0
- package/auth/client.mjs +45 -0
- package/auth/contract.d.mts +24 -0
- package/auth/contract.mjs +498 -0
- package/auth/files.d.mts +28 -0
- package/auth/files.mjs +231 -0
- package/auth/index.d.mts +199 -0
- package/auth/index.mjs +3 -0
- package/auth/key.d.mts +19 -0
- package/auth/key.mjs +28 -0
- package/auth/mail.d.mts +31 -0
- package/auth/mail.mjs +138 -0
- package/auth/password.d.mts +2 -0
- package/auth/password.mjs +2 -0
- package/auth/stand-in.d.mts +15 -0
- package/auth/stand-in.mjs +41 -0
- package/auth-BM6vB3XD.mjs +754 -0
- package/billing/index.d.mts +6 -3
- package/billing/index.mjs +2 -1
- package/client-BshDU1b2.d.mts +155 -0
- package/{connection-C_JSWUrt.mjs → client-C7QtAX5u.mjs} +668 -3
- package/database/client.d.mts +1 -153
- package/database/client.mjs +1 -665
- package/database/react.d.mts +1 -1
- package/database/stand-in.d.mts +1 -1
- package/package.json +62 -1
- package/{store-CsBhnabU.mjs → store-dsVD9VnM.mjs} +1 -1
- package/store-gCz6XVaG.d.mts +15 -0
- package/{tabs-gHJHkhm2.mjs → tabs-C85sXTwS.mjs} +1 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { AuthClient } from "better-auth/client";
|
|
2
|
+
import { AdminClientOptions, OrganizationClientOptions, adminClient, emailOTPClient, magicLinkClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
|
|
3
|
+
import { passkeyClient } from "@better-auth/passkey/client";
|
|
4
|
+
import { oauthProviderClient } from "@better-auth/oauth-provider/client";
|
|
5
|
+
//#region src/auth/client.d.ts
|
|
6
|
+
type AuthPlugin = ReturnType<typeof emailOTPClient> | ReturnType<typeof magicLinkClient> | ReturnType<typeof organizationClient<OrganizationClientOptions>> | ReturnType<typeof twoFactorClient> | ReturnType<typeof passkeyClient> | ReturnType<typeof adminClient<AdminClientOptions>> | ReturnType<typeof oauthProviderClient>;
|
|
7
|
+
/** What `authClient()` returns: better-auth's client with every plugin's methods, such as `emailOtp` and `organization`. */
|
|
8
|
+
type MidsummerAuthClient = AuthClient<{
|
|
9
|
+
basePath: string;
|
|
10
|
+
baseURL?: string;
|
|
11
|
+
plugins: AuthPlugin[];
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* The client plugins that match the server's. With `oauthProviderClient`, a sign-in on the app's sign-in page
|
|
15
|
+
* that an MCP client sent the person to carries on to the page that asks them, with nothing more to write.
|
|
16
|
+
*/
|
|
17
|
+
declare const authPlugins: () => AuthPlugin[];
|
|
18
|
+
/** A client for the page's own sign-in, or the address `baseURL` gives when the app's server is elsewhere. */
|
|
19
|
+
declare function authClient(options?: {
|
|
20
|
+
readonly baseURL?: string;
|
|
21
|
+
}): MidsummerAuthClient;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { MidsummerAuthClient, authClient, authPlugins };
|
package/auth/client.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createAuthClient } from "better-auth/client";
|
|
2
|
+
import { adminClient, emailOTPClient, magicLinkClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
|
|
3
|
+
import { passkeyClient } from "@better-auth/passkey/client";
|
|
4
|
+
import { oauthProviderClient } from "@better-auth/oauth-provider/client";
|
|
5
|
+
//#region src/auth/client.ts
|
|
6
|
+
/**
|
|
7
|
+
* Sign-in from the browser: better-auth's client with the plugins `@midsummer-ai/sdk/auth` turns on, talking to
|
|
8
|
+
* `/api/auth` on the page's own address.
|
|
9
|
+
*
|
|
10
|
+
* import { authClient } from "@midsummer-ai/sdk/auth/client"
|
|
11
|
+
*
|
|
12
|
+
* const auth = authClient()
|
|
13
|
+
* await auth.signUp.email({ email, password, name })
|
|
14
|
+
* await auth.emailOtp.sendVerificationOtp({ email, type: "sign-in" })
|
|
15
|
+
* await auth.signIn.emailOtp({ email, otp })
|
|
16
|
+
* await auth.signIn.social({ provider: "google", callbackURL: "/" })
|
|
17
|
+
* await auth.organization.create({ name: "Acme", slug: "acme" })
|
|
18
|
+
* const { data } = await auth.getSession()
|
|
19
|
+
*
|
|
20
|
+
* `auth.useSession` is a store any framework can subscribe to; in React, `better-auth/react`'s `createAuthClient`
|
|
21
|
+
* takes the same `plugins`.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* The client plugins that match the server's. With `oauthProviderClient`, a sign-in on the app's sign-in page
|
|
25
|
+
* that an MCP client sent the person to carries on to the page that asks them, with nothing more to write.
|
|
26
|
+
*/
|
|
27
|
+
const authPlugins = () => [
|
|
28
|
+
emailOTPClient(),
|
|
29
|
+
magicLinkClient(),
|
|
30
|
+
organizationClient(),
|
|
31
|
+
twoFactorClient(),
|
|
32
|
+
passkeyClient(),
|
|
33
|
+
adminClient(),
|
|
34
|
+
oauthProviderClient()
|
|
35
|
+
];
|
|
36
|
+
/** A client for the page's own sign-in, or the address `baseURL` gives when the app's server is elsewhere. */
|
|
37
|
+
function authClient(options = {}) {
|
|
38
|
+
return createAuthClient({
|
|
39
|
+
basePath: "/api/auth",
|
|
40
|
+
...options.baseURL ? { baseURL: options.baseURL } : {},
|
|
41
|
+
plugins: authPlugins()
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
export { authClient, authPlugins };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { SignInMail } from "./mail.mjs";
|
|
2
|
+
import { Auth } from "./index.mjs";
|
|
3
|
+
//#region src/auth/contract.d.ts
|
|
4
|
+
interface AuthHarness {
|
|
5
|
+
/** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
|
|
6
|
+
readonly auth: Auth;
|
|
7
|
+
/** The mail it sent, oldest first. */
|
|
8
|
+
outbox(): ReadonlyArray<SignInMail>;
|
|
9
|
+
/** How many calls reached the rows so far. */
|
|
10
|
+
calls(): number;
|
|
11
|
+
}
|
|
12
|
+
interface AuthContractCase {
|
|
13
|
+
readonly name: string;
|
|
14
|
+
run(harness: AuthHarness): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
declare const CONTRACT_ORIGIN = "https://shop.contract.test";
|
|
17
|
+
/** The scopes every harness's sign-in declares. */
|
|
18
|
+
declare const CONTRACT_SCOPES: {
|
|
19
|
+
readonly "notes:read": "Read your notes";
|
|
20
|
+
readonly "notes:write": "Add and change your notes";
|
|
21
|
+
};
|
|
22
|
+
declare const authContract: ReadonlyArray<AuthContractCase>;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { AuthContractCase, AuthHarness, CONTRACT_ORIGIN, CONTRACT_SCOPES, authContract };
|
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { n as AuthError } from "../auth-BM6vB3XD.mjs";
|
|
2
|
+
//#region src/auth/contract.ts
|
|
3
|
+
/**
|
|
4
|
+
* Sign-in's contract: what every store promises, as cases any test runner can run. Each case is given sign-in
|
|
5
|
+
* over a store with no users, whose mail it can read, and how many calls reached the rows. The Stand-in runs
|
|
6
|
+
* them in this package; the Project's Database runs the same cases through `db/auth.ts` (`databaseStore`).
|
|
7
|
+
*
|
|
8
|
+
* for (const c of authContract) test(c.name, () => c.run(harness()))
|
|
9
|
+
*
|
|
10
|
+
* Every case talks to sign-in as a browser does: requests to `/api/auth/...` with the cookies it was given.
|
|
11
|
+
*/
|
|
12
|
+
const CONTRACT_ORIGIN = "https://shop.contract.test";
|
|
13
|
+
/** The scopes every harness's sign-in declares. */
|
|
14
|
+
const CONTRACT_SCOPES = {
|
|
15
|
+
"notes:read": "Read your notes",
|
|
16
|
+
"notes:write": "Add and change your notes"
|
|
17
|
+
};
|
|
18
|
+
/** Where the contract's MCP client comes back to: an app on someone's own computer. */
|
|
19
|
+
const CLIENT_CALLBACK = "http://127.0.0.1:33418/callback";
|
|
20
|
+
/** A browser's cookies for one origin: what each response set, sent with the next request. */
|
|
21
|
+
var Jar = class {
|
|
22
|
+
cookies = /* @__PURE__ */ new Map();
|
|
23
|
+
take(response) {
|
|
24
|
+
for (const line of response.headers.getSetCookie()) {
|
|
25
|
+
const [pair = ""] = line.split(";");
|
|
26
|
+
const at = pair.indexOf("=");
|
|
27
|
+
const name = pair.slice(0, at).trim(), value = pair.slice(at + 1).trim();
|
|
28
|
+
if (/max-age=0/i.test(line) || value === "") this.cookies.delete(name);
|
|
29
|
+
else this.cookies.set(name, value);
|
|
30
|
+
}
|
|
31
|
+
return response;
|
|
32
|
+
}
|
|
33
|
+
get header() {
|
|
34
|
+
return [...this.cookies].map(([name, value]) => `${name}=${value}`).join("; ");
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
async function ask(auth, jar, path, body) {
|
|
38
|
+
const headers = { origin: CONTRACT_ORIGIN };
|
|
39
|
+
if (jar.header) headers.cookie = jar.header;
|
|
40
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
41
|
+
const request = new Request(`${CONTRACT_ORIGIN}/api/auth${path}`, {
|
|
42
|
+
method: body === void 0 ? "GET" : "POST",
|
|
43
|
+
headers,
|
|
44
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
45
|
+
});
|
|
46
|
+
return jar.take(await auth.handler(request));
|
|
47
|
+
}
|
|
48
|
+
/** Who the jar's cookies sign in, as the app's own code asks. */
|
|
49
|
+
async function who(auth, jar) {
|
|
50
|
+
return (await auth.session(new Request(`https://shop.contract.test/`, { headers: jar.header ? { cookie: jar.header } : {} })))?.user.email ?? null;
|
|
51
|
+
}
|
|
52
|
+
function equal(actual, expected, what, pick = (value) => value) {
|
|
53
|
+
if (JSON.stringify(pick(actual)) !== JSON.stringify(expected)) throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(pick(actual))}`);
|
|
54
|
+
}
|
|
55
|
+
async function signUp(auth, jar, email) {
|
|
56
|
+
const answer = await ask(auth, jar, "/sign-up/email", {
|
|
57
|
+
email,
|
|
58
|
+
password: "correct horse battery",
|
|
59
|
+
name: email.split("@")[0]
|
|
60
|
+
});
|
|
61
|
+
equal(answer.status, 200, `signing up ${email}`);
|
|
62
|
+
return (await answer.json()).user.id;
|
|
63
|
+
}
|
|
64
|
+
/** A request as the signed-in person's browser sends it. */
|
|
65
|
+
const asPerson = (jar, path = "/") => new Request(`${CONTRACT_ORIGIN}${path}`, { headers: { cookie: jar.header } });
|
|
66
|
+
/** A request as an agent sends it, with a key or an MCP client's token. */
|
|
67
|
+
const asAgent = (credential, path = "/mcp") => new Request(`${CONTRACT_ORIGIN}${path}`, { headers: { authorization: `Bearer ${credential}` } });
|
|
68
|
+
/** A form posted as a client's own code posts it, with no cookies. */
|
|
69
|
+
const postForm = (auth, path, fields) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth${path}`, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
72
|
+
body: new URLSearchParams(fields)
|
|
73
|
+
}));
|
|
74
|
+
/** What a protected route returns: who the request acts for. */
|
|
75
|
+
const whoActs = (auth, scope) => auth.protect(scope, (_request, signedIn) => Response.json({
|
|
76
|
+
via: signedIn.via,
|
|
77
|
+
email: signedIn.user.email
|
|
78
|
+
}));
|
|
79
|
+
async function refusal(work) {
|
|
80
|
+
try {
|
|
81
|
+
await work();
|
|
82
|
+
return null;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof AuthError) return error;
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
89
|
+
const authContract = [
|
|
90
|
+
{
|
|
91
|
+
name: "signing up with an email and a password signs the person in",
|
|
92
|
+
async run({ auth }) {
|
|
93
|
+
const jar = new Jar();
|
|
94
|
+
await signUp(auth, jar, "ada@example.com");
|
|
95
|
+
equal(await who(auth, jar), "ada@example.com", "who the cookie signs in");
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: "signing out ends the session, and the password signs in again",
|
|
100
|
+
async run({ auth }) {
|
|
101
|
+
const jar = new Jar();
|
|
102
|
+
await signUp(auth, jar, "lin@example.com");
|
|
103
|
+
equal((await ask(auth, jar, "/sign-out", {})).status, 200, "signing out");
|
|
104
|
+
equal(await who(auth, jar), null, "who is signed in after signing out");
|
|
105
|
+
equal((await ask(auth, jar, "/sign-in/email", {
|
|
106
|
+
email: "lin@example.com",
|
|
107
|
+
password: "correct horse battery"
|
|
108
|
+
})).status, 200, "signing in");
|
|
109
|
+
equal(await who(auth, jar), "lin@example.com", "who is signed in again");
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
name: "a wrong password and an unknown email are refused alike",
|
|
114
|
+
async run({ auth }) {
|
|
115
|
+
await signUp(auth, new Jar(), "grace@example.com");
|
|
116
|
+
equal((await ask(auth, new Jar(), "/sign-in/email", {
|
|
117
|
+
email: "grace@example.com",
|
|
118
|
+
password: "wrong horse battery"
|
|
119
|
+
})).status, 401, "a wrong password");
|
|
120
|
+
equal((await ask(auth, new Jar(), "/sign-in/email", {
|
|
121
|
+
email: "nobody@example.com",
|
|
122
|
+
password: "correct horse battery"
|
|
123
|
+
})).status, 401, "an unknown email");
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: "a store starts with no users: nobody signs in until someone signs up",
|
|
128
|
+
async run({ auth }) {
|
|
129
|
+
equal((await ask(auth, new Jar(), "/sign-in/email", {
|
|
130
|
+
email: "ada@example.com",
|
|
131
|
+
password: "correct horse battery"
|
|
132
|
+
})).status, 401, "signing in to a new store");
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
name: "a code sent by mail signs the person in, once",
|
|
137
|
+
async run({ auth, outbox }) {
|
|
138
|
+
const jar = new Jar();
|
|
139
|
+
equal((await ask(auth, jar, "/email-otp/send-verification-otp", {
|
|
140
|
+
email: "kay@example.com",
|
|
141
|
+
type: "sign-in"
|
|
142
|
+
})).status, 200, "asking for a code");
|
|
143
|
+
const mail = outbox().at(-1);
|
|
144
|
+
equal([
|
|
145
|
+
mail?.to,
|
|
146
|
+
mail?.kind,
|
|
147
|
+
/^\d{6}$/.test(mail?.code ?? "")
|
|
148
|
+
], [
|
|
149
|
+
"kay@example.com",
|
|
150
|
+
"code",
|
|
151
|
+
true
|
|
152
|
+
], "the mail sent");
|
|
153
|
+
equal((await ask(auth, jar, "/sign-in/email-otp", {
|
|
154
|
+
email: "kay@example.com",
|
|
155
|
+
otp: mail.code
|
|
156
|
+
})).status, 200, "signing in with the code");
|
|
157
|
+
equal(await who(auth, jar), "kay@example.com", "who the code signed in");
|
|
158
|
+
equal((await ask(auth, new Jar(), "/sign-in/email-otp", {
|
|
159
|
+
email: "kay@example.com",
|
|
160
|
+
otp: mail.code
|
|
161
|
+
})).status === 200, false, "the same code again");
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
name: "a session kept in its cookie is read without reaching the rows",
|
|
166
|
+
async run({ auth, calls }) {
|
|
167
|
+
const jar = new Jar();
|
|
168
|
+
await signUp(auth, jar, "max@example.com");
|
|
169
|
+
equal(await who(auth, jar), "max@example.com", "the first read");
|
|
170
|
+
const before = calls();
|
|
171
|
+
for (let i = 0; i < 5; i++) equal(await who(auth, jar), "max@example.com", "a read from the cookie");
|
|
172
|
+
equal(calls() - before, 0, "calls that reached the rows for five reads");
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
name: "a revoked session is refused once its cookie is not trusted on its own",
|
|
177
|
+
async run({ auth }) {
|
|
178
|
+
const jar = new Jar();
|
|
179
|
+
await signUp(auth, jar, "ola@example.com");
|
|
180
|
+
const context = await auth.at(CONTRACT_ORIGIN).$context;
|
|
181
|
+
const signedIn = await auth.session(new Request(`${CONTRACT_ORIGIN}/`, { headers: { cookie: jar.header } }));
|
|
182
|
+
await context.internalAdapter.deleteSession(signedIn.session.token);
|
|
183
|
+
equal(await auth.at(CONTRACT_ORIGIN).api.getSession({
|
|
184
|
+
headers: new Headers({ cookie: jar.header }),
|
|
185
|
+
query: { disableCookieCache: true }
|
|
186
|
+
}), null, "the session read from its row");
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
name: "a banned user can't sign in",
|
|
191
|
+
async run({ auth }) {
|
|
192
|
+
const id = await signUp(auth, new Jar(), "zed@example.com");
|
|
193
|
+
const context = await auth.at(CONTRACT_ORIGIN).$context;
|
|
194
|
+
await context.internalAdapter.updateUser(id, {
|
|
195
|
+
banned: true,
|
|
196
|
+
banReason: "spam"
|
|
197
|
+
});
|
|
198
|
+
await context.internalAdapter.deleteUserSessions(id);
|
|
199
|
+
equal((await ask(auth, new Jar(), "/sign-in/email", {
|
|
200
|
+
email: "zed@example.com",
|
|
201
|
+
password: "correct horse battery"
|
|
202
|
+
})).status, 403, "signing in banned");
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
name: "a key made with one scope acts for its person where that scope is asked, and is refused by name where another is",
|
|
207
|
+
async run({ auth }) {
|
|
208
|
+
const jar = new Jar();
|
|
209
|
+
await signUp(auth, jar, "ivy@example.com");
|
|
210
|
+
const made = await auth.keys.create(asPerson(jar), {
|
|
211
|
+
name: "reader",
|
|
212
|
+
scopes: ["notes:read"]
|
|
213
|
+
});
|
|
214
|
+
equal([made.key.startsWith("key_"), made.scopes], [true, ["notes:read"]], "the key made");
|
|
215
|
+
const agent = await auth.session(asAgent(made.key), { scope: "notes:read" });
|
|
216
|
+
equal([
|
|
217
|
+
agent?.via,
|
|
218
|
+
agent?.user.email,
|
|
219
|
+
agent?.via === "key" ? agent.agent.name : null
|
|
220
|
+
], [
|
|
221
|
+
"key",
|
|
222
|
+
"ivy@example.com",
|
|
223
|
+
"reader"
|
|
224
|
+
], "who the key acts for");
|
|
225
|
+
const refused = await refusal(() => auth.session(asAgent(made.key), { scope: "notes:write" }));
|
|
226
|
+
equal([
|
|
227
|
+
refused?.code,
|
|
228
|
+
refused?.scope,
|
|
229
|
+
refused?.message
|
|
230
|
+
], [
|
|
231
|
+
"forbidden",
|
|
232
|
+
"notes:write",
|
|
233
|
+
"This key can't do that: it lacks the scope notes:write."
|
|
234
|
+
], "asking for a scope it lacks");
|
|
235
|
+
equal(await auth.session(asAgent(made.key)), null, "a route with no scope");
|
|
236
|
+
equal((await auth.keys.list(asPerson(jar))).map((key) => [
|
|
237
|
+
key.name,
|
|
238
|
+
key.scopes,
|
|
239
|
+
"key" in key,
|
|
240
|
+
key.lastUsedAt !== null
|
|
241
|
+
]), [[
|
|
242
|
+
"reader",
|
|
243
|
+
["notes:read"],
|
|
244
|
+
false,
|
|
245
|
+
true
|
|
246
|
+
]], "the person's keys");
|
|
247
|
+
equal((await refusal(() => auth.keys.create(asPerson(jar), {
|
|
248
|
+
name: "wide",
|
|
249
|
+
scopes: ["everything"]
|
|
250
|
+
})))?.code, "invalid", "a key with a scope the app doesn't declare");
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: "a revoked key, an expired key, an unknown key and a banned person's key sign no one in",
|
|
255
|
+
async run({ auth }) {
|
|
256
|
+
const jar = new Jar();
|
|
257
|
+
await signUp(auth, jar, "jo@example.com");
|
|
258
|
+
const gone = await auth.keys.create(asPerson(jar), {
|
|
259
|
+
name: "gone",
|
|
260
|
+
scopes: ["notes:read"]
|
|
261
|
+
});
|
|
262
|
+
const old = await auth.keys.create(asPerson(jar), {
|
|
263
|
+
name: "old",
|
|
264
|
+
scopes: ["notes:read"],
|
|
265
|
+
expiresIn: 86400
|
|
266
|
+
});
|
|
267
|
+
await auth.keys.revoke(asPerson(jar), gone.id);
|
|
268
|
+
const context = await auth.at(CONTRACT_ORIGIN).$context;
|
|
269
|
+
await context.adapter.update({
|
|
270
|
+
model: "apikey",
|
|
271
|
+
where: [{
|
|
272
|
+
field: "id",
|
|
273
|
+
value: old.id
|
|
274
|
+
}],
|
|
275
|
+
update: { expiresAt: /* @__PURE__ */ new Date(Date.now() - 1e3) }
|
|
276
|
+
});
|
|
277
|
+
equal(await auth.session(asAgent(gone.key), { scope: "notes:read" }), null, "a revoked key");
|
|
278
|
+
equal(await auth.session(asAgent(old.key), { scope: "notes:read" }), null, "an expired key");
|
|
279
|
+
equal(await auth.session(asAgent("key_never-made"), { scope: "notes:read" }), null, "an unknown key");
|
|
280
|
+
equal((await refusal(() => auth.keys.list(asAgent(old.key))))?.code, "forbidden", "an agent listing keys");
|
|
281
|
+
const live = await auth.keys.create(asPerson(jar), {
|
|
282
|
+
name: "live",
|
|
283
|
+
scopes: ["notes:read"]
|
|
284
|
+
});
|
|
285
|
+
await context.internalAdapter.updateUser((await auth.session(asPerson(jar))).user.id, { banned: true });
|
|
286
|
+
equal(await auth.session(asAgent(live.key), { scope: "notes:read" }), null, "a banned person's key");
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
name: "a key's calls one after another read its rows once",
|
|
291
|
+
async run({ auth, calls }) {
|
|
292
|
+
const jar = new Jar();
|
|
293
|
+
await signUp(auth, jar, "ned@example.com");
|
|
294
|
+
const made = await auth.keys.create(asPerson(jar), {
|
|
295
|
+
name: "busy",
|
|
296
|
+
scopes: ["notes:read"]
|
|
297
|
+
});
|
|
298
|
+
equal((await auth.session(asAgent(made.key), { scope: "notes:read" }))?.user.email, "ned@example.com", "the first call");
|
|
299
|
+
const before = calls();
|
|
300
|
+
for (let i = 0; i < 5; i++) equal((await auth.session(asAgent(made.key), { scope: "notes:read" }))?.via, "key", "a call after");
|
|
301
|
+
equal(calls() - before, 0, "calls that reached the rows for five more");
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
{
|
|
305
|
+
name: "a new store has no keys, clients or grants",
|
|
306
|
+
async run({ auth }) {
|
|
307
|
+
const jar = new Jar();
|
|
308
|
+
await signUp(auth, jar, "una@example.com");
|
|
309
|
+
equal([await auth.keys.list(asPerson(jar)), await auth.grants.list(asPerson(jar))], [[], []], "a new person's keys and grants");
|
|
310
|
+
const context = await auth.at(CONTRACT_ORIGIN).$context;
|
|
311
|
+
equal(await Promise.all([
|
|
312
|
+
"apikey",
|
|
313
|
+
"oauthClient",
|
|
314
|
+
"oauthConsent",
|
|
315
|
+
"oauthRefreshToken"
|
|
316
|
+
].map((model) => context.adapter.count({ model }))), [
|
|
317
|
+
0,
|
|
318
|
+
0,
|
|
319
|
+
0,
|
|
320
|
+
0
|
|
321
|
+
], "rows kept for agents");
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
name: "an MCP client finds the app's sign-in, registers, is let in by a person, calls a protected route, renews its token, and is stopped when its grant is removed",
|
|
326
|
+
async run({ auth, calls }) {
|
|
327
|
+
const route = whoActs(auth, "notes:read");
|
|
328
|
+
const unsigned = await route(new Request(`${CONTRACT_ORIGIN}/mcp`, { method: "POST" }));
|
|
329
|
+
equal([unsigned.status, unsigned.headers.get("www-authenticate")], [401, `Bearer scope="notes:read", resource_metadata="${CONTRACT_ORIGIN}/.well-known/oauth-protected-resource/mcp"`], "a call with no token");
|
|
330
|
+
equal(await (await auth.handler(new Request(`${CONTRACT_ORIGIN}/.well-known/oauth-protected-resource/mcp`))).json(), {
|
|
331
|
+
resource: `${CONTRACT_ORIGIN}/mcp`,
|
|
332
|
+
authorization_servers: [`${CONTRACT_ORIGIN}/api/auth`],
|
|
333
|
+
scopes_supported: ["notes:read", "notes:write"]
|
|
334
|
+
}, "the protected resource's metadata, less what it says of DPoP", (value) => ({
|
|
335
|
+
resource: value.resource,
|
|
336
|
+
authorization_servers: value.authorization_servers,
|
|
337
|
+
scopes_supported: value.scopes_supported
|
|
338
|
+
}));
|
|
339
|
+
const server = await (await auth.handler(new Request(`${CONTRACT_ORIGIN}/.well-known/oauth-authorization-server/api/auth`))).json();
|
|
340
|
+
equal([
|
|
341
|
+
server.issuer,
|
|
342
|
+
server.registration_endpoint,
|
|
343
|
+
server.token_endpoint,
|
|
344
|
+
server.code_challenge_methods_supported.includes("S256"),
|
|
345
|
+
server.authorization_response_iss_parameter_supported
|
|
346
|
+
], [
|
|
347
|
+
`${CONTRACT_ORIGIN}/api/auth`,
|
|
348
|
+
`${CONTRACT_ORIGIN}/api/auth/oauth2/register`,
|
|
349
|
+
`${CONTRACT_ORIGIN}/api/auth/oauth2/token`,
|
|
350
|
+
true,
|
|
351
|
+
true
|
|
352
|
+
], "the authorization server's metadata");
|
|
353
|
+
equal((await (await auth.handler(new Request(`${CONTRACT_ORIGIN}/.well-known/oauth-authorization-server`))).json()).issuer, server.issuer, "the same document at the address's root");
|
|
354
|
+
const registered = await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/oauth2/register`, {
|
|
355
|
+
method: "POST",
|
|
356
|
+
headers: { "content-type": "application/json" },
|
|
357
|
+
body: JSON.stringify({
|
|
358
|
+
client_name: "Contract client",
|
|
359
|
+
redirect_uris: [CLIENT_CALLBACK],
|
|
360
|
+
token_endpoint_auth_method: "none",
|
|
361
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
362
|
+
response_types: ["code"]
|
|
363
|
+
})
|
|
364
|
+
}));
|
|
365
|
+
equal(registered.status, 201, "registering");
|
|
366
|
+
const { client_id: clientId } = await registered.json();
|
|
367
|
+
const verifier = base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
368
|
+
const challenged = base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
369
|
+
const asked = new URLSearchParams({
|
|
370
|
+
response_type: "code",
|
|
371
|
+
client_id: clientId,
|
|
372
|
+
redirect_uri: CLIENT_CALLBACK,
|
|
373
|
+
scope: "notes:read offline_access",
|
|
374
|
+
state: "s1",
|
|
375
|
+
code_challenge: challenged,
|
|
376
|
+
code_challenge_method: "S256",
|
|
377
|
+
resource: `${CONTRACT_ORIGIN}/mcp`
|
|
378
|
+
});
|
|
379
|
+
const jar = new Jar();
|
|
380
|
+
const toSignIn = await auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/oauth2/authorize?${asked}`));
|
|
381
|
+
const signInAt = new URL(toSignIn.headers.get("location") ?? "", CONTRACT_ORIGIN);
|
|
382
|
+
equal([toSignIn.status, signInAt.pathname], [302, "/sign-in"], "authorizing signed out");
|
|
383
|
+
const signedUp = await ask(auth, jar, "/sign-up/email", {
|
|
384
|
+
email: "mia@example.com",
|
|
385
|
+
password: "correct horse battery",
|
|
386
|
+
name: "Mia",
|
|
387
|
+
oauth_query: signInAt.search.slice(1)
|
|
388
|
+
});
|
|
389
|
+
const consentAt = new URL((await signedUp.json()).url, CONTRACT_ORIGIN);
|
|
390
|
+
equal(consentAt.pathname, "/api/auth/agent-consent", "where signing in leads");
|
|
391
|
+
const page = await auth.handler(new Request(consentAt, { headers: { cookie: jar.header } }));
|
|
392
|
+
const html = await page.text();
|
|
393
|
+
equal([
|
|
394
|
+
page.status,
|
|
395
|
+
html.includes("Contract client wants to use"),
|
|
396
|
+
html.includes("<li>Read your notes</li>"),
|
|
397
|
+
html.includes("127.0.0.1:33418"),
|
|
398
|
+
html.includes("mia@example.com")
|
|
399
|
+
], [
|
|
400
|
+
200,
|
|
401
|
+
true,
|
|
402
|
+
true,
|
|
403
|
+
true,
|
|
404
|
+
true
|
|
405
|
+
], "the page that asks: the client, the scope in the app's words, where it goes back, and who is asked");
|
|
406
|
+
const answer = (origin) => auth.handler(new Request(`${CONTRACT_ORIGIN}/api/auth/agent-consent`, {
|
|
407
|
+
method: "POST",
|
|
408
|
+
headers: {
|
|
409
|
+
origin,
|
|
410
|
+
cookie: jar.header,
|
|
411
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
412
|
+
},
|
|
413
|
+
body: new URLSearchParams({
|
|
414
|
+
accept: "true",
|
|
415
|
+
oauth_query: consentAt.search.slice(1)
|
|
416
|
+
})
|
|
417
|
+
}));
|
|
418
|
+
equal((await answer("https://evil.example")).status, 403, "an answer posted from another site");
|
|
419
|
+
const allowed = await answer(CONTRACT_ORIGIN);
|
|
420
|
+
const back = new URL(allowed.headers.get("location") ?? "");
|
|
421
|
+
equal([
|
|
422
|
+
allowed.status,
|
|
423
|
+
`${back.origin}${back.pathname}`,
|
|
424
|
+
back.searchParams.get("state"),
|
|
425
|
+
back.searchParams.get("iss")
|
|
426
|
+
], [
|
|
427
|
+
302,
|
|
428
|
+
CLIENT_CALLBACK,
|
|
429
|
+
"s1",
|
|
430
|
+
`${CONTRACT_ORIGIN}/api/auth`
|
|
431
|
+
], "going back to the client");
|
|
432
|
+
const exchange = (fields) => postForm(auth, "/oauth2/token", {
|
|
433
|
+
client_id: clientId,
|
|
434
|
+
resource: `${CONTRACT_ORIGIN}/mcp`,
|
|
435
|
+
...fields
|
|
436
|
+
});
|
|
437
|
+
equal((await exchange({
|
|
438
|
+
grant_type: "authorization_code",
|
|
439
|
+
code: back.searchParams.get("code"),
|
|
440
|
+
redirect_uri: CLIENT_CALLBACK,
|
|
441
|
+
code_verifier: "not-the-verifier-not-the-verifier-not-the-verifier"
|
|
442
|
+
})).status === 200, false, "the code with another verifier");
|
|
443
|
+
const first = await (await exchange({
|
|
444
|
+
grant_type: "authorization_code",
|
|
445
|
+
code: new URL((await (await ask(auth, jar, "/oauth2/consent", {
|
|
446
|
+
accept: true,
|
|
447
|
+
oauth_query: consentAt.search.slice(1)
|
|
448
|
+
})).json()).url).searchParams.get("code"),
|
|
449
|
+
redirect_uri: CLIENT_CALLBACK,
|
|
450
|
+
code_verifier: verifier
|
|
451
|
+
})).json();
|
|
452
|
+
equal([
|
|
453
|
+
typeof first.access_token,
|
|
454
|
+
typeof first.refresh_token,
|
|
455
|
+
first.expires_in
|
|
456
|
+
], [
|
|
457
|
+
"string",
|
|
458
|
+
"string",
|
|
459
|
+
300
|
|
460
|
+
], "the tokens");
|
|
461
|
+
const called = await route(asAgent(first.access_token));
|
|
462
|
+
equal([called.status, await called.json()], [200, {
|
|
463
|
+
via: "client",
|
|
464
|
+
email: "mia@example.com"
|
|
465
|
+
}], "a call with the token");
|
|
466
|
+
const before = calls();
|
|
467
|
+
equal((await route(asAgent(first.access_token))).status, 200, "a second call");
|
|
468
|
+
equal(calls() - before, 0, "calls that reached the rows for the second call");
|
|
469
|
+
const lacking = await whoActs(auth, "notes:write")(asAgent(first.access_token));
|
|
470
|
+
equal([lacking.status, lacking.headers.get("www-authenticate")], [403, `Bearer error="insufficient_scope", scope="notes:write", resource_metadata="${CONTRACT_ORIGIN}/.well-known/oauth-protected-resource/mcp"`], "a call that needs another scope");
|
|
471
|
+
equal((await route(asAgent(`${first.access_token.slice(0, -4)}AAAA`))).status, 401, "a token whose signature is changed");
|
|
472
|
+
const renewed = await (await exchange({
|
|
473
|
+
grant_type: "refresh_token",
|
|
474
|
+
refresh_token: first.refresh_token
|
|
475
|
+
})).json();
|
|
476
|
+
equal((await route(asAgent(renewed.access_token))).status, 200, "a call with the renewed token");
|
|
477
|
+
const grants = await auth.grants.list(asPerson(jar));
|
|
478
|
+
equal(grants.map((grant) => [
|
|
479
|
+
grant.client,
|
|
480
|
+
grant.clientId === clientId,
|
|
481
|
+
grant.scopes
|
|
482
|
+
]), [[
|
|
483
|
+
"Contract client",
|
|
484
|
+
true,
|
|
485
|
+
["notes:read", "offline_access"]
|
|
486
|
+
]], "the person's grants");
|
|
487
|
+
await auth.grants.revoke(asPerson(jar), grants[0].id);
|
|
488
|
+
const after = await exchange({
|
|
489
|
+
grant_type: "refresh_token",
|
|
490
|
+
refresh_token: renewed.refresh_token
|
|
491
|
+
});
|
|
492
|
+
equal([after.status, (await after.json()).error], [400, "invalid_grant"], "renewing after the grant is removed");
|
|
493
|
+
equal(await auth.grants.list(asPerson(jar)), [], "the person's grants after");
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
];
|
|
497
|
+
//#endregion
|
|
498
|
+
export { CONTRACT_ORIGIN, CONTRACT_SCOPES, authContract };
|
package/auth/files.d.mts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { BetterAuthOptions } from "better-auth";
|
|
2
|
+
//#region src/auth/files.d.ts
|
|
3
|
+
/** The tables sign-in keeps, by table name: each field's shape, and the fields rows are looked up by. */
|
|
4
|
+
interface AuthTable {
|
|
5
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
6
|
+
readonly indexed: ReadonlyArray<string>;
|
|
7
|
+
readonly unique: ReadonlyArray<string>;
|
|
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
|
+
declare function authTablesOf(options: BetterAuthOptions): Readonly<Record<string, AuthTable>>;
|
|
15
|
+
/** `db/authTables.ts`: each table as `defineTable(...)` with its indexes, and the fields each is looked up by. */
|
|
16
|
+
declare function tablesFile(tables: Readonly<Record<string, AuthTable>>): string;
|
|
17
|
+
/** The lines db/schema.ts names sign-in's tables with, inside `defineSchema({ ... })`. */
|
|
18
|
+
declare function schemaLines(tables: Readonly<Record<string, AuthTable>>): string;
|
|
19
|
+
/**
|
|
20
|
+
* `db/auth.ts`: what `@midsummer-ai/sdk/auth` calls, `auth.create`, `auth.findOne`, `auth.findMany`,
|
|
21
|
+
* `auth.count`, `auth.update`, `auth.updateMany`, `auth.deleteMany`, `auth.increment` and `auth.consume`. A `where` is
|
|
22
|
+
* better-auth's: clauses of `{ field, operator, value, connector, mode }`, `id` meaning the row's `_id`. All
|
|
23
|
+
* joined by AND with an `eq` (or a range) on a field looked up by reads only that index's rows; anything else
|
|
24
|
+
* reads the table.
|
|
25
|
+
*/
|
|
26
|
+
declare 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.\nimport { mutation, query, v } from \"./_generated/server\"\nimport { authLookups } from \"./authTables\"\n\nconst where = v.optional(v.array(v.any()))\n\nfunction server(ctx) {\n if (!ctx.identity.server) throw new Error(\"Only the app's own server reads and writes sign-in's tables.\")\n}\nfunction table(model) {\n if (!Object.hasOwn(authLookups, model)) throw new Error(`${model} is not one of sign-in's tables`)\n return model\n}\n/** A row as better-auth takes it: its `_id` as `id`. */\nfunction shown(doc) {\n if (!doc) return null\n const { _id, _creationTime, _version, ...fields } = doc\n return { id: _id, ...fields }\n}\nconst text = (value) => (typeof value === \"string\" ? value.toLowerCase() : value)\nfunction holds(row, clause) {\n const { field, value, operator = \"eq\", mode } = clause\n const have = row[field], loose = mode === \"insensitive\"\n const same = (a, b) => (loose ? text(a) === text(b) : a === b)\n switch (operator) {\n case \"eq\": return value === null ? have == null : same(have, value)\n case \"ne\": return value === null ? have != null : !same(have, value)\n case \"in\": return Array.isArray(value) && value.some((one) => same(have, one))\n case \"not_in\": return Array.isArray(value) && !value.some((one) => same(have, one))\n case \"lt\": return value != null && have != null && have < value\n case \"lte\": return value != null && have != null && have <= value\n case \"gt\": return value != null && have != null && have > value\n case \"gte\": return value != null && have != null && have >= value\n case \"contains\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).includes(text(value)) : have.includes(value))\n case \"starts_with\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).startsWith(text(value)) : have.startsWith(value))\n case \"ends_with\": return typeof have === \"string\" && typeof value === \"string\" && (loose ? text(have).endsWith(text(value)) : have.endsWith(value))\n default: throw new Error(`sign-in asked with an operator the Database's sign-in tables don't take: ${operator}`)\n }\n}\n/** Whether a row matches a where: its clauses in order, each joined to those before by its own connector. */\nfunction matches(row, clauses) {\n if (!clauses?.length) return true\n let result = holds(row, clauses[0])\n for (const clause of clauses.slice(1)) result = clause.connector === \"OR\" ? result || holds(row, clause) : result && holds(row, clause)\n return result\n}\nconst RANGE = { lt: \"lt\", lte: \"lte\", gt: \"gt\", gte: \"gte\" }\n/** 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. */\nasync function candidates(ctx, model, clauses) {\n const all = clauses ?? []\n const ands = all.every((clause, index) => index === 0 || clause.connector !== \"OR\")\n if (ands) {\n const byId = all.find((clause) => clause.field === \"id\" && (clause.operator ?? \"eq\") === \"eq\")\n if (byId) {\n const id = typeof byId.value === \"string\" ? ctx.db.normalizeId(model, byId.value) : null\n const doc = id ? await ctx.db.get(model, id) : null\n return doc ? [doc] : []\n }\n const ids = all.find((clause) => clause.field === \"id\" && clause.operator === \"in\" && Array.isArray(clause.value))\n 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)\n const lookups = authLookups[model]\n // Of the fields it asks for by value, the one listed first finds the fewest rows: a unique one, a key or a token.\n 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]\n if (exact) return ctx.db.query(model).withIndex(`by_${exact.field}`, (q) => q.eq(exact.field, exact.value)).collect()\n const ranged = all.find((clause) => RANGE[clause.operator] && clause.value != null && lookups.includes(clause.field))\n if (ranged) return ctx.db.query(model).withIndex(`by_${ranged.field}`, (q) => q[RANGE[ranged.operator]](ranged.field, ranged.value)).collect()\n }\n return ctx.db.query(model).collect()\n}\nasync function found(ctx, model, clauses) {\n return (await candidates(ctx, model, clauses)).map(shown).filter((row) => matches(row, clauses))\n}\nfunction ordered(rows, sortBy) {\n if (!sortBy) return rows\n const sign = sortBy.direction === \"desc\" ? -1 : 1\n return [...rows].sort((a, b) => {\n const x = a[sortBy.field], y = b[sortBy.field]\n return x == null && y == null ? 0 : x == null ? -sign : y == null ? sign : x < y ? -sign : x > y ? sign : 0\n })\n}\n/** A row's fields as written: better-auth's id is the Database's, and `undefined` takes a field out. */\nconst fieldsOf = (data) => Object.fromEntries(Object.entries(data ?? {}).filter(([field]) => field !== \"id\" && field !== \"_id\"))\n\nexport const create = mutation({\n args: { model: v.string(), data: v.any() },\n handler: async (ctx, { model, data }) => {\n server(ctx)\n const id = await ctx.db.insert(table(model), fieldsOf(data))\n return shown(await ctx.db.get(model, id))\n },\n})\nexport const findOne = query({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n return (await found(ctx, table(model), where))[0] ?? null\n },\n})\nexport const findMany = query({\n args: { model: v.string(), where, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.any()) },\n handler: async (ctx, { model, where, limit, offset, sortBy }) => {\n server(ctx)\n const rows = ordered(await found(ctx, table(model), where), sortBy)\n return rows.slice(offset ?? 0, limit === undefined ? undefined : (offset ?? 0) + limit)\n },\n})\nexport const count = query({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n return (await found(ctx, table(model), where)).length\n },\n})\nexport const update = mutation({\n args: { model: v.string(), where, update: v.any() },\n handler: async (ctx, { model, where, update }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n await ctx.db.patch(model, row.id, fieldsOf(update))\n return shown(await ctx.db.get(model, row.id))\n },\n})\nexport const updateMany = mutation({\n args: { model: v.string(), where, update: v.any() },\n handler: async (ctx, { model, where, update }) => {\n server(ctx)\n const rows = await found(ctx, table(model), where)\n await Promise.all(rows.map((row) => ctx.db.patch(model, row.id, fieldsOf(update))))\n return rows.length\n },\n})\nexport const deleteMany = mutation({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n const rows = await found(ctx, table(model), where)\n await Promise.all(rows.map((row) => ctx.db.delete(model, row.id)))\n return rows.length\n },\n})\n/** 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. */\nexport const increment = mutation({\n args: { model: v.string(), where, increment: v.any(), set: v.optional(v.any()) },\n handler: async (ctx, { model, where, increment, set }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n const next = fieldsOf(set)\n for (const [field, delta] of Object.entries(increment ?? {})) next[field] = (row[field] ?? 0) + delta\n await ctx.db.patch(model, row.id, next)\n return shown(await ctx.db.get(model, row.id))\n },\n})\n/** Deletes the first row a where holds and returns it, in one step: a code or a link is used once. */\nexport const consume = mutation({\n args: { model: v.string(), where },\n handler: async (ctx, { model, where }) => {\n server(ctx)\n const row = (await found(ctx, table(model), where))[0]\n if (!row) return null\n await ctx.db.delete(model, row.id)\n return row\n },\n})\n";
|
|
27
|
+
//#endregion
|
|
28
|
+
export { AuthTable, FUNCTIONS_FILE, authTablesOf, schemaLines, tablesFile };
|