@slotform/auth 0.0.0-stage → 0.1.1
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 +945 -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
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { RateLimitBinding } from "@slotform/api/procedure";
|
|
2
|
+
import { CLIENT_IP_HEADER } from "../types.ts";
|
|
3
|
+
import { emailKey } from "./email-key.ts";
|
|
4
|
+
import { tooManyRequests } from "./oauth.ts";
|
|
5
|
+
|
|
6
|
+
// The limiters the runtime finds bound: docs/architecture/plugins/auth.md, "Rate limiting".
|
|
7
|
+
// A type alias, so a consumer's declaration emit writes it out where it
|
|
8
|
+
// cannot name it.
|
|
9
|
+
export type AuthRateLimiter = {
|
|
10
|
+
ip?: RateLimitBinding;
|
|
11
|
+
email?: RateLimitBinding;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// The sends are the email-bombing amplifiers — the only auth routes that get
|
|
15
|
+
// a per-email limit on top of the blanket per-IP one. Both share the email's
|
|
16
|
+
// bucket. The magic-link verify is a GET with no body: per-IP only.
|
|
17
|
+
const EMAIL_SEND_SUFFIXES = [
|
|
18
|
+
"/email-otp/send-verification-otp",
|
|
19
|
+
"/sign-in/magic-link",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
// Reads `email` off a cloned request body — the original must still reach
|
|
23
|
+
// Better Auth unconsumed. A body that fails to parse, or carries no
|
|
24
|
+
// non-empty string `email`, isn't an error here: the per-email check is
|
|
25
|
+
// simply skipped (the per-IP limit still applies).
|
|
26
|
+
async function readRequestEmail(request: Request): Promise<string | null> {
|
|
27
|
+
try {
|
|
28
|
+
const body: unknown = await request.clone().json();
|
|
29
|
+
if (body && typeof body === "object" && "email" in body) {
|
|
30
|
+
const email = body.email;
|
|
31
|
+
if (typeof email === "string" && email.length > 0) return email;
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
// not JSON / no body — skip the per-email check
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function checkRateLimit(
|
|
40
|
+
request: Request,
|
|
41
|
+
url: URL,
|
|
42
|
+
rateLimiter: AuthRateLimiter | undefined,
|
|
43
|
+
): Promise<Response | null> {
|
|
44
|
+
if (!rateLimiter) return null;
|
|
45
|
+
|
|
46
|
+
if (rateLimiter.ip) {
|
|
47
|
+
const ip = request.headers.get(CLIENT_IP_HEADER) ?? "unknown";
|
|
48
|
+
const result = await rateLimiter.ip.limit({ key: ip });
|
|
49
|
+
if (!result.success) return tooManyRequests();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (
|
|
53
|
+
rateLimiter.email &&
|
|
54
|
+
EMAIL_SEND_SUFFIXES.some((suffix) => url.pathname.endsWith(suffix))
|
|
55
|
+
) {
|
|
56
|
+
const email = await readRequestEmail(request);
|
|
57
|
+
if (email) {
|
|
58
|
+
const result = await rateLimiter.email.limit({ key: emailKey(email) });
|
|
59
|
+
if (!result.success) return tooManyRequests();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
2
|
+
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
3
|
+
|
|
4
|
+
// Code and field error of a reserved organization slug: docs/architecture/plugins/auth.md, "Reserved slugs".
|
|
5
|
+
const ORGANIZATION_SLUG_RESERVED = "ORGANIZATION_SLUG_RESERVED";
|
|
6
|
+
|
|
7
|
+
export function refuseReservedSlug(
|
|
8
|
+
reserved: ReadonlySet<string>,
|
|
9
|
+
slug: unknown,
|
|
10
|
+
): void {
|
|
11
|
+
if (typeof slug !== "string" || !reserved.has(slug)) return;
|
|
12
|
+
const message = `The address /${slug} is reserved. Choose another.`;
|
|
13
|
+
throw new APIError("BAD_REQUEST", {
|
|
14
|
+
code: ORGANIZATION_SLUG_RESERVED,
|
|
15
|
+
message,
|
|
16
|
+
fieldErrors: { slug: message },
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// better-auth's `/organization/check-slug` answers only whether an
|
|
21
|
+
// organization holds the slug, so a reserved one would read as free until
|
|
22
|
+
// the create refused it: this refuses it there first, with the same answer.
|
|
23
|
+
export function reservedSlugCheck(
|
|
24
|
+
reserved: ReadonlySet<string>,
|
|
25
|
+
): BetterAuthPlugin {
|
|
26
|
+
return {
|
|
27
|
+
id: "reserved-slugs",
|
|
28
|
+
hooks: {
|
|
29
|
+
before: [
|
|
30
|
+
{
|
|
31
|
+
matcher: (ctx) => ctx.path === "/organization/check-slug",
|
|
32
|
+
handler: createAuthMiddleware(async (ctx) =>
|
|
33
|
+
refuseReservedSlug(reserved, ctx.body?.slug),
|
|
34
|
+
),
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { channel } from "node:diagnostics_channel";
|
|
2
|
+
|
|
3
|
+
// Where the worker says a session is over: docs/architecture/plugins/auth.md, "Session end".
|
|
4
|
+
export const SESSION_ENDED_CHANNEL = "slotform:auth:session-ended";
|
|
5
|
+
|
|
6
|
+
const ended = channel(SESSION_ENDED_CHANNEL);
|
|
7
|
+
|
|
8
|
+
export function publishSessionEnded(session: {
|
|
9
|
+
id: string;
|
|
10
|
+
userId: string;
|
|
11
|
+
}): void {
|
|
12
|
+
if (!ended.hasSubscribers) return;
|
|
13
|
+
ended.publish({ sessionId: session.id, userId: session.userId });
|
|
14
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
2
|
+
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
3
|
+
|
|
4
|
+
// The sign-up refusal code and sentence: docs/architecture/plugins/auth.md, "Sign-up policy".
|
|
5
|
+
const SIGN_UP_CLOSED = "SIGN_UP_CLOSED";
|
|
6
|
+
const SIGN_UP_CLOSED_MESSAGE =
|
|
7
|
+
"Sign-up is closed. Ask for an invitation to join.";
|
|
8
|
+
|
|
9
|
+
// The adapter calls the sign-up policy reads.
|
|
10
|
+
export interface PolicyAdapter {
|
|
11
|
+
count(args: { model: string }): Promise<number>;
|
|
12
|
+
findMany<T>(args: {
|
|
13
|
+
model: string;
|
|
14
|
+
where: { field: string; value: unknown }[];
|
|
15
|
+
}): Promise<T[]>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Whether `email` may create an account under `mode`. An invitation is open
|
|
19
|
+
// while pending and unexpired; `first` also lets the app's first account in.
|
|
20
|
+
async function maySignUp(
|
|
21
|
+
adapter: PolicyAdapter,
|
|
22
|
+
mode: "invite" | "first",
|
|
23
|
+
email: string,
|
|
24
|
+
): Promise<boolean> {
|
|
25
|
+
if (mode === "first" && (await adapter.count({ model: "user" })) === 0) {
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
const invitations = await adapter.findMany<{ expiresAt: Date | number }>({
|
|
29
|
+
model: "invitation",
|
|
30
|
+
where: [
|
|
31
|
+
{ field: "email", value: email.toLowerCase() },
|
|
32
|
+
{ field: "status", value: "pending" },
|
|
33
|
+
],
|
|
34
|
+
});
|
|
35
|
+
return invitations.some((i) => new Date(i.expiresAt).getTime() > Date.now());
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function signUpClosed(): APIError {
|
|
39
|
+
return new APIError("FORBIDDEN", {
|
|
40
|
+
code: SIGN_UP_CLOSED,
|
|
41
|
+
message: SIGN_UP_CLOSED_MESSAGE,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// A closed sign-up, refused where the account is made (every method, OAuth
|
|
46
|
+
// and the code or link verification included) and where a code or link would
|
|
47
|
+
// be sent to an address that could not use it. An existing account passes.
|
|
48
|
+
// Passkey registration needs a session, so it makes no account.
|
|
49
|
+
export function signUpPolicy(
|
|
50
|
+
mode: "invite" | "first",
|
|
51
|
+
adapterOf: () => Promise<PolicyAdapter>,
|
|
52
|
+
): {
|
|
53
|
+
plugin: BetterAuthPlugin;
|
|
54
|
+
beforeCreate: (user: { email: string }) => Promise<void>;
|
|
55
|
+
} {
|
|
56
|
+
const refuse = async (email: unknown): Promise<void> => {
|
|
57
|
+
if (typeof email !== "string") return;
|
|
58
|
+
const adapter = await adapterOf();
|
|
59
|
+
const existing = await adapter.findMany<{ id: string }>({
|
|
60
|
+
model: "user",
|
|
61
|
+
where: [{ field: "email", value: email.toLowerCase() }],
|
|
62
|
+
});
|
|
63
|
+
if (existing.length > 0) return;
|
|
64
|
+
if (!(await maySignUp(adapter, mode, email))) throw signUpClosed();
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
beforeCreate: async (user) => {
|
|
68
|
+
const adapter = await adapterOf();
|
|
69
|
+
if (!(await maySignUp(adapter, mode, user.email))) throw signUpClosed();
|
|
70
|
+
},
|
|
71
|
+
plugin: {
|
|
72
|
+
id: "sign-up-policy",
|
|
73
|
+
hooks: {
|
|
74
|
+
before: [
|
|
75
|
+
{
|
|
76
|
+
matcher: (ctx) =>
|
|
77
|
+
(ctx.path === "/email-otp/send-verification-otp" &&
|
|
78
|
+
ctx.body?.type === "sign-in") ||
|
|
79
|
+
ctx.path === "/sign-in/magic-link",
|
|
80
|
+
handler: createAuthMiddleware(async (ctx) =>
|
|
81
|
+
refuse(ctx.body?.email),
|
|
82
|
+
),
|
|
83
|
+
},
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { and, eq, type SQL, sql } from "@slotform/db/orm";
|
|
2
|
+
import {
|
|
3
|
+
member,
|
|
4
|
+
organization as organizationTable,
|
|
5
|
+
} from "../schema/organization.ts";
|
|
6
|
+
import type { MemberRow, Membership, Scope, ScopeContext } from "../scope.ts";
|
|
7
|
+
|
|
8
|
+
// The request context's tenancy capability: docs/architecture/plugins/auth.md, "Scopes".
|
|
9
|
+
export interface Tenancy {
|
|
10
|
+
// Resolve a scope's chain for an id: docs/architecture/plugins/auth.md, "Scopes".
|
|
11
|
+
resolve<S extends Scope>(
|
|
12
|
+
scope: S,
|
|
13
|
+
id: string,
|
|
14
|
+
userId: string,
|
|
15
|
+
): Promise<ScopeContext<S> | null>;
|
|
16
|
+
// The same chain for the row a URL names: its slug, unique within the
|
|
17
|
+
// parent whose id comes along (none for the organization).
|
|
18
|
+
bySlug<S extends Scope>(
|
|
19
|
+
scope: S,
|
|
20
|
+
slug: string,
|
|
21
|
+
parentId: string | undefined,
|
|
22
|
+
userId: string,
|
|
23
|
+
): Promise<ScopeContext<S> | null>;
|
|
24
|
+
// Whether `role` grants every action named in `permissions`. A request that
|
|
25
|
+
// names no resource or no action is refused, so an empty list closes the gate.
|
|
26
|
+
can(role: string, permissions: Record<string, readonly string[]>): boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The surface of the drizzle client the auth reads use: selects, joined,
|
|
30
|
+
// filtered and ordered. The sqlite and D1 clients both answer `get()` and
|
|
31
|
+
// `all()`, one synchronously, one with a promise, and `await` reads both.
|
|
32
|
+
// `db` is `unknown` across the plugin boundary and the answers are
|
|
33
|
+
// `unknown`, so each read casts to the rows it selects.
|
|
34
|
+
interface SelectQuery {
|
|
35
|
+
innerJoin(table: unknown, on: unknown): SelectQuery;
|
|
36
|
+
where(condition: unknown): SelectQuery;
|
|
37
|
+
orderBy(order: unknown): SelectQuery;
|
|
38
|
+
get(): unknown;
|
|
39
|
+
all(): unknown;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface DbClient {
|
|
43
|
+
select(fields: Record<string, unknown>): {
|
|
44
|
+
from(table: unknown): SelectQuery;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// `pin` restricts every match to one organization: docs/architecture/plugins/auth.md, "MCP OAuth".
|
|
49
|
+
export function createTenancy(
|
|
50
|
+
db: unknown,
|
|
51
|
+
roles: Record<string, unknown>,
|
|
52
|
+
membership: Membership | null = null,
|
|
53
|
+
pin?: string,
|
|
54
|
+
): Tenancy {
|
|
55
|
+
const client = db as DbClient;
|
|
56
|
+
|
|
57
|
+
// The organization matching `where` and the caller's membership of it, in
|
|
58
|
+
// one join; the consumer's membership predicate decides whether the
|
|
59
|
+
// caller's `member` row counts.
|
|
60
|
+
async function resolveOrganization(
|
|
61
|
+
where: SQL,
|
|
62
|
+
userId: string,
|
|
63
|
+
): Promise<{ organization: unknown; member: MemberRow } | null> {
|
|
64
|
+
const row = (await client
|
|
65
|
+
.select({ organization: organizationTable, member })
|
|
66
|
+
.from(member)
|
|
67
|
+
.innerJoin(
|
|
68
|
+
organizationTable,
|
|
69
|
+
eq(member.organizationId, organizationTable.id),
|
|
70
|
+
)
|
|
71
|
+
.where(
|
|
72
|
+
and(
|
|
73
|
+
where,
|
|
74
|
+
eq(member.userId, userId),
|
|
75
|
+
membership ? sql`(${membership.where})` : undefined,
|
|
76
|
+
pin === undefined ? undefined : eq(organizationTable.id, pin),
|
|
77
|
+
),
|
|
78
|
+
)
|
|
79
|
+
.get()) as { organization: unknown; member: MemberRow } | undefined;
|
|
80
|
+
return row ? { organization: row.organization, member: row.member } : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Bottom-up, each tier's row and its parent's id up to the organization;
|
|
84
|
+
// then, once the root answers with the caller's member row, top-down, one
|
|
85
|
+
// read per tier that declares a visibility predicate. A non-member never
|
|
86
|
+
// reaches a visibility read, and a tier under an invisible one is refused
|
|
87
|
+
// with it.
|
|
88
|
+
async function resolve<S extends Scope>(
|
|
89
|
+
scope: S,
|
|
90
|
+
id: string,
|
|
91
|
+
userId: string,
|
|
92
|
+
): Promise<ScopeContext<S> | null> {
|
|
93
|
+
const tiers: { scope: Scope; id: string; row: unknown }[] = [];
|
|
94
|
+
let tier: Scope = scope;
|
|
95
|
+
let tierId = id;
|
|
96
|
+
while (tier.parent !== null) {
|
|
97
|
+
const [parent, parentColumn] = tier.parent;
|
|
98
|
+
const found = (await client
|
|
99
|
+
.select({ row: tier.table, parentId: parentColumn })
|
|
100
|
+
.from(tier.table)
|
|
101
|
+
.where(eq(tier.table.id, tierId))
|
|
102
|
+
.get()) as { row: unknown; parentId: unknown } | undefined;
|
|
103
|
+
if (!found || typeof found.parentId !== "string") return null;
|
|
104
|
+
tiers.push({ scope: tier, id: tierId, row: found.row });
|
|
105
|
+
tier = parent;
|
|
106
|
+
tierId = found.parentId;
|
|
107
|
+
}
|
|
108
|
+
const root = await resolveOrganization(
|
|
109
|
+
eq(organizationTable.id, tierId),
|
|
110
|
+
userId,
|
|
111
|
+
);
|
|
112
|
+
if (!root) return null;
|
|
113
|
+
// The entries are keyed by the chain's scope names, which `ScopeContext<S>`
|
|
114
|
+
// spells for the one `scope` the type parameter names.
|
|
115
|
+
const entries: Record<string, unknown> = { ...root };
|
|
116
|
+
for (const { scope: below, id: rowId, row } of tiers.reverse()) {
|
|
117
|
+
if (below.where) {
|
|
118
|
+
const visible = await client
|
|
119
|
+
.select({ id: below.table.id })
|
|
120
|
+
.from(below.table)
|
|
121
|
+
.where(
|
|
122
|
+
and(eq(below.table.id, rowId), sql`(${below.where(root.member)})`),
|
|
123
|
+
)
|
|
124
|
+
.get();
|
|
125
|
+
if (!visible) return null;
|
|
126
|
+
}
|
|
127
|
+
entries[below.name] = row;
|
|
128
|
+
}
|
|
129
|
+
return entries as ScopeContext<S>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
resolve,
|
|
134
|
+
async bySlug<S extends Scope>(
|
|
135
|
+
scope: S,
|
|
136
|
+
slug: string,
|
|
137
|
+
parentId: string | undefined,
|
|
138
|
+
userId: string,
|
|
139
|
+
): Promise<ScopeContext<S> | null> {
|
|
140
|
+
if (scope.slug === null) return null;
|
|
141
|
+
if (scope.parent === null) {
|
|
142
|
+
// The organization root answers `organization` and `member`, the
|
|
143
|
+
// whole `ScopeContext` of the organization scope.
|
|
144
|
+
return resolveOrganization(
|
|
145
|
+
eq(scope.slug, slug),
|
|
146
|
+
userId,
|
|
147
|
+
) as Promise<ScopeContext<S> | null>;
|
|
148
|
+
}
|
|
149
|
+
if (parentId === undefined) return null;
|
|
150
|
+
const found = (await client
|
|
151
|
+
.select({ id: scope.table.id })
|
|
152
|
+
.from(scope.table)
|
|
153
|
+
.where(and(eq(scope.slug, slug), eq(scope.parent[1], parentId)))
|
|
154
|
+
.get()) as { id: string } | undefined;
|
|
155
|
+
return found ? resolve(scope, found.id, userId) : null;
|
|
156
|
+
},
|
|
157
|
+
can(role, permissions) {
|
|
158
|
+
const grants = resolveGrants(role, roles);
|
|
159
|
+
const asked = Object.entries(permissions);
|
|
160
|
+
return (
|
|
161
|
+
asked.length > 0 &&
|
|
162
|
+
asked.every(
|
|
163
|
+
([resource, actions]) =>
|
|
164
|
+
actions.length > 0 &&
|
|
165
|
+
actions.every((action) => grants[resource]?.includes(action)),
|
|
166
|
+
)
|
|
167
|
+
);
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The ids of the organizations `userId` is a member of, the membership
|
|
173
|
+
// predicate applied: what a tenancy resolves for them at the root. The
|
|
174
|
+
// authorization flow counts these to decide whether the member chooses.
|
|
175
|
+
// `db` is `unknown` across the plugin boundary, as in `createTenancy`.
|
|
176
|
+
export async function listOrganizations(
|
|
177
|
+
db: unknown,
|
|
178
|
+
membership: Membership | null,
|
|
179
|
+
userId: string,
|
|
180
|
+
): Promise<string[]> {
|
|
181
|
+
const rows = (await (db as DbClient)
|
|
182
|
+
.select({ id: member.organizationId })
|
|
183
|
+
.from(member)
|
|
184
|
+
.where(
|
|
185
|
+
and(
|
|
186
|
+
eq(member.userId, userId),
|
|
187
|
+
membership ? sql`(${membership.where})` : undefined,
|
|
188
|
+
),
|
|
189
|
+
)
|
|
190
|
+
.all()) as { id: string }[];
|
|
191
|
+
return rows.map((row) => row.id);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// A role's grants, either the bare `{resource: actions[]}` record
|
|
195
|
+
// `createAccessControl().newRole()` (`../access.ts`) and `defaultOrgRoles`
|
|
196
|
+
// return, or `.statements` on a real better-auth `Role` (a consumer who
|
|
197
|
+
// imported `better-auth/plugins/access` directly).
|
|
198
|
+
function grantsOf(role: unknown): Record<string, readonly string[]> | null {
|
|
199
|
+
if (!role || typeof role !== "object") return null;
|
|
200
|
+
if ("statements" in role) {
|
|
201
|
+
const statements = role.statements;
|
|
202
|
+
// A role's grants are lists of action names by contract; no check reads them.
|
|
203
|
+
if (statements && typeof statements === "object") {
|
|
204
|
+
return statements as Record<string, readonly string[]>;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return role as Record<string, readonly string[]>;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// better-auth's member role is a comma-separated multi-role string: the
|
|
211
|
+
// grants are the union of every named role's. An unknown name adds nothing.
|
|
212
|
+
export function resolveGrants(
|
|
213
|
+
roleField: string,
|
|
214
|
+
roles: Record<string, unknown>,
|
|
215
|
+
): Record<string, readonly string[]> {
|
|
216
|
+
const merged = new Map<string, Set<string>>();
|
|
217
|
+
for (const name of roleField.split(",")) {
|
|
218
|
+
const grants = grantsOf(roles[name]);
|
|
219
|
+
if (!grants) continue;
|
|
220
|
+
for (const [resource, actions] of Object.entries(grants)) {
|
|
221
|
+
const set = merged.get(resource) ?? new Set<string>();
|
|
222
|
+
for (const action of actions) set.add(action);
|
|
223
|
+
merged.set(resource, set);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return Object.fromEntries(
|
|
227
|
+
[...merged].map(([resource, actions]) => [resource, [...actions]]),
|
|
228
|
+
);
|
|
229
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { AuthCallbacks } from "@slotform/auth/runtime";
|
|
2
|
+
|
|
3
|
+
// Which callback each option requires, and what each payload carries:
|
|
4
|
+
// node_modules/@slotform/auth/guide/callbacks.md.
|
|
5
|
+
// `slotform dev` sets `SLOTFORM_DEV`; your worker's `Env` does not declare it.
|
|
6
|
+
const isDev = (env: unknown) =>
|
|
7
|
+
(env as { SLOTFORM_DEV?: string }).SLOTFORM_DEV === "1";
|
|
8
|
+
|
|
9
|
+
const callbacks: AuthCallbacks = {
|
|
10
|
+
sendOTP({ email, code, env }) {
|
|
11
|
+
// TODO: send OTP email
|
|
12
|
+
if (!isDev(env))
|
|
13
|
+
throw new Error(
|
|
14
|
+
"sendOTP is not implemented: edit src/worker/plugins/auth.ts",
|
|
15
|
+
);
|
|
16
|
+
console.log(`OTP for ${email}: ${code}`);
|
|
17
|
+
},
|
|
18
|
+
sendInvitation({ invitationId, email, organization, env }) {
|
|
19
|
+
// TODO: send invitation email linking to your accept page
|
|
20
|
+
if (!isDev(env))
|
|
21
|
+
throw new Error(
|
|
22
|
+
"sendInvitation is not implemented: edit src/worker/plugins/auth.ts",
|
|
23
|
+
);
|
|
24
|
+
console.log(
|
|
25
|
+
`Invitation ${invitationId} for ${email} to ${organization.name}`,
|
|
26
|
+
);
|
|
27
|
+
},
|
|
28
|
+
// sendMagicLink({ email, url, env }) {
|
|
29
|
+
// // TODO: send the magic link email
|
|
30
|
+
// if (!isDev(env))
|
|
31
|
+
// throw new Error(
|
|
32
|
+
// "sendMagicLink is not implemented: edit src/worker/plugins/auth.ts",
|
|
33
|
+
// );
|
|
34
|
+
// console.log(`Magic link for ${email}: ${url}`);
|
|
35
|
+
// },
|
|
36
|
+
// Your own better-auth plugins, registered after the framework's:
|
|
37
|
+
// plugins: [myEnrolmentLink()],
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export default callbacks;
|