@softistx/janus-hono 0.0.0-stage → 0.11.35

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +547 -2
  3. package/dist/bind.d.ts +104 -0
  4. package/dist/bind.d.ts.map +1 -0
  5. package/dist/device.d.ts +15 -0
  6. package/dist/device.d.ts.map +1 -0
  7. package/dist/errors.d.ts +60 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/fresh.d.ts +41 -0
  10. package/dist/fresh.d.ts.map +1 -0
  11. package/dist/index.d.ts +47 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +496 -0
  14. package/dist/index.js.map +22 -0
  15. package/dist/no-store.d.ts +8 -0
  16. package/dist/no-store.d.ts.map +1 -0
  17. package/dist/passkeys/body.d.ts +12 -0
  18. package/dist/passkeys/body.d.ts.map +1 -0
  19. package/dist/passkeys/index.d.ts +8 -0
  20. package/dist/passkeys/index.d.ts.map +1 -0
  21. package/dist/passkeys/routes.d.ts +32 -0
  22. package/dist/passkeys/routes.d.ts.map +1 -0
  23. package/dist/passkeys/types.d.ts +105 -0
  24. package/dist/passkeys/types.d.ts.map +1 -0
  25. package/dist/permission.d.ts +80 -0
  26. package/dist/permission.d.ts.map +1 -0
  27. package/dist/provide.d.ts +19 -0
  28. package/dist/provide.d.ts.map +1 -0
  29. package/dist/session.d.ts +156 -0
  30. package/dist/session.d.ts.map +1 -0
  31. package/dist/social/index.d.ts +9 -0
  32. package/dist/social/index.d.ts.map +1 -0
  33. package/dist/social/redirect.d.ts +9 -0
  34. package/dist/social/redirect.d.ts.map +1 -0
  35. package/dist/social/refusals.d.ts +14 -0
  36. package/dist/social/refusals.d.ts.map +1 -0
  37. package/dist/social/routes.d.ts +32 -0
  38. package/dist/social/routes.d.ts.map +1 -0
  39. package/dist/social/types.d.ts +90 -0
  40. package/dist/social/types.d.ts.map +1 -0
  41. package/docs/README.md +15 -0
  42. package/docs/guide/permissions.md +225 -0
  43. package/docs/guide/routes.md +1164 -0
  44. package/docs/roadmap.md +76 -0
  45. package/docs/troubleshooting.md +871 -0
  46. package/package.json +62 -5
@@ -0,0 +1,156 @@
1
+ import type { ApiKey, Principal, Session, SharedApi } from '@softistx/janus';
2
+ import type { Context, MiddlewareHandler } from 'hono';
3
+ import { type DeviceCookieOptions } from './device';
4
+ /** Anything `janus()` answered: the part of it this package calls. */
5
+ export type Auth<U extends {
6
+ readonly type: string;
7
+ }> = Pick<SharedApi<U>, 'authenticate' | 'signOut' | 'cookie'>;
8
+ /** The users an `auth` instance knows, as a union narrowed by `user.type`. */
9
+ export type UserOfAuth<A> = A extends Auth<infer U> ? U : never;
10
+ /**
11
+ * What `session()` sets on the context: `c.var.user` and `c.var.session`,
12
+ * both `null` for an anonymous request unless the route requires a user.
13
+ *
14
+ * `new Hono<SessionEnv<typeof auth>>()` types every route of an app that
15
+ * wires `app.use(session(auth))` once.
16
+ */
17
+ export type SessionEnv<A, T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type'], Required extends boolean = false> = {
18
+ Variables: Required extends true ? {
19
+ user: Extract<UserOfAuth<A>, {
20
+ readonly type: T;
21
+ }>;
22
+ session: Session;
23
+ } : {
24
+ user: Extract<UserOfAuth<A>, {
25
+ readonly type: T;
26
+ }> | null;
27
+ session: Session | null;
28
+ };
29
+ };
30
+ /**
31
+ * What `session(auth, { apiKey: true })` sets: `c.var.user` of whoever was
32
+ * authenticated, and beside them `c.var.principal` (narrow on `via`),
33
+ * `c.var.apiKey` (`null` for a session) and `c.var.session` — **`null` for a
34
+ * key**, which has none. Read `c.var.principal.via` before `c.var.session`.
35
+ */
36
+ export type PrincipalEnv<A, T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type'], Required extends boolean = false> = {
37
+ Variables: Required extends true ? {
38
+ user: Extract<UserOfAuth<A>, {
39
+ readonly type: T;
40
+ }>;
41
+ session: Session | null;
42
+ principal: Principal<Extract<UserOfAuth<A>, {
43
+ readonly type: T;
44
+ }>>;
45
+ apiKey: ApiKey | null;
46
+ } : {
47
+ user: Extract<UserOfAuth<A>, {
48
+ readonly type: T;
49
+ }> | null;
50
+ session: Session | null;
51
+ principal: Principal<Extract<UserOfAuth<A>, {
52
+ readonly type: T;
53
+ }>> | null;
54
+ apiKey: ApiKey | null;
55
+ };
56
+ };
57
+ export interface SessionOptions<T extends string> {
58
+ /** Only a user of this type is authenticated here; any other is anonymous. */
59
+ readonly type?: T;
60
+ /**
61
+ * `true`: an anonymous request is answered 401, with no body, and the
62
+ * route never runs — so `c.var.user` is never `null` in it. Only a literal
63
+ * `true` types it so: a computed `boolean` leaves `c.var.user` nullable.
64
+ */
65
+ readonly required?: boolean;
66
+ /**
67
+ * `true`: a bearer shaped like an API key is accepted too, and the route
68
+ * runs for the key's user. Opt-in per route group — a key reaches only
69
+ * the routes behind a `session(auth, { apiKey: true })`. Sets
70
+ * `c.var.principal` and `c.var.apiKey`; `c.var.session` is `null` for a
71
+ * key. Needs `janus({ apiKeys })`, a `TypeError` at the first request
72
+ * otherwise. Only a literal `true` types the extra variables.
73
+ */
74
+ readonly apiKey?: boolean;
75
+ }
76
+ /**
77
+ * The middleware that reads who a request belongs to — `auth.authenticate`
78
+ * on the request — and sets `c.var.user` and `c.var.session`.
79
+ *
80
+ * With `apiKey: true` a key-shaped bearer is accepted as well, and
81
+ * `c.var.principal` / `c.var.apiKey` say which one it was (see `PrincipalEnv`).
82
+ *
83
+ * **An outage is not anonymous**: a store that cannot answer rejects with
84
+ * `STORE_FAILED`, and this middleware lets it through to `app.onError` —
85
+ * `janusErrors()` answers it 503, never 401.
86
+ *
87
+ * A session renewed in passing is sent again as a cookie, after the route
88
+ * ran — but only to a request that presented it as one: a client that sends
89
+ * `Authorization: Bearer` is not handed a cookie it never asked for. And
90
+ * never over a session cookie the route set itself — `sendSession` after a
91
+ * sign-in, `signOut`'s clearing — which a browser would otherwise overwrite.
92
+ */
93
+ export declare function session<A extends Auth<{
94
+ readonly type: string;
95
+ }>, const T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type']>(auth: A, options: SessionOptions<T> & {
96
+ readonly required: true;
97
+ readonly apiKey: true;
98
+ }): MiddlewareHandler<PrincipalEnv<A, T, true>>;
99
+ export declare function session<A extends Auth<{
100
+ readonly type: string;
101
+ }>, const T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type']>(auth: A, options: SessionOptions<T> & {
102
+ readonly apiKey: true;
103
+ }): MiddlewareHandler<PrincipalEnv<A, T>>;
104
+ export declare function session<A extends Auth<{
105
+ readonly type: string;
106
+ }>, const T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type']>(auth: A, options: SessionOptions<T> & {
107
+ readonly required: true;
108
+ readonly apiKey?: false;
109
+ }): MiddlewareHandler<SessionEnv<A, T, true>>;
110
+ export declare function session<A extends Auth<{
111
+ readonly type: string;
112
+ }>, const T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type']>(auth: A, options?: SessionOptions<T> & {
113
+ readonly required?: false;
114
+ readonly apiKey?: false;
115
+ }): MiddlewareHandler<SessionEnv<A, T>>;
116
+ export declare function session<A extends Auth<{
117
+ readonly type: string;
118
+ }>, const T extends UserOfAuth<A>['type'] = UserOfAuth<A>['type']>(auth: A, options: SessionOptions<T>): MiddlewareHandler<SessionEnv<A, T>>;
119
+ /** What `sendSession` takes besides: the device cookie's options. */
120
+ export interface SendSessionOptions {
121
+ readonly device?: DeviceCookieOptions;
122
+ }
123
+ /**
124
+ * Sends the session cookie — after `signUp`, `signIn`, or anything else that
125
+ * answered a session token and its session — and answers the user. Appends: a
126
+ * cookie set before stays. The response says `Cache-Control: no-store`: it
127
+ * carries a session token. `session()` calls it for a renewal too, and only
128
+ * then.
129
+ *
130
+ * When the answer carries a `deviceToken` — the sign-in was given a
131
+ * `device` — the device cookie is set too, or set again so it lasts another
132
+ * four hundred days.
133
+ *
134
+ * ```ts
135
+ * const signedIn = await auth.signIn({ email, password }, { device: deviceOf(c) });
136
+ * const user = sendSession(c, auth, signedIn);
137
+ * return c.json({ id: user.id }); // the token is in the cookie, never in the body
138
+ * ```
139
+ */
140
+ export declare function sendSession<U>(c: Context, auth: Pick<Auth<{
141
+ readonly type: string;
142
+ }>, 'cookie'>, signedIn: {
143
+ readonly token: string;
144
+ readonly session: Session;
145
+ readonly user: U;
146
+ readonly deviceToken?: string | null;
147
+ }, options?: SendSessionOptions): U;
148
+ /**
149
+ * Revokes the session the request presents and clears the cookie — cleared
150
+ * whatever the answer, so a browser holding a stale cookie drops it too.
151
+ * `false` when the request presented no session, or an unknown one.
152
+ */
153
+ export declare function signOut(c: Context, auth: Pick<Auth<{
154
+ readonly type: string;
155
+ }>, 'signOut' | 'cookie'>): Promise<boolean>;
156
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC7E,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEvD,OAAO,EAAE,KAAK,mBAAmB,EAAc,MAAM,UAAU,CAAC;AAGhE,sEAAsE;AACtE,MAAM,MAAM,IAAI,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,IAAI,IAAI,CAC3D,SAAS,CAAC,CAAC,CAAC,EACZ,cAAc,GAAG,SAAS,GAAG,QAAQ,CACrC,CAAC;AAEF,8EAA8E;AAC9E,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEhE;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,CACrB,CAAC,EACD,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,CAAC,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,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EACzC,KAAK,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAC5D,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AA0C5E,qEAAqE;AACrE,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,MAAM,CAAC,EAAE,mBAAmB,CAAC;CACtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAC5B,CAAC,EAAE,OAAO,EACV,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,QAAQ,CAAC,EACrD,QAAQ,EAAE;IACT,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IACjB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACrC,EACD,OAAO,GAAE,kBAAuB,GAC9B,CAAC,CAaH;AAED;;;;GAIG;AACH,wBAAsB,OAAO,CAC5B,CAAC,EAAE,OAAO,EACV,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC,GAC/D,OAAO,CAAC,OAAO,CAAC,CAIlB"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The social sign-in routes for Hono, gathered from the files beside this
3
+ * one: `routes.ts` (the sub-app), `types.ts` (its options and the part of
4
+ * `auth` it calls), `refusals.ts` (which errors redirect) and `redirect.ts`
5
+ * (where the visitor lands).
6
+ */
7
+ export { socialRoutes } from './routes';
8
+ export type { SecondFactorOf, SocialAuth, SocialRoutesOptions, SocialSurface, } from './types';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/social/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACX,cAAc,EACd,UAAU,EACV,mBAAmB,EACnB,aAAa,GACb,MAAM,SAAS,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Where the social callback sends the visitor: the core's `returnTo` check
3
+ * run again as a backstop, and the `?socialError=<code>` a refusal adds.
4
+ */
5
+ /** `value` when it is a path of this site (the core's `isReturnTo`), else `fallback`. */
6
+ export declare function localPathOr(value: unknown, fallback: string): string;
7
+ /** `path` with `socialError=<code>` in its query, before any fragment. No URL parsing: it would normalise `/.//x` into `//x`. */
8
+ export declare function withSocialError(path: string, code: string): string;
9
+ //# sourceMappingURL=redirect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirect.d.ts","sourceRoot":"","sources":["../../src/social/redirect.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,yFAAyF;AACzF,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED,iIAAiI;AACjI,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAMlE"}
@@ -0,0 +1,14 @@
1
+ /** Which errors of the callback are a visitor's refusal, and the redirect that answers one. */
2
+ import { JanusError } from '@softistx/janus';
3
+ import type { Context } from 'hono';
4
+ import type { SocialAuth, SocialRoutesOptions } from './types';
5
+ /** Whether `error` is one of the visitor's refusals, rather than an outage or a bug. */
6
+ export declare function isRefusal(error: unknown): error is JanusError;
7
+ /**
8
+ * The answer to a refused callback: 302 to the flow's `returnTo` (or the
9
+ * default) with `?socialError=<code>`, or the application's `onRefusal`.
10
+ * The flow cookie is cleared unless the error was raised before the flow was
11
+ * spent: the real callback may still come.
12
+ */
13
+ export declare function refusedResponse<A extends SocialAuth>(c: Context, error: JanusError, flowCookieClear: string, options: SocialRoutesOptions<A>, defaultReturnTo: string): Response | Promise<Response>;
14
+ //# sourceMappingURL=refusals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refusals.d.ts","sourceRoot":"","sources":["../../src/social/refusals.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAE/F,OAAO,EAAE,UAAU,EAAuB,MAAM,iBAAiB,CAAC;AAClE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAyB/D,wFAAwF;AACxF,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,UAAU,CAE7D;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,UAAU,EACnD,CAAC,EAAE,OAAO,EACV,KAAK,EAAE,UAAU,EACjB,eAAe,EAAE,MAAM,EACvB,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC/B,eAAe,EAAE,MAAM,GACrB,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW9B"}
@@ -0,0 +1,32 @@
1
+ /** The social sign-in routes: one named handler per route, assembled by `socialRoutes()`. */
2
+ import { Hono } from 'hono';
3
+ import type { SocialAuth, SocialRoutesOptions } from './types';
4
+ /**
5
+ * The social sign-in routes, as a Hono sub-app to `route()` under a prefix:
6
+ *
7
+ * - `GET /:provider?returnTo=/path` — starts a sign-in: the flow cookie and a
8
+ * 302 to the provider;
9
+ * - `GET /:provider/callback` — completes it: clears the flow cookie (but
10
+ * keeps it when the callback was refused before the flow was spent, so a
11
+ * forged callback cannot burn the visitor's flow), sends the session cookie
12
+ * and 302s to the path the flow was started with; a second factor goes to
13
+ * `onSecondFactor`; a refusal 302s to that path with `?socialError=<code>`;
14
+ * - `POST /:provider/link` — behind `session()` and `fresh()`: starts linking
15
+ * an account to the signed-in user, 303 to the provider;
16
+ * - `DELETE /links/:provider/:accountId` — behind the same: unlinks, 204, or
17
+ * 404 for a link that is not the user's.
18
+ *
19
+ * ```ts
20
+ * app.route('/auth/social', socialRoutes(auth, {
21
+ * onSecondFactor: (c, result) => c.redirect(`/2fa?c=${result.challenge}`),
22
+ * }));
23
+ * ```
24
+ *
25
+ * The callback redirects only for the refusals of a visitor (the ten social
26
+ * codes, `USER_INACTIVE`, `EMAIL_UNVERIFIED`, `STEP_UP_REQUIRED`). Every other
27
+ * error — `STORE_FAILED` first — is thrown to `app.onError`: an outage is 503
28
+ * with `janusErrors()`, never a redirect. A bad `returnTo` or an unknown
29
+ * provider at the *start* is thrown too (400, 404).
30
+ */
31
+ export declare function socialRoutes<const A extends SocialAuth>(auth: A, options: SocialRoutesOptions<A>): Hono;
32
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/social/routes.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAO7F,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAC;AAQlE,OAAO,KAAK,EAAkB,UAAU,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAc/E;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,YAAY,CAAC,KAAK,CAAC,CAAC,SAAS,UAAU,EACtD,IAAI,EAAE,CAAC,EACP,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAC7B,IAAI,CAmCN"}
@@ -0,0 +1,90 @@
1
+ /** What `socialRoutes()` takes and what it needs of `auth`. */
2
+ import type { Authenticated, Duration, JanusError, SecondFactorRequired, SignInOptions, SocialCompleted, SocialFlowStart } from '@softistx/janus';
3
+ import type { Context, MiddlewareHandler } from 'hono';
4
+ import type { DeviceCookieOptions } from '../device';
5
+ import type { FreshOptions } from '../fresh';
6
+ import type { Auth } from '../session';
7
+ /** The part of `auth.social` these routes call: loose on the provider's name, which a path carries. */
8
+ export interface SocialSurface {
9
+ start(options: {
10
+ readonly provider: string;
11
+ readonly returnTo?: string;
12
+ readonly type?: string;
13
+ }): Promise<SocialFlowStart>;
14
+ link(current: Authenticated<never>, options: {
15
+ readonly provider: string;
16
+ readonly returnTo?: string;
17
+ }): Promise<SocialFlowStart>;
18
+ complete(input: {
19
+ readonly callback: URLSearchParams;
20
+ readonly flow: string;
21
+ readonly current?: {
22
+ readonly user: {
23
+ readonly id: string;
24
+ };
25
+ } | null;
26
+ }, options?: SignInOptions): Promise<SocialCompleted<{
27
+ readonly id: string;
28
+ }, SecondFactorRequired>>;
29
+ unlink(user: {
30
+ readonly id: string;
31
+ }, link: {
32
+ readonly provider: string;
33
+ readonly accountId: string;
34
+ }): Promise<boolean>;
35
+ readonly cookie: {
36
+ readonly name: string;
37
+ clear(): string;
38
+ };
39
+ }
40
+ /** What `socialRoutes()` takes as `auth`: the `janus()` instance of a type that configures `social`. */
41
+ export type SocialAuth = Auth<{
42
+ readonly type: string;
43
+ readonly id: string;
44
+ }> & {
45
+ readonly social: SocialSurface;
46
+ };
47
+ /** What `complete` answers when a second factor is due. */
48
+ export type SecondFactorOf<A extends SocialAuth> = Extract<Awaited<ReturnType<A['social']['complete']>>, {
49
+ readonly status: 'secondFactor';
50
+ }>;
51
+ /** What `socialRoutes()` takes besides `auth`. */
52
+ export interface SocialRoutesOptions<A extends SocialAuth> {
53
+ /** The user type, needed only when several types configure `social`. */
54
+ readonly type?: string;
55
+ /**
56
+ * The callback found a user with a second factor: answer the response that
57
+ * asks for the code (keep `result.challenge` in a short-lived HttpOnly
58
+ * cookie). The flow cookie is cleared already. A handler that returns its
59
+ * own `Response` loses the headers set on `c` (`no-store`, the flow-clear
60
+ * cookie): set them on that response.
61
+ */
62
+ readonly onSecondFactor: (c: Context, result: SecondFactorOf<A>) => Response | Promise<Response>;
63
+ /**
64
+ * The callback was refused. Default: 302 to the `returnTo` (or
65
+ * `defaultReturnTo`) with `?socialError=<code>`. `location` is that
66
+ * redirect, already safe. Never put `error.message` or `error.cause` in
67
+ * a response: `PROVIDER_ERROR` may carry the provider's raw answer.
68
+ */
69
+ readonly onRefusal?: (c: Context, error: JanusError, location: string) => Response | Promise<Response>;
70
+ /** Where the visitor lands when the flow carried no (valid) `returnTo`. Default `/`. */
71
+ readonly defaultReturnTo?: string;
72
+ /**
73
+ * The middleware that authenticates `POST /:provider/link` and
74
+ * `DELETE /links/...`, when `session(auth, { required: true })` is not it.
75
+ * It must answer 401 to an anonymous request and set `c.var.session`.
76
+ */
77
+ readonly session?: MiddlewareHandler;
78
+ /**
79
+ * Present when `janus({ devices })` is wired: the callback then reads the
80
+ * device cookie (named by these options) as the sign-in's `device`, and
81
+ * sets it again. Absent, no device is given, which `janus()` without
82
+ * `devices` requires.
83
+ */
84
+ readonly device?: DeviceCookieOptions;
85
+ /** How recent the proof must be to link or unlink; match `social.freshWithin`. Default `'10m'`. */
86
+ readonly freshWithin?: Duration;
87
+ /** The clock given to `janus()`, when it is not the system's. */
88
+ readonly clock?: FreshOptions['clock'];
89
+ }
90
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/social/types.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAE/D,OAAO,KAAK,EACX,aAAa,EACb,QAAQ,EACR,UAAU,EACV,oBAAoB,EACpB,aAAa,EACb,eAAe,EACf,eAAe,EACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,KA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,QAAQ,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC;IAChC,iEAAiE;IACjE,QAAQ,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;CACvC"}
package/docs/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # @softistx/janus-hono — documentation
2
+
3
+ The [README](../README.md) shows the whole wiring in one example; these pages
4
+ give the detail.
5
+
6
+ | Page | Read it when |
7
+ | --- | --- |
8
+ | [The routes of an application](guide/routes.md) | You are writing sign-up, sign-in, a second factor's code, a sign-in by e-mailed code or link, accepting an invitation, the device cookie of a sign-in from a new device, sign-in through an external provider, passkeys as a second factor, sign-out and the e-mail flows as Hono routes, with one user type or several |
9
+ | [Guarded routes and writing tuples](guide/permissions.md) | You are guarding a route with a permission, passing a condition's context, or granting and revoking from a route |
10
+ | [Troubleshooting](troubleshooting.md) | A route answers something you did not expect, or the compiler refuses one |
11
+ | [Roadmap](roadmap.md) | You want to know what is coming, what shipped, and what is deliberately not planned |
12
+
13
+ The words — user, session, object, permission, failure, denial — are
14
+ [`@softistx/janus`'s vocabulary](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/vocabulary.md),
15
+ and mean the same here.
@@ -0,0 +1,225 @@
1
+ # Guarded routes and writing tuples
2
+
3
+ The permissions side of `@softistx/janus` in Hono routes. A **guarded route** runs
4
+ only when its subject holds a permission on the object it serves:
5
+ `permission()` makes it one. `provide()` puts the instances on the context, for
6
+ the routes that grant and revoke. The model, `can` and the tuples are
7
+ [`@softistx/janus`'s permissions guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/permissions.md);
8
+ this page is only about the routes.
9
+
10
+ The examples use this model, and one loader for its records:
11
+
12
+ ```ts
13
+ import { byParam } from '@softistx/janus-hono';
14
+ import { defineModel, fromField, permissions, when } from '@softistx/janus/permissions';
15
+
16
+ const model = defineModel({
17
+ subjects: auth.types, // 'patient', 'staff'
18
+ types: {
19
+ record: {
20
+ related: {
21
+ owners: ['patient'],
22
+ // Read from the record itself; the lookup lets list() find a doctor's records.
23
+ doctors: fromField('doctorId', 'staff', {
24
+ lookup: (staffId) => records.idsByDoctor(staffId),
25
+ }),
26
+ },
27
+ permits: {
28
+ view: ['owners', 'doctors'],
29
+ edit: [when('owners', (ctx: { locked: boolean }) => !ctx.locked)],
30
+ },
31
+ },
32
+ },
33
+ });
34
+
35
+ export const access = permissions({ model, store: relations });
36
+
37
+ /** The record a route's `:id` names; `null`, a 404, when there is none. */
38
+ export const recordOf = byParam('id', (id) => records.find(id)); // records: your own store
39
+ ```
40
+
41
+ `byParam(name, find)` is a `load`: it reads one path parameter and answers
42
+ `find(id)`. Written by hand, it is
43
+
44
+ ```ts
45
+ import type { Context } from 'hono';
46
+
47
+ const recordOfByHand = (c: Context) => {
48
+ const id = c.req.param('id');
49
+ return id === undefined ? null : records.find(id);
50
+ };
51
+ ```
52
+
53
+ A loader takes a plain `Context` because it is written apart from any route,
54
+ and `permission()` is too: Hono types a path's parameters only in a handler
55
+ written inline on that route. So `c.req.param('id')` is `string | undefined`
56
+ in a loader, and the missing case is answered `null`. Pass `find` as an arrow
57
+ — `(id) => records.find(id)` — when it is a method that reads `this`.
58
+
59
+ ## A guarded route
60
+
61
+ ```ts
62
+ import { permission, session } from '@softistx/janus-hono';
63
+
64
+ app.get(
65
+ '/records/:id',
66
+ session(auth),
67
+ permission(access, 'view', 'record', recordOf),
68
+ (c) => c.json(c.var.object),
69
+ );
70
+ ```
71
+
72
+ `permission(access, permission, type, load)` — the order of `list(subject,
73
+ permission, type)` — runs in this order:
74
+
75
+ | Step | When it stops | Answered |
76
+ | --- | --- | --- |
77
+ | 1. The subject: `c.var.user`, set by `session()` | anonymous | 401, no body — nothing is loaded |
78
+ | 2. `load(c)` | it answers `null` | 404, no body |
79
+ | 3. `access.can(subject, permission, object)`, the object seen with `type` added | `false` | 403, no body |
80
+ | 4. `c.set('object', object)`, then the route | — | the route's answer |
81
+
82
+ A relation store that cannot answer at step 3 **throws** `STORE_FAILED`, and
83
+ `janusErrors()` answers it 503 — never 403: an outage does not deny anybody.
84
+ Whatever `load` throws reaches `app.onError` too, and goes to
85
+ `janusErrors({ fallback })`.
86
+
87
+ ### What `load` answers
88
+
89
+ The object as your application keeps it: its `id`, **every field a
90
+ `fromField` of its type reads** — `doctorId` here — and whatever else it
91
+ carries. The route gets exactly that, with its own type: `c.var.object` is
92
+ your record, not a reference to it, and the route does not load it again.
93
+
94
+ `can()` sees the object with `type` set to the object type named in
95
+ `permission()` — a `type` field of your own is not read by the check, and
96
+ stays in `c.var.object`. Every other field is read from the object itself, so
97
+ a class instance's getters and an ORM document's accessors answer as they do
98
+ in the route.
99
+
100
+ An object missing a `fromField`'s field is a compile error. At run time it
101
+ would be a `TypeError` from `can()`, never a denial. A field that holds nobody
102
+ is `null`.
103
+
104
+ ### One per route
105
+
106
+ `permission()` sets `c.var.object`, so a route has one. A second throws a
107
+ `TypeError` at the first request rather than type `c.var.object` as both
108
+ objects at once. A parent — the folder of a record — is checked through an
109
+ arrow in the model: `view: ['owners', 'folders->view']`.
110
+
111
+ ### A condition's context
112
+
113
+ A permission that reaches a `when()` needs its `ctx`, and `permission()`
114
+ requires the option exactly then, typed from the condition — through arrows
115
+ too. It is a function of the request and the loaded object:
116
+
117
+ ```ts
118
+ app.put(
119
+ '/records/:id',
120
+ session(auth),
121
+ permission(access, 'edit', 'record', recordOf, {
122
+ ctx: (c, record) => ({ locked: record.locked }),
123
+ }),
124
+ async (c) => c.json(await records.update(c.var.object.id, await c.req.json())),
125
+ );
126
+ ```
127
+
128
+ ### Another subject
129
+
130
+ `c.var.user` is the subject by default. Pass `subject` when your users are not
131
+ `janus()`'s — the permissions side used alone — or when the subject is not the
132
+ signed-in user:
133
+
134
+ ```ts
135
+ permission(access, 'view', 'record', recordOf, {
136
+ subject: (c) => subjectOfApiKey(c.req.header('x-api-key')), // { type, id } or null
137
+ });
138
+ ```
139
+
140
+ `null` is anonymous, and answered 401 before anything is loaded. Without
141
+ `session()` before it and without `subject`, `permission()` throws a
142
+ `TypeError` at the first request: a wiring error, never an anonymous 401.
143
+
144
+ ### Hiding what exists
145
+
146
+ A 403 tells the caller the object exists. Where that is a leak, make `load`
147
+ answer `null` for what the user may not see — ask `can()` there, so a record
148
+ they may not view is a 404 like one that does not exist:
149
+
150
+ ```ts
151
+ permission(access, 'view', 'record', async (c) => {
152
+ const record = await recordOf(c);
153
+ return record !== null &&
154
+ (await access.can(c.get('user'), 'view', { ...record, type: 'record' }))
155
+ ? record
156
+ : null;
157
+ });
158
+ ```
159
+
160
+ ## A list route
161
+
162
+ `permission()` guards one object. For the objects a user may see, ask
163
+ `list()` — through `provide()` — and load what it answers:
164
+
165
+ ```ts
166
+ app.get(
167
+ '/records',
168
+ session(auth, { required: true }),
169
+ provide({ access }),
170
+ async (c) => {
171
+ const page = await c.var.access.list(c.var.user, 'view', 'record', {
172
+ after: c.req.query('after') ?? null,
173
+ });
174
+ return c.json({
175
+ records: await records.findMany(page.items),
176
+ nextCursor: page.nextCursor,
177
+ });
178
+ },
179
+ );
180
+ ```
181
+
182
+ `list()` reverses every rule of `view`, so `doctors` needs its `lookup`:
183
+ without one, this call does not compile. When a user only ever sees what
184
+ names them — a patient's own records — a query filtered on `c.var.user.id`
185
+ is shorter, and needs no `list()`.
186
+
187
+ ## Writing tuples from a route
188
+
189
+ `provide({ auth, access })` sets `c.var.auth` and `c.var.access` to the
190
+ instances — only those given, and typed — so a route writes through the
191
+ context rather than a module import, and a test can hand those routes other
192
+ instances. `permission()` takes its instance as an argument.
193
+
194
+ ```ts
195
+ import { permission, provide, session } from '@softistx/janus-hono';
196
+
197
+ const app = new Hono().use(session(auth), provide({ auth, access }));
198
+
199
+ app.post('/records', session(auth, { type: 'patient', required: true }), async (c) => {
200
+ const record = await records.create(await c.req.json());
201
+ await c.var.access.grant({ type: 'record', id: record.id }, 'owners', c.var.user);
202
+ return c.json(record, 201);
203
+ });
204
+
205
+ app.delete(
206
+ '/records/:id/owner',
207
+ session(auth, { type: 'patient', required: true }),
208
+ permission(access, 'edit', 'record', recordOf, {
209
+ ctx: (c, record) => ({ locked: record.locked }),
210
+ }),
211
+ async (c) => {
212
+ await c.var.access.revoke({ type: 'record', id: c.var.object.id }, 'owners', c.var.user);
213
+ return c.body(null, 204);
214
+ },
215
+ );
216
+ ```
217
+
218
+ `grant` and `revoke` are typed from the model as everywhere: a relation read
219
+ from a field — `doctors` — cannot be granted, and a subject the relation does
220
+ not admit is a compile error. Both are idempotent.
221
+
222
+ ## See also
223
+
224
+ - [The routes of an application](routes.md) — `session()`, the cookie, the statuses
225
+ - [Troubleshooting](../troubleshooting.md)