@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
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
2
|
+
export interface PolicyAdapter {
|
|
3
|
+
count(args: {
|
|
4
|
+
model: string;
|
|
5
|
+
}): Promise<number>;
|
|
6
|
+
findMany<T>(args: {
|
|
7
|
+
model: string;
|
|
8
|
+
where: {
|
|
9
|
+
field: string;
|
|
10
|
+
value: unknown;
|
|
11
|
+
}[];
|
|
12
|
+
}): Promise<T[]>;
|
|
13
|
+
}
|
|
14
|
+
export declare function signUpPolicy(mode: "invite" | "first", adapterOf: () => Promise<PolicyAdapter>): {
|
|
15
|
+
plugin: BetterAuthPlugin;
|
|
16
|
+
beforeCreate: (user: {
|
|
17
|
+
email: string;
|
|
18
|
+
}) => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=sign-up-policy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-up-policy.d.ts","sourceRoot":"","sources":["../../src/worker/sign-up-policy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AASpD,MAAM,WAAW,aAAa;IAC7B,KAAK,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAChD,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE;QACjB,KAAK,EAAE,MAAM,CAAC;QACd,KAAK,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,OAAO,CAAA;SAAE,EAAE,CAAC;KAC3C,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CACjB;AAiCD,wBAAgB,YAAY,CAC3B,IAAI,EAAE,QAAQ,GAAG,OAAO,EACxB,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,GACrC;IACF,MAAM,EAAE,gBAAgB,CAAC;IACzB,YAAY,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD,CAiCA"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
2
|
+
// The sign-up refusal code and sentence: docs/architecture/plugins/auth.md, "Sign-up policy".
|
|
3
|
+
const SIGN_UP_CLOSED = "SIGN_UP_CLOSED";
|
|
4
|
+
const SIGN_UP_CLOSED_MESSAGE = "Sign-up is closed. Ask for an invitation to join.";
|
|
5
|
+
// Whether `email` may create an account under `mode`. An invitation is open
|
|
6
|
+
// while pending and unexpired; `first` also lets the app's first account in.
|
|
7
|
+
async function maySignUp(adapter, mode, email) {
|
|
8
|
+
if (mode === "first" && (await adapter.count({ model: "user" })) === 0) {
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
const invitations = await adapter.findMany({
|
|
12
|
+
model: "invitation",
|
|
13
|
+
where: [
|
|
14
|
+
{ field: "email", value: email.toLowerCase() },
|
|
15
|
+
{ field: "status", value: "pending" },
|
|
16
|
+
],
|
|
17
|
+
});
|
|
18
|
+
return invitations.some((i) => new Date(i.expiresAt).getTime() > Date.now());
|
|
19
|
+
}
|
|
20
|
+
function signUpClosed() {
|
|
21
|
+
return new APIError("FORBIDDEN", {
|
|
22
|
+
code: SIGN_UP_CLOSED,
|
|
23
|
+
message: SIGN_UP_CLOSED_MESSAGE,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
// A closed sign-up, refused where the account is made (every method, OAuth
|
|
27
|
+
// and the code or link verification included) and where a code or link would
|
|
28
|
+
// be sent to an address that could not use it. An existing account passes.
|
|
29
|
+
// Passkey registration needs a session, so it makes no account.
|
|
30
|
+
export function signUpPolicy(mode, adapterOf) {
|
|
31
|
+
const refuse = async (email) => {
|
|
32
|
+
if (typeof email !== "string")
|
|
33
|
+
return;
|
|
34
|
+
const adapter = await adapterOf();
|
|
35
|
+
const existing = await adapter.findMany({
|
|
36
|
+
model: "user",
|
|
37
|
+
where: [{ field: "email", value: email.toLowerCase() }],
|
|
38
|
+
});
|
|
39
|
+
if (existing.length > 0)
|
|
40
|
+
return;
|
|
41
|
+
if (!(await maySignUp(adapter, mode, email)))
|
|
42
|
+
throw signUpClosed();
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
beforeCreate: async (user) => {
|
|
46
|
+
const adapter = await adapterOf();
|
|
47
|
+
if (!(await maySignUp(adapter, mode, user.email)))
|
|
48
|
+
throw signUpClosed();
|
|
49
|
+
},
|
|
50
|
+
plugin: {
|
|
51
|
+
id: "sign-up-policy",
|
|
52
|
+
hooks: {
|
|
53
|
+
before: [
|
|
54
|
+
{
|
|
55
|
+
matcher: (ctx) => (ctx.path === "/email-otp/send-verification-otp" &&
|
|
56
|
+
ctx.body?.type === "sign-in") ||
|
|
57
|
+
ctx.path === "/sign-in/magic-link",
|
|
58
|
+
handler: createAuthMiddleware(async (ctx) => refuse(ctx.body?.email)),
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=sign-up-policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-up-policy.js","sourceRoot":"","sources":["../../src/worker/sign-up-policy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEjE,8FAA8F;AAC9F,MAAM,cAAc,GAAG,gBAAgB,CAAC;AACxC,MAAM,sBAAsB,GAC3B,mDAAmD,CAAC;AAWrD,4EAA4E;AAC5E,6EAA6E;AAC7E,KAAK,UAAU,SAAS,CACvB,OAAsB,EACtB,IAAwB,EACxB,KAAa;IAEb,IAAI,IAAI,KAAK,OAAO,IAAI,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;QACxE,OAAO,IAAI,CAAC;IACb,CAAC;IACD,MAAM,WAAW,GAAG,MAAM,OAAO,CAAC,QAAQ,CAA+B;QACxE,KAAK,EAAE,YAAY;QACnB,KAAK,EAAE;YACN,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,WAAW,EAAE,EAAE;YAC9C,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAE;SACrC;KACD,CAAC,CAAC;IACH,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,G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I,KAAK,kCAAkC;4BAC/C,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK,SAAS,CAAC;4BAC9B,GAAG,CAAC,IAAI,KAAK,qBAAqB;wBACnC,OAAO,EAAE,oBAAoB,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAC3C,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CACvB;qBACD;iBACD;aACD;SACD;KACD,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Membership, Scope, ScopeContext } from "../scope.ts";
|
|
2
|
+
export interface Tenancy {
|
|
3
|
+
resolve<S extends Scope>(scope: S, id: string, userId: string): Promise<ScopeContext<S> | null>;
|
|
4
|
+
bySlug<S extends Scope>(scope: S, slug: string, parentId: string | undefined, userId: string): Promise<ScopeContext<S> | null>;
|
|
5
|
+
can(role: string, permissions: Record<string, readonly string[]>): boolean;
|
|
6
|
+
}
|
|
7
|
+
interface SelectQuery {
|
|
8
|
+
innerJoin(table: unknown, on: unknown): SelectQuery;
|
|
9
|
+
where(condition: unknown): SelectQuery;
|
|
10
|
+
orderBy(order: unknown): SelectQuery;
|
|
11
|
+
get(): unknown;
|
|
12
|
+
all(): unknown;
|
|
13
|
+
}
|
|
14
|
+
export interface DbClient {
|
|
15
|
+
select(fields: Record<string, unknown>): {
|
|
16
|
+
from(table: unknown): SelectQuery;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export declare function createTenancy(db: unknown, roles: Record<string, unknown>, membership?: Membership | null, pin?: string): Tenancy;
|
|
20
|
+
export declare function listOrganizations(db: unknown, membership: Membership | null, userId: string): Promise<string[]>;
|
|
21
|
+
export declare function resolveGrants(roleField: string, roles: Record<string, unknown>): Record<string, readonly string[]>;
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=tenancy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tenancy.d.ts","sourceRoot":"","sources":["../../src/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AC,EAAE,MAAM,GACV,OAAO,CAoHT;AAMD,wBAAsB,iBAAiB,CACtC,EAAE,EAAE,OAAO,EACX,UAAU,EAAE,UAAU,GAAG,IAAI,EAC7B,MAAM,EAAE,MAAM,GACZ,OAAO,CAAC,MAAM,EAAE,CAAC,CAYnB;AAoBD,wBAAgB,aAAa,CAC5B,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAcnC"}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { and, eq, sql } from "@slotform/db/orm";
|
|
2
|
+
import { member, organization as organizationTable, } from "../schema/organization.js";
|
|
3
|
+
// `pin` restricts every match to one organization: docs/architecture/plugins/auth.md, "MCP OAuth".
|
|
4
|
+
export function createTenancy(db, roles, membership = null, pin) {
|
|
5
|
+
const client = db;
|
|
6
|
+
// The organization matching `where` and the caller's membership of it, in
|
|
7
|
+
// one join; the consumer's membership predicate decides whether the
|
|
8
|
+
// caller's `member` row counts.
|
|
9
|
+
async function resolveOrganization(where, userId) {
|
|
10
|
+
const row = (await client
|
|
11
|
+
.select({ organization: organizationTable, member })
|
|
12
|
+
.from(member)
|
|
13
|
+
.innerJoin(organizationTable, eq(member.organizationId, organizationTable.id))
|
|
14
|
+
.where(and(where, eq(member.userId, userId), membership ? sql `(${membership.where})` : undefined, pin === undefined ? undefined : eq(organizationTable.id, pin)))
|
|
15
|
+
.get());
|
|
16
|
+
return row ? { organization: row.organization, member: row.member } : null;
|
|
17
|
+
}
|
|
18
|
+
// Bottom-up, each tier's row and its parent's id up to the organization;
|
|
19
|
+
// then, once the root answers with the caller's member row, top-down, one
|
|
20
|
+
// read per tier that declares a visibility predicate. A non-member never
|
|
21
|
+
// reaches a visibility read, and a tier under an invisible one is refused
|
|
22
|
+
// with it.
|
|
23
|
+
async function resolve(scope, id, userId) {
|
|
24
|
+
const tiers = [];
|
|
25
|
+
let tier = scope;
|
|
26
|
+
let tierId = id;
|
|
27
|
+
while (tier.parent !== null) {
|
|
28
|
+
const [parent, parentColumn] = tier.parent;
|
|
29
|
+
const found = (await client
|
|
30
|
+
.select({ row: tier.table, parentId: parentColumn })
|
|
31
|
+
.from(tier.table)
|
|
32
|
+
.where(eq(tier.table.id, tierId))
|
|
33
|
+
.get());
|
|
34
|
+
if (!found || typeof found.parentId !== "string")
|
|
35
|
+
return null;
|
|
36
|
+
tiers.push({ scope: tier, id: tierId, row: found.row });
|
|
37
|
+
tier = parent;
|
|
38
|
+
tierId = found.parentId;
|
|
39
|
+
}
|
|
40
|
+
const root = await resolveOrganization(eq(organizationTable.id, tierId), userId);
|
|
41
|
+
if (!root)
|
|
42
|
+
return null;
|
|
43
|
+
// The entries are keyed by the chain's scope names, which `ScopeContext<S>`
|
|
44
|
+
// spells for the one `scope` the type parameter names.
|
|
45
|
+
const entries = { ...root };
|
|
46
|
+
for (const { scope: below, id: rowId, row } of tiers.reverse()) {
|
|
47
|
+
if (below.where) {
|
|
48
|
+
const visible = await client
|
|
49
|
+
.select({ id: below.table.id })
|
|
50
|
+
.from(below.table)
|
|
51
|
+
.where(and(eq(below.table.id, rowId), sql `(${below.where(root.member)})`))
|
|
52
|
+
.get();
|
|
53
|
+
if (!visible)
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
entries[below.name] = row;
|
|
57
|
+
}
|
|
58
|
+
return entries;
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
resolve,
|
|
62
|
+
async bySlug(scope, slug, parentId, userId) {
|
|
63
|
+
if (scope.slug === null)
|
|
64
|
+
return null;
|
|
65
|
+
if (scope.parent === null) {
|
|
66
|
+
// The organization root answers `organization` and `member`, the
|
|
67
|
+
// whole `ScopeContext` of the organization scope.
|
|
68
|
+
return resolveOrganization(eq(scope.slug, slug), userId);
|
|
69
|
+
}
|
|
70
|
+
if (parentId === undefined)
|
|
71
|
+
return null;
|
|
72
|
+
const found = (await client
|
|
73
|
+
.select({ id: scope.table.id })
|
|
74
|
+
.from(scope.table)
|
|
75
|
+
.where(and(eq(scope.slug, slug), eq(scope.parent[1], parentId)))
|
|
76
|
+
.get());
|
|
77
|
+
return found ? resolve(scope, found.id, userId) : null;
|
|
78
|
+
},
|
|
79
|
+
can(role, permissions) {
|
|
80
|
+
const grants = resolveGrants(role, roles);
|
|
81
|
+
const asked = Object.entries(permissions);
|
|
82
|
+
return (asked.length > 0 &&
|
|
83
|
+
asked.every(([resource, actions]) => actions.length > 0 &&
|
|
84
|
+
actions.every((action) => grants[resource]?.includes(action))));
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
// The ids of the organizations `userId` is a member of, the membership
|
|
89
|
+
// predicate applied: what a tenancy resolves for them at the root. The
|
|
90
|
+
// authorization flow counts these to decide whether the member chooses.
|
|
91
|
+
// `db` is `unknown` across the plugin boundary, as in `createTenancy`.
|
|
92
|
+
export async function listOrganizations(db, membership, userId) {
|
|
93
|
+
const rows = (await db
|
|
94
|
+
.select({ id: member.organizationId })
|
|
95
|
+
.from(member)
|
|
96
|
+
.where(and(eq(member.userId, userId), membership ? sql `(${membership.where})` : undefined))
|
|
97
|
+
.all());
|
|
98
|
+
return rows.map((row) => row.id);
|
|
99
|
+
}
|
|
100
|
+
// A role's grants, either the bare `{resource: actions[]}` record
|
|
101
|
+
// `createAccessControl().newRole()` (`../access.ts`) and `defaultOrgRoles`
|
|
102
|
+
// return, or `.statements` on a real better-auth `Role` (a consumer who
|
|
103
|
+
// imported `better-auth/plugins/access` directly).
|
|
104
|
+
function grantsOf(role) {
|
|
105
|
+
if (!role || typeof role !== "object")
|
|
106
|
+
return null;
|
|
107
|
+
if ("statements" in role) {
|
|
108
|
+
const statements = role.statements;
|
|
109
|
+
// A role's grants are lists of action names by contract; no check reads them.
|
|
110
|
+
if (statements && typeof statements === "object") {
|
|
111
|
+
return statements;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return role;
|
|
115
|
+
}
|
|
116
|
+
// better-auth's member role is a comma-separated multi-role string: the
|
|
117
|
+
// grants are the union of every named role's. An unknown name adds nothing.
|
|
118
|
+
export function resolveGrants(roleField, roles) {
|
|
119
|
+
const merged = new Map();
|
|
120
|
+
for (const name of roleField.split(",")) {
|
|
121
|
+
const grants = grantsOf(roles[name]);
|
|
122
|
+
if (!grants)
|
|
123
|
+
continue;
|
|
124
|
+
for (const [resource, actions] of Object.entries(grants)) {
|
|
125
|
+
const set = merged.get(resource) ?? new Set();
|
|
126
|
+
for (const action of actions)
|
|
127
|
+
set.add(action);
|
|
128
|
+
merged.set(resource, set);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return Object.fromEntries([...merged].map(([resource, actions]) => [resource, [...actions]]));
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=tenancy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tenancy.js","sourceRoot":"","sources":["../../src/worker/tenancy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAY,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EACN,MAAM,EACN,YAAY,IAAI,iBAAiB,GACjC,MAAM,2BAA2B,CAAC;AA2CnC,mGAAmG;AACnG,MAAM,UAAU,aAAa,CAC5B,EAAW,EACX,KAA8B,EAC9B,UAAU,GAAsB,IAAI,EACpC,GAAY;IAEZ,MAAM,MAAM,GAAG,EAAc,CAAC;IAE9B,0EAA0E;IAC1E,oEAAoE;IACpE,gCAAgC;IAChC,KAAK,UAAU,mBAAmB,CACjC,KAAU,EACV,MAAc;QAEd,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM;aACvB,MAAM,CAAC,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC;aACnD,IAAI,CAAC,MAAM,CAAC;aACZ,SAAS,CACT,iBAAiB,EACjB,EAAE,CAAC,MAAM,CAAC,c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;AACxE,4EAA4E;AAC5E,MAAM,UAAU,aAAa,CAC5B,SAAiB,EACjB,KAA8B;IAE9B,MAAM,MAAM,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC9C,KAAK,MAAM,IAAI,IAAI,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACzC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;QACrC,IAAI,CAAC,MAAM;YAAE,SAAS;QACtB,KAAK,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC1D,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,GAAG,EAAU,CAAC;YACtD,KAAK,MAAM,MAAM,IAAI,OAAO;gBAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YAC9C,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;QAC3B,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC,WAAW,CACxB,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAClE,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Record abilities
|
|
2
|
+
|
|
3
|
+
A role says what a member may do anywhere in the organization. An ability says what a caller may
|
|
4
|
+
do to one record, from the record's own data: an owner column, a per-record seat. Build it in the
|
|
5
|
+
handler from `@slotform/auth/ability`, which re-exports everything it needs.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// src/worker/lib/ability.ts
|
|
9
|
+
import { defineAbility } from "@slotform/auth/ability";
|
|
10
|
+
|
|
11
|
+
type Subjects = {
|
|
12
|
+
Expense: { paidById: string }; // checked per row: conditions read these fields
|
|
13
|
+
Billing: never; // checked by name only: conditions are a type error
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function expenseAbility(userId: string, isOrganizer: boolean) {
|
|
17
|
+
const { can, build } = defineAbility<Subjects, "read" | "update" | "delete">();
|
|
18
|
+
can("read", "Expense");
|
|
19
|
+
can("update", "Expense", { paidById: userId });
|
|
20
|
+
if (isOrganizer) can("delete", "Expense");
|
|
21
|
+
return build();
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
In the procedure, gate with `assertCan`, tagging the row with `subject`:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { assertCan, packAbility, subject } from "@slotform/auth/ability";
|
|
29
|
+
|
|
30
|
+
const ability = expenseAbility(context.user.id, seat.role === "organizer");
|
|
31
|
+
assertCan(ability, "update", subject("Expense", expense));
|
|
32
|
+
return { expense, rules: packAbility(ability) };
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`assertCan` returns when allowed and throws `FORBIDDEN` when denied. `{ cloak: true }` throws
|
|
36
|
+
`NOT_FOUND` instead, at a site that must not reveal the record exists; `{ message }` replaces the
|
|
37
|
+
denial copy.
|
|
38
|
+
|
|
39
|
+
## On the client
|
|
40
|
+
|
|
41
|
+
Return `packAbility(ability)` on the query's output, typed `PackedRuleSet`, and pass it to
|
|
42
|
+
`useAbility(organizationId, data?.rules)`, which layers it over the caller's role (the query plugin's
|
|
43
|
+
abilities page, `node_modules/@slotform/query/guide/abilities.md`). Outside an organization, `unpackAbility(rules)`
|
|
44
|
+
rebuilds it.
|
|
45
|
+
|
|
46
|
+
## Rules
|
|
47
|
+
|
|
48
|
+
- Build an ability in the handler, from rows the handler loaded: the rules depend on data only
|
|
49
|
+
its queries know.
|
|
50
|
+
- Never install or import `@casl/ability`: the subpath re-exports what an app uses.
|
|
51
|
+
- Never call an action `"manage"` or a subject `"all"`: both are wildcards and grant everything.
|
|
52
|
+
- Gate organization-wide permissions with the procedure's `can`, and keep abilities for what
|
|
53
|
+
differs per record.
|
|
54
|
+
|
|
55
|
+
**Check:** `pnpm check` passes, and the procedure answers `FORBIDDEN` to a caller the rule refuses.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Add a role or a permission
|
|
2
|
+
|
|
3
|
+
A permission is an action on a resource in the access control; a role grants a set of them. Work
|
|
4
|
+
the steps in order; each names the page it needs and ends with its check.
|
|
5
|
+
|
|
6
|
+
## 1. Declare it
|
|
7
|
+
|
|
8
|
+
Add the action to its resource in `ac` (a new resource is a new key), then grant it to each role
|
|
9
|
+
that holds it, or add the role with `ac.newRole`. With `organization: true` still in the config,
|
|
10
|
+
move to `{ ac, roles }` first and copy the default roles you keep. Page:
|
|
11
|
+
[organizations](./organizations.md).
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// src/shared/access.ts
|
|
15
|
+
export const ac = createAccessControl({ /* ... */ project: ["create", "update", "delete", "archive"] });
|
|
16
|
+
export const roles = { /* ... */ editor: ac.newRole({ project: ["create", "update", "archive"] }) };
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
**Check:** `slotform generate`, then `pnpm check` passes.
|
|
20
|
+
|
|
21
|
+
## 2. Gate the procedure
|
|
22
|
+
|
|
23
|
+
Set `can: ["archive", "project"]` on the procedure, beside its `auth: true` and `scope`. Page:
|
|
24
|
+
api's procedures page (`node_modules/@slotform/api/guide/procedures.md`).
|
|
25
|
+
|
|
26
|
+
**Check:** `pnpm check` passes, and the action and resource autocomplete in `can`.
|
|
27
|
+
|
|
28
|
+
## 3. Gate the screen
|
|
29
|
+
|
|
30
|
+
Show the control only when `useAbility(organizationId).can("archive", "project")` answers yes.
|
|
31
|
+
Page: the query plugin's abilities page (`node_modules/@slotform/query/guide/abilities.md`).
|
|
32
|
+
|
|
33
|
+
**Check:** under `pnpm dev`, a member without the grant sees no control.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Auth callbacks
|
|
2
|
+
|
|
3
|
+
`src/worker/plugins/auth.ts` holds the code auth runs for you: sending a code, an invitation, a
|
|
4
|
+
deletion link. `slotform init` and `slotform add auth` scaffold it; the generated worker imports it.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
// src/worker/plugins/auth.ts
|
|
8
|
+
import type { AuthCallbacks } from "@slotform/auth/runtime";
|
|
9
|
+
|
|
10
|
+
const callbacks: AuthCallbacks<Env> = {
|
|
11
|
+
async sendOTP({ email, code, type, env }) {
|
|
12
|
+
// send code to email through a binding or a secret on env; type says why
|
|
13
|
+
},
|
|
14
|
+
async sendInvitation({ invitationId, email, organization, inviter, env }) {
|
|
15
|
+
const url = `${env.APP_URL}/invitations/${invitationId}`;
|
|
16
|
+
// send url to email, naming inviter.name and organization.name
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export default callbacks;
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Every payload carries `env`, the request's env, so a callback reaches a binding or a secret
|
|
24
|
+
through it. `AuthCallbacks<Env>` types it with the worker's `Env`; bare `AuthCallbacks` leaves it
|
|
25
|
+
`unknown`.
|
|
26
|
+
|
|
27
|
+
| Callback | Runs when |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `sendOTP` | A one-time code is issued. `type` is `sign-in`, `email-verification`, `forget-password` or `change-email` (`OtpType`). Required while `emailOtp` is on |
|
|
30
|
+
| `sendMagicLink` | A magic link is requested. It carries `email`, the `url` to send and its `token`. Required while `magicLink` is on |
|
|
31
|
+
| `sendInvitation` | An organization invitation is sent. It carries `invitationId` (what the accept link names), `role`, `organization` (`id`, `name`, `slug`) and `inviter` (`id`, `name`, `email`). An invitation expires after 48 hours. Required while `organization` is on |
|
|
32
|
+
| `generateOTP` | A code is about to be generated. Return a string to fix it (a review account's code), `undefined` for a random one. Synchronous |
|
|
33
|
+
| `beforeDelete` | `user.deleteUser` is on and an account is about to go. Throw to refuse; clean up storage and personal data here |
|
|
34
|
+
| `sendDeleteVerification` | `user.deleteUser` is on: `deleteUser()` emails `url` instead of deleting, and the account goes when the link opens, with no fresh session needed. Implement it in a passwordless app |
|
|
35
|
+
|
|
36
|
+
## Rules
|
|
37
|
+
|
|
38
|
+
- The scaffold is a stub: each callback logs its code or link in dev and throws
|
|
39
|
+
(`sendOTP is not implemented: edit src/worker/plugins/auth.ts`) when `SLOTFORM_DEV` is not `1`, so a
|
|
40
|
+
deployed stub never writes a sign-in code to the logs. `slotform deploy` refuses while the stub's
|
|
41
|
+
`// TODO` marker line stays for a callback the options require (`sendOTP` with `emailOtp`,
|
|
42
|
+
`sendMagicLink` with `magicLink`, `sendInvitation` with `organization`): implement the send, then
|
|
43
|
+
delete the marker.
|
|
44
|
+
- Import only `@slotform/auth/runtime` here, never the package root: the file is bundled
|
|
45
|
+
into the worker, and the root drags in the plugin's Node-only codegen.
|
|
46
|
+
- While a callback is required (`sendOTP` with `emailOtp`, `sendMagicLink` with `magicLink`,
|
|
47
|
+
`sendInvitation` with `organization`), a missing file fails `slotform generate`, and a file
|
|
48
|
+
without it makes the worker refuse to start auth. With none of the three on the file is optional.
|
|
49
|
+
- Key a `generateOTP` override on `type` as well as `email`: it runs for every code type.
|
|
50
|
+
- Without `sendDeleteVerification`, deletion needs a session younger than `session.freshAge`;
|
|
51
|
+
never set `freshAge: 0` to get around it.
|
|
52
|
+
|
|
53
|
+
## A sign-in flow of your own
|
|
54
|
+
|
|
55
|
+
A flow auth does not ship (a one-time link, an enrolment token) is a Better Auth plugin you write
|
|
56
|
+
and list on `plugins`. It registers after auth's own, under `/api/auth`. A table it declares lives
|
|
57
|
+
in `src/schema/index.ts`, exported under the plugin's model name.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const callbacks: AuthCallbacks<Env> = {
|
|
61
|
+
sendOTP({ email, code }) { /* ... */ },
|
|
62
|
+
plugins: [enrolmentLink()],
|
|
63
|
+
};
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A plugin needs Better Auth's own helpers, and the app holds no `better-auth` dependency of its
|
|
67
|
+
own: pinning a second copy beside Slotform's would split `APIError` in two, and the router would no
|
|
68
|
+
longer read a refusal as its own. Import them from `@slotform/auth/runtime`, never from
|
|
69
|
+
`better-auth`: `createAuthEndpoint` (an endpoint), `setSessionCookie` (the cookie of a session
|
|
70
|
+
it mints), `customSession` (fields the session read carries), `createAuthMiddleware`,
|
|
71
|
+
`getSessionFromCtx`, `APIError`, `isAPIError` and the `BetterAuthPlugin` type.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import {
|
|
75
|
+
type BetterAuthPlugin, APIError, createAuthMiddleware, getSessionFromCtx,
|
|
76
|
+
} from "@slotform/auth/runtime";
|
|
77
|
+
|
|
78
|
+
export const gate = (): BetterAuthPlugin => ({
|
|
79
|
+
id: "gate",
|
|
80
|
+
hooks: {
|
|
81
|
+
before: [{
|
|
82
|
+
matcher: (ctx) => ctx.path === "/organization/accept-invitation",
|
|
83
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
84
|
+
const session = await getSessionFromCtx(ctx); // the endpoint has not resolved it yet
|
|
85
|
+
if (session && !allowed(session.user.email))
|
|
86
|
+
throw new APIError("BAD_REQUEST", { code: "NOT_ALLOWED", message: "Not allowed" });
|
|
87
|
+
}),
|
|
88
|
+
}],
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Before writing one, check [sign-in](./sign-in.md): a flow every app needs is a shortfall in Slotform
|
|
94
|
+
(`node_modules/@slotform/cli/guide/shortfall.md`).
|
|
95
|
+
|
|
96
|
+
**Check:** `slotform generate`, then `pnpm check` passes, and under `pnpm dev` a sign-in code
|
|
97
|
+
reaches `sendOTP`; `slotform deploy` stops at the `// TODO` marker until the stub is replaced.
|
package/guide/config.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Auth config
|
|
2
|
+
|
|
3
|
+
`auth()` in `slotform.config.ts` turns on sign-in, sessions and, when asked, organizations. It needs
|
|
4
|
+
`api()` and `db()` in the config, and runs on Cloudflare and on Node alike.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
// slotform.config.ts
|
|
8
|
+
auth({
|
|
9
|
+
cookies: { prefix: "my-app" },
|
|
10
|
+
organization: true,
|
|
11
|
+
passkey: {},
|
|
12
|
+
socialProviders: { google: true },
|
|
13
|
+
}),
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Options
|
|
17
|
+
|
|
18
|
+
| Option | Default | Effect |
|
|
19
|
+
| --- | --- | --- |
|
|
20
|
+
| `cookies.prefix` / `cookies.domain` | `better-auth` / unset | The session cookie's name prefix and domain |
|
|
21
|
+
| `session.expiresIn` | 7 days | Session length, in seconds |
|
|
22
|
+
| `session.updateAge` | unset | How often, in seconds, a session's expiry is refreshed |
|
|
23
|
+
| `session.freshAge` | 1 day | How young a session must be to count as fresh. `0` turns the check off, so any stolen cookie can delete its account |
|
|
24
|
+
| `emailOtp` | `true` | Email one-time-code sign-in; `false` for an OAuth-only app |
|
|
25
|
+
| `magicLink` | `false` | Magic-link sign-in; on, `sendMagicLink` is required, see [sign-in](./sign-in.md) |
|
|
26
|
+
| `signUp` | `"open"` | Who may create an account: `"open"`, `"invite"` or `"first"`; the closed modes need `organization`, see [sign-in](./sign-in.md#who-may-sign-up) |
|
|
27
|
+
| `socialProviders.google` / `.apple` | off | OAuth, see [sign-in](./sign-in.md) |
|
|
28
|
+
| `passkey` | `false` | `{}` turns passkeys on, see [sign-in](./sign-in.md) |
|
|
29
|
+
| `organization` | off | `true` or `{ ac, roles }`, see [organizations](./organizations.md) |
|
|
30
|
+
| `user.deleteUser` | `false` | Account deletion, see [callbacks](./callbacks.md). A native app on the App Store needs it |
|
|
31
|
+
| `mcp` | `false` | An authorization server for MCP clients; needs `organization`, see [mcp-oauth](./mcp-oauth.md) |
|
|
32
|
+
| `devices` | `false` | Named, revocable bearer keys a member makes for a machine with no browser, see [devices](./devices.md) |
|
|
33
|
+
| `expo` | off | A native client: trusts the deep-link scheme `expo()` registers, or on a server that is no Expo app (a web or node hub serving a separate phone app) `expo: { scheme: "vault" }`, the phone's; see `node_modules/@slotform/expo/guide/native-auth.md` |
|
|
34
|
+
| `secretVar` / `appUrlVar` | `AUTH_SECRET` / `APP_URL` | The env var names below |
|
|
35
|
+
| `rateLimiter.ip` / `.email` / `.agent` | 100, 3 and 120 per 60 s | Cloudflare rate-limiter `binding`, `limit` and `period` (10 or 60). `agent` is one bucket per MCP grant, bound only with `mcp`. Node has no limiter |
|
|
36
|
+
|
|
37
|
+
## Env vars
|
|
38
|
+
|
|
39
|
+
Auth declares its env vars, so each reaches `.dev.vars` on Cloudflare, the dev process on Node,
|
|
40
|
+
and the worker's check on its first request, which refuses to serve while one is missing.
|
|
41
|
+
|
|
42
|
+
| Var | Dev value | Production |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `AUTH_SECRET` | a placeholder of 32 characters or more | 32 characters or more |
|
|
45
|
+
| `APP_URL` | the first frontend dev origin, else the server's | the app's public URL; a non-local one while `SLOTFORM_DEV` is set refuses to serve. A Node listener with an origin of its own signs in at that origin instead, with `Secure` cookies when it is https |
|
|
46
|
+
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `APPLE_CLIENT_ID`, `APPLE_CLIENT_SECRET` | placeholders, per enabled provider | the provider's credentials |
|
|
47
|
+
|
|
48
|
+
## Schema
|
|
49
|
+
|
|
50
|
+
The identity tables are auth's. Re-export them from `src/schema/index.ts`, so they are migrated:
|
|
51
|
+
the adapter never creates a table.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// src/schema/index.ts
|
|
55
|
+
export * from "@slotform/auth/schema"; // user, session, account, verification: always
|
|
56
|
+
export * from "@slotform/auth/schema/organization"; // organization, member, invitation: with `organization`
|
|
57
|
+
export * from "@slotform/auth/schema/passkey"; // passkey: with `passkey`
|
|
58
|
+
export * from "@slotform/auth/schema/oauth"; // the OAuth grant tables and jwks: with `mcp`
|
|
59
|
+
export * from "@slotform/auth/schema/devices"; // apikey: with `devices`
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Rules
|
|
63
|
+
|
|
64
|
+
- Migrate the auth tables with the db plugin's commands, never `@better-auth/cli migrate`.
|
|
65
|
+
- Never add a column to an auth table. Data kept per user or per organization lives in your own
|
|
66
|
+
table keyed by `user.id` or `organization.id`, its reference `onDelete: "cascade"`.
|
|
67
|
+
- The OAuth tables carry no cascade, so a user with grants cannot be deleted, as one with
|
|
68
|
+
memberships cannot.
|
|
69
|
+
- The auth tables' names are entities already: `reads: ["member"]` type-checks without your
|
|
70
|
+
schema exporting them under its own names.
|
|
71
|
+
- The session's user has `id`, `name`, `email`, `emailVerified`, `image`, `createdAt` and
|
|
72
|
+
`updatedAt`; type it with `SessionUser` from `@slotform/auth/infer`.
|
|
73
|
+
- Type the session from the config, never by hand: it carries `activeOrganizationId` exactly when
|
|
74
|
+
`auth({ organization })` is set.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// src/shared/session.ts
|
|
78
|
+
import type { InferSession } from "@slotform/auth/infer";
|
|
79
|
+
import type config from "../../slotform.config";
|
|
80
|
+
|
|
81
|
+
export type Session = InferSession<typeof config>;
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**Check:** `slotform generate`, then `pnpm check` passes.
|
package/guide/devices.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Device credentials
|
|
2
|
+
|
|
3
|
+
`auth({ devices: true })` lets a signed-in member make a named, revocable key for a machine with no
|
|
4
|
+
browser: an agent daemon, a sync client. The machine sends it as `Authorization: Bearer <key>` and
|
|
5
|
+
acts as that member. It is accepted wherever a session is: `procedure({ auth: true })` and its
|
|
6
|
+
scopes, the `/ws` upgrade, and a service route.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
// slotform.config.ts
|
|
10
|
+
auth({ organization: true, devices: true }),
|
|
11
|
+
// src/schema/index.ts
|
|
12
|
+
export * from "@slotform/auth/schema/devices"; // the device key table
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**Check:** `slotform generate`, `slotform db generate`, then `orpc.auth.devices.list` answers `[]`.
|
|
16
|
+
|
|
17
|
+
## The member's calls
|
|
18
|
+
|
|
19
|
+
A member signed in with a session makes, lists and revokes keys. A device key cannot.
|
|
20
|
+
|
|
21
|
+
| Procedure | Does |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| `auth.devices.create({ name, expiresInDays? })` | Answers `{ device, key }`. The key is shown once and stored hashed. Without `expiresInDays` it does not expire; the most is 365 |
|
|
24
|
+
| `auth.devices.list` | Each device's `id`, `name`, `start` (the key's first characters), `createdAt`, `expiresAt` and `lastUsedAt` |
|
|
25
|
+
| `auth.devices.revoke({ id })` | Ends the key; its next request is refused |
|
|
26
|
+
|
|
27
|
+
A name is 1 to 40 characters and a member holds 25 live keys at most (`DEVICE_LIMIT`). Make one key
|
|
28
|
+
per machine, so revoking a lost one ends only it.
|
|
29
|
+
|
|
30
|
+
## The machine's calls
|
|
31
|
+
|
|
32
|
+
The member pastes the key into the machine's configuration once. The machine then calls the API
|
|
33
|
+
with the app's own client, its `/ws` channels with a header, and its service routes with a plain
|
|
34
|
+
`fetch`:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// the daemon
|
|
38
|
+
import { createClient } from "@slotform/api/client";
|
|
39
|
+
import { createWsClient } from "@slotform/node/client";
|
|
40
|
+
import type { AppRouter } from "../.slotform/worker";
|
|
41
|
+
|
|
42
|
+
const headers = { authorization: `Bearer ${key}` };
|
|
43
|
+
const api = createClient<AppRouter>({ url: `${hub}/rpc`, headers });
|
|
44
|
+
const ws = createWsClient({ url: `${hub.replace("http", "ws")}/ws`, headers });
|
|
45
|
+
await fetch(`${hub}/sync/push`, { method: "POST", headers, body });
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
A service route asks who is calling with `http.session`, which resolves the request as `/ws` does
|
|
49
|
+
(see the node plugin's services page):
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// src/server/services/sync.ts
|
|
53
|
+
http.mount("/sync", async (request) => {
|
|
54
|
+
const session = await http.session(request);
|
|
55
|
+
if (!session) return new Response("Unauthorized", { status: 401 });
|
|
56
|
+
// session.user.id is the member; session.session.id is the key's id
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
A procedure sees the member as `context.user` and `context.session`. `session.id` is the key's id,
|
|
61
|
+
`activeOrganizationId` is unset (a key has no active organization: name the organization in the
|
|
62
|
+
input, as a scope does), and a scope resolves the member's membership on every call, so removing
|
|
63
|
+
the member from an organization ends the key's reach into it at once.
|
|
64
|
+
|
|
65
|
+
A revoked, expired or unknown key answers `UNAUTHORIZED`; a key over its rate limit answers
|
|
66
|
+
`TOO_MANY_REQUESTS`.
|
|
67
|
+
|
|
68
|
+
## What a key cannot do
|
|
69
|
+
|
|
70
|
+
On the auth routes a key reaches the session lookup and the reads of its member's organizations,
|
|
71
|
+
nothing else, so a stolen key cannot mint another key, change the sign-in, delete the account or
|
|
72
|
+
change an organization. Those answer `FORBIDDEN` (`DEVICE_CREDENTIAL_REFUSED`). The key routes are
|
|
73
|
+
off HTTP: only the `auth.devices.*` procedures reach them.
|
|
74
|
+
|
|
75
|
+
Everything the app's own procedures allow its member, a key does. Give the machine its own member
|
|
76
|
+
in the organization, with a narrower role, when it should do less than a person.
|
|
77
|
+
|
|
78
|
+
## Rules
|
|
79
|
+
|
|
80
|
+
- A key counts each lookup: 600 a minute, and a procedure that also calls an auth endpoint counts
|
|
81
|
+
two. A daemon batches its calls.
|
|
82
|
+
- Revoking stops the next request, not a socket already open: a channel that must honour it closes
|
|
83
|
+
the socket itself.
|
|
84
|
+
- A machine stores the key like a password: a file only its user reads, or the operating system's
|
|
85
|
+
secret store; never a log line, a URL or a repository. Send it over HTTPS only.
|