@gadicc/loom 1.34.0 → 1.35.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 (104) hide show
  1. package/README.md +108 -41
  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 +2806 -437
  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 +2807 -437
  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 +111 -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
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BETTER_AUTH_API_KEY_HTTP_PATHS = void 0;
4
+ exports.createBetterAuthApiKeyVerifier = createBetterAuthApiKeyVerifier;
5
+ exports.withBetterAuthApiKeyHttpPathsDisabled = withBetterAuthApiKeyHttpPathsDisabled;
6
+ const permissions_js_1 = require("./permissions.js");
7
+ function isObject(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ function malformed(detail) {
11
+ return new Error(`Better Auth verifyApiKey returned ${detail}.`);
12
+ }
13
+ function optionalString(value) {
14
+ return typeof value === "string" ? value : undefined;
15
+ }
16
+ /** True for a parseable expiry at or before now; unparseable values expire. */
17
+ function isExpired(expiresAt) {
18
+ if (expiresAt === null || expiresAt === undefined)
19
+ return false;
20
+ // The tag check also accepts a Date from another realm.
21
+ const time = Object.prototype.toString.call(expiresAt) === "[object Date]"
22
+ ? expiresAt.valueOf()
23
+ : typeof expiresAt === "string" || typeof expiresAt === "number"
24
+ ? new Date(expiresAt).valueOf()
25
+ : Number.NaN;
26
+ return !Number.isFinite(time) || time <= Date.now();
27
+ }
28
+ /**
29
+ * Creates a Loom `ApiKeyVerifier` that makes exactly one Better Auth
30
+ * `verifyApiKey` call per authorization and decides the requested permission
31
+ * locally.
32
+ *
33
+ * The plugin reports a valid key that lacks a requested permission as
34
+ * `KEY_NOT_FOUND`, indistinguishable from a forged or revoked key, so this
35
+ * verifier never sends `permissions`. Instead it checks the decoded grants
36
+ * with `hasApiKeyPermission` and reports a miss as `insufficient_permission`
37
+ * (403). Better Auth still owns hashing, config scoping, enablement, expiry,
38
+ * and usage accounting.
39
+ *
40
+ * Classification:
41
+ * - `valid: false` with code `RATE_LIMITED` (per-key rate limit) or
42
+ * `USAGE_EXCEEDED` (`remaining` quota spent; the plugin reports it as 429
43
+ * and deletes an exhausted key that has no refill) → `rate_limited` (429);
44
+ * - any other `valid: false`, `valid: true` without a key, or a returned key
45
+ * that is disabled or expired → `invalid_credential` (401);
46
+ * - a valid key without the exact permission → `insufficient_permission`
47
+ * (403), carrying the key's `principal` so Loom attributes the audit row
48
+ * to its owner;
49
+ * - a malformed result, key ID, or owner throws, which Loom records as
50
+ * `verification_error` (500). Exceptions from Better Auth propagate too.
51
+ *
52
+ * Caveats:
53
+ * - A scope miss now passes through the plugin's usage claim. It updates
54
+ * `lastRequest`/`requestCount`/`updatedAt` and, with per-key rate limits or
55
+ * `remaining` quotas enabled, would spend them and could delete an exhausted
56
+ * key. Keep those disabled or account for it.
57
+ * - The plugin catches internal failures such as a database outage and
58
+ * returns them as `INVALID_API_KEY`, so they deny as `invalid_credential`
59
+ * (fail closed) rather than `verification_error`. Monitor Better Auth's
60
+ * "Failed to validate API key" log to tell an outage from bad keys.
61
+ */
62
+ function createBetterAuthApiKeyVerifier(options) {
63
+ const { auth, configId, ownerId, scopes } = options;
64
+ if (typeof auth?.api?.verifyApiKey !== "function") {
65
+ throw new Error("createBetterAuthApiKeyVerifier requires a Better Auth instance with the api-key plugin.");
66
+ }
67
+ if (typeof configId !== "string" || configId.length === 0) {
68
+ throw new Error("createBetterAuthApiKeyVerifier requires a configId.");
69
+ }
70
+ if (ownerId !== undefined && typeof ownerId !== "function") {
71
+ throw new Error("createBetterAuthApiKeyVerifier ownerId must be a function.");
72
+ }
73
+ return {
74
+ async verify(request) {
75
+ // `permissions` is deliberately absent; see the JSDoc above.
76
+ const result = await auth.api.verifyApiKey({
77
+ body: { configId, key: request.credential },
78
+ });
79
+ if (!isObject(result))
80
+ throw malformed("a non-object result");
81
+ if (typeof result.valid !== "boolean") {
82
+ throw malformed("a result without a boolean `valid`");
83
+ }
84
+ if (result.valid !== true) {
85
+ const error = result.error;
86
+ if (isObject(error) &&
87
+ (error.code === "RATE_LIMITED" || error.code === "USAGE_EXCEEDED")) {
88
+ return { code: "rate_limited", ok: false };
89
+ }
90
+ return { code: "invalid_credential", ok: false };
91
+ }
92
+ if (result.error !== null && result.error !== undefined) {
93
+ throw malformed("a valid result that also carries an error");
94
+ }
95
+ const key = result.key;
96
+ if (key === null || key === undefined) {
97
+ return { code: "invalid_credential", ok: false };
98
+ }
99
+ if (!isObject(key))
100
+ throw malformed("a non-object key");
101
+ if (typeof key.id !== "string" || key.id.length === 0) {
102
+ throw malformed("a key without an ID");
103
+ }
104
+ const verifiedKey = key;
105
+ const owner = ownerId ? ownerId(verifiedKey) : verifiedKey.referenceId;
106
+ if (typeof owner !== "string" || owner.length === 0) {
107
+ throw malformed("a key without a resolvable owner");
108
+ }
109
+ // Better Auth already rejects these; re-checking keeps a plugin
110
+ // regression from granting a disabled or expired key.
111
+ if (verifiedKey.enabled === false || isExpired(verifiedKey.expiresAt)) {
112
+ return { code: "invalid_credential", ok: false };
113
+ }
114
+ const principal = {
115
+ keyId: verifiedKey.id,
116
+ keyName: optionalString(verifiedKey.name),
117
+ keyStart: optionalString(verifiedKey.start),
118
+ ownerId: owner,
119
+ permissions: scopes
120
+ ? (0, permissions_js_1.apiKeyPrincipalPermissions)(scopes, verifiedKey.permissions)
121
+ : (0, permissions_js_1.apiKeyGrantedPermissions)(verifiedKey.permissions),
122
+ };
123
+ if (!(0, permissions_js_1.hasApiKeyPermission)(verifiedKey.permissions, request.permission)) {
124
+ // The key is genuine, so the denial is attributed to its owner.
125
+ return { code: "insufficient_permission", ok: false, principal };
126
+ }
127
+ return { ok: true, principal };
128
+ },
129
+ };
130
+ }
131
+ /**
132
+ * Better Auth api-key plugin endpoints served over HTTP, relative to the auth
133
+ * base path.
134
+ *
135
+ * Each is session-authenticated, so any signed-in user can call it for their
136
+ * own keys: `update` can re-enable an administratively revoked key or remove
137
+ * its expiry, `delete` hard-deletes the key row instead of soft-revoking it,
138
+ * and `create` skips the app's own validation. `verifyApiKey` and expired-key
139
+ * cleanup are server-only and are not listed.
140
+ */
141
+ exports.BETTER_AUTH_API_KEY_HTTP_PATHS = Object.freeze([
142
+ "/api-key/create",
143
+ "/api-key/update",
144
+ "/api-key/delete",
145
+ "/api-key/get",
146
+ "/api-key/list",
147
+ ]);
148
+ /**
149
+ * Returns Better Auth `disabledPaths` that also block every api-key plugin
150
+ * HTTP endpoint, preserving `existing` entries first and removing duplicates.
151
+ *
152
+ * Use it in the app-owned `betterAuth()` options so key lifecycle only goes
153
+ * through server actions that call `auth.api.*`; server-side calls never pass
154
+ * through the HTTP router, so they keep working:
155
+ *
156
+ * ```ts
157
+ * export const auth = betterAuth({
158
+ * disabledPaths: withBetterAuthApiKeyHttpPathsDisabled(),
159
+ * plugins: [apiKey({ ... })],
160
+ * });
161
+ * ```
162
+ */
163
+ function withBetterAuthApiKeyHttpPathsDisabled(existing = []) {
164
+ if (!Array.isArray(existing) ||
165
+ existing.some((path) => typeof path !== "string")) {
166
+ throw new Error("Better Auth disabledPaths must be an array of strings.");
167
+ }
168
+ return [...new Set([...existing, ...exports.BETTER_AUTH_API_KEY_HTTP_PATHS])];
169
+ }
@@ -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,13 +1,62 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveApiKeyCredentialOptions = resolveApiKeyCredentialOptions;
4
+ exports.describeApiKeyTransports = describeApiKeyTransports;
3
5
  exports.extractApiKeyCredential = extractApiKeyCredential;
4
6
  const DEFAULT_QUERY_NAME = "apiKey";
5
7
  const DEFAULT_X_API_KEY_HEADER = "x-api-key";
8
+ /**
9
+ * Applies Loom's credential defaults: Bearer and the `x-api-key` header are
10
+ * accepted unless disabled, and query credentials only when enabled.
11
+ * `extractApiKeyCredential` uses the same resolution.
12
+ */
13
+ function resolveApiKeyCredentialOptions(options = {}) {
14
+ return {
15
+ allowAuthorizationBearer: options.allowAuthorizationBearer !== false,
16
+ allowQuery: options.allowQuery === true,
17
+ allowXApiKey: options.allowXApiKey !== false,
18
+ queryName: options.queryName ?? DEFAULT_QUERY_NAME,
19
+ xApiKeyHeaderName: options.xApiKeyHeaderName ?? DEFAULT_X_API_KEY_HEADER,
20
+ };
21
+ }
22
+ /**
23
+ * Describes which transports `options` accept and which to recommend, so UI
24
+ * copy can derive from the same object the authorizer uses. Pure and
25
+ * import-free at runtime, so client components can call it.
26
+ */
27
+ function describeApiKeyTransports(options = {}) {
28
+ const resolved = resolveApiKeyCredentialOptions(options);
29
+ const accepted = [];
30
+ if (resolved.allowAuthorizationBearer)
31
+ accepted.push("authorization-bearer");
32
+ if (resolved.allowXApiKey)
33
+ accepted.push("x-api-key");
34
+ if (resolved.allowQuery)
35
+ accepted.push("query");
36
+ return {
37
+ accepted,
38
+ bearer: resolved.allowAuthorizationBearer,
39
+ headerName: resolved.allowXApiKey ? resolved.xApiKeyHeaderName : null,
40
+ preferred: accepted[0] ?? null,
41
+ queryName: resolved.allowQuery ? resolved.queryName : null,
42
+ };
43
+ }
44
+ // API keys and Bearer tokens (RFC 6750) never contain a comma, so a comma
45
+ // means several credentials arrived, never one key. Repeated `x-api-key` lines
46
+ // reach `Headers.get` joined with ", " on Node and in fetch runtimes. Node's
47
+ // HTTP parser instead keeps only the first of repeated `Authorization` lines,
48
+ // so there the comma check only covers a literal comma in the header (and any
49
+ // runtime that joins); the first value still goes through full verification.
6
50
  function bearerCandidate(headers) {
7
51
  const value = headers.get("authorization");
8
52
  if (value === null)
9
53
  return null;
10
- const match = /^Bearer ([^\s]+)$/.exec(value);
54
+ if (value.includes(",")) {
55
+ return { ambiguous: true, transport: "authorization-bearer" };
56
+ }
57
+ // The auth-scheme name is case-insensitive (RFC 7235); the single space
58
+ // and the whitespace-free token are not relaxed.
59
+ const match = /^Bearer ([^\s]+)$/i.exec(value);
11
60
  return match
12
61
  ? { credential: match[1], transport: "authorization-bearer" }
13
62
  : { malformed: true, transport: "authorization-bearer" };
@@ -15,32 +64,46 @@ function bearerCandidate(headers) {
15
64
  function valueCandidate(value, transport) {
16
65
  if (value === null)
17
66
  return null;
67
+ if (transport === "x-api-key" && value.includes(",")) {
68
+ return { ambiguous: true, transport };
69
+ }
18
70
  if (value.trim() === "" || value !== value.trim()) {
19
71
  return { malformed: true, transport };
20
72
  }
21
73
  return { credential: value, transport };
22
74
  }
23
- /** Extracts exactly one API-key credential without selecting a precedence. */
75
+ function queryCandidate(searchParams, name) {
76
+ const values = searchParams?.getAll(name) ?? [];
77
+ if (values.length > 1)
78
+ return { ambiguous: true, transport: "query" };
79
+ return valueCandidate(values[0] ?? null, "query");
80
+ }
81
+ /**
82
+ * Extracts exactly one API-key credential without selecting a precedence.
83
+ * Several transports, a repeated header (a comma in its value), or a repeated
84
+ * query parameter are `ambiguous`.
85
+ */
24
86
  function extractApiKeyCredential(source, options = {}) {
87
+ const resolved = resolveApiKeyCredentialOptions(options);
25
88
  const candidates = [];
26
- if (options.allowAuthorizationBearer !== false) {
89
+ if (resolved.allowAuthorizationBearer) {
27
90
  const candidate = bearerCandidate(source.headers);
28
91
  if (candidate)
29
92
  candidates.push(candidate);
30
93
  }
31
- if (options.allowXApiKey !== false) {
32
- const candidate = valueCandidate(source.headers.get(options.xApiKeyHeaderName ?? DEFAULT_X_API_KEY_HEADER), "x-api-key");
94
+ if (resolved.allowXApiKey) {
95
+ const candidate = valueCandidate(source.headers.get(resolved.xApiKeyHeaderName), "x-api-key");
33
96
  if (candidate)
34
97
  candidates.push(candidate);
35
98
  }
36
- if (options.allowQuery === true) {
37
- const candidate = valueCandidate(source.searchParams?.get(options.queryName ?? DEFAULT_QUERY_NAME) ?? null, "query");
99
+ if (resolved.allowQuery) {
100
+ const candidate = queryCandidate(source.searchParams, resolved.queryName);
38
101
  if (candidate)
39
102
  candidates.push(candidate);
40
103
  }
41
104
  if (candidates.length === 0)
42
105
  return { kind: "missing" };
43
- if (candidates.length > 1) {
106
+ if (candidates.length > 1 || candidates.some((candidate) => candidate.ambiguous)) {
44
107
  return {
45
108
  kind: "ambiguous",
46
109
  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,7 @@
1
+ "use strict";
2
+ /**
3
+ * Type-only contracts shared by an app's API-key lifecycle server actions and
4
+ * the optional MUI components. This module has no runtime code, so server
5
+ * action files can import these types without touching a client module.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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"}