@gadicc/loom 1.34.0 → 1.35.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.
Files changed (104) hide show
  1. package/README.md +126 -49
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +3060 -451
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +3061 -451
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +125 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
@@ -1,4 +1,39 @@
1
- import type { ApiKeyCredentialExtractionResult, ApiKeyCredentialOptions, ApiKeyCredentialSource } from "./types.js";
2
- /** Extracts exactly one API-key credential without selecting a precedence. */
1
+ import type { ApiKeyCredentialExtractionResult, ApiKeyCredentialOptions, ApiKeyCredentialSource, ApiKeyCredentialTransport } from "./types.js";
2
+ /** `ApiKeyCredentialOptions` with Loom's defaults applied. */
3
+ export type ResolvedApiKeyCredentialOptions = Required<ApiKeyCredentialOptions>;
4
+ /**
5
+ * Applies Loom's credential defaults: Bearer and the `x-api-key` header are
6
+ * accepted unless disabled, and query credentials only when enabled.
7
+ * `extractApiKeyCredential` uses the same resolution.
8
+ */
9
+ export declare function resolveApiKeyCredentialOptions(options?: ApiKeyCredentialOptions): ResolvedApiKeyCredentialOptions;
10
+ /** The accepted transports of one `ApiKeyCredentialOptions`, for UI copy. */
11
+ export interface ApiKeyTransportDescription {
12
+ /** Accepted transports in preference order: Bearer, header, query. */
13
+ accepted: ApiKeyCredentialTransport[];
14
+ /** Whether `Authorization: Bearer <key>` is accepted. */
15
+ bearer: boolean;
16
+ /** The accepted `x-api-key` header name, or `null` when disabled. */
17
+ headerName: string | null;
18
+ /**
19
+ * The transport to recommend: Bearer when enabled, otherwise the header,
20
+ * and the query parameter only when it is the sole option. `null` when no
21
+ * transport is accepted.
22
+ */
23
+ preferred: ApiKeyCredentialTransport | null;
24
+ /** The accepted query parameter name, or `null` when disabled. */
25
+ queryName: string | null;
26
+ }
27
+ /**
28
+ * Describes which transports `options` accept and which to recommend, so UI
29
+ * copy can derive from the same object the authorizer uses. Pure and
30
+ * import-free at runtime, so client components can call it.
31
+ */
32
+ export declare function describeApiKeyTransports(options?: ApiKeyCredentialOptions): ApiKeyTransportDescription;
33
+ /**
34
+ * Extracts exactly one API-key credential without selecting a precedence.
35
+ * Several transports, a repeated header (a comma in its value), or a repeated
36
+ * query parameter are `ambiguous`.
37
+ */
3
38
  export declare function extractApiKeyCredential(source: ApiKeyCredentialSource, options?: ApiKeyCredentialOptions): ApiKeyCredentialExtractionResult;
4
39
  //# sourceMappingURL=credentials.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/credentials.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,EAEvB,MAAM,YAAY,CAAC;AAgCpB,8EAA8E;AAC9E,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,uBAA4B,GACpC,gCAAgC,CAwClC"}
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/credentials.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,EACtB,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAKpB,8DAA8D;AAC9D,MAAM,MAAM,+BAA+B,GAAG,QAAQ,CAAC,uBAAuB,CAAC,CAAC;AAEhF;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,OAAO,GAAE,uBAA4B,GACpC,+BAA+B,CAQjC;AAED,6EAA6E;AAC7E,MAAM,WAAW,0BAA0B;IACzC,sEAAsE;IACtE,QAAQ,EAAE,yBAAyB,EAAE,CAAC;IACtC,yDAAyD;IACzD,MAAM,EAAE,OAAO,CAAC;IAChB,qEAAqE;IACrE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B;;;;OAIG;IACH,SAAS,EAAE,yBAAyB,GAAG,IAAI,CAAC;IAC5C,kEAAkE;IAClE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,GAAE,uBAA4B,GACpC,0BAA0B,CAa5B;AAuDD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,uBAA4B,GACpC,gCAAgC,CAsClC"}
@@ -1,10 +1,57 @@
1
1
  const DEFAULT_QUERY_NAME = "apiKey";
2
2
  const DEFAULT_X_API_KEY_HEADER = "x-api-key";
3
+ /**
4
+ * Applies Loom's credential defaults: Bearer and the `x-api-key` header are
5
+ * accepted unless disabled, and query credentials only when enabled.
6
+ * `extractApiKeyCredential` uses the same resolution.
7
+ */
8
+ export function resolveApiKeyCredentialOptions(options = {}) {
9
+ return {
10
+ allowAuthorizationBearer: options.allowAuthorizationBearer !== false,
11
+ allowQuery: options.allowQuery === true,
12
+ allowXApiKey: options.allowXApiKey !== false,
13
+ queryName: options.queryName ?? DEFAULT_QUERY_NAME,
14
+ xApiKeyHeaderName: options.xApiKeyHeaderName ?? DEFAULT_X_API_KEY_HEADER,
15
+ };
16
+ }
17
+ /**
18
+ * Describes which transports `options` accept and which to recommend, so UI
19
+ * copy can derive from the same object the authorizer uses. Pure and
20
+ * import-free at runtime, so client components can call it.
21
+ */
22
+ export function describeApiKeyTransports(options = {}) {
23
+ const resolved = resolveApiKeyCredentialOptions(options);
24
+ const accepted = [];
25
+ if (resolved.allowAuthorizationBearer)
26
+ accepted.push("authorization-bearer");
27
+ if (resolved.allowXApiKey)
28
+ accepted.push("x-api-key");
29
+ if (resolved.allowQuery)
30
+ accepted.push("query");
31
+ return {
32
+ accepted,
33
+ bearer: resolved.allowAuthorizationBearer,
34
+ headerName: resolved.allowXApiKey ? resolved.xApiKeyHeaderName : null,
35
+ preferred: accepted[0] ?? null,
36
+ queryName: resolved.allowQuery ? resolved.queryName : null,
37
+ };
38
+ }
39
+ // API keys and Bearer tokens (RFC 6750) never contain a comma, so a comma
40
+ // means several credentials arrived, never one key. Repeated `x-api-key` lines
41
+ // reach `Headers.get` joined with ", " on Node and in fetch runtimes. Node's
42
+ // HTTP parser instead keeps only the first of repeated `Authorization` lines,
43
+ // so there the comma check only covers a literal comma in the header (and any
44
+ // runtime that joins); the first value still goes through full verification.
3
45
  function bearerCandidate(headers) {
4
46
  const value = headers.get("authorization");
5
47
  if (value === null)
6
48
  return null;
7
- const match = /^Bearer ([^\s]+)$/.exec(value);
49
+ if (value.includes(",")) {
50
+ return { ambiguous: true, transport: "authorization-bearer" };
51
+ }
52
+ // The auth-scheme name is case-insensitive (RFC 7235); the single space
53
+ // and the whitespace-free token are not relaxed.
54
+ const match = /^Bearer ([^\s]+)$/i.exec(value);
8
55
  return match
9
56
  ? { credential: match[1], transport: "authorization-bearer" }
10
57
  : { malformed: true, transport: "authorization-bearer" };
@@ -12,32 +59,46 @@ function bearerCandidate(headers) {
12
59
  function valueCandidate(value, transport) {
13
60
  if (value === null)
14
61
  return null;
62
+ if (transport === "x-api-key" && value.includes(",")) {
63
+ return { ambiguous: true, transport };
64
+ }
15
65
  if (value.trim() === "" || value !== value.trim()) {
16
66
  return { malformed: true, transport };
17
67
  }
18
68
  return { credential: value, transport };
19
69
  }
20
- /** Extracts exactly one API-key credential without selecting a precedence. */
70
+ function queryCandidate(searchParams, name) {
71
+ const values = searchParams?.getAll(name) ?? [];
72
+ if (values.length > 1)
73
+ return { ambiguous: true, transport: "query" };
74
+ return valueCandidate(values[0] ?? null, "query");
75
+ }
76
+ /**
77
+ * Extracts exactly one API-key credential without selecting a precedence.
78
+ * Several transports, a repeated header (a comma in its value), or a repeated
79
+ * query parameter are `ambiguous`.
80
+ */
21
81
  export function extractApiKeyCredential(source, options = {}) {
82
+ const resolved = resolveApiKeyCredentialOptions(options);
22
83
  const candidates = [];
23
- if (options.allowAuthorizationBearer !== false) {
84
+ if (resolved.allowAuthorizationBearer) {
24
85
  const candidate = bearerCandidate(source.headers);
25
86
  if (candidate)
26
87
  candidates.push(candidate);
27
88
  }
28
- if (options.allowXApiKey !== false) {
29
- const candidate = valueCandidate(source.headers.get(options.xApiKeyHeaderName ?? DEFAULT_X_API_KEY_HEADER), "x-api-key");
89
+ if (resolved.allowXApiKey) {
90
+ const candidate = valueCandidate(source.headers.get(resolved.xApiKeyHeaderName), "x-api-key");
30
91
  if (candidate)
31
92
  candidates.push(candidate);
32
93
  }
33
- if (options.allowQuery === true) {
34
- const candidate = valueCandidate(source.searchParams?.get(options.queryName ?? DEFAULT_QUERY_NAME) ?? null, "query");
94
+ if (resolved.allowQuery) {
95
+ const candidate = queryCandidate(source.searchParams, resolved.queryName);
35
96
  if (candidate)
36
97
  candidates.push(candidate);
37
98
  }
38
99
  if (candidates.length === 0)
39
100
  return { kind: "missing" };
40
- if (candidates.length > 1) {
101
+ if (candidates.length > 1 || candidates.some((candidate) => candidate.ambiguous)) {
41
102
  return {
42
103
  kind: "ambiguous",
43
104
  transports: candidates.map((candidate) => candidate.transport),
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Type-only contracts shared by an app's API-key lifecycle server actions and
3
+ * the optional MUI components. This module has no runtime code, so server
4
+ * action files can import these types without touching a client module.
5
+ */
6
+ /** Input collected by the create dialog and passed to `onCreate`. */
7
+ export interface ApiKeyCreateInput {
8
+ /**
9
+ * ISO timestamp, or `null` when "Never" was chosen. The plugin then applies
10
+ * `keyExpiration.defaultExpiresIn`, which must be `null` for "Never".
11
+ */
12
+ expiresAt: string | null;
13
+ /** Trimmed key name. */
14
+ name: string;
15
+ scopeIds: string[];
16
+ }
17
+ /** The one-time secret and display fields returned after key creation. */
18
+ export interface ApiKeyCreateResult {
19
+ key: string;
20
+ keyStart?: string;
21
+ name: string;
22
+ }
23
+ /**
24
+ * A user-correctable failure returned, rather than thrown, by a lifecycle
25
+ * action. Next.js replaces thrown Server Function messages with a generic one
26
+ * in production, so return this for messages the user must see.
27
+ */
28
+ export type ApiKeyActionFailure = {
29
+ message: string;
30
+ ok: false;
31
+ };
32
+ /** Result-returning form of a create action (`onCreate`). */
33
+ export type ApiKeyCreateActionResult = {
34
+ created: ApiKeyCreateResult;
35
+ ok: true;
36
+ } | ApiKeyActionFailure;
37
+ /** Result-returning form of a rename or revoke action. */
38
+ export type ApiKeyMutationResult = {
39
+ ok: true;
40
+ } | ApiKeyActionFailure;
41
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/lifecycle.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,qEAAqE;AACrE,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,wBAAwB;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,0EAA0E;AAC1E,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,KAAK,CAAA;CAAE,CAAC;AAEjE,6DAA6D;AAC7D,MAAM,MAAM,wBAAwB,GAChC;IAAE,OAAO,EAAE,kBAAkB,CAAC;IAAC,EAAE,EAAE,IAAI,CAAA;CAAE,GACzC,mBAAmB,CAAC;AAExB,0DAA0D;AAC1D,MAAM,MAAM,oBAAoB,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG,mBAAmB,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Type-only contracts shared by an app's API-key lifecycle server actions and
3
+ * the optional MUI components. This module has no runtime code, so server
4
+ * action files can import these types without touching a client module.
5
+ */
6
+ export {};
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Bounds shared by API-key lifecycle validation, the MUI dialogs, and the
3
+ * consumer's Better Auth api-key plugin configuration.
4
+ *
5
+ * Pass the same values to the plugin (see `betterAuthApiKeyLimitOptions`) and
6
+ * to these validators so input the app accepts is never rejected later by the
7
+ * plugin with a raw library message.
8
+ */
9
+ export interface ApiKeyLimits {
10
+ /**
11
+ * Longest custom expiry, in days (plugin `keyExpiration.maxExpiresIn`).
12
+ * Keys created without an expiry never expire and are not bound by this.
13
+ */
14
+ maxExpiresInDays: number;
15
+ /** Longest trimmed key name (plugin `maximumNameLength`). */
16
+ maxNameLength: number;
17
+ /** Shortest custom expiry, in days (plugin `keyExpiration.minExpiresIn`). */
18
+ minExpiresInDays: number;
19
+ /** Shortest trimmed key name (plugin `minimumNameLength`). At least 1. */
20
+ minNameLength: number;
21
+ }
22
+ /** A validated value, or a message that is safe to show to the user. */
23
+ export type ApiKeyValidationResult<TValue> = {
24
+ ok: true;
25
+ value: TValue;
26
+ } | {
27
+ message: string;
28
+ ok: false;
29
+ };
30
+ /** User-facing messages derived from one set of limits. */
31
+ export interface ApiKeyLimitMessages {
32
+ /** A custom expiry that is not a parseable date. */
33
+ expiryInvalid: string;
34
+ /** No expiry was chosen although no-expiry keys are not allowed. */
35
+ expiryRequired: string;
36
+ /** A custom expiry beyond `maxExpiresInDays`. */
37
+ expiryTooLate: string;
38
+ /** A custom expiry before `minExpiresInDays`, or not in the future. */
39
+ expiryTooSoon: string;
40
+ /** A blank or out-of-range trimmed key name. */
41
+ nameLength: string;
42
+ }
43
+ /** Options for `resolveApiKeyExpiresIn`. */
44
+ export interface ResolveApiKeyExpiresInOptions {
45
+ /**
46
+ * Whether a missing expiry (`null`/`undefined`) is accepted. It means
47
+ * "never expires" only while the plugin's `keyExpiration.defaultExpiresIn`
48
+ * is `null`. Defaults to `true`; pass `false` when the app requires every
49
+ * key to expire.
50
+ */
51
+ allowNoExpiry?: boolean;
52
+ /** Reference time; defaults to `Date.now()`. */
53
+ now?: Date | number;
54
+ /**
55
+ * Slack, in seconds, for an expiry chosen right at a limit. Defaults to
56
+ * `API_KEY_EXPIRY_TOLERANCE_SECONDS`.
57
+ */
58
+ toleranceSeconds?: number;
59
+ }
60
+ /** Better Auth api-key plugin options derived from `ApiKeyLimits`. */
61
+ export interface BetterAuthApiKeyLimitOptions {
62
+ /** Both values are in days, matching the plugin. */
63
+ keyExpiration: {
64
+ maxExpiresIn: number;
65
+ minExpiresIn: number;
66
+ };
67
+ maximumNameLength: number;
68
+ minimumNameLength: number;
69
+ }
70
+ /** Seconds in one day; the plugin compares `expiresIn / 86400` to its limits. */
71
+ export declare const API_KEY_SECONDS_PER_DAY = 86400;
72
+ /**
73
+ * Default slack for a custom expiry chosen right at a limit. The browser
74
+ * converts the chosen date before the request reaches the server, and clocks
75
+ * drift, so "one day from now" arrives a little under one day away. Values
76
+ * within this slack are clamped onto the limit instead of being rejected.
77
+ */
78
+ export declare const API_KEY_EXPIRY_TOLERANCE_SECONDS = 300;
79
+ /**
80
+ * Builds the user-facing messages for one set of limits.
81
+ *
82
+ * Server validation, the MUI dialogs, and `betterAuthApiKeyInputErrorMessage`
83
+ * all use these, so the same input produces the same text everywhere. Bounds
84
+ * omitted from `limits` fall back to the generic messages Loom's dialogs used
85
+ * before limits existed.
86
+ */
87
+ export declare function apiKeyLimitMessages(limits: Partial<ApiKeyLimits>): ApiKeyLimitMessages;
88
+ /**
89
+ * Validates and trims an untrusted key name.
90
+ *
91
+ * Accepts `unknown` because server-action arguments are untrusted. A blank
92
+ * name is always rejected. Omitted bounds are not enforced here, so pass the
93
+ * same complete `ApiKeyLimits` given to the plugin.
94
+ */
95
+ export declare function validateApiKeyName(name: unknown, limits: Partial<ApiKeyLimits>): ApiKeyValidationResult<string>;
96
+ /**
97
+ * Converts an untrusted absolute expiry into the plugin's relative
98
+ * `expiresIn` seconds, or `null` when no expiry was chosen.
99
+ *
100
+ * Only strings are accepted (parsed with `Date`; send ISO timestamps), and
101
+ * `null`/`undefined` mean no expiry unless `allowNoExpiry` is `false`. Values
102
+ * beyond the tolerance past a limit are rejected with a readable message;
103
+ * values within it are clamped onto the limit, so a returned number always
104
+ * lies inside the plugin's inclusive bounds. The result is never below 1,
105
+ * because the plugin treats a falsy `expiresIn` as "not given". Pass
106
+ * `value ?? undefined` to `createApiKey`.
107
+ *
108
+ * For a key without `expiresIn` the plugin applies
109
+ * `keyExpiration.defaultExpiresIn`, so `null` only means "never expires"
110
+ * while that option is `null` (the plugin default).
111
+ */
112
+ export declare function resolveApiKeyExpiresIn(expiresAt: unknown, limits: Partial<ApiKeyLimits>, options?: ResolveApiKeyExpiresInOptions): ApiKeyValidationResult<number | null>;
113
+ /**
114
+ * Maps a correctable Better Auth api-key plugin rejection to the same message
115
+ * local validation would show, or returns `null` for anything else.
116
+ *
117
+ * Structural, like Better Auth's own `isAPIError`: it reads `error.body.code`
118
+ * from an error named `APIError` without importing Better Auth. Every other
119
+ * error, including other plugin codes, returns `null` and should be rethrown
120
+ * unchanged.
121
+ */
122
+ export declare function betterAuthApiKeyInputErrorMessage(error: unknown, limits: ApiKeyLimits): string | null;
123
+ /**
124
+ * Returns the Better Auth api-key plugin options that enforce `limits`.
125
+ *
126
+ * Merge `keyExpiration` with any other expiration options the app sets, for
127
+ * example `keyExpiration: { ...options.keyExpiration, defaultExpiresIn: null }`.
128
+ * It deliberately leaves `defaultExpiresIn` alone: keep it `null` (the plugin
129
+ * default) when "Never" should mean a key that never expires.
130
+ */
131
+ export declare function betterAuthApiKeyLimitOptions(limits: ApiKeyLimits): BetterAuthApiKeyLimitOptions;
132
+ //# sourceMappingURL=limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/limits.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,gBAAgB,EAAE,MAAM,CAAC;IACzB,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,6EAA6E;IAC7E,gBAAgB,EAAE,MAAM,CAAC;IACzB,0EAA0E;IAC1E,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,wEAAwE;AACxE,MAAM,MAAM,sBAAsB,CAAC,MAAM,IACrC;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,KAAK,CAAA;CAAE,CAAC;AAEnC,2DAA2D;AAC3D,MAAM,WAAW,mBAAmB;IAClC,oDAAoD;IACpD,aAAa,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,cAAc,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,aAAa,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,aAAa,EAAE,MAAM,CAAC;IACtB,gDAAgD;IAChD,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,4CAA4C;AAC5C,MAAM,WAAW,6BAA6B;IAC5C;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,gDAAgD;IAChD,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IACpB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,sEAAsE;AACtE,MAAM,WAAW,4BAA4B;IAC3C,oDAAoD;IACpD,aAAa,EAAE;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9D,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,iFAAiF;AACjF,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAE9C;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,MAAM,CAAC;AAwFpD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,GAC5B,mBAAmB,CA4BrB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,OAAO,EACb,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,GAC5B,sBAAsB,CAAC,MAAM,CAAC,CAahC;AAcD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,OAAO,EAClB,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,EAC7B,OAAO,GAAE,6BAAkC,GAC1C,sBAAsB,CAAC,MAAM,GAAG,IAAI,CAAC,CA4CvC;AAiBD;;;;;;;;GAQG;AACH,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,YAAY,GACnB,MAAM,GAAG,IAAI,CAcf;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,YAAY,GACnB,4BAA4B,CAU9B"}
@@ -0,0 +1,246 @@
1
+ /** Seconds in one day; the plugin compares `expiresIn / 86400` to its limits. */
2
+ export const API_KEY_SECONDS_PER_DAY = 86_400;
3
+ /**
4
+ * Default slack for a custom expiry chosen right at a limit. The browser
5
+ * converts the chosen date before the request reaches the server, and clocks
6
+ * drift, so "one day from now" arrives a little under one day away. Values
7
+ * within this slack are clamped onto the limit instead of being rejected.
8
+ */
9
+ export const API_KEY_EXPIRY_TOLERANCE_SECONDS = 300;
10
+ const NAME_REQUIRED_MESSAGE = "Enter a name for this key.";
11
+ const EXPIRY_IN_FUTURE_MESSAGE = "Choose a future expiry date.";
12
+ function formatDays(days) {
13
+ return days === 1 ? "1 day" : `${days} days`;
14
+ }
15
+ function formatCharacters(count) {
16
+ return count === 1 ? "1 character" : `${count} characters`;
17
+ }
18
+ function assertDays(field, value) {
19
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
20
+ throw new Error(`Invalid API-key limits: ${field} must be a finite number of days >= 0.`);
21
+ }
22
+ }
23
+ function assertNameLength(field, value) {
24
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
25
+ throw new Error(`Invalid API-key limits: ${field} must be a safe integer >= 1.`);
26
+ }
27
+ }
28
+ /**
29
+ * Rejects malformed limits so a misconfiguration fails loudly rather than
30
+ * silently validating nothing. Omitted fields are allowed here; the public
31
+ * Better Auth helpers require every field through their types.
32
+ */
33
+ function assertLimits(limits) {
34
+ if (!limits || typeof limits !== "object") {
35
+ throw new Error("Invalid API-key limits: expected an object.");
36
+ }
37
+ const { maxExpiresInDays, maxNameLength, minExpiresInDays, minNameLength } = limits;
38
+ if (minExpiresInDays !== undefined) {
39
+ assertDays("minExpiresInDays", minExpiresInDays);
40
+ }
41
+ if (maxExpiresInDays !== undefined) {
42
+ assertDays("maxExpiresInDays", maxExpiresInDays);
43
+ }
44
+ if (minNameLength !== undefined) {
45
+ assertNameLength("minNameLength", minNameLength);
46
+ }
47
+ if (maxNameLength !== undefined) {
48
+ assertNameLength("maxNameLength", maxNameLength);
49
+ }
50
+ if (minExpiresInDays !== undefined && maxExpiresInDays !== undefined &&
51
+ minExpiresInDays > maxExpiresInDays) {
52
+ throw new Error("Invalid API-key limits: minExpiresInDays exceeds maxExpiresInDays.");
53
+ }
54
+ if (minNameLength !== undefined && maxNameLength !== undefined &&
55
+ minNameLength > maxNameLength) {
56
+ throw new Error("Invalid API-key limits: minNameLength exceeds maxNameLength.");
57
+ }
58
+ }
59
+ function assertCompleteLimits(limits) {
60
+ assertLimits(limits);
61
+ for (const field of [
62
+ "maxExpiresInDays",
63
+ "maxNameLength",
64
+ "minExpiresInDays",
65
+ "minNameLength",
66
+ ]) {
67
+ if (limits[field] === undefined) {
68
+ throw new Error(`Invalid API-key limits: ${field} is required.`);
69
+ }
70
+ }
71
+ }
72
+ /**
73
+ * Builds the user-facing messages for one set of limits.
74
+ *
75
+ * Server validation, the MUI dialogs, and `betterAuthApiKeyInputErrorMessage`
76
+ * all use these, so the same input produces the same text everywhere. Bounds
77
+ * omitted from `limits` fall back to the generic messages Loom's dialogs used
78
+ * before limits existed.
79
+ */
80
+ export function apiKeyLimitMessages(limits) {
81
+ assertLimits(limits);
82
+ const { maxExpiresInDays, maxNameLength, minExpiresInDays, minNameLength } = limits;
83
+ let nameLength = NAME_REQUIRED_MESSAGE;
84
+ if (minNameLength !== undefined && maxNameLength !== undefined) {
85
+ nameLength =
86
+ `Key names must be between ${minNameLength} and ${maxNameLength} characters.`;
87
+ }
88
+ else if (maxNameLength !== undefined) {
89
+ nameLength = `Key names must be at most ${formatCharacters(maxNameLength)}.`;
90
+ }
91
+ else if (minNameLength !== undefined) {
92
+ nameLength = `Key names must be at least ${formatCharacters(minNameLength)}.`;
93
+ }
94
+ return {
95
+ expiryInvalid: "Expiry must be a valid date.",
96
+ expiryRequired: "Choose an expiry date.",
97
+ expiryTooLate: maxExpiresInDays === undefined
98
+ ? "Expiry is too far in the future."
99
+ : `Expiry must be no more than ${formatDays(maxExpiresInDays)} from now.`,
100
+ expiryTooSoon: minExpiresInDays === undefined || minExpiresInDays === 0
101
+ ? EXPIRY_IN_FUTURE_MESSAGE
102
+ : `Expiry must be at least ${formatDays(minExpiresInDays)} from now.`,
103
+ nameLength,
104
+ };
105
+ }
106
+ /**
107
+ * Validates and trims an untrusted key name.
108
+ *
109
+ * Accepts `unknown` because server-action arguments are untrusted. A blank
110
+ * name is always rejected. Omitted bounds are not enforced here, so pass the
111
+ * same complete `ApiKeyLimits` given to the plugin.
112
+ */
113
+ export function validateApiKeyName(name, limits) {
114
+ const messages = apiKeyLimitMessages(limits);
115
+ const trimmed = typeof name === "string" ? name.trim() : "";
116
+ if (trimmed.length === 0 ||
117
+ (limits.minNameLength !== undefined &&
118
+ trimmed.length < limits.minNameLength) ||
119
+ (limits.maxNameLength !== undefined &&
120
+ trimmed.length > limits.maxNameLength)) {
121
+ return { message: messages.nameLength, ok: false };
122
+ }
123
+ return { ok: true, value: trimmed };
124
+ }
125
+ function referenceTime(now) {
126
+ const value = now === undefined
127
+ ? Date.now()
128
+ : typeof now === "number"
129
+ ? now
130
+ : now.valueOf();
131
+ if (!Number.isFinite(value)) {
132
+ throw new Error("resolveApiKeyExpiresIn: `now` must be a valid time.");
133
+ }
134
+ return value;
135
+ }
136
+ /**
137
+ * Converts an untrusted absolute expiry into the plugin's relative
138
+ * `expiresIn` seconds, or `null` when no expiry was chosen.
139
+ *
140
+ * Only strings are accepted (parsed with `Date`; send ISO timestamps), and
141
+ * `null`/`undefined` mean no expiry unless `allowNoExpiry` is `false`. Values
142
+ * beyond the tolerance past a limit are rejected with a readable message;
143
+ * values within it are clamped onto the limit, so a returned number always
144
+ * lies inside the plugin's inclusive bounds. The result is never below 1,
145
+ * because the plugin treats a falsy `expiresIn` as "not given". Pass
146
+ * `value ?? undefined` to `createApiKey`.
147
+ *
148
+ * For a key without `expiresIn` the plugin applies
149
+ * `keyExpiration.defaultExpiresIn`, so `null` only means "never expires"
150
+ * while that option is `null` (the plugin default).
151
+ */
152
+ export function resolveApiKeyExpiresIn(expiresAt, limits, options = {}) {
153
+ const messages = apiKeyLimitMessages(limits);
154
+ const tolerance = options.toleranceSeconds ??
155
+ API_KEY_EXPIRY_TOLERANCE_SECONDS;
156
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
157
+ throw new Error("resolveApiKeyExpiresIn: toleranceSeconds must be a finite number >= 0.");
158
+ }
159
+ if (expiresAt === null || expiresAt === undefined) {
160
+ return options.allowNoExpiry === false
161
+ ? { message: messages.expiryRequired, ok: false }
162
+ : { ok: true, value: null };
163
+ }
164
+ const target = typeof expiresAt === "string"
165
+ ? new Date(expiresAt).valueOf()
166
+ : Number.NaN;
167
+ if (!Number.isFinite(target)) {
168
+ return { message: messages.expiryInvalid, ok: false };
169
+ }
170
+ const seconds = Math.floor((target - referenceTime(options.now)) / 1000);
171
+ // The slack only ever applies above "in the future": a past expiry is never
172
+ // clamped into a valid one, whatever the configured minimum.
173
+ const minSeconds = (limits.minExpiresInDays ?? 0) * API_KEY_SECONDS_PER_DAY;
174
+ if (seconds < Math.max(1, minSeconds - tolerance)) {
175
+ return { message: messages.expiryTooSoon, ok: false };
176
+ }
177
+ if (limits.maxExpiresInDays !== undefined) {
178
+ const maxSeconds = limits.maxExpiresInDays * API_KEY_SECONDS_PER_DAY;
179
+ if (seconds > maxSeconds + tolerance) {
180
+ return { message: messages.expiryTooLate, ok: false };
181
+ }
182
+ }
183
+ const lower = Math.max(1, Math.ceil(minSeconds));
184
+ const upper = limits.maxExpiresInDays === undefined
185
+ ? Number.POSITIVE_INFINITY
186
+ : Math.floor(limits.maxExpiresInDays * API_KEY_SECONDS_PER_DAY);
187
+ if (upper < lower) {
188
+ // A sub-second maximum cannot express any expiry the plugin accepts.
189
+ return { message: messages.expiryTooLate, ok: false };
190
+ }
191
+ return { ok: true, value: Math.min(Math.max(seconds, lower), upper) };
192
+ }
193
+ /**
194
+ * Plugin rejection codes a user can correct, mapped to message keys. Local
195
+ * validation with the same limits should make these unreachable; mapping them
196
+ * keeps configuration drift from showing a raw library message.
197
+ */
198
+ const BETTER_AUTH_INPUT_ERROR_MESSAGE_KEYS = new Map([
199
+ ["EXPIRES_IN_IS_TOO_SMALL", "expiryTooSoon"],
200
+ ["EXPIRES_IN_IS_TOO_LARGE", "expiryTooLate"],
201
+ ["INVALID_NAME_LENGTH", "nameLength"],
202
+ ["NAME_REQUIRED", "nameLength"],
203
+ ]);
204
+ /**
205
+ * Maps a correctable Better Auth api-key plugin rejection to the same message
206
+ * local validation would show, or returns `null` for anything else.
207
+ *
208
+ * Structural, like Better Auth's own `isAPIError`: it reads `error.body.code`
209
+ * from an error named `APIError` without importing Better Auth. Every other
210
+ * error, including other plugin codes, returns `null` and should be rethrown
211
+ * unchanged.
212
+ */
213
+ export function betterAuthApiKeyInputErrorMessage(error, limits) {
214
+ assertCompleteLimits(limits);
215
+ if (!error || typeof error !== "object" ||
216
+ error.name !== "APIError") {
217
+ return null;
218
+ }
219
+ const body = error.body;
220
+ if (!body || typeof body !== "object")
221
+ return null;
222
+ const code = body.code;
223
+ if (typeof code !== "string")
224
+ return null;
225
+ const key = BETTER_AUTH_INPUT_ERROR_MESSAGE_KEYS.get(code);
226
+ return key ? apiKeyLimitMessages(limits)[key] : null;
227
+ }
228
+ /**
229
+ * Returns the Better Auth api-key plugin options that enforce `limits`.
230
+ *
231
+ * Merge `keyExpiration` with any other expiration options the app sets, for
232
+ * example `keyExpiration: { ...options.keyExpiration, defaultExpiresIn: null }`.
233
+ * It deliberately leaves `defaultExpiresIn` alone: keep it `null` (the plugin
234
+ * default) when "Never" should mean a key that never expires.
235
+ */
236
+ export function betterAuthApiKeyLimitOptions(limits) {
237
+ assertCompleteLimits(limits);
238
+ return {
239
+ keyExpiration: {
240
+ maxExpiresIn: limits.maxExpiresInDays,
241
+ minExpiresIn: limits.minExpiresInDays,
242
+ },
243
+ maximumNameLength: limits.maxNameLength,
244
+ minimumNameLength: limits.minNameLength,
245
+ };
246
+ }
@@ -1,8 +1,12 @@
1
1
  import "../../_dnt.polyfills.js";
2
2
  export * from "./authorize.js";
3
+ export * from "./betterAuth.js";
3
4
  export * from "./country.js";
4
5
  export * from "./credentials.js";
5
6
  export * from "./fingerprint.js";
7
+ export * from "./lifecycle.js";
8
+ export * from "./limits.js";
9
+ export * from "./permissions.js";
6
10
  export * from "./policy.js";
7
11
  export * from "./retention.js";
8
12
  export * from "./types.js";
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/mod.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../src/src/apiKeys/mod.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
@@ -1,8 +1,12 @@
1
1
  import "../../_dnt.polyfills.js";
2
2
  export * from "./authorize.js";
3
+ export * from "./betterAuth.js";
3
4
  export * from "./country.js";
4
5
  export * from "./credentials.js";
5
6
  export * from "./fingerprint.js";
7
+ export * from "./lifecycle.js";
8
+ export * from "./limits.js";
9
+ export * from "./permissions.js";
6
10
  export * from "./policy.js";
7
11
  export * from "./retention.js";
8
12
  export * from "./types.js";