@slotform/auth 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/ability/index.d.ts +31 -0
- package/dist/ability/index.d.ts.map +1 -0
- package/dist/ability/index.js +64 -0
- package/dist/ability/index.js.map +1 -0
- package/dist/access.d.ts +19 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +33 -0
- package/dist/access.js.map +1 -0
- package/dist/callback-stubs.d.ts +15 -0
- package/dist/callback-stubs.d.ts.map +1 -0
- package/dist/callback-stubs.js +28 -0
- package/dist/callback-stubs.js.map +1 -0
- package/dist/client.d.ts +38 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +37 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +190 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +451 -0
- package/dist/index.js.map +1 -0
- package/dist/infer.d.ts +31 -0
- package/dist/infer.d.ts.map +1 -0
- package/dist/infer.js +2 -0
- package/dist/infer.js.map +1 -0
- package/dist/schema/devices.d.ts +404 -0
- package/dist/schema/devices.d.ts.map +1 -0
- package/dist/schema/devices.js +45 -0
- package/dist/schema/devices.js.map +1 -0
- package/dist/schema/index.d.ts +679 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +94 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/oauth.d.ts +2062 -0
- package/dist/schema/oauth.d.ts.map +1 -0
- package/dist/schema/oauth.js +245 -0
- package/dist/schema/oauth.js.map +1 -0
- package/dist/schema/organization.d.ts +388 -0
- package/dist/schema/organization.d.ts.map +1 -0
- package/dist/schema/organization.js +75 -0
- package/dist/schema/organization.js.map +1 -0
- package/dist/schema/passkey.d.ts +215 -0
- package/dist/schema/passkey.d.ts.map +1 -0
- package/dist/schema/passkey.js +29 -0
- package/dist/schema/passkey.js.map +1 -0
- package/dist/schema/sets.d.ts +3715 -0
- package/dist/schema/sets.d.ts.map +1 -0
- package/dist/schema/sets.js +48 -0
- package/dist/schema/sets.js.map +1 -0
- package/dist/scope.d.ts +36 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +59 -0
- package/dist/scope.js.map +1 -0
- package/dist/screens-fixtures.d.ts +148 -0
- package/dist/screens-fixtures.d.ts.map +1 -0
- package/dist/screens-fixtures.js +122 -0
- package/dist/screens-fixtures.js.map +1 -0
- package/dist/screens-session.d.ts +4 -0
- package/dist/screens-session.d.ts.map +1 -0
- package/dist/screens-session.js +24 -0
- package/dist/screens-session.js.map +1 -0
- package/dist/screens.d.ts +3 -0
- package/dist/screens.d.ts.map +1 -0
- package/dist/screens.js +8 -0
- package/dist/screens.js.map +1 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +44 -0
- package/dist/serve.js.map +1 -0
- package/dist/types.d.ts +152 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +215 -0
- package/dist/types.js.map +1 -0
- package/dist/worker/callback-url.d.ts +6 -0
- package/dist/worker/callback-url.d.ts.map +1 -0
- package/dist/worker/callback-url.js +57 -0
- package/dist/worker/callback-url.js.map +1 -0
- package/dist/worker/cimd-transport.d.ts +2 -0
- package/dist/worker/cimd-transport.d.ts.map +1 -0
- package/dist/worker/cimd-transport.js +86 -0
- package/dist/worker/cimd-transport.js.map +1 -0
- package/dist/worker/devices.d.ts +6 -0
- package/dist/worker/devices.d.ts.map +1 -0
- package/dist/worker/devices.js +70 -0
- package/dist/worker/devices.js.map +1 -0
- package/dist/worker/email-key.d.ts +2 -0
- package/dist/worker/email-key.d.ts.map +1 -0
- package/dist/worker/email-key.js +20 -0
- package/dist/worker/email-key.js.map +1 -0
- package/dist/worker/index.d.ts +156 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +507 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/listener.d.ts +12 -0
- package/dist/worker/listener.d.ts.map +1 -0
- package/dist/worker/listener.js +37 -0
- package/dist/worker/listener.js.map +1 -0
- package/dist/worker/oauth.d.ts +95 -0
- package/dist/worker/oauth.d.ts.map +1 -0
- package/dist/worker/oauth.js +456 -0
- package/dist/worker/oauth.js.map +1 -0
- package/dist/worker/outputs.d.ts +75 -0
- package/dist/worker/outputs.d.ts.map +1 -0
- package/dist/worker/outputs.js +7 -0
- package/dist/worker/outputs.js.map +1 -0
- package/dist/worker/procedures.d.ts +360 -0
- package/dist/worker/procedures.d.ts.map +1 -0
- package/dist/worker/procedures.js +464 -0
- package/dist/worker/procedures.js.map +1 -0
- package/dist/worker/rate-limit.d.ts +7 -0
- package/dist/worker/rate-limit.d.ts.map +1 -0
- package/dist/worker/rate-limit.js +49 -0
- package/dist/worker/rate-limit.js.map +1 -0
- package/dist/worker/reserved-slugs.d.ts +4 -0
- package/dist/worker/reserved-slugs.d.ts.map +1 -0
- package/dist/worker/reserved-slugs.js +30 -0
- package/dist/worker/reserved-slugs.js.map +1 -0
- package/dist/worker/session-ended.d.ts +6 -0
- package/dist/worker/session-ended.d.ts.map +1 -0
- package/dist/worker/session-ended.js +10 -0
- package/dist/worker/session-ended.js.map +1 -0
- package/dist/worker/sign-up-policy.d.ts +20 -0
- package/dist/worker/sign-up-policy.d.ts.map +1 -0
- package/dist/worker/sign-up-policy.js +65 -0
- package/dist/worker/sign-up-policy.js.map +1 -0
- package/dist/worker/tenancy.d.ts +23 -0
- package/dist/worker/tenancy.d.ts.map +1 -0
- package/dist/worker/tenancy.js +133 -0
- package/dist/worker/tenancy.js.map +1 -0
- package/guide/abilities.md +55 -0
- package/guide/add-a-role.md +33 -0
- package/guide/callbacks.md +97 -0
- package/guide/config.md +84 -0
- package/guide/devices.md +85 -0
- package/guide/mcp-oauth.md +97 -0
- package/guide/organizations.md +114 -0
- package/guide/protect-by-scope.md +29 -0
- package/guide/scopes.md +87 -0
- package/guide/sign-in.md +127 -0
- package/package.json +155 -3
- package/src/ability/index.ts +174 -0
- package/src/access.ts +45 -0
- package/src/callback-stubs.ts +45 -0
- package/src/client.ts +119 -0
- package/src/expo.tsx +275 -0
- package/src/index.ts +574 -0
- package/src/infer.ts +44 -0
- package/src/schema/devices.ts +54 -0
- package/src/schema/index.ts +128 -0
- package/src/schema/oauth.ts +320 -0
- package/src/schema/organization.ts +104 -0
- package/src/schema/passkey.ts +38 -0
- package/src/schema/sets.ts +73 -0
- package/src/scope.ts +135 -0
- package/src/screens-fixtures.ts +149 -0
- package/src/screens-session.ts +26 -0
- package/src/screens.ts +10 -0
- package/src/serve.ts +49 -0
- package/src/types.ts +313 -0
- package/src/worker/callback-url.ts +65 -0
- package/src/worker/cimd-transport.ts +115 -0
- package/src/worker/devices.ts +83 -0
- package/src/worker/email-key.ts +21 -0
- package/src/worker/index.ts +941 -0
- package/src/worker/listener.ts +55 -0
- package/src/worker/oauth.ts +709 -0
- package/src/worker/outputs.ts +102 -0
- package/src/worker/procedures.ts +758 -0
- package/src/worker/rate-limit.ts +64 -0
- package/src/worker/reserved-slugs.ts +39 -0
- package/src/worker/session-ended.ts +14 -0
- package/src/worker/sign-up-policy.ts +88 -0
- package/src/worker/tenancy.ts +229 -0
- package/templates/callbacks.ts +40 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
import type { PluginRuntimeEntry } from "@slotform/api";
|
|
2
|
+
import { api } from "@slotform/api";
|
|
3
|
+
import { RESERVED_SLUGS } from "@slotform/api/lib/slugify";
|
|
4
|
+
import type { ContributionCtx } from "@slotform/cli";
|
|
5
|
+
import { callback, GENERATED_DIR, plugin, slot } from "@slotform/cli";
|
|
6
|
+
import type { TsExpression, TsImportSpec } from "@slotform/cli/ast";
|
|
7
|
+
import { literalToProps } from "@slotform/cli/ast";
|
|
8
|
+
import { cliSlots } from "@slotform/cli/cli-slots";
|
|
9
|
+
import { SlotformError } from "@slotform/cli/errors";
|
|
10
|
+
import { cloudflare } from "@slotform/cloudflare";
|
|
11
|
+
import { db } from "@slotform/db";
|
|
12
|
+
import { screens } from "@slotform/screens";
|
|
13
|
+
import { defaultOrgStatements } from "./access.ts";
|
|
14
|
+
import {
|
|
15
|
+
pendingCallbacks,
|
|
16
|
+
requiredCallbacks,
|
|
17
|
+
stubbedCallbacksMessage,
|
|
18
|
+
} from "./callback-stubs.ts";
|
|
19
|
+
import type { AuthClientOptions, OrganizationAccess } from "./client.ts";
|
|
20
|
+
import { tableSetsOf } from "./schema/sets.ts";
|
|
21
|
+
import {
|
|
22
|
+
AUTH_PREFIX,
|
|
23
|
+
type AuthCallbackPayloads,
|
|
24
|
+
authOptionsSchema,
|
|
25
|
+
OAUTH_DISCOVERY_PREFIXES,
|
|
26
|
+
type ResolvedAuthOptions,
|
|
27
|
+
resolveSocialProviders,
|
|
28
|
+
} from "./types.ts";
|
|
29
|
+
|
|
30
|
+
const SOURCE = "auth";
|
|
31
|
+
|
|
32
|
+
// Canonical path of the callback file: docs/architecture/plugins/auth.md, "Callbacks".
|
|
33
|
+
const CALLBACK_FILE = "src/worker/plugins/auth.ts";
|
|
34
|
+
|
|
35
|
+
// The scope descriptors file: docs/architecture/plugins/auth.md, "Scopes".
|
|
36
|
+
const SCOPES_FILE = "src/shared/scopes.ts";
|
|
37
|
+
const SCOPES_IDENTIFIER = "scopes";
|
|
38
|
+
|
|
39
|
+
// The statements of the consumer's `ac`. `ac` and `roles` are `unknown` in the
|
|
40
|
+
// options schema (an `ac` is a function-bearing object no schema can hold).
|
|
41
|
+
function statementsOf(
|
|
42
|
+
org: ResolvedAuthOptions["organization"],
|
|
43
|
+
): Record<string, readonly string[]> | undefined {
|
|
44
|
+
if (typeof org !== "object") return undefined;
|
|
45
|
+
return (
|
|
46
|
+
org.ac as { statements?: Record<string, readonly string[]> } | undefined
|
|
47
|
+
)?.statements;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Access control as generated code holds it: docs/architecture/plugins/auth.md, "Access control".
|
|
51
|
+
function organizationAccess(
|
|
52
|
+
org: ResolvedAuthOptions["organization"],
|
|
53
|
+
): OrganizationAccess | boolean {
|
|
54
|
+
if (typeof org !== "object") return Boolean(org);
|
|
55
|
+
const statements = statementsOf(org);
|
|
56
|
+
return {
|
|
57
|
+
...(statements ? { statements } : {}),
|
|
58
|
+
...(org.roles
|
|
59
|
+
? {
|
|
60
|
+
roles: org.roles as Record<string, Record<string, readonly string[]>>,
|
|
61
|
+
}
|
|
62
|
+
: {}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function wiresScopes(
|
|
67
|
+
ctx: { fileExists(path: string): Promise<boolean> },
|
|
68
|
+
options: ResolvedAuthOptions,
|
|
69
|
+
): Promise<boolean> {
|
|
70
|
+
return Boolean(options.organization) && (await ctx.fileExists(SCOPES_FILE));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── Slot declarations ──────────────────────────────────────────────
|
|
74
|
+
//
|
|
75
|
+
// `runtimeOptions` is a derived slot: docs/architecture/plugins/auth.md, "Runtime options".
|
|
76
|
+
|
|
77
|
+
// Addresses an organization's slug may not take: docs/architecture/plugins/auth.md, "Reserved slugs".
|
|
78
|
+
const reservedSlugs = slot.list<string>({
|
|
79
|
+
source: SOURCE,
|
|
80
|
+
name: "reservedSlugs",
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const runtimeOptions = slot.derived({
|
|
84
|
+
source: SOURCE,
|
|
85
|
+
name: "runtimeOptions",
|
|
86
|
+
inputs: {
|
|
87
|
+
cors: api.slots.cors,
|
|
88
|
+
devCors: api.slots.devCorsOrigins,
|
|
89
|
+
devTargets: api.slots.devTargetOrigins,
|
|
90
|
+
reserved: reservedSlugs,
|
|
91
|
+
nativeScheme: api.slots.nativeScheme,
|
|
92
|
+
},
|
|
93
|
+
compute: async (
|
|
94
|
+
inp,
|
|
95
|
+
ctx: ContributionCtx<ResolvedAuthOptions>,
|
|
96
|
+
): Promise<Record<string, TsExpression>> => {
|
|
97
|
+
// An empty origin list refuses generation: docs/architecture/plugins/auth.md, "Origins and cookies".
|
|
98
|
+
if (inp.cors.length === 0) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
"auth: cannot generate runtime — no trusted origins are available. " +
|
|
101
|
+
"Better Auth requires at least one trusted origin for CSRF protection. " +
|
|
102
|
+
"Fix by one of:\n" +
|
|
103
|
+
" • set `app.domain` in slotform.config.ts (derives https://<domain> + https://app.<domain>)\n" +
|
|
104
|
+
" • set `app.origins: [...]` to supply the allow-list explicitly",
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Seed the runtime options with the consumer's options: docs/architecture/plugins/auth.md, "Plugin shape".
|
|
109
|
+
// `ctx.options` is the plugin's typed options, spread here as a record.
|
|
110
|
+
const rawOptions = { ...(ctx.options as Record<string, unknown>) };
|
|
111
|
+
delete rawOptions.callbacks;
|
|
112
|
+
// Only binding names are baked: docs/architecture/plugins/auth.md, "Rate limiting".
|
|
113
|
+
rawOptions.rateLimiter = {
|
|
114
|
+
ip: { binding: ctx.options.rateLimiter.ip.binding },
|
|
115
|
+
email: { binding: ctx.options.rateLimiter.email.binding },
|
|
116
|
+
...(ctx.options.mcp
|
|
117
|
+
? { agent: { binding: ctx.options.rateLimiter.agent.binding } }
|
|
118
|
+
: {}),
|
|
119
|
+
};
|
|
120
|
+
// Baked only when on, so the runtime's context types the `oauth`
|
|
121
|
+
// capability from the literal.
|
|
122
|
+
if (!ctx.options.mcp) delete rawOptions.mcp;
|
|
123
|
+
// Bake provider env-var references, never the raw input: docs/architecture/plugins/auth.md, "Social providers".
|
|
124
|
+
const resolvedProviders = resolveSocialProviders(
|
|
125
|
+
ctx.options.socialProviders,
|
|
126
|
+
);
|
|
127
|
+
if (Object.keys(resolvedProviders).length > 0) {
|
|
128
|
+
rawOptions.socialProviders = resolvedProviders;
|
|
129
|
+
} else {
|
|
130
|
+
delete rawOptions.socialProviders;
|
|
131
|
+
}
|
|
132
|
+
// Baked only when on, as `mcp` is.
|
|
133
|
+
if (!ctx.options.devices) delete rawOptions.devices;
|
|
134
|
+
const expoEnabled = Boolean(ctx.options.expo);
|
|
135
|
+
// The runtime reads a flag; the scheme is baked into `trustedOrigins`.
|
|
136
|
+
if (expoEnabled) rawOptions.expo = true;
|
|
137
|
+
else delete rawOptions.expo;
|
|
138
|
+
const scheme =
|
|
139
|
+
typeof ctx.options.expo === "object"
|
|
140
|
+
? ctx.options.expo.scheme
|
|
141
|
+
: inp.nativeScheme;
|
|
142
|
+
|
|
143
|
+
// Passkey defaults are baked: docs/architecture/plugins/auth.md, "Passkeys".
|
|
144
|
+
const devOrigins = [...inp.devCors, ...inp.devTargets];
|
|
145
|
+
const passkey = ctx.options.passkey;
|
|
146
|
+
if (passkey) {
|
|
147
|
+
rawOptions.passkey = {
|
|
148
|
+
rpID: passkey.rpID ?? ctx.app.domain,
|
|
149
|
+
rpName: passkey.rpName ?? ctx.app.name,
|
|
150
|
+
origin: passkey.origin ?? inp.cors,
|
|
151
|
+
...(devOrigins.length > 0 ? { devOrigin: devOrigins } : {}),
|
|
152
|
+
...(passkey.authenticatorSelection
|
|
153
|
+
? { authenticatorSelection: passkey.authenticatorSelection }
|
|
154
|
+
: {}),
|
|
155
|
+
};
|
|
156
|
+
} else {
|
|
157
|
+
delete rawOptions.passkey;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (typeof ctx.options.organization === "object") {
|
|
161
|
+
rawOptions.organization = organizationAccess(ctx.options.organization);
|
|
162
|
+
}
|
|
163
|
+
// The slugs the runtime refuses on organization create and update.
|
|
164
|
+
if (ctx.options.organization) {
|
|
165
|
+
rawOptions.reservedSlugs = [
|
|
166
|
+
...new Set([...RESERVED_SLUGS, ...inp.reserved]),
|
|
167
|
+
].sort();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const props = literalToProps(rawOptions);
|
|
171
|
+
|
|
172
|
+
// `trustedOrigins`: docs/architecture/plugins/auth.md, "Origins and cookies".
|
|
173
|
+
const trustedOrigins = [...inp.cors];
|
|
174
|
+
if (expoEnabled) {
|
|
175
|
+
if (scheme === null) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
"auth: `expo: true` trusts the native app's deep-link scheme, and no plugin contributes one. Add `expo()` to slotform.config.ts, or name the phone's scheme: `expo: { scheme }`.",
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
trustedOrigins.push(`${scheme}://`, `${scheme}://*`);
|
|
181
|
+
}
|
|
182
|
+
props.trustedOrigins = {
|
|
183
|
+
kind: "array",
|
|
184
|
+
items: trustedOrigins.map((o) => ({ kind: "string", value: o })),
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// Dev-server origins: docs/architecture/plugins/auth.md, "Origins and cookies".
|
|
188
|
+
if (devOrigins.length > 0) {
|
|
189
|
+
props.devTrustedOrigins = {
|
|
190
|
+
kind: "array",
|
|
191
|
+
items: devOrigins.map((o) => ({ kind: "string", value: o })),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// `sameSite` for native and dev: docs/architecture/plugins/auth.md, "Origins and cookies".
|
|
196
|
+
if (expoEnabled) {
|
|
197
|
+
props.sameSite = { kind: "string", value: "none" };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Paired with the namespace import contributed to
|
|
201
|
+
// `api.slots.workerImports` below.
|
|
202
|
+
if (await wiresScopes(ctx, ctx.options)) {
|
|
203
|
+
props.scopes = { kind: "identifier", name: SCOPES_IDENTIFIER };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return props;
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// `APP_URL`'s devDefault: docs/architecture/plugins/auth.md, "APP_URL default".
|
|
211
|
+
const appUrlDevDefault = slot.derived({
|
|
212
|
+
source: SOURCE,
|
|
213
|
+
name: "appUrlDevDefault",
|
|
214
|
+
inputs: {
|
|
215
|
+
devCors: api.slots.devCorsOrigins,
|
|
216
|
+
devTargets: api.slots.devTargetOrigins,
|
|
217
|
+
},
|
|
218
|
+
compute: (inp, ctx): string =>
|
|
219
|
+
inp.devCors[0] ?? inp.devTargets[0] ?? `https://${ctx.app.domain}`,
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// The callback file location: docs/architecture/plugins/auth.md, "Callbacks".
|
|
223
|
+
const callbackFile = slot.value<string>({
|
|
224
|
+
source: SOURCE,
|
|
225
|
+
name: "callbackFile",
|
|
226
|
+
seed: () => CALLBACK_FILE,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
// The resolved session-cookie prefix: docs/architecture/plugins/auth.md, "Cookie prefix".
|
|
230
|
+
const cookiePrefix = slot.value<string, ResolvedAuthOptions>({
|
|
231
|
+
source: SOURCE,
|
|
232
|
+
name: "cookiePrefix",
|
|
233
|
+
seed: (ctx) => ctx.options.cookies?.prefix ?? "better-auth",
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// The web client's flags: docs/architecture/plugins/auth.md, "Web client".
|
|
237
|
+
export type AuthClientFlags = Required<Omit<AuthClientOptions, "baseURL">>;
|
|
238
|
+
|
|
239
|
+
const clientFlags = slot.value<AuthClientFlags | null>({
|
|
240
|
+
source: SOURCE,
|
|
241
|
+
name: "clientFlags",
|
|
242
|
+
seed: () => null,
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
export const auth = plugin("auth", {
|
|
246
|
+
label: "Auth",
|
|
247
|
+
|
|
248
|
+
schema: authOptionsSchema,
|
|
249
|
+
|
|
250
|
+
requires: ["api", "db"],
|
|
251
|
+
|
|
252
|
+
// Callback payload shapes: docs/architecture/plugins/auth.md, "Callbacks".
|
|
253
|
+
callbacks: {
|
|
254
|
+
// Required only while `emailOtp` is on; the runtime refuses to build
|
|
255
|
+
// better-auth without it then.
|
|
256
|
+
sendOTP: callback.optional<AuthCallbackPayloads["sendOTP"]>(),
|
|
257
|
+
// Required only while `magicLink` is on, as `sendOTP` is for `emailOtp`.
|
|
258
|
+
sendMagicLink: callback.optional<AuthCallbackPayloads["sendMagicLink"]>(),
|
|
259
|
+
sendInvitation: callback.optional<AuthCallbackPayloads["sendInvitation"]>(),
|
|
260
|
+
beforeDelete: callback.optional<AuthCallbackPayloads["beforeDelete"]>(),
|
|
261
|
+
sendDeleteVerification:
|
|
262
|
+
callback.optional<AuthCallbackPayloads["sendDeleteVerification"]>(),
|
|
263
|
+
// Read synchronously by better-auth, and `undefined` means "use the
|
|
264
|
+
// default generator for this request", so the return type is declared
|
|
265
|
+
// rather than left at the framework's awaited default.
|
|
266
|
+
generateOTP: callback.optional<
|
|
267
|
+
AuthCallbackPayloads["generateOTP"],
|
|
268
|
+
string | undefined
|
|
269
|
+
>(),
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
guide: [
|
|
273
|
+
{
|
|
274
|
+
page: "config",
|
|
275
|
+
trigger:
|
|
276
|
+
"Configuring auth: `auth()` options, its env vars, or the auth tables `src/schema/index.ts` re-exports",
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
page: "callbacks",
|
|
280
|
+
trigger:
|
|
281
|
+
"Writing `src/worker/plugins/auth.ts`: sending codes, magic links or invitations, account deletion, or a sign-in flow of your own",
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
page: "sign-in",
|
|
285
|
+
trigger:
|
|
286
|
+
"Adding OAuth, passkeys or magic links, or calling auth from the web or native client",
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
page: "mcp-oauth",
|
|
290
|
+
trigger:
|
|
291
|
+
"Letting an MCP client connect (`mcp: true`), verifying its access token, or listing and revoking the clients a member connected",
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
page: "devices",
|
|
295
|
+
trigger:
|
|
296
|
+
"Letting a machine with no browser (an agent daemon, a sync client) call the API, `/ws` or a service route as a member (`devices: true`)",
|
|
297
|
+
},
|
|
298
|
+
{
|
|
299
|
+
page: "organizations",
|
|
300
|
+
trigger:
|
|
301
|
+
"Working with organizations, members, invitations, roles or organization slugs",
|
|
302
|
+
},
|
|
303
|
+
{
|
|
304
|
+
page: "scopes",
|
|
305
|
+
trigger:
|
|
306
|
+
"Declaring a tenancy tier below the organization (`defineScope`)",
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
page: "abilities",
|
|
310
|
+
trigger:
|
|
311
|
+
"Gating access by a record's own data (an owner column, a per-record role)",
|
|
312
|
+
},
|
|
313
|
+
{ page: "add-a-role", trigger: "Adding a role or a permission" },
|
|
314
|
+
{
|
|
315
|
+
page: "protect-by-scope",
|
|
316
|
+
trigger:
|
|
317
|
+
"Restricting a procedure to the members of an organization or a scope",
|
|
318
|
+
},
|
|
319
|
+
],
|
|
320
|
+
|
|
321
|
+
slots: {
|
|
322
|
+
runtimeOptions,
|
|
323
|
+
appUrlDevDefault,
|
|
324
|
+
callbackFile,
|
|
325
|
+
cookiePrefix,
|
|
326
|
+
clientFlags,
|
|
327
|
+
reservedSlugs,
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
contributes: (self) => [
|
|
331
|
+
cliSlots.initPrompts.contribute((ctx) => {
|
|
332
|
+
const cookiePrefixDefault = ctx.app.name;
|
|
333
|
+
return {
|
|
334
|
+
plugin: "auth",
|
|
335
|
+
ask: async (rawCtx) => {
|
|
336
|
+
// ContributionCtx carries `prompt` in its CLI shape (the ask
|
|
337
|
+
// function is invoked by command code with the real ctx). We
|
|
338
|
+
// cast narrowly to read prompt without widening the public
|
|
339
|
+
// PromptSpec surface.
|
|
340
|
+
const c = rawCtx as {
|
|
341
|
+
prompt: {
|
|
342
|
+
text: (
|
|
343
|
+
msg: string,
|
|
344
|
+
opts?: { default?: string },
|
|
345
|
+
) => Promise<string>;
|
|
346
|
+
confirm: (msg: string) => Promise<boolean>;
|
|
347
|
+
};
|
|
348
|
+
};
|
|
349
|
+
const prefix = await c.prompt.text("Cookie prefix:", {
|
|
350
|
+
default: cookiePrefixDefault,
|
|
351
|
+
});
|
|
352
|
+
const organization = await c.prompt.confirm("Include organizations?");
|
|
353
|
+
return {
|
|
354
|
+
cookies: { prefix },
|
|
355
|
+
organization,
|
|
356
|
+
};
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}),
|
|
360
|
+
|
|
361
|
+
// `nodejs_compat` flag: docs/architecture/plugins/auth.md, "Slot contributions".
|
|
362
|
+
cloudflare.slots.compatibilityFlags.contribute(() => "nodejs_compat"),
|
|
363
|
+
|
|
364
|
+
cloudflare.slots.bindings.contribute(() => [
|
|
365
|
+
{
|
|
366
|
+
kind: "rate_limiter" as const,
|
|
367
|
+
binding: self.options.rateLimiter.ip.binding,
|
|
368
|
+
simple: {
|
|
369
|
+
limit: self.options.rateLimiter.ip.limit,
|
|
370
|
+
period: self.options.rateLimiter.ip.period,
|
|
371
|
+
},
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
kind: "rate_limiter" as const,
|
|
375
|
+
binding: self.options.rateLimiter.email.binding,
|
|
376
|
+
simple: {
|
|
377
|
+
limit: self.options.rateLimiter.email.limit,
|
|
378
|
+
period: self.options.rateLimiter.email.period,
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
// One bucket per agent grant, bound only while agents connect.
|
|
382
|
+
...(self.options.mcp
|
|
383
|
+
? [
|
|
384
|
+
{
|
|
385
|
+
kind: "rate_limiter" as const,
|
|
386
|
+
binding: self.options.rateLimiter.agent.binding,
|
|
387
|
+
simple: {
|
|
388
|
+
limit: self.options.rateLimiter.agent.limit,
|
|
389
|
+
period: self.options.rateLimiter.agent.period,
|
|
390
|
+
},
|
|
391
|
+
},
|
|
392
|
+
]
|
|
393
|
+
: []),
|
|
394
|
+
]),
|
|
395
|
+
|
|
396
|
+
api.slots.env.contribute(async (ctx) => {
|
|
397
|
+
const devAppUrl = await ctx.resolve(self.slots.appUrlDevDefault);
|
|
398
|
+
// One client-id + client-secret entry per enabled OAuth provider, so
|
|
399
|
+
// the generated `.dev.vars` template prompts for real credentials.
|
|
400
|
+
const providerSecrets = Object.values(
|
|
401
|
+
resolveSocialProviders(self.options.socialProviders),
|
|
402
|
+
)
|
|
403
|
+
.filter((p): p is NonNullable<typeof p> => p !== undefined)
|
|
404
|
+
.flatMap((p) => [
|
|
405
|
+
{ name: p.clientIdVar, devDefault: "dev-oauth-client-id" },
|
|
406
|
+
{ name: p.clientSecretVar, devDefault: "dev-oauth-client-secret" },
|
|
407
|
+
]);
|
|
408
|
+
return [
|
|
409
|
+
{
|
|
410
|
+
// Dev default satisfies its own minLength so a fresh project
|
|
411
|
+
// serves out of the box; better-auth warns below 32 chars.
|
|
412
|
+
name: self.options.secretVar,
|
|
413
|
+
devDefault: "dev-secret-change-me-32-chars-minimum",
|
|
414
|
+
validate: { minLength: 32 },
|
|
415
|
+
},
|
|
416
|
+
{
|
|
417
|
+
name: self.options.appUrlVar,
|
|
418
|
+
devDefault: devAppUrl,
|
|
419
|
+
// `devLocalhost`: a non-local APP_URL while SLOTFORM_DEV is set
|
|
420
|
+
// means dev settings leaked into a deploy — refuse to serve.
|
|
421
|
+
validate: { url: true, devLocalhost: true },
|
|
422
|
+
},
|
|
423
|
+
...providerSecrets,
|
|
424
|
+
];
|
|
425
|
+
}),
|
|
426
|
+
|
|
427
|
+
// Route prefixes: docs/architecture/plugins/auth.md, "Slot contributions".
|
|
428
|
+
api.slots.routePrefixes.contribute(() =>
|
|
429
|
+
self.options.mcp
|
|
430
|
+
? [AUTH_PREFIX, ...OAUTH_DISCOVERY_PREFIXES]
|
|
431
|
+
: AUTH_PREFIX,
|
|
432
|
+
),
|
|
433
|
+
|
|
434
|
+
// `slotform screens serve` env: docs/architecture/plugins/auth.md, "Screens".
|
|
435
|
+
screens.slots.serveEnv.contribute(() => ({ url }) => ({
|
|
436
|
+
[self.options.appUrlVar]: url,
|
|
437
|
+
...(self.options.emailOtp === false
|
|
438
|
+
? {}
|
|
439
|
+
: {
|
|
440
|
+
SLOTFORM_SERVE_EMAIL: "fixture@example.com",
|
|
441
|
+
SLOTFORM_SERVE_CODE: "000000",
|
|
442
|
+
}),
|
|
443
|
+
})),
|
|
444
|
+
|
|
445
|
+
// The `/fixture/link` control of the served worker, which signs in with
|
|
446
|
+
// the email code above.
|
|
447
|
+
screens.slots.serveControls.contribute(() =>
|
|
448
|
+
self.options.emailOtp === false ? undefined : "@slotform/auth/serve",
|
|
449
|
+
),
|
|
450
|
+
|
|
451
|
+
// Workbench session handlers: docs/architecture/plugins/auth.md, "Screens".
|
|
452
|
+
screens.slots.handlerModules.contribute(() => "@slotform/auth/screens"),
|
|
453
|
+
screens.slots.fixtureModules.contribute(
|
|
454
|
+
() => "@slotform/auth/screens-fixtures",
|
|
455
|
+
),
|
|
456
|
+
|
|
457
|
+
// The server has auth: a client app of this server reads it from the
|
|
458
|
+
// manifest api writes.
|
|
459
|
+
api.slots.serverAuth.contribute(() => true),
|
|
460
|
+
|
|
461
|
+
// The MCP endpoint (api's `src/worker/mcp.ts`) authenticates through
|
|
462
|
+
// this provider, and answers at `/mcp`: no organization may take it.
|
|
463
|
+
api.slots.mcpAuth.contribute(() => (self.options.mcp ? true : undefined)),
|
|
464
|
+
self.slots.reservedSlugs.contribute(() =>
|
|
465
|
+
self.options.mcp ? "mcp" : undefined,
|
|
466
|
+
),
|
|
467
|
+
|
|
468
|
+
// The extension stays, as on the callbacks import: the node target runs
|
|
469
|
+
// the generated worker as written.
|
|
470
|
+
api.slots.workerImports.contribute(
|
|
471
|
+
async (ctx): Promise<TsImportSpec | undefined> =>
|
|
472
|
+
(await wiresScopes(ctx, self.options))
|
|
473
|
+
? { source: `../${SCOPES_FILE}`, namespace: SCOPES_IDENTIFIER }
|
|
474
|
+
: undefined,
|
|
475
|
+
),
|
|
476
|
+
|
|
477
|
+
self.slots.clientFlags.contribute(() => ({
|
|
478
|
+
passkey: self.options.passkey !== false,
|
|
479
|
+
emailOtp: self.options.emailOtp,
|
|
480
|
+
magicLink: self.options.magicLink,
|
|
481
|
+
organization: organizationAccess(self.options.organization),
|
|
482
|
+
mcp: self.options.mcp,
|
|
483
|
+
})),
|
|
484
|
+
|
|
485
|
+
// Worker runtime entry: docs/architecture/plugins/auth.md, "Runtime options".
|
|
486
|
+
api.slots.pluginRuntimes.contribute(
|
|
487
|
+
async (ctx): Promise<PluginRuntimeEntry> => {
|
|
488
|
+
const options = await ctx.resolve(self.slots.runtimeOptions);
|
|
489
|
+
return {
|
|
490
|
+
plugin: "auth",
|
|
491
|
+
import: {
|
|
492
|
+
source: "@slotform/auth/runtime",
|
|
493
|
+
default: "authRuntime",
|
|
494
|
+
},
|
|
495
|
+
identifier: "authRuntime",
|
|
496
|
+
options,
|
|
497
|
+
};
|
|
498
|
+
},
|
|
499
|
+
),
|
|
500
|
+
|
|
501
|
+
// Callback file wiring: docs/architecture/plugins/auth.md, "Callbacks".
|
|
502
|
+
api.slots.callbacks.contribute(async (ctx) => {
|
|
503
|
+
const path = await ctx.resolve(self.slots.callbackFile);
|
|
504
|
+
const exists = await ctx.fileExists(path);
|
|
505
|
+
if (!exists) {
|
|
506
|
+
// With no callback required, no file is wired.
|
|
507
|
+
const required = requiredCallbacks(self.options);
|
|
508
|
+
if (required.length === 0) return undefined;
|
|
509
|
+
const needs = required.map((name) => `\`${name}\``).join(" and ");
|
|
510
|
+
throw new Error(
|
|
511
|
+
`auth: callback file \`${path}\` is missing. ` +
|
|
512
|
+
`The consumer implements ${needs} there. ` +
|
|
513
|
+
"Run `slotform init` / `slotform add auth` to scaffold the file, " +
|
|
514
|
+
"or turn the sign-in that needs it off.",
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
// The callback file stays under `src/`: docs/architecture/plugins/auth.md, "Callbacks".
|
|
518
|
+
if (!path.startsWith("src/")) {
|
|
519
|
+
throw new Error(
|
|
520
|
+
`auth: \`auth.slots.callbackFile\` must live under \`src/\` ` +
|
|
521
|
+
`(got \`${path}\`). The generated worker imports callbacks relative ` +
|
|
522
|
+
`to \`${GENERATED_DIR}/worker.ts\` and cannot reach paths outside \`src/\`.`,
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
// The extension stays: the Node target runs the generated worker as
|
|
526
|
+
// written, and ESM resolves no extensionless path.
|
|
527
|
+
const importSource = `../${path}`;
|
|
528
|
+
return {
|
|
529
|
+
auth: {
|
|
530
|
+
import: {
|
|
531
|
+
source: importSource,
|
|
532
|
+
default: "authCallbacks",
|
|
533
|
+
},
|
|
534
|
+
identifier: "authCallbacks",
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
}),
|
|
538
|
+
|
|
539
|
+
// Pre-deploy guard: docs/architecture/plugins/auth.md, "Callbacks".
|
|
540
|
+
cliSlots.deployChecks.contribute(async (ctx) => {
|
|
541
|
+
const path = await ctx.resolve(self.slots.callbackFile);
|
|
542
|
+
if (!(await ctx.fileExists(path))) return undefined;
|
|
543
|
+
const pending = pendingCallbacks(
|
|
544
|
+
await ctx.readFile(path),
|
|
545
|
+
requiredCallbacks(self.options),
|
|
546
|
+
);
|
|
547
|
+
if (pending.length === 0) return undefined;
|
|
548
|
+
throw new SlotformError(
|
|
549
|
+
stubbedCallbacksMessage(path, pending),
|
|
550
|
+
"AUTH_CALLBACK_STUB",
|
|
551
|
+
);
|
|
552
|
+
}),
|
|
553
|
+
|
|
554
|
+
// RBAC statements: docs/architecture/slot-catalog.md, "`api.slots.*` (the `api` plugin)".
|
|
555
|
+
api.slots.rbacStatements.contribute(() => {
|
|
556
|
+
const org = self.options.organization;
|
|
557
|
+
if (!org) return undefined;
|
|
558
|
+
return statementsOf(org) ?? defaultOrgStatements;
|
|
559
|
+
}),
|
|
560
|
+
|
|
561
|
+
// Entity vocabulary handoff: docs/architecture/plugins/db.md, "Entity vocabulary".
|
|
562
|
+
api.slots.entities.contribute(() =>
|
|
563
|
+
tableSetsOf(self.options).flatMap((set) => Object.keys(set.tables)),
|
|
564
|
+
),
|
|
565
|
+
|
|
566
|
+
// The scaffolded schema re-exports auth's tables, so they migrate with
|
|
567
|
+
// the app's own.
|
|
568
|
+
db.slots.schemaModules.contribute(() =>
|
|
569
|
+
tableSetsOf(self.options).map((set) => set.module),
|
|
570
|
+
),
|
|
571
|
+
],
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
export type { AuthOptions } from "./types.ts";
|
package/src/infer.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PluginConfig } from "@slotform/cli";
|
|
2
|
+
|
|
3
|
+
// The user as the session carries it: better-auth's base user, the same for
|
|
4
|
+
// every configuration.
|
|
5
|
+
export type SessionUser = {
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
email: string;
|
|
9
|
+
emailVerified: boolean;
|
|
10
|
+
image: string | null;
|
|
11
|
+
createdAt: Date;
|
|
12
|
+
updatedAt: Date;
|
|
13
|
+
// Set only on a call an agent makes through an OAuth grant at `/mcp`.
|
|
14
|
+
agent?: true;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type BaseSession = {
|
|
18
|
+
id: string;
|
|
19
|
+
userId: string;
|
|
20
|
+
expiresAt: Date;
|
|
21
|
+
ipAddress: string | null;
|
|
22
|
+
userAgent: string | null;
|
|
23
|
+
createdAt: Date;
|
|
24
|
+
updatedAt: Date;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
type OrgSessionFields<TOptions> = TOptions extends { organization: infer O }
|
|
28
|
+
? O extends undefined | false
|
|
29
|
+
? Record<never, never>
|
|
30
|
+
: { activeOrganizationId: string | null }
|
|
31
|
+
: Record<never, never>;
|
|
32
|
+
|
|
33
|
+
// The session for auth configured with `TOptions` as written, so
|
|
34
|
+
// `organization: true` is the literal, not the resolved options' union.
|
|
35
|
+
export type SessionOf<TOptions> = BaseSession & OrgSessionFields<TOptions>;
|
|
36
|
+
|
|
37
|
+
// The session for a `defineConfig` result: the auth entry's literal input.
|
|
38
|
+
export type InferSession<TConfig extends { plugins: readonly PluginConfig[] }> =
|
|
39
|
+
Extract<
|
|
40
|
+
TConfig["plugins"][number],
|
|
41
|
+
PluginConfig<"auth">
|
|
42
|
+
> extends PluginConfig<"auth", unknown, infer TInput>
|
|
43
|
+
? SessionOf<TInput>
|
|
44
|
+
: never;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The device credentials' table (`apikey`), as a Drizzle SQLite table.
|
|
2
|
+
// Schema tables: docs/architecture/plugins/auth.md, "Schema tables".
|
|
3
|
+
|
|
4
|
+
// Drizzle types the emitted declarations spell, named through `@slotform/db`: docs/architecture/plugins/db.md, "Type resolution".
|
|
5
|
+
// biome-ignore lint/correctness/noUnusedImports: read by the declaration emit
|
|
6
|
+
import type { One, Relations, SQLiteTableWithColumns } from "@slotform/db/orm";
|
|
7
|
+
import { index, integer, relations, sqliteTable, text } from "@slotform/db/orm";
|
|
8
|
+
import { user } from "./index.ts";
|
|
9
|
+
|
|
10
|
+
export const apikey = sqliteTable(
|
|
11
|
+
"apikey",
|
|
12
|
+
{
|
|
13
|
+
id: text("id").primaryKey(),
|
|
14
|
+
configId: text("config_id").default("default").notNull(),
|
|
15
|
+
name: text("name"),
|
|
16
|
+
// The first characters of the key, kept so a list can tell keys apart.
|
|
17
|
+
start: text("start"),
|
|
18
|
+
referenceId: text("reference_id")
|
|
19
|
+
.notNull()
|
|
20
|
+
.references(() => user.id, { onDelete: "cascade" }),
|
|
21
|
+
prefix: text("prefix"),
|
|
22
|
+
// The key's SHA-256, never the key.
|
|
23
|
+
key: text("key").notNull(),
|
|
24
|
+
refillInterval: integer("refill_interval"),
|
|
25
|
+
refillAmount: integer("refill_amount"),
|
|
26
|
+
lastRefillAt: integer("last_refill_at", { mode: "timestamp_ms" }),
|
|
27
|
+
enabled: integer("enabled", { mode: "boolean" }).default(true),
|
|
28
|
+
rateLimitEnabled: integer("rate_limit_enabled", {
|
|
29
|
+
mode: "boolean",
|
|
30
|
+
}).default(true),
|
|
31
|
+
rateLimitTimeWindow: integer("rate_limit_time_window"),
|
|
32
|
+
rateLimitMax: integer("rate_limit_max"),
|
|
33
|
+
requestCount: integer("request_count").default(0),
|
|
34
|
+
remaining: integer("remaining"),
|
|
35
|
+
lastRequest: integer("last_request", { mode: "timestamp_ms" }),
|
|
36
|
+
expiresAt: integer("expires_at", { mode: "timestamp_ms" }),
|
|
37
|
+
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
|
|
38
|
+
updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
|
|
39
|
+
permissions: text("permissions"),
|
|
40
|
+
metadata: text("metadata"),
|
|
41
|
+
},
|
|
42
|
+
(table) => [
|
|
43
|
+
index("apikey_configId_idx").on(table.configId),
|
|
44
|
+
index("apikey_referenceId_idx").on(table.referenceId),
|
|
45
|
+
index("apikey_key_idx").on(table.key),
|
|
46
|
+
],
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
export const apikeyRelations = relations(apikey, ({ one }) => ({
|
|
50
|
+
user: one(user, {
|
|
51
|
+
fields: [apikey.referenceId],
|
|
52
|
+
references: [user.id],
|
|
53
|
+
}),
|
|
54
|
+
}));
|