@vite-hub/auth 0.1.0 → 0.3.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/README.md +333 -49
- package/dist/abilities-DfAnFYwG.d.ts +93 -0
- package/dist/abilities.d.ts +2 -0
- package/dist/abilities.js +43 -0
- package/dist/ability-error-CqgBrBfR.js +91 -0
- package/dist/ability-error-DcgChwCN.d.ts +34 -0
- package/dist/admin-claim-code-CDipqeAU.js +22 -0
- package/dist/agent.d.ts +5 -5
- package/dist/agent.js +17 -9
- package/dist/application-path-DuTpfGFj.js +62 -0
- package/dist/auth-instance-CR6b1W80.js +1168 -0
- package/dist/bun-sqlite.d.ts +8 -0
- package/dist/cli-ubYJpAL_.d.ts +163 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +47 -7
- package/dist/console-runtime-DTopBP-x.d.ts +71 -0
- package/dist/console-runtime-J9_Vx9pT.js +1166 -0
- package/dist/console-runtime.d.ts +3 -3
- package/dist/console-runtime.js +2 -819
- package/dist/console.d.ts +215 -3
- package/dist/console.js +1 -1
- package/dist/database-options-BRNef9oy.js +29 -0
- package/dist/database-schema-options-ENuRMduM.js +12 -0
- package/dist/database.d.ts +12 -0
- package/dist/database.js +45 -0
- package/dist/definition-CqQMcDEK.js +280 -0
- package/dist/error-diagnostics-C8XtVz0i.js +138 -0
- package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +120 -0
- package/dist/host-declarations.d.ts +2 -1
- package/dist/index.d.ts +24 -3
- package/dist/index.js +3 -102
- package/dist/internal/server.d.ts +5 -0
- package/dist/internal/server.js +858 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/mcp.d.ts +187 -0
- package/dist/mcp.js +353 -0
- package/dist/members-D9lfaEO_.js +533 -0
- package/dist/nuxt-bridge-Cl988STZ.js +44 -0
- package/dist/nuxt.d.ts +13 -5
- package/dist/nuxt.js +90 -13
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/page-tools-shared-l4eyj53D.js +19 -0
- package/dist/presets.js +1 -1
- package/dist/request-z6DHHmrb.js +47 -0
- package/dist/runtime/console.d.ts +3 -7
- package/dist/runtime/console.js +4 -42
- package/dist/runtime/empty-abilities.d.ts +5 -0
- package/dist/runtime/empty-abilities.js +4 -0
- package/dist/runtime/empty-client.d.ts +6 -0
- package/dist/runtime/empty-client.js +5 -0
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/nuxt.js +1 -1
- package/dist/runtime/server.d.ts +2 -0
- package/dist/runtime/server.js +77 -0
- package/dist/runtime/vue-nuxt.d.ts +3 -2
- package/dist/runtime/vue-nuxt.js +157 -5
- package/dist/runtime-state-ojQCzKOc.js +25 -0
- package/dist/schema.d.ts +137 -0
- package/dist/schema.js +147 -0
- package/dist/server-C0qnKN2W.d.ts +143 -0
- package/dist/server-bQGzVQ--.d.ts +41 -0
- package/dist/server.d.ts +3 -2
- package/dist/server.js +3 -3
- package/dist/session-cookies-BbH3UR2m.js +227 -0
- package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
- package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
- package/dist/table-specs-8gq_FCaq.js +771 -0
- package/dist/table-specs-DbXyaXWs.d.ts +842 -0
- package/dist/test.d.ts +26 -0
- package/dist/test.js +25 -0
- package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
- package/dist/vite-CV400XXY.js +1556 -0
- package/dist/vite.d.ts +138 -20
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +330 -21
- package/dist/vue.js +583 -36
- package/package.json +84 -15
- package/dist/application-path-C290OAIs.js +0 -18
- package/dist/cli-mgXvsBtA.d.ts +0 -85
- package/dist/console-B7eERmGv.d.ts +0 -180
- package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
- package/dist/error-diagnostics-CL0yjHiM.js +0 -79
- package/dist/events-config-CjcFOhTE.js +0 -177
- package/dist/inspect-DPtsW8dB.d.ts +0 -36
- package/dist/server-B7LU19dS.js +0 -1730
- package/dist/server-CTD_JAww.d.ts +0 -77
- package/dist/vite-COWkwxsj.js +0 -990
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { l as AuthAnonymousAuthorization, p as AuthAuthorization, z as RegisteredAuth } from "./types-CNaeH2Fd.js";
|
|
2
|
+
//#region src/abilities.d.ts
|
|
3
|
+
/** A 4xx status that a rule can refuse with. `403` is the default. */
|
|
4
|
+
type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
|
|
5
|
+
declare const abilityDenial: unique symbol;
|
|
6
|
+
/** A refusal that `deny()` made: its code, its details, and the HTTP status of the server error. */
|
|
7
|
+
interface AbilityDenial<Code extends string = string, Details = unknown> {
|
|
8
|
+
readonly [abilityDenial]: true;
|
|
9
|
+
readonly code: Code;
|
|
10
|
+
readonly details: Details;
|
|
11
|
+
readonly status: AbilityStatus;
|
|
12
|
+
}
|
|
13
|
+
/** What a rule returns. Only `true` allows. `false`, a code, or `deny()` refuse. */
|
|
14
|
+
type AbilityVerdict = boolean | string | AbilityDenial;
|
|
15
|
+
/** The signed-in user that a rule receives, typed from the app's Auth Definition. */
|
|
16
|
+
type AbilityUser = RegisteredAuth["$Infer"]["Session"]["user"];
|
|
17
|
+
/**
|
|
18
|
+
* A rule: the signed-in user, then the arguments it is about. Rules run on the server and in the browser, so they are
|
|
19
|
+
* synchronous. Load the data first and pass it in. Method syntax makes the parameters bivariant, so each rule can type
|
|
20
|
+
* its own arguments.
|
|
21
|
+
*/
|
|
22
|
+
type AbilityRule = {
|
|
23
|
+
rule(user: AbilityUser, ...args: unknown[]): AbilityVerdict;
|
|
24
|
+
}["rule"];
|
|
25
|
+
/** The rules of an app, by name. */
|
|
26
|
+
type AbilityRules = Record<string, AbilityRule>;
|
|
27
|
+
/** A rule that `guest()` opened to signed-out visitors. */
|
|
28
|
+
type GuestAbilityRule<Args extends unknown[] = unknown[], Verdict extends AbilityVerdict = AbilityVerdict> = ((user: AbilityUser | null, ...args: Args) => Verdict) & {
|
|
29
|
+
readonly guest: true;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Defines the app's rules in `shared/abilities.ts`. The server and the app run the same rules.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* export default defineAbilities({
|
|
36
|
+
* "posts.edit": (user, post: Post) => user.id === post.authorId || deny("not-author"),
|
|
37
|
+
* })
|
|
38
|
+
*/
|
|
39
|
+
declare function defineAbilities<const Rules extends AbilityRules>(rules: Rules): Rules;
|
|
40
|
+
/**
|
|
41
|
+
* Refuses with a code, and optionally a status other than `403` and details for the page.
|
|
42
|
+
* A rule that needs neither can return the code string, or `false`.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* deny("not-author")
|
|
46
|
+
* deny("plan-limit", { status: 402, details: { limit: 3 } })
|
|
47
|
+
*/
|
|
48
|
+
declare function deny<const Code extends string, const Details = undefined>(code: Code, options?: {
|
|
49
|
+
status?: AbilityStatus;
|
|
50
|
+
details?: Details;
|
|
51
|
+
}): AbilityDenial<Code, Details>;
|
|
52
|
+
/**
|
|
53
|
+
* Opens a rule to signed-out visitors: `user` is `null` for them. Without `guest()`, a signed-out visitor gets `401`
|
|
54
|
+
* before the rule runs.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* "posts.read": guest((user, post: Post) => post.published || user?.id === post.authorId),
|
|
58
|
+
*/
|
|
59
|
+
declare function guest<Args extends unknown[], Verdict extends AbilityVerdict>(rule: (user: AbilityUser | null, ...args: Args) => Verdict): GuestAbilityRule<Args, Verdict>;
|
|
60
|
+
type RegisteredAbilities = ViteHub.AuthRegistry extends {
|
|
61
|
+
abilities: infer Rules;
|
|
62
|
+
} ? Rules : Record<never, never>;
|
|
63
|
+
/** The name of a rule in the app's `shared/abilities.ts`. */
|
|
64
|
+
type AbilityName = keyof RegisteredAbilities & string;
|
|
65
|
+
/** What a rule takes after the user. */
|
|
66
|
+
type AbilityArgs<Name extends string> = Name extends keyof RegisteredAbilities ? RegisteredAbilities[Name] extends ((user: never, ...args: infer Args) => unknown) ? Args : never : never;
|
|
67
|
+
type RefusalOf<Verdict> = Verdict extends false ? {
|
|
68
|
+
code: undefined;
|
|
69
|
+
details: undefined;
|
|
70
|
+
} : Verdict extends AbilityDenial<infer Code, infer Details> ? {
|
|
71
|
+
code: Code;
|
|
72
|
+
details: Details;
|
|
73
|
+
} : Verdict extends string ? {
|
|
74
|
+
code: Verdict;
|
|
75
|
+
details: undefined;
|
|
76
|
+
} : never;
|
|
77
|
+
/**
|
|
78
|
+
* Each way a rule can refuse, as `<Can>` passes it to the `#denied` slot and the server error puts it in `data`.
|
|
79
|
+
* A signed-out visitor gets `signed-out` from every rule that is not open to guests.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* AbilityRefusal<"posts.edit"> // { code: "not-author", details: undefined } | { code: "signed-out", details: undefined }
|
|
83
|
+
*/
|
|
84
|
+
type AbilityRefusal<Name extends string = AbilityName> = (Name extends keyof RegisteredAbilities ? RegisteredAbilities[Name] extends ((...args: never[]) => infer Verdict) ? RefusalOf<Exclude<Verdict, true>> : never : never) | {
|
|
85
|
+
code: "signed-out";
|
|
86
|
+
details: undefined;
|
|
87
|
+
};
|
|
88
|
+
/** The checked request, session, and user that `requireAbility()` returns. A guest rule can return a signed-out caller. */
|
|
89
|
+
type AbilityAuthorization<Name extends string> = Name extends keyof RegisteredAbilities ? RegisteredAbilities[Name] extends {
|
|
90
|
+
guest: true;
|
|
91
|
+
} ? AuthAuthorization | AuthAnonymousAuthorization : AuthAuthorization : AuthAuthorization;
|
|
92
|
+
//#endregion
|
|
93
|
+
export { AbilityRefusal as a, AbilityStatus as c, GuestAbilityRule as d, defineAbilities as f, AbilityName as i, AbilityUser as l, guest as m, AbilityAuthorization as n, AbilityRule as o, deny as p, AbilityDenial as r, AbilityRules as s, AbilityArgs as t, AbilityVerdict as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-DfAnFYwG.js";
|
|
2
|
+
export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
//#region src/abilities.ts
|
|
2
|
+
/**
|
|
3
|
+
* Defines the app's rules in `shared/abilities.ts`. The server and the app run the same rules.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* export default defineAbilities({
|
|
7
|
+
* "posts.edit": (user, post: Post) => user.id === post.authorId || deny("not-author"),
|
|
8
|
+
* })
|
|
9
|
+
*/
|
|
10
|
+
function defineAbilities(rules) {
|
|
11
|
+
return rules;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Refuses with a code, and optionally a status other than `403` and details for the page.
|
|
15
|
+
* A rule that needs neither can return the code string, or `false`.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* deny("not-author")
|
|
19
|
+
* deny("plan-limit", { status: 402, details: { limit: 3 } })
|
|
20
|
+
*/
|
|
21
|
+
function deny(code, options = {}) {
|
|
22
|
+
const denial = {
|
|
23
|
+
[Symbol.for("vitehub.auth.denial")]: true,
|
|
24
|
+
code,
|
|
25
|
+
details: options.details,
|
|
26
|
+
status: options.status ?? 403
|
|
27
|
+
};
|
|
28
|
+
return Object.freeze(denial);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Opens a rule to signed-out visitors: `user` is `null` for them. Without `guest()`, a signed-out visitor gets `401`
|
|
32
|
+
* before the rule runs.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* "posts.read": guest((user, post: Post) => post.published || user?.id === post.authorId),
|
|
36
|
+
*/
|
|
37
|
+
function guest(rule) {
|
|
38
|
+
const open = (user, ...args) => rule(user, ...args);
|
|
39
|
+
Object.defineProperty(open, "guest", { value: true });
|
|
40
|
+
return open;
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { defineAbilities, deny, guest };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { HTTPError } from "nitro/h3";
|
|
3
|
+
//#region src/ability-check.ts
|
|
4
|
+
const signedOut = Object.freeze({
|
|
5
|
+
status: 401,
|
|
6
|
+
code: "signed-out"
|
|
7
|
+
});
|
|
8
|
+
/** Finds a rule by name, or fails with `AUTH_R0020`. */
|
|
9
|
+
function findAbilityRule(rules, name) {
|
|
10
|
+
const rule = Object.prototype.hasOwnProperty.call(rules, name) ? Reflect.get(rules, name) : void 0;
|
|
11
|
+
if (typeof rule !== "function") throw authErrorDiagnostics.AUTH_R0020({ message: `[vitehub] There is no ability named ${JSON.stringify(name)}. Add it to shared/abilities.ts with defineAbilities().` });
|
|
12
|
+
return rule;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Asks a rule about a user. Returns `null` when the rule allows, or the refusal. A signed-out user gets `401` unless the
|
|
16
|
+
* rule is open to guests. A rule that throws throws here too.
|
|
17
|
+
*/
|
|
18
|
+
function checkAbility(rules, user, name, args) {
|
|
19
|
+
const rule = findAbilityRule(rules, name);
|
|
20
|
+
if (!user && rule.guest !== true) return signedOut;
|
|
21
|
+
return toRefusal(rule(user, ...args), name);
|
|
22
|
+
}
|
|
23
|
+
function toRefusal(verdict, name) {
|
|
24
|
+
if (verdict === true) return null;
|
|
25
|
+
if (typeof verdict === "string") return {
|
|
26
|
+
status: 403,
|
|
27
|
+
code: verdict
|
|
28
|
+
};
|
|
29
|
+
if (typeof verdict === "object" && verdict !== null) {
|
|
30
|
+
if (Symbol.for("vitehub.auth.denial") in verdict) {
|
|
31
|
+
const { code, details, status } = verdict;
|
|
32
|
+
return {
|
|
33
|
+
status,
|
|
34
|
+
code,
|
|
35
|
+
details
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
if (typeof Reflect.get(verdict, "then") === "function") throw authErrorDiagnostics.AUTH_R0021({ message: `[vitehub] The ability ${JSON.stringify(name)} returned a Promise. Rules also run in the browser, so they must return at once. Load the data first and pass it to the rule.` });
|
|
39
|
+
}
|
|
40
|
+
return { status: 403 };
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/ability-error.ts
|
|
44
|
+
const statusTexts = {
|
|
45
|
+
400: "Bad Request",
|
|
46
|
+
401: "Unauthorized",
|
|
47
|
+
402: "Payment Required",
|
|
48
|
+
403: "Forbidden",
|
|
49
|
+
404: "Not Found",
|
|
50
|
+
405: "Method Not Allowed",
|
|
51
|
+
409: "Conflict",
|
|
52
|
+
410: "Gone",
|
|
53
|
+
422: "Unprocessable Content",
|
|
54
|
+
423: "Locked",
|
|
55
|
+
429: "Too Many Requests",
|
|
56
|
+
451: "Unavailable For Legal Reasons"
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* The error that `requireAbility()` throws when a rule refuses. H3 2 and Nitro answer it like their own `HTTPError`:
|
|
60
|
+
* the rule's status, and `{ code, details }` in `data`. Other hosts can catch it and read `status` and `data`.
|
|
61
|
+
*/
|
|
62
|
+
var AbilityError = class extends HTTPError {
|
|
63
|
+
constructor(refusal) {
|
|
64
|
+
const statusText = statusTexts[refusal.status] ?? "Forbidden";
|
|
65
|
+
super({
|
|
66
|
+
message: `${statusText}.`,
|
|
67
|
+
status: refusal.status,
|
|
68
|
+
statusText,
|
|
69
|
+
data: {
|
|
70
|
+
code: refusal.code,
|
|
71
|
+
details: refusal.details
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
get statusCode() {
|
|
76
|
+
return this.status;
|
|
77
|
+
}
|
|
78
|
+
get statusMessage() {
|
|
79
|
+
return this.statusText;
|
|
80
|
+
}
|
|
81
|
+
toJSON() {
|
|
82
|
+
return {
|
|
83
|
+
status: this.status,
|
|
84
|
+
statusText: this.statusText,
|
|
85
|
+
message: this.message,
|
|
86
|
+
data: this.data
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
//#endregion
|
|
91
|
+
export { checkAbility as n, AbilityError as t };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { HTTPError } from "nitro/h3";
|
|
2
|
+
//#region src/ability-check.d.ts
|
|
3
|
+
/** Why a rule refused: the HTTP status, and the code and details for the page. */
|
|
4
|
+
interface AbilityCheckRefusal {
|
|
5
|
+
status: number;
|
|
6
|
+
code?: string;
|
|
7
|
+
details?: unknown;
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/ability-error.d.ts
|
|
11
|
+
/** The code and details of a refusal, as the error body's `data` and the `#denied` slot of `<Can>` carry them. */
|
|
12
|
+
interface AbilityErrorData {
|
|
13
|
+
code?: string;
|
|
14
|
+
details?: unknown;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The error that `requireAbility()` throws when a rule refuses. H3 2 and Nitro answer it like their own `HTTPError`:
|
|
18
|
+
* the rule's status, and `{ code, details }` in `data`. Other hosts can catch it and read `status` and `data`.
|
|
19
|
+
*/
|
|
20
|
+
declare class AbilityError extends HTTPError<AbilityErrorData> {
|
|
21
|
+
readonly statusText: string;
|
|
22
|
+
readonly data: AbilityErrorData;
|
|
23
|
+
constructor(refusal: AbilityCheckRefusal);
|
|
24
|
+
get statusCode(): number;
|
|
25
|
+
get statusMessage(): string;
|
|
26
|
+
toJSON(): {
|
|
27
|
+
status: number;
|
|
28
|
+
statusText: string;
|
|
29
|
+
message: string;
|
|
30
|
+
data: AbilityErrorData;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { AbilityErrorData as n, AbilityError as t };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/admin-claim-code.ts
|
|
2
|
+
/** The variable with the SHA-256 of a one-time claim code, written by `vitehub auth claim`. */
|
|
3
|
+
const adminClaimVariable = "VITEHUB_ADMIN_CLAIM";
|
|
4
|
+
/** Crockford Base32 without I, L, O, and U, so a person can read the code aloud without mistakes. */
|
|
5
|
+
const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
6
|
+
/** A random code of 16 characters (80 bits), in groups of four. */
|
|
7
|
+
function createAdminClaimCode() {
|
|
8
|
+
const characters = [...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))].map((byte) => alphabet[byte % 32]).join("");
|
|
9
|
+
return [
|
|
10
|
+
0,
|
|
11
|
+
4,
|
|
12
|
+
8,
|
|
13
|
+
12
|
|
14
|
+
].map((start) => characters.slice(start, start + 4)).join("-");
|
|
15
|
+
}
|
|
16
|
+
/** The `VITEHUB_ADMIN_CLAIM` value of a code. Case, spaces, and dashes do not change it. */
|
|
17
|
+
async function adminClaimHash(code) {
|
|
18
|
+
const normalized = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
|
|
19
|
+
return `sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(normalized)))].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { adminClaimVariable as n, createAdminClaimCode as r, adminClaimHash as t };
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import {
|
|
2
|
+
import { AgentInvoker, AgentInvokerOptions, AgentInvokerResolveContext, AgentRuntimeConfig, MaybePromise } from "@vite-hub/agent";
|
|
3
3
|
//#region src/agent.d.ts
|
|
4
4
|
export interface AuthenticatedUser {
|
|
5
5
|
email?: string | null;
|
|
@@ -38,15 +38,15 @@ export interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig
|
|
|
38
38
|
}
|
|
39
39
|
/**
|
|
40
40
|
* The `auth` primitive that Agent Capabilities receive when Auth is configured. Generated Agent routes and Schedules
|
|
41
|
-
* pass it, so a Capability can act for the Auth user behind an Agent
|
|
41
|
+
* pass it, so a Capability can act for the Auth user behind an Agent Invoker.
|
|
42
42
|
*/
|
|
43
43
|
export interface AgentAuth {
|
|
44
44
|
/**
|
|
45
|
-
* The Auth user an
|
|
46
|
-
* that user from the Auth database again, so it also works when an approved tool call runs later. Null for an
|
|
45
|
+
* The Auth user an Invoker stands for. `authenticated()` records the user id as `invoker.meta.authUserId`, and this reads
|
|
46
|
+
* that user from the Auth database again, so it also works when an approved tool call runs later. Null for an Invoker
|
|
47
47
|
* without `authUserId`, or when the user no longer exists.
|
|
48
48
|
*/
|
|
49
|
-
user(
|
|
49
|
+
user(invoker: AgentInvoker | null | undefined): Promise<AuthenticatedUser | null>;
|
|
50
50
|
}
|
|
51
51
|
export declare const agentAuth: AgentAuth;
|
|
52
52
|
export declare function authenticated<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData>(options?: AuthenticatedOptions<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>): AgentInvokerOptions<TRuntimeConfig, CALL_OPTIONS>;
|
package/dist/agent.js
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import {
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-C8NOhdRE.js";
|
|
3
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
4
|
+
import { r as getAuthenticationSession, t as prepareSessionCookies } from "./session-cookies-BbH3UR2m.js";
|
|
3
5
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
4
6
|
//#region src/agent.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
let server;
|
|
8
|
+
const loadServer = () => server ??= import("./server.js").catch((error) => {
|
|
9
|
+
server = void 0;
|
|
10
|
+
throw error;
|
|
11
|
+
});
|
|
12
|
+
const agentAuth = { async user(invoker) {
|
|
13
|
+
const meta = invoker?.meta;
|
|
7
14
|
const userId = isRecord(meta) ? readString(meta.authUserId) : void 0;
|
|
8
15
|
if (!userId) return null;
|
|
16
|
+
const { getAuth } = await loadServer();
|
|
9
17
|
let user;
|
|
10
18
|
try {
|
|
11
19
|
user = await (await getAuth().$context).internalAdapter.findUserById(userId);
|
|
@@ -48,14 +56,17 @@ function authenticated(options = {}) {
|
|
|
48
56
|
}
|
|
49
57
|
async function defaultAuthenticatedSource(context) {
|
|
50
58
|
if (!context.request) return void 0;
|
|
51
|
-
const
|
|
52
|
-
|
|
59
|
+
const { useAuth } = await loadServer();
|
|
60
|
+
const auth = useAuth(context.request);
|
|
61
|
+
const { session, setCookies } = await getAuthenticationSession(auth, {
|
|
53
62
|
headers: context.request.headers,
|
|
54
63
|
query: {
|
|
55
64
|
disableCookieCache: true,
|
|
56
65
|
disableRefresh: true
|
|
57
66
|
}
|
|
58
67
|
});
|
|
68
|
+
prepareSessionCookies(context.request, setCookies);
|
|
69
|
+
return session;
|
|
59
70
|
}
|
|
60
71
|
function readProviderField(read) {
|
|
61
72
|
try {
|
|
@@ -96,8 +107,5 @@ function normalizeMeta(value) {
|
|
|
96
107
|
function readString(value) {
|
|
97
108
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
98
109
|
}
|
|
99
|
-
function isRecord(value) {
|
|
100
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
101
|
-
}
|
|
102
110
|
//#endregion
|
|
103
111
|
export { agentAuth, authenticated };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region src/application-path.ts
|
|
2
|
+
/**
|
|
3
|
+
* Prefix an application path with a base URL, such as Nitro `baseURL`. A path that already starts with the base path is
|
|
4
|
+
* returned unchanged, so a caller such as Console Auth that mounts its own paths below the base path is not prefixed
|
|
5
|
+
* twice.
|
|
6
|
+
*/
|
|
7
|
+
function prefixApplicationPath(baseURL, path) {
|
|
8
|
+
const segments = baseURL.split("/").filter(Boolean);
|
|
9
|
+
const base = segments.length ? `/${segments.join("/")}` : "";
|
|
10
|
+
if (!base || path === base || path.startsWith(`${base}/`)) return path;
|
|
11
|
+
return `${base}${path}`;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Prefix an application path, such as the Auth Base Path, with the application base path: `appBaseURL` when given,
|
|
15
|
+
* such as Nuxt's runtime `app.baseURL`, else the base path of the build.
|
|
16
|
+
*/
|
|
17
|
+
function resolveAuthMountPath(path, appBaseURL) {
|
|
18
|
+
return prefixApplicationPath(appBaseURL ?? authApplicationBaseURL(), path);
|
|
19
|
+
}
|
|
20
|
+
function authApplicationBaseURL() {
|
|
21
|
+
return typeof __VITEHUB_AUTH_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_AUTH_APP_BASE_URL__;
|
|
22
|
+
}
|
|
23
|
+
/** Characters that H3 percent-encodes in a route, as its `normalizeRoute()` does. */
|
|
24
|
+
const routeEncodeRE = /[^!-~]|["#<>^`]/gu;
|
|
25
|
+
/** Escapes of characters that need no escape in a path. H3 decodes them before it routes a request. */
|
|
26
|
+
const needlessEscapeRE = /%(?:2[146-9A-E]|3[0-9ABD]|4[0-9A-F]|5[0-9ABDF]|6[1-9A-F]|7[0-9ACE])/gi;
|
|
27
|
+
/**
|
|
28
|
+
* The path as the Nitro router reads it, so that two spellings of one path give the same string. H3 decodes needless
|
|
29
|
+
* escapes, such as `%62` for `b`, and rou3 ignores one trailing slash. The other escapes get upper-case hex digits.
|
|
30
|
+
*/
|
|
31
|
+
function canonicalAccessPath(path) {
|
|
32
|
+
const canonical = path.replace(routeEncodeRE, encodeURIComponent).replace(needlessEscapeRE, (escape) => String.fromCharCode(Number.parseInt(escape.slice(1), 16))).replace(/%[\da-f]{2}/gi, (escape) => escape.toUpperCase());
|
|
33
|
+
return canonical.length > 1 && canonical.endsWith("/") ? canonical.slice(0, -1) : canonical;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The error message for an access route that uses route pattern syntax or a dot segment, or undefined for a literal
|
|
37
|
+
* path. Only a final `/**` is a pattern. The access middleware does not read `*`, `:name`, `(`, `{`, or `?` as
|
|
38
|
+
* patterns, so such a route would guard nothing. H3 decodes escapes such as `%3A` and resolves `.` and `..` in a handler
|
|
39
|
+
* route, so the check reads the route after the same decoding.
|
|
40
|
+
*/
|
|
41
|
+
function accessRouteSyntaxError(route, label) {
|
|
42
|
+
const path = canonicalAccessPath(route.endsWith("/**") ? route.slice(0, -3) : route);
|
|
43
|
+
if (path.split("/").some((segment) => segment === "." || segment === "..")) return `\`defineAuth()\` ${label} has a \`.\` or \`..\` segment in ${JSON.stringify(route)}. Access routes match literal paths, so write the path without dot segments.`;
|
|
44
|
+
const syntax = /[*:(){}?\\]/.exec(path)?.[0];
|
|
45
|
+
if (!syntax) return;
|
|
46
|
+
return `\`defineAuth()\` ${label} uses \`${syntax}\` in ${JSON.stringify(route)}. Access routes match literal paths, and only a final \`/**\` matches the paths below a route.`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The path that an access route guards below the base URL, as the access middleware matches it. A route that ends with
|
|
50
|
+
* `/**` is recursive: it guards `path` and every path below it, and an empty `path` guards every path. All other
|
|
51
|
+
* characters of the route are literal. The path is canonical, see `canonicalAccessPath()`.
|
|
52
|
+
*/
|
|
53
|
+
function resolveAccessRoutePath(route, baseURL = authApplicationBaseURL()) {
|
|
54
|
+
const recursive = route.endsWith("/**");
|
|
55
|
+
const resolved = canonicalAccessPath(prefixApplicationPath(baseURL, (recursive ? route.slice(0, -3) : route).replace(/\/+$/, "") || "/"));
|
|
56
|
+
return {
|
|
57
|
+
path: recursive && resolved === "/" ? "" : resolved,
|
|
58
|
+
recursive
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { resolveAuthMountPath as i, canonicalAccessPath as n, resolveAccessRoutePath as r, accessRouteSyntaxError as t };
|