@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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/dist/ability/index.d.ts +31 -0
  4. package/dist/ability/index.d.ts.map +1 -0
  5. package/dist/ability/index.js +64 -0
  6. package/dist/ability/index.js.map +1 -0
  7. package/dist/access.d.ts +19 -0
  8. package/dist/access.d.ts.map +1 -0
  9. package/dist/access.js +33 -0
  10. package/dist/access.js.map +1 -0
  11. package/dist/callback-stubs.d.ts +15 -0
  12. package/dist/callback-stubs.d.ts.map +1 -0
  13. package/dist/callback-stubs.js +28 -0
  14. package/dist/callback-stubs.js.map +1 -0
  15. package/dist/client.d.ts +38 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +37 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/index.d.ts +190 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +451 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/infer.d.ts +31 -0
  24. package/dist/infer.d.ts.map +1 -0
  25. package/dist/infer.js +2 -0
  26. package/dist/infer.js.map +1 -0
  27. package/dist/schema/devices.d.ts +404 -0
  28. package/dist/schema/devices.d.ts.map +1 -0
  29. package/dist/schema/devices.js +45 -0
  30. package/dist/schema/devices.js.map +1 -0
  31. package/dist/schema/index.d.ts +679 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +94 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/oauth.d.ts +2062 -0
  36. package/dist/schema/oauth.d.ts.map +1 -0
  37. package/dist/schema/oauth.js +245 -0
  38. package/dist/schema/oauth.js.map +1 -0
  39. package/dist/schema/organization.d.ts +388 -0
  40. package/dist/schema/organization.d.ts.map +1 -0
  41. package/dist/schema/organization.js +75 -0
  42. package/dist/schema/organization.js.map +1 -0
  43. package/dist/schema/passkey.d.ts +215 -0
  44. package/dist/schema/passkey.d.ts.map +1 -0
  45. package/dist/schema/passkey.js +29 -0
  46. package/dist/schema/passkey.js.map +1 -0
  47. package/dist/schema/sets.d.ts +3715 -0
  48. package/dist/schema/sets.d.ts.map +1 -0
  49. package/dist/schema/sets.js +48 -0
  50. package/dist/schema/sets.js.map +1 -0
  51. package/dist/scope.d.ts +36 -0
  52. package/dist/scope.d.ts.map +1 -0
  53. package/dist/scope.js +59 -0
  54. package/dist/scope.js.map +1 -0
  55. package/dist/screens-fixtures.d.ts +148 -0
  56. package/dist/screens-fixtures.d.ts.map +1 -0
  57. package/dist/screens-fixtures.js +122 -0
  58. package/dist/screens-fixtures.js.map +1 -0
  59. package/dist/screens-session.d.ts +4 -0
  60. package/dist/screens-session.d.ts.map +1 -0
  61. package/dist/screens-session.js +24 -0
  62. package/dist/screens-session.js.map +1 -0
  63. package/dist/screens.d.ts +3 -0
  64. package/dist/screens.d.ts.map +1 -0
  65. package/dist/screens.js +8 -0
  66. package/dist/screens.js.map +1 -0
  67. package/dist/serve.d.ts +3 -0
  68. package/dist/serve.d.ts.map +1 -0
  69. package/dist/serve.js +44 -0
  70. package/dist/serve.js.map +1 -0
  71. package/dist/types.d.ts +152 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +215 -0
  74. package/dist/types.js.map +1 -0
  75. package/dist/worker/callback-url.d.ts +6 -0
  76. package/dist/worker/callback-url.d.ts.map +1 -0
  77. package/dist/worker/callback-url.js +57 -0
  78. package/dist/worker/callback-url.js.map +1 -0
  79. package/dist/worker/cimd-transport.d.ts +2 -0
  80. package/dist/worker/cimd-transport.d.ts.map +1 -0
  81. package/dist/worker/cimd-transport.js +86 -0
  82. package/dist/worker/cimd-transport.js.map +1 -0
  83. package/dist/worker/devices.d.ts +6 -0
  84. package/dist/worker/devices.d.ts.map +1 -0
  85. package/dist/worker/devices.js +70 -0
  86. package/dist/worker/devices.js.map +1 -0
  87. package/dist/worker/email-key.d.ts +2 -0
  88. package/dist/worker/email-key.d.ts.map +1 -0
  89. package/dist/worker/email-key.js +20 -0
  90. package/dist/worker/email-key.js.map +1 -0
  91. package/dist/worker/index.d.ts +156 -0
  92. package/dist/worker/index.d.ts.map +1 -0
  93. package/dist/worker/index.js +507 -0
  94. package/dist/worker/index.js.map +1 -0
  95. package/dist/worker/listener.d.ts +12 -0
  96. package/dist/worker/listener.d.ts.map +1 -0
  97. package/dist/worker/listener.js +37 -0
  98. package/dist/worker/listener.js.map +1 -0
  99. package/dist/worker/oauth.d.ts +95 -0
  100. package/dist/worker/oauth.d.ts.map +1 -0
  101. package/dist/worker/oauth.js +456 -0
  102. package/dist/worker/oauth.js.map +1 -0
  103. package/dist/worker/outputs.d.ts +75 -0
  104. package/dist/worker/outputs.d.ts.map +1 -0
  105. package/dist/worker/outputs.js +7 -0
  106. package/dist/worker/outputs.js.map +1 -0
  107. package/dist/worker/procedures.d.ts +360 -0
  108. package/dist/worker/procedures.d.ts.map +1 -0
  109. package/dist/worker/procedures.js +464 -0
  110. package/dist/worker/procedures.js.map +1 -0
  111. package/dist/worker/rate-limit.d.ts +7 -0
  112. package/dist/worker/rate-limit.d.ts.map +1 -0
  113. package/dist/worker/rate-limit.js +49 -0
  114. package/dist/worker/rate-limit.js.map +1 -0
  115. package/dist/worker/reserved-slugs.d.ts +4 -0
  116. package/dist/worker/reserved-slugs.d.ts.map +1 -0
  117. package/dist/worker/reserved-slugs.js +30 -0
  118. package/dist/worker/reserved-slugs.js.map +1 -0
  119. package/dist/worker/session-ended.d.ts +6 -0
  120. package/dist/worker/session-ended.d.ts.map +1 -0
  121. package/dist/worker/session-ended.js +10 -0
  122. package/dist/worker/session-ended.js.map +1 -0
  123. package/dist/worker/sign-up-policy.d.ts +20 -0
  124. package/dist/worker/sign-up-policy.d.ts.map +1 -0
  125. package/dist/worker/sign-up-policy.js +65 -0
  126. package/dist/worker/sign-up-policy.js.map +1 -0
  127. package/dist/worker/tenancy.d.ts +23 -0
  128. package/dist/worker/tenancy.d.ts.map +1 -0
  129. package/dist/worker/tenancy.js +133 -0
  130. package/dist/worker/tenancy.js.map +1 -0
  131. package/guide/abilities.md +55 -0
  132. package/guide/add-a-role.md +33 -0
  133. package/guide/callbacks.md +97 -0
  134. package/guide/config.md +84 -0
  135. package/guide/devices.md +85 -0
  136. package/guide/mcp-oauth.md +97 -0
  137. package/guide/organizations.md +114 -0
  138. package/guide/protect-by-scope.md +29 -0
  139. package/guide/scopes.md +87 -0
  140. package/guide/sign-in.md +127 -0
  141. package/package.json +155 -3
  142. package/src/ability/index.ts +174 -0
  143. package/src/access.ts +45 -0
  144. package/src/callback-stubs.ts +45 -0
  145. package/src/client.ts +119 -0
  146. package/src/expo.tsx +275 -0
  147. package/src/index.ts +574 -0
  148. package/src/infer.ts +44 -0
  149. package/src/schema/devices.ts +54 -0
  150. package/src/schema/index.ts +128 -0
  151. package/src/schema/oauth.ts +320 -0
  152. package/src/schema/organization.ts +104 -0
  153. package/src/schema/passkey.ts +38 -0
  154. package/src/schema/sets.ts +73 -0
  155. package/src/scope.ts +135 -0
  156. package/src/screens-fixtures.ts +149 -0
  157. package/src/screens-session.ts +26 -0
  158. package/src/screens.ts +10 -0
  159. package/src/serve.ts +49 -0
  160. package/src/types.ts +313 -0
  161. package/src/worker/callback-url.ts +65 -0
  162. package/src/worker/cimd-transport.ts +115 -0
  163. package/src/worker/devices.ts +83 -0
  164. package/src/worker/email-key.ts +21 -0
  165. package/src/worker/index.ts +941 -0
  166. package/src/worker/listener.ts +55 -0
  167. package/src/worker/oauth.ts +709 -0
  168. package/src/worker/outputs.ts +102 -0
  169. package/src/worker/procedures.ts +758 -0
  170. package/src/worker/rate-limit.ts +64 -0
  171. package/src/worker/reserved-slugs.ts +39 -0
  172. package/src/worker/session-ended.ts +14 -0
  173. package/src/worker/sign-up-policy.ts +88 -0
  174. package/src/worker/tenancy.ts +229 -0
  175. package/templates/callbacks.ts +40 -0
@@ -0,0 +1,65 @@
1
+ // Where a sign-in link may send the member: docs/architecture/plugins/auth.md, "Procedures".
2
+
3
+ // A control character or backslash lets a browser read a path as another
4
+ // host (`/\evil.com`, a tab inside `//`), so none is accepted anywhere.
5
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point.
6
+ const UNSAFE = /[\u0000-\u001f\u007f\\]/;
7
+
8
+ function schemeOf(pattern: string): string | undefined {
9
+ const match = /^([a-z][a-z0-9+.-]*):\/\/\*?$/i.exec(pattern);
10
+ return match ? `${match[1]?.toLowerCase()}:` : undefined;
11
+ }
12
+
13
+ function matchesOrigin(url: URL, pattern: string): boolean {
14
+ const scheme = schemeOf(pattern);
15
+ if (scheme) return url.protocol === scheme;
16
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
17
+ if (!pattern.includes("*")) return url.origin === pattern.toLowerCase();
18
+ const source = pattern
19
+ .toLowerCase()
20
+ .split("*")
21
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
22
+ .join("[^/@?#:]+");
23
+ return new RegExp(`^${source}$`).test(url.origin);
24
+ }
25
+
26
+ export function isSafeCallbackURL(
27
+ value: string,
28
+ trustedOrigins: readonly string[],
29
+ ): boolean {
30
+ if (UNSAFE.test(value)) return false;
31
+ if (value.startsWith("/")) return !value.startsWith("//");
32
+ let url: URL;
33
+ try {
34
+ url = new URL(value);
35
+ } catch {
36
+ return false;
37
+ }
38
+ // A userinfo (`https://app.example.com@evil.com`) is how a lookalike
39
+ // passes a prefix check; the origin of a parsed URL already ignores it,
40
+ // but a link that carries one is never one an app means to send.
41
+ if (url.username || url.password) return false;
42
+ return trustedOrigins.some((pattern) => matchesOrigin(url, pattern));
43
+ }
44
+
45
+ const REDIRECT_FIELDS = [
46
+ "callbackURL",
47
+ "newUserCallbackURL",
48
+ "errorCallbackURL",
49
+ ] as const;
50
+
51
+ export type RedirectInput = Partial<
52
+ Record<(typeof REDIRECT_FIELDS)[number], string | undefined>
53
+ >;
54
+
55
+ // The fields of an input that carry a redirect, by name; the first one that
56
+ // is not safe, so the refusal can name it.
57
+ export function unsafeCallbackField(
58
+ input: RedirectInput,
59
+ trustedOrigins: readonly string[],
60
+ ): (typeof REDIRECT_FIELDS)[number] | undefined {
61
+ return REDIRECT_FIELDS.find((field) => {
62
+ const value = input[field];
63
+ return value !== undefined && !isSafeCallbackURL(value, trustedOrigins);
64
+ });
65
+ }
@@ -0,0 +1,115 @@
1
+ import { isPublicRoutableHost } from "@better-auth/core/utils/host";
2
+
3
+ // Fetch transport `@better-auth/cimd` requires on a Worker: docs/architecture/plugins/auth.md, "MCP OAuth".
4
+
5
+ const DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query";
6
+ const TYPE_A = 1;
7
+ const TYPE_AAAA = 28;
8
+
9
+ // RFC 6761 and RFC 6762 special-use names, and the names no public resolver
10
+ // answers: a host equal to one or below it is refused before any lookup.
11
+ const SPECIAL_USE_NAMES = [
12
+ "localhost",
13
+ "local",
14
+ "test",
15
+ "invalid",
16
+ "example",
17
+ "internal",
18
+ "onion",
19
+ "home.arpa",
20
+ ];
21
+
22
+ // The URL parser reduces every numeric host form (decimal, octal, hex) to
23
+ // dotted decimal, and an IPv6 literal keeps its brackets.
24
+ function isIpLiteral(hostname: string): boolean {
25
+ return hostname.startsWith("[") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname);
26
+ }
27
+
28
+ function isSpecialUseName(hostname: string): boolean {
29
+ const name = hostname.replace(/\.$/, "");
30
+ return SPECIAL_USE_NAMES.some(
31
+ (special) => name === special || name.endsWith(`.${special}`),
32
+ );
33
+ }
34
+
35
+ interface DohAnswer {
36
+ Status?: number;
37
+ Answer?: { type?: number; data?: string }[];
38
+ }
39
+
40
+ // The A or AAAA addresses one DoH query answers, refusing a failed request and
41
+ // any status but NOERROR. Records of other types (a CNAME chain's links) are
42
+ // not judged: only the addresses the chain ends in are.
43
+ async function resolveAddresses(
44
+ hostname: string,
45
+ type: typeof TYPE_A | typeof TYPE_AAAA,
46
+ signal: AbortSignal | undefined,
47
+ ): Promise<string[]> {
48
+ const url = new URL(DOH_ENDPOINT);
49
+ url.searchParams.set("name", hostname);
50
+ url.searchParams.set("type", type === TYPE_A ? "A" : "AAAA");
51
+ const response = await globalThis.fetch(url, {
52
+ headers: { accept: "application/dns-json" },
53
+ signal,
54
+ });
55
+ if (!response.ok) {
56
+ throw new TypeError(`DNS lookup of the metadata host failed (${type})`);
57
+ }
58
+ // The DoH JSON answer is read as the shape `DohAnswer` names; a field of
59
+ // another type fails the `typeof` checks below.
60
+ const body = (await response.json()) as DohAnswer;
61
+ if (body.Status !== 0) {
62
+ throw new TypeError(
63
+ `DNS lookup of the metadata host answered status ${body.Status}`,
64
+ );
65
+ }
66
+ return (body.Answer ?? []).flatMap((record) =>
67
+ record.type === type && typeof record.data === "string"
68
+ ? [record.data]
69
+ : [],
70
+ );
71
+ }
72
+
73
+ export async function fetchClientMetadataResource(
74
+ input: RequestInfo | URL,
75
+ init?: RequestInit,
76
+ ): Promise<Response> {
77
+ const request = new Request(input, init);
78
+ const url = new URL(request.url);
79
+ if (url.protocol !== "https:") {
80
+ throw new TypeError("CIMD transport requires an HTTPS URL");
81
+ }
82
+ if (request.method !== "GET" && request.method !== "HEAD") {
83
+ throw new TypeError("CIMD transport supports only GET and HEAD");
84
+ }
85
+ if (isIpLiteral(url.hostname)) {
86
+ throw new TypeError("CIMD transport refuses an IP literal host");
87
+ }
88
+ if (isSpecialUseName(url.hostname)) {
89
+ throw new TypeError("CIMD transport refuses a special-use host name");
90
+ }
91
+
92
+ const signal =
93
+ init?.signal ?? (input instanceof Request ? input.signal : undefined);
94
+ const [v4, v6] = await Promise.all([
95
+ resolveAddresses(url.hostname, TYPE_A, signal),
96
+ resolveAddresses(url.hostname, TYPE_AAAA, signal),
97
+ ]);
98
+ const addresses = [...v4, ...v6];
99
+ if (addresses.length === 0) {
100
+ throw new TypeError("metadata hostname returned no DNS addresses");
101
+ }
102
+ if (!addresses.every((address) => isPublicRoutableHost(address))) {
103
+ throw new TypeError(
104
+ "metadata hostname must resolve only to public-routable addresses",
105
+ );
106
+ }
107
+
108
+ // A redirect comes back as the 302 it is: the caller refuses it.
109
+ return globalThis.fetch(url, {
110
+ method: request.method,
111
+ headers: request.headers,
112
+ redirect: "manual",
113
+ signal,
114
+ });
115
+ }
@@ -0,0 +1,83 @@
1
+ import { apiKey } from "@better-auth/api-key";
2
+ import type { BetterAuthPlugin } from "better-auth";
3
+ import { APIError, createAuthMiddleware } from "better-auth/api";
4
+ import { DEVICE_KEY_LENGTH, DEVICE_KEY_PREFIX } from "./outputs.ts";
5
+
6
+ // Device credentials: docs/architecture/plugins/auth.md, "Devices".
7
+
8
+ // Calls one key may make in a window, enforced in the database row, so it
9
+ // holds on Node as on Cloudflare. Pinned, not options: a daemon that batches
10
+ // stays far under it, and one that loops is the case it exists for.
11
+ const RATE_LIMIT = { timeWindow: 60_000, maxRequests: 600 };
12
+
13
+ // Longest name a member can give a device.
14
+ export const DEVICE_NAME_MAX = 40;
15
+
16
+ // Furthest a key's expiry may be set, in days; a key made without one does
17
+ // not expire.
18
+ export const DEVICE_EXPIRES_MAX_DAYS = 365;
19
+
20
+ const BEARER = new RegExp(`^bearer\\s+(${DEVICE_KEY_PREFIX}\\S+)$`, "i");
21
+
22
+ // The device key the request carries, or null. Anything else in the header is
23
+ // not ours and is left to the plugins that read it.
24
+ export function deviceCredential(
25
+ headers: Headers | undefined | null,
26
+ ): string | null {
27
+ const value = headers?.get("authorization")?.trim();
28
+ return (value && BEARER.exec(value)?.[1]) || null;
29
+ }
30
+
31
+ // Auth endpoints a device key may reach: docs/architecture/plugins/auth.md, "Devices".
32
+ const DEVICE_ENDPOINTS = new Set([
33
+ "/get-session",
34
+ "/organization/list",
35
+ "/organization/get-full-organization",
36
+ "/organization/get-active-member",
37
+ "/organization/list-members",
38
+ "/organization/has-permission",
39
+ ]);
40
+
41
+ const DEVICE_REFUSED = "DEVICE_CREDENTIAL_REFUSED";
42
+
43
+ // Registered before the key plugin, so it refuses before a key is spent.
44
+ const guard: BetterAuthPlugin = {
45
+ id: "device-guard",
46
+ hooks: {
47
+ before: [
48
+ {
49
+ matcher: (ctx) =>
50
+ deviceCredential(ctx.headers) !== null &&
51
+ !DEVICE_ENDPOINTS.has(ctx.path ?? ""),
52
+ handler: createAuthMiddleware(async () => {
53
+ throw new APIError("FORBIDDEN", {
54
+ code: DEVICE_REFUSED,
55
+ message: "A device credential cannot call this endpoint.",
56
+ });
57
+ }),
58
+ },
59
+ ],
60
+ },
61
+ };
62
+
63
+ export function devicePlugins(): BetterAuthPlugin[] {
64
+ return [
65
+ guard,
66
+ apiKey({
67
+ defaultPrefix: DEVICE_KEY_PREFIX,
68
+ defaultKeyLength: DEVICE_KEY_LENGTH,
69
+ requireName: true,
70
+ maximumNameLength: DEVICE_NAME_MAX,
71
+ enableMetadata: false,
72
+ // The key stands in for the session on `get-session`.
73
+ enableSessionForAPIKeys: true,
74
+ customAPIKeyGetter: (ctx) => deviceCredential(ctx.headers),
75
+ rateLimit: { enabled: true, ...RATE_LIMIT },
76
+ keyExpiration: {
77
+ defaultExpiresIn: null,
78
+ minExpiresIn: 1,
79
+ maxExpiresIn: DEVICE_EXPIRES_MAX_DAYS,
80
+ },
81
+ }),
82
+ ];
83
+ }
@@ -0,0 +1,21 @@
1
+ // Folds addressing variants of the same inbox into one canonical key, so
2
+ // per-email rate limiting can't be evaded by `+tag` or (Gmail-only) dot
3
+ // placement. Not a general-purpose email normalizer — narrow to the abuse
4
+ // surface it defends.
5
+ const DOT_FOLDING_DOMAINS = new Set(["gmail.com", "googlemail.com"]);
6
+
7
+ export function emailKey(email: string): string {
8
+ const lower = email.toLowerCase();
9
+ const at = lower.lastIndexOf("@");
10
+ if (at === -1) return lower;
11
+
12
+ const domain = lower.slice(at + 1);
13
+ let local = lower.slice(0, at);
14
+
15
+ const plus = local.indexOf("+");
16
+ if (plus !== -1) local = local.slice(0, plus);
17
+
18
+ if (DOT_FOLDING_DOMAINS.has(domain)) local = local.replaceAll(".", "");
19
+
20
+ return `${local}@${domain}`;
21
+ }