@softistx/janus-graphql 0.0.0-stage → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +716 -2
  3. package/dist/api-keys/index.d.ts +11 -0
  4. package/dist/api-keys/index.d.ts.map +1 -0
  5. package/dist/api-keys/resolvers/deps.d.ts +39 -0
  6. package/dist/api-keys/resolvers/deps.d.ts.map +1 -0
  7. package/dist/api-keys/resolvers/index.d.ts +39 -0
  8. package/dist/api-keys/resolvers/index.d.ts.map +1 -0
  9. package/dist/api-keys/resolvers/list.d.ts +16 -0
  10. package/dist/api-keys/resolvers/list.d.ts.map +1 -0
  11. package/dist/api-keys/resolvers/manage.d.ts +17 -0
  12. package/dist/api-keys/resolvers/manage.d.ts.map +1 -0
  13. package/dist/api-keys/sdl.d.ts +14 -0
  14. package/dist/api-keys/sdl.d.ts.map +1 -0
  15. package/dist/api-keys/shape.d.ts +38 -0
  16. package/dist/api-keys/shape.d.ts.map +1 -0
  17. package/dist/api-keys/types.d.ts +149 -0
  18. package/dist/api-keys/types.d.ts.map +1 -0
  19. package/dist/avatar/index.d.ts +32 -0
  20. package/dist/avatar/index.d.ts.map +1 -0
  21. package/dist/avatar/resolvers.d.ts +41 -0
  22. package/dist/avatar/resolvers.d.ts.map +1 -0
  23. package/dist/avatar/sdl.d.ts +16 -0
  24. package/dist/avatar/sdl.d.ts.map +1 -0
  25. package/dist/bad-input.d.ts +17 -0
  26. package/dist/bad-input.d.ts.map +1 -0
  27. package/dist/connection/connection.d.ts +36 -0
  28. package/dist/connection/connection.d.ts.map +1 -0
  29. package/dist/connection/credential.d.ts +34 -0
  30. package/dist/connection/credential.d.ts.map +1 -0
  31. package/dist/connection/types.d.ts +61 -0
  32. package/dist/connection/types.d.ts.map +1 -0
  33. package/dist/context/create.d.ts +32 -0
  34. package/dist/context/create.d.ts.map +1 -0
  35. package/dist/context/index.d.ts +9 -0
  36. package/dist/context/index.d.ts.map +1 -0
  37. package/dist/context/registry.d.ts +72 -0
  38. package/dist/context/registry.d.ts.map +1 -0
  39. package/dist/context/resolve.d.ts +20 -0
  40. package/dist/context/resolve.d.ts.map +1 -0
  41. package/dist/device.d.ts +28 -0
  42. package/dist/device.d.ts.map +1 -0
  43. package/dist/directives/apply.d.ts +51 -0
  44. package/dist/directives/apply.d.ts.map +1 -0
  45. package/dist/directives/guard.d.ts +22 -0
  46. package/dist/directives/guard.d.ts.map +1 -0
  47. package/dist/directives/permission/enforce.d.ts +24 -0
  48. package/dist/directives/permission/enforce.d.ts.map +1 -0
  49. package/dist/directives/permission/model.d.ts +35 -0
  50. package/dist/directives/permission/model.d.ts.map +1 -0
  51. package/dist/directives/permission/path.d.ts +31 -0
  52. package/dist/directives/permission/path.d.ts.map +1 -0
  53. package/dist/directives/permission/validate.d.ts +42 -0
  54. package/dist/directives/permission/validate.d.ts.map +1 -0
  55. package/dist/directives/read.d.ts +43 -0
  56. package/dist/directives/read.d.ts.map +1 -0
  57. package/dist/directives/validate.d.ts +39 -0
  58. package/dist/directives/validate.d.ts.map +1 -0
  59. package/dist/directives/words.d.ts +7 -0
  60. package/dist/directives/words.d.ts.map +1 -0
  61. package/dist/errors/denial.d.ts +6 -0
  62. package/dist/errors/denial.d.ts.map +1 -0
  63. package/dist/errors/index.d.ts +12 -0
  64. package/dist/errors/index.d.ts.map +1 -0
  65. package/dist/errors/janus-error.d.ts +20 -0
  66. package/dist/errors/janus-error.d.ts.map +1 -0
  67. package/dist/errors/mask.d.ts +69 -0
  68. package/dist/errors/mask.d.ts.map +1 -0
  69. package/dist/fresh.d.ts +44 -0
  70. package/dist/fresh.d.ts.map +1 -0
  71. package/dist/helpers.d.ts +56 -0
  72. package/dist/helpers.d.ts.map +1 -0
  73. package/dist/index.d.ts +86 -0
  74. package/dist/index.d.ts.map +1 -0
  75. package/dist/index.js +3393 -0
  76. package/dist/index.js.map +75 -0
  77. package/dist/invitations/index.d.ts +12 -0
  78. package/dist/invitations/index.d.ts.map +1 -0
  79. package/dist/invitations/resolvers/anonymous.d.ts +11 -0
  80. package/dist/invitations/resolvers/anonymous.d.ts.map +1 -0
  81. package/dist/invitations/resolvers/deps.d.ts +38 -0
  82. package/dist/invitations/resolvers/deps.d.ts.map +1 -0
  83. package/dist/invitations/resolvers/index.d.ts +37 -0
  84. package/dist/invitations/resolvers/index.d.ts.map +1 -0
  85. package/dist/invitations/resolvers/owner.d.ts +17 -0
  86. package/dist/invitations/resolvers/owner.d.ts.map +1 -0
  87. package/dist/invitations/sdl/accept.d.ts +7 -0
  88. package/dist/invitations/sdl/accept.d.ts.map +1 -0
  89. package/dist/invitations/sdl/index.d.ts +14 -0
  90. package/dist/invitations/sdl/index.d.ts.map +1 -0
  91. package/dist/invitations/sdl/owner.d.ts +8 -0
  92. package/dist/invitations/sdl/owner.d.ts.map +1 -0
  93. package/dist/invitations/shape.d.ts +63 -0
  94. package/dist/invitations/shape.d.ts.map +1 -0
  95. package/dist/invitations/types/index.d.ts +5 -0
  96. package/dist/invitations/types/index.d.ts.map +1 -0
  97. package/dist/invitations/types/options.d.ts +104 -0
  98. package/dist/invitations/types/options.d.ts.map +1 -0
  99. package/dist/invitations/types/out.d.ts +136 -0
  100. package/dist/invitations/types/out.d.ts.map +1 -0
  101. package/dist/invitations/types/surface.d.ts +18 -0
  102. package/dist/invitations/types/surface.d.ts.map +1 -0
  103. package/dist/map-code.d.ts +10 -0
  104. package/dist/map-code.d.ts.map +1 -0
  105. package/dist/mask-error.d.ts +18 -0
  106. package/dist/mask-error.d.ts.map +1 -0
  107. package/dist/memo.d.ts +16 -0
  108. package/dist/memo.d.ts.map +1 -0
  109. package/dist/options.d.ts +17 -0
  110. package/dist/options.d.ts.map +1 -0
  111. package/dist/passkeys/deps.d.ts +23 -0
  112. package/dist/passkeys/deps.d.ts.map +1 -0
  113. package/dist/passkeys/first-factor.types.d.ts +38 -0
  114. package/dist/passkeys/first-factor.types.d.ts.map +1 -0
  115. package/dist/passkeys/index.d.ts +14 -0
  116. package/dist/passkeys/index.d.ts.map +1 -0
  117. package/dist/passkeys/resolvers.d.ts +23 -0
  118. package/dist/passkeys/resolvers.d.ts.map +1 -0
  119. package/dist/passkeys/sdl.d.ts +14 -0
  120. package/dist/passkeys/sdl.d.ts.map +1 -0
  121. package/dist/passkeys/shape.d.ts +14 -0
  122. package/dist/passkeys/shape.d.ts.map +1 -0
  123. package/dist/passkeys/sign-in.resolvers.d.ts +19 -0
  124. package/dist/passkeys/sign-in.resolvers.d.ts.map +1 -0
  125. package/dist/passkeys/sign-in.sdl.d.ts +16 -0
  126. package/dist/passkeys/sign-in.sdl.d.ts.map +1 -0
  127. package/dist/passkeys/types.d.ts +193 -0
  128. package/dist/passkeys/types.d.ts.map +1 -0
  129. package/dist/plugin.d.ts +59 -0
  130. package/dist/plugin.d.ts.map +1 -0
  131. package/dist/renewal.d.ts +51 -0
  132. package/dist/renewal.d.ts.map +1 -0
  133. package/dist/report.d.ts +29 -0
  134. package/dist/report.d.ts.map +1 -0
  135. package/dist/sdl.d.ts +12 -0
  136. package/dist/sdl.d.ts.map +1 -0
  137. package/dist/second-factor/index.d.ts +12 -0
  138. package/dist/second-factor/index.d.ts.map +1 -0
  139. package/dist/second-factor/resolvers/deps.d.ts +39 -0
  140. package/dist/second-factor/resolvers/deps.d.ts.map +1 -0
  141. package/dist/second-factor/resolvers/index.d.ts +39 -0
  142. package/dist/second-factor/resolvers/index.d.ts.map +1 -0
  143. package/dist/second-factor/resolvers/sign-in.d.ts +10 -0
  144. package/dist/second-factor/resolvers/sign-in.d.ts.map +1 -0
  145. package/dist/second-factor/resolvers/status.d.ts +10 -0
  146. package/dist/second-factor/resolvers/status.d.ts.map +1 -0
  147. package/dist/second-factor/resolvers/step-up.d.ts +16 -0
  148. package/dist/second-factor/resolvers/step-up.d.ts.map +1 -0
  149. package/dist/second-factor/resolvers/writes.d.ts +19 -0
  150. package/dist/second-factor/resolvers/writes.d.ts.map +1 -0
  151. package/dist/second-factor/sdl.d.ts +14 -0
  152. package/dist/second-factor/sdl.d.ts.map +1 -0
  153. package/dist/second-factor/shape.d.ts +18 -0
  154. package/dist/second-factor/shape.d.ts.map +1 -0
  155. package/dist/second-factor/types/index.d.ts +5 -0
  156. package/dist/second-factor/types/index.d.ts.map +1 -0
  157. package/dist/second-factor/types/options.d.ts +61 -0
  158. package/dist/second-factor/types/options.d.ts.map +1 -0
  159. package/dist/second-factor/types/out.d.ts +84 -0
  160. package/dist/second-factor/types/out.d.ts.map +1 -0
  161. package/dist/second-factor/types/surface.d.ts +89 -0
  162. package/dist/second-factor/types/surface.d.ts.map +1 -0
  163. package/dist/social/index.d.ts +10 -0
  164. package/dist/social/index.d.ts.map +1 -0
  165. package/dist/social/resolvers.d.ts +25 -0
  166. package/dist/social/resolvers.d.ts.map +1 -0
  167. package/dist/social/sdl.d.ts +13 -0
  168. package/dist/social/sdl.d.ts.map +1 -0
  169. package/dist/social/shape.d.ts +11 -0
  170. package/dist/social/shape.d.ts.map +1 -0
  171. package/dist/social/types.d.ts +160 -0
  172. package/dist/social/types.d.ts.map +1 -0
  173. package/dist/surface/api.d.ts +16 -0
  174. package/dist/surface/api.d.ts.map +1 -0
  175. package/dist/surface/request.d.ts +10 -0
  176. package/dist/surface/request.d.ts.map +1 -0
  177. package/dist/surface/signed-in.d.ts +30 -0
  178. package/dist/surface/signed-in.d.ts.map +1 -0
  179. package/dist/types.d.ts +117 -0
  180. package/dist/types.d.ts.map +1 -0
  181. package/dist/wiring.d.ts +56 -0
  182. package/dist/wiring.d.ts.map +1 -0
  183. package/docs/README.md +26 -0
  184. package/docs/guide/api-keys.md +365 -0
  185. package/docs/guide/avatars.md +129 -0
  186. package/docs/guide/context.md +371 -0
  187. package/docs/guide/directives.md +371 -0
  188. package/docs/guide/errors.md +318 -0
  189. package/docs/guide/federation.md +71 -0
  190. package/docs/guide/invitations.md +269 -0
  191. package/docs/guide/passkeys.md +207 -0
  192. package/docs/guide/second-factor.md +238 -0
  193. package/docs/guide/social.md +190 -0
  194. package/docs/guide/step-up.md +208 -0
  195. package/docs/guide/subscriptions.md +255 -0
  196. package/docs/guide/telemetry.md +45 -0
  197. package/docs/roadmap.md +124 -0
  198. package/docs/troubleshooting.md +1265 -0
  199. package/graphql/janus-api-keys.graphqls +237 -0
  200. package/graphql/janus-avatar.graphqls +19 -0
  201. package/graphql/janus-invitations.graphqls +280 -0
  202. package/graphql/janus-passkey-sign-in.graphqls +40 -0
  203. package/graphql/janus-passkeys.graphqls +134 -0
  204. package/graphql/janus-second-factor.graphqls +199 -0
  205. package/graphql/janus-social.graphqls +155 -0
  206. package/graphql/janus.graphqls +44 -0
  207. package/package.json +80 -5
@@ -0,0 +1,71 @@
1
+ # Federation
2
+
3
+ This page is for a subgraph of a federated graph: where the directives are
4
+ checked, how the router must forward the request, and how to keep them in
5
+ the supergraph with `@composeDirective`.
6
+
7
+ ## Checked in the subgraph
8
+
9
+ `useJanus()` guards the schema of the server it is plugged into. In a
10
+ federated graph that is the subgraph: each subgraph that serves a guarded
11
+ field runs its own `useJanus({ auth, access })`, and checks the directive
12
+ when the router asks it for the field. Nothing is checked by the router.
13
+
14
+ So **the router must forward what `authenticate` reads**: the
15
+ `Authorization` header, `X-Session-Token`, or the session cookie. A router
16
+ that forwards none of them turns every signed-in user into an anonymous one,
17
+ answered `UNAUTHENTICATED` by the subgraph. Configure header propagation in
18
+ the router for the subgraphs that use this package.
19
+
20
+ An entity's fields are guarded as any object type's: a type-level
21
+ `@permission` reads `parent.id`, and the parent is what your
22
+ `__resolveReference` answered, so it carries the fields its `fromField`s
23
+ read when your reference resolver loads them.
24
+
25
+ ```graphql
26
+ type Record @key(fields: "id") @permission(name: "view", type: "record") {
27
+ id: ID!
28
+ title: String
29
+ }
30
+ ```
31
+
32
+ ## The shipped SDL
33
+
34
+ The directives and the `JanusPermissionDenial` enum ship twice, as the same text:
35
+ `janusTypeDefs`, and `graphql/janus.graphqls` in the package —
36
+ `node_modules/@softistx/janus-graphql/graphql/janus.graphqls`. Composition
37
+ requires a directive to be declared identically in every subgraph that
38
+ composes it, and reading it from the package, rather than copying it, keeps
39
+ every subgraph on the definition of the version it installed.
40
+
41
+ A subgraph built with `@apollo/subgraph` or `@graphql-tools/federation`
42
+ takes `janusTypeDefs` among its type definitions, like any server; a
43
+ schema-first toolchain reads the file.
44
+
45
+ ## Keeping the directives in the supergraph
46
+
47
+ Composition drops a subgraph's own directives from the supergraph unless
48
+ they are composed. The checks do not need them there — they run in the
49
+ subgraph — but a client generator or a schema registry reading the
50
+ supergraph does, to show which fields are guarded. Link them under a
51
+ specification URL of your own and compose them:
52
+
53
+ ```graphql
54
+ extend schema
55
+ @link(url: "https://specs.apollo.dev/federation/v2.1", import: ["@key", "@composeDirective"])
56
+ @link(url: "https://example.com/janus/v1.0", import: ["@authenticated", "@fresh", "@permission"])
57
+ @composeDirective(name: "@authenticated")
58
+ @composeDirective(name: "@fresh")
59
+ @composeDirective(name: "@permission")
60
+ ```
61
+
62
+ Every subgraph that composes a directive must declare it identically, which
63
+ the shipped SDL does, and link it under the same URL, with the same major
64
+ version.
65
+
66
+ **Do not import federation's own `@authenticated`.** Federation 2.5 declares
67
+ a directive of that name, read by the router, and a subgraph that imports it
68
+ from the federation `@link` while declaring `janusTypeDefs` has two
69
+ definitions of one name. Import only what you use from the federation
70
+ specification — `@key`, `@composeDirective` — and let this package's
71
+ `@authenticated` be the one the subgraph checks.
@@ -0,0 +1,269 @@
1
+ # Invitations
2
+
3
+ This page is for inviting people into a scope (an organization, a team, a
4
+ clinic) from a GraphQL API: the schema, the resolvers, who may invite, where
5
+ the code goes, what the invitee sees, the cookies, the errors and the traps. It
6
+ is opt-in: nothing here is declared by `janusTypeDefs`, and a server without
7
+ invitations imports none of it.
8
+
9
+ What an invitation is, its lifetime, the limits and what accepting does to an
10
+ existing account are
11
+ [`@softistx/janus`'s invitations](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/README.md).
12
+ This package puts the six calls of `auth.invitations` in the schema.
13
+
14
+ ## The schema
15
+
16
+ ```ts
17
+ import {
18
+ can,
19
+ invitationResolvers,
20
+ type JanusContext,
21
+ janusInvitationTypeDefs,
22
+ janusMaskError,
23
+ janusTypeDefs,
24
+ useJanus,
25
+ } from '@softistx/janus-graphql';
26
+ import { createSchema, createYoga, type YogaInitialContext } from 'graphql-yoga';
27
+
28
+ // The context the hooks read: each hook is a method, so `ctx` takes your type.
29
+ type Context = YogaInitialContext & JanusContext<typeof auth, typeof access>;
30
+
31
+ const typeDefs = /* GraphQL */ `
32
+ type Query { hello: String! }
33
+ type Mutation { noop: Boolean }
34
+ type Viewer { email: String! }
35
+ extend type InvitationSignedIn { user: Viewer! } # optional: the user who just signed in
36
+ `;
37
+
38
+ const schema = createSchema({
39
+ typeDefs: [janusTypeDefs, janusInvitationTypeDefs, typeDefs],
40
+ resolvers: {
41
+ ...invitationResolvers({
42
+ auth, // janus({ …, invitations: { store, create, onAccepted } })
43
+ authorize: (action, { scope }, ctx: Context) =>
44
+ can(ctx, 'invite', { type: 'organization', id: scope }),
45
+ sendInvitation: ({ invitation, code }) =>
46
+ mailer.sendInvitation(invitation, `https://app.test/join#${code}`),
47
+ }),
48
+ InvitationSignedIn: { user: (signedIn: { user: unknown }) => signedIn.user },
49
+ },
50
+ });
51
+
52
+ createYoga({ schema, plugins: [useJanus({ auth })], maskedErrors: { maskError: janusMaskError() } });
53
+ ```
54
+
55
+ `janusInvitationTypeDefs` `extend`s your `Query` and `Mutation`. The same text
56
+ ships as `graphql/janus-invitations.graphqls`. Timestamps are ISO-8601
57
+ `String`s, and `status` is a `String` (`pending`, `accepted`, `revoked`).
58
+
59
+ | Field | Who | What |
60
+ | --- | --- | --- |
61
+ | `invitations(scope, status?, role?, ref?, lapsed?, order?, limit?, after?)` | A signed-in user `authorize` lets list | A page of the scope's invitations, `OLDEST` first unless `order: NEWEST`, with `totalCount` |
62
+ | `issueInvitation(scope, email, name, role, locale?, ref?, type?)` | A signed-in user `authorize` lets issue | Invites an address; the inviter is the request's user |
63
+ | `resendInvitation(scope, id)` | as above | A new code and lifetime; the old code stops working |
64
+ | `revokeInvitation(scope, id)` | as above | Takes a pending invitation back |
65
+ | `invitationPreview(code)` | Whoever holds the code | What the page the invitee lands on shows |
66
+ | `acceptInvitation(code, password?)` | Whoever holds the code | Accepts; a new invitee is signed in |
67
+
68
+ `ref` is an opaque reference to your own record (1 to 100 characters): given
69
+ at issue, answered on `JanusInvitation.ref` (null when absent) and usable as a
70
+ filter. `type` is the user type the invitee becomes. It is required when the
71
+ instance lists several user types (`INVITATION_INVALID`, `field: 'type'`, when
72
+ absent or unlisted); null or absent means the instance's single type. It is
73
+ answered on `JanusInvitation.type`, a `String!`: an invitation stored before
74
+ types existed reads as the first type.
75
+
76
+ `status`, `role` and `ref` filter `invitations` by equality (an empty `role` or
77
+ `ref` is `BAD_USER_INPUT`, before `authorize` is asked). `lapsed` is
78
+ `EXCLUDE` (leave out the invitations that are pending and past `expiresAt`,
79
+ keeping every other one) or `ONLY` (keep just those); `totalCount` follows it.
80
+ `lapsed` needs `@softistx/janus` 0.49 or later, the release that added it to the core.
81
+ `order` is `OLDEST`
82
+ (the default) or `NEWEST`, and `after` is the cursor of the previous page, with
83
+ the same scope, filters and order: a cursor replayed against another list is
84
+ `BAD_USER_INPUT` (`CURSOR_FILTER_MISMATCH` in the core).
85
+
86
+ ```graphql
87
+ mutation {
88
+ issueInvitation(scope: "acme", email: "grace@example.test", name: "Grace",
89
+ role: "member", ref: "crm-1", type: "staff") {
90
+ invitation { id ref type }
91
+ }
92
+ }
93
+ ```
94
+
95
+ `JanusInvitationPage.totalCount` is how many invitations of the scope match the
96
+ filters, whatever the paging. It is counted only when the query selects it, only on a
97
+ page `invitations` returned (a page of your own fails), and
98
+ `authorize` is asked once, for `list`, as for the items. A pending invitation
99
+ past `expiresAt` still counts, as it is still listed.
100
+
101
+ ```graphql
102
+ query {
103
+ invitations(scope: "acme", role: "member", ref: "crm-1", order: NEWEST, limit: 20) {
104
+ items { id email ref type status }
105
+ nextCursor
106
+ totalCount
107
+ }
108
+ }
109
+ ```
110
+
111
+ `resendInvitation` and `revokeInvitation` pass the request's user as `by`, so
112
+ `JanusInvitation.resentBy` and `revokedBy` (nullable `ID`s) say who did it.
113
+
114
+ ## Who may invite: `authorize`
115
+
116
+ The core authorises nobody, so `authorize` is required and is the only guard:
117
+
118
+ ```ts
119
+ authorize: async (action, { user, scope }, ctx: Context) => {
120
+ await requireFresh(ctx, '10m'); // a thrown GraphQLError is answered as it is
121
+ return can(ctx, 'invite', { type: 'organization', id: scope });
122
+ },
123
+ ```
124
+
125
+ `action` is `'issue' | 'resend' | 'revoke' | 'list'`. The subject also says what
126
+ the call is about, so a guard can look at it:
127
+
128
+ | `action` | Extra field | Holds |
129
+ | --- | --- | --- |
130
+ | `issue` | `input` | `{ scope, email, name, role, locale?, ref?, type? }` as asked |
131
+ | `resend`, `revoke` | `invitation` | The stored `Invitation`, read before `authorize` runs; absent when the id names none (see below) |
132
+ | `list` | `page` | The `status`, `role`, `ref`, `lapsed` (`'exclude'` or `'only'`), `order` (`'asc'` or `'desc'`), `limit` and `after` the query gave (only those present); a malformed `status` or `limit` is `BAD_USER_INPUT` before `authorize` is asked |
133
+
134
+ ```ts
135
+ authorize: (action, { user, scope, input, invitation }, ctx: Context) => {
136
+ if (action === 'issue' && input?.role === 'admin') return isAdmin(ctx, user, scope);
137
+ if (action === 'revoke') return invitation?.invitedBy === user.id || isAdmin(ctx, user, scope);
138
+ return isMember(ctx, user, scope);
139
+ },
140
+ ```
141
+
142
+ `JanusInvitation.invitedBy` is `null` for an invitation the system issued
143
+ (`auth.invitations.issue({ …, invitedBy: null })` from a script; the mutation
144
+ itself always records the signed-in user), so a client must not assume an id.
145
+
146
+ To type a standalone guard, use the exported `InvitationSubject` (the second
147
+ argument) and `InvitationAction` (the first).
148
+
149
+ For `resend` and `revoke`, an id that names no invitation in the scope is
150
+ `NOT_FOUND`, the same answer a refusal gives, so existence is not revealed.
151
+ `authorize` is still asked, on the scope and without an `invitation`, so both
152
+ cases take the same path. Its answer is ignored, and so is any error it throws
153
+ except a `GraphQLError` (a step-up from `requireFresh`, say), which is answered
154
+ as it is, as for a known id. A callback that reads `subject.invitation` need not
155
+ guard against this. An anonymous caller still gets `UNAUTHENTICATED` either
156
+ way. The invitation is read with the core's `invitations.get({ id, scope })`;
157
+ a `null` answer (unknown, malformed or other-scope id) is `NOT_FOUND`. `false` answers
158
+ `NOT_FOUND`, as the core does for another scope's id and `@permission` by
159
+ default: a scope's existence is not revealed. The inviter is whatever
160
+ `ctx.janus.user()` answers, an API key's owner included under
161
+ `useJanus({ apiKey: true })`; `inviterType: 'staff'` refuses (`FORBIDDEN`) a user
162
+ of another type before `authorize` runs.
163
+
164
+ ## Where the code goes
165
+
166
+ The code is a secret that only the e-mail's link should carry. Two options:
167
+
168
+ - `sendInvitation({ action, invitation, code }, ctx)` — called after `issue`
169
+ and `resend`, where you send the e-mail. The answer's `code` is `null`.
170
+ - `answerCode: true` — `JanusIssuedInvitation.code` carries it, for an inviter
171
+ who copies the link.
172
+
173
+ Neither given is a `TypeError` at wiring: the code would reach nobody. Every
174
+ `issueInvitation` and `resendInvitation` response is `Cache-Control: no-store`
175
+ (through `useJanus()`'s `onResponse`, so over HTTP through Yoga).
176
+
177
+ If `sendInvitation` throws, the error goes up and the invitation **stays
178
+ pending**, counted against `maxPending`: call `resendInvitation` to deliver it
179
+ again.
180
+
181
+ ## What the invitee sees
182
+
183
+ `invitationPreview(code)` answers the invitation's `id`, `scope`, `email`,
184
+ `name`, `role`, `locale`, `type` (the user type the invitation is for, so the
185
+ page can adapt its wording or flow), `organization`, `expiresAt` and
186
+ `needsPassword`, without spending the code, and never who invited. Then
187
+ `acceptInvitation(code, password)` answers a member of
188
+ `InvitationAcceptResult`:
189
+
190
+ | Member | When | Cookie |
191
+ | --- | --- | --- |
192
+ | `InvitationSignedIn` | A new invitee, an account whose e-mail was never proved, or a proved account with no password yet, given one | The session cookie (and the device cookie with `device`), or `token` with `answerToken: true` |
193
+ | `InvitationSecondFactor` | A second factor is still to prove | None: confirm with `confirmSecondFactor` (`janusSecondFactorTypeDefs`) |
194
+ | `InvitationSignIn` | The address belongs to a proved user who already has a password (the password given is ignored), or who has none and gave none | None: send them to the sign-in page |
195
+
196
+ An anonymous caller learns the invitation's id, scope and role and, for
197
+ `InvitationSignIn`, the address the code was sent to; never who invited and
198
+ never the id of an existing user. Every accept response is `no-store`.
199
+
200
+ ### Naming the organization
201
+
202
+ The preview knows the scope as a string. To say "Join Acme School" on the
203
+ accept page, give `describeScope(scope, ctx)`: it answers `{ name }`, or `null`
204
+ for a scope it does not know, and `organization` carries the name (`null`
205
+ otherwise, or when the option is not given). A throw or rejection fails the
206
+ preview: return `null` to leave the name out. Nothing is stored: the name stays
207
+ in your data.
208
+
209
+ ```ts
210
+ invitationResolvers({
211
+ auth,
212
+ authorize,
213
+ sendInvitation,
214
+ describeScope: async (scope, ctx: Context) => {
215
+ const school = await schools.findOne({ slug: scope });
216
+ return school === null ? null : { name: school.name };
217
+ },
218
+ });
219
+ // query { invitationPreview(code: "…") { scope organization } }
220
+ ```
221
+
222
+ ## Errors
223
+
224
+ | Code | Status | When |
225
+ | --- | --- | --- |
226
+ | `INVITATION_INVALID` | 400 | A bad input (`extensions.field` names it), or a code that names no pending, unlapsed invitation: unknown, accepted, revoked, lapsed: `extensions.reason` is `unknown`, `expired`, `accepted` or `revoked` (a deactivated user, a taken login and a lost race stay `unknown`) |
227
+ | `INVITATION_LIMIT` | 409 | The scope holds `maxPending` invitations; `extensions.maxActive` |
228
+ | `INVITATION_NOT_PENDING` | 409 | `resendInvitation` or `revokeInvitation` of an accepted or revoked invitation |
229
+ | `INVITATION_REFUSED` | 403 | `acceptInvitation` refused by the `beforeAccept` hook of `invitations`; nothing was written, the invitation is still pending (`Forbidden`) |
230
+ | `PASSWORD_REQUIRED` | 400 | A new invitee (or an e-mail never proved) accepted without a password; nothing was written |
231
+ | `PASSWORD_TOO_SHORT`, `USER_INVALID`, `USER_INACTIVE` | per `statusOf` | As for `signUp` |
232
+ | `NOT_FOUND` | 404 | `authorize` answered `false`, or an id of another scope, or an unknown id on resend or revoke (`authorize` is asked without an `invitation`; its answer is ignored) |
233
+ | `UNAUTHENTICATED` | 401 | An owner field with no signed-in user |
234
+ | `BAD_USER_INPUT` | 400 | A `status` that is not one of the three, a `limit` that is not a positive integer, an `after` cursor issued for another scope, status, role, ref, lapsed or order, or a string over its maximum (`extensions.field` names it; see below) |
235
+
236
+ ### Bounded arguments
237
+
238
+ Every string argument has a maximum, checked before `authorize`, a hash or a
239
+ store is asked, and refused as `BAD_USER_INPUT`, 400, with the argument in
240
+ `extensions.field`:
241
+
242
+ | Argument | Maximum |
243
+ | --- | --- |
244
+ | `password` (`acceptInvitation`) | 1024 characters |
245
+ | `code` (`invitationPreview`, `acceptInvitation`) | 43, the length of a code |
246
+ | `scope` | 512 |
247
+ | `email` | 254, once trimmed |
248
+ | `name` | 100, once trimmed |
249
+ | `role`, `ref` | 100 |
250
+ | `locale` | 35 |
251
+
252
+ The core has no maximum on a password, only a minimum; 1024 is this layer's,
253
+ so a holder of a valid code cannot make the server hash a request-sized
254
+ secret. The other maxima are the core's own, held here so the refusal comes
255
+ first. The refusal spends nothing: the code stays pending.
256
+
257
+ ## Traps
258
+
259
+ - **Throttle `invitationPreview` and `acceptInvitation`.** The library does not:
260
+ a rate limit by IP in front of GraphQL, on these two operations.
261
+ - **`describeScope` runs for whoever holds a code**, with no session: answer a
262
+ display name only, never data the invitee should not see. A code that names
263
+ no invitation fails before it is called.
264
+ - **Send the code by POST.** In the variables, never in a GET's URL: proxies
265
+ and access logs keep URLs. In the e-mail's link, prefer the fragment
266
+ (`/join#<code>`), which the browser does not send.
267
+ - **Accepting while signed in as somebody else** replaces the session cookie
268
+ of the new invitee's accept: the page should say so, or sign the other user out first.
269
+ - **`InvitationSignIn` is not a session.** Do not treat it as a sign-in.
@@ -0,0 +1,207 @@
1
+ # Passkeys
2
+
3
+ This page is for letting users hold passkeys as a second factor, and sign in
4
+ with one, from a GraphQL API: the schema, the resolvers, how the browser's JSON
5
+ travels, the cookies, the guards and the errors. It is opt-in: nothing here is
6
+ declared by `janusTypeDefs`, and a server without passkeys imports none of it.
7
+
8
+ What a passkey is in Janus (a second factor beside TOTP, never instead of it),
9
+ the wiring of `janus({ passkeys })`, the verifier and the counter rule are
10
+ [`@softistx/janus`'s passkeys guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passkeys.md).
11
+ This package only puts `auth.passkeys` and `auth.secondFactor.confirmPasskey` in the schema.
12
+
13
+ ## The schema
14
+
15
+ ```ts
16
+ import {
17
+ janusMaskError,
18
+ janusPasskeyTypeDefs,
19
+ janusTypeDefs,
20
+ passkeyResolvers,
21
+ useJanus,
22
+ } from '@softistx/janus-graphql';
23
+ import { createSchema, createYoga } from 'graphql-yoga';
24
+
25
+ const typeDefs = /* GraphQL */ `
26
+ type Query { me: Viewer @authenticated }
27
+ type Mutation { noop: Boolean }
28
+ type Viewer { email: String! }
29
+ extend type PasskeySignedIn { user: Viewer! }
30
+ `;
31
+
32
+ export const yoga = createYoga({
33
+ schema: createSchema({
34
+ typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, typeDefs],
35
+ resolvers: {
36
+ ...passkeyResolvers({ auth }),
37
+ PasskeySignedIn: { user: (signedIn) => signedIn.user },
38
+ },
39
+ }),
40
+ plugins: [useJanus({ auth })],
41
+ maskedErrors: { maskError: janusMaskError() },
42
+ });
43
+ ```
44
+
45
+ `janusPasskeyTypeDefs` (also `graphql/janus-passkeys.graphqls`) `extend`s your
46
+ `Query` and `Mutation`, so both must exist, and it uses `@authenticated`, so
47
+ `janusTypeDefs` goes beside it. `passkeyResolvers` returns the keys `Query` and
48
+ `Mutation`: with resolvers of your own on either, merge the maps
49
+ (`mergeResolvers` from `@graphql-tools/merge`) instead of spreading over them.
50
+ `passkeyResolvers` throws a `TypeError` at wiring when `auth` has no
51
+ `passkeys` (see [troubleshooting](../troubleshooting.md#typeerror-passkeyresolvers-auth-has-no-passkeys--)).
52
+
53
+ | Field | Guard | Answers |
54
+ | --- | --- | --- |
55
+ | `passkeys` (on `Query`) | `@authenticated` | `[JanusPasskey!]!`, oldest first: `credentialId`, `name`, `transports`, `aaguid`, `backupEligible`, `backedUp`, `createdAt`, `lastUsedAt` (ISO-8601). Never the public key or the counter |
56
+ | `passkeyRegistrationOptions` (on `Query`) | `@authenticated` | `JanusPasskeyRegistration!`: `options` (JSON text), `challenge`, `expiresAt`. It makes and stores a challenge, though it is a query; its response carries `Cache-Control: no-store` (through `useJanus()`'s `onResponse`, over HTTP) |
57
+ | `registerPasskey(challenge: String!, response: String!, name: String!)` | `@authenticated` | `JanusPasskey!`. The core asks for a fresh session |
58
+ | `renamePasskey(credentialId: ID!, name: String!)` | `@authenticated` | `Boolean!`: `false` for a passkey that is not the user's |
59
+ | `removePasskey(credentialId: ID!)` | `@authenticated` | `Boolean!`: whether this call removed it. The core asks for a fresh session |
60
+ | `confirmSecondFactorPasskey(challenge: String!, assertion: String!)` | none | `PasskeySignedIn!`: `token`, `userId`, `expiresAt`, `newDevice` |
61
+
62
+ `registerPasskey` and `removePasskey` carry no `@fresh`: the core refuses a
63
+ session older than `passkeys.freshWithin` (10 minutes by default) with
64
+ `STEP_UP_REQUIRED`, 403, so the client runs the [step-up](step-up.md) and
65
+ retries, and the window stays the one `janus({ passkeys })` configured.
66
+
67
+ ## JSON travels as strings
68
+
69
+ The browser's options, responses and assertions are JSON the verifier shaped
70
+ and the page passes along untouched, so they are `String`s in the schema:
71
+
72
+ ```ts
73
+ // 1. Registration
74
+ const { options, challenge } = (await gql(`{ passkeyRegistrationOptions { options challenge } }`)).passkeyRegistrationOptions;
75
+ const credential = await navigator.credentials.create({ publicKey: parseCreationOptionsFromJSON(JSON.parse(options)) });
76
+ await gql(
77
+ `mutation($c: String!, $r: String!) { registerPasskey(challenge: $c, response: $r, name: "Laptop") { credentialId } }`,
78
+ { c: challenge, r: JSON.stringify(credential.toJSON()) },
79
+ );
80
+ ```
81
+
82
+ A `response` or `assertion` that is not JSON is `BAD_USER_INPUT`, 400, with a
83
+ fixed message and **before anything is spent**; the text is never echoed back.
84
+
85
+ ## Signing in with a passkey
86
+
87
+ The sign-in mutation is yours (`auth.signIn`, a code, a link): when it answers
88
+ `SecondFactorRequired`, show `result.methods` and hand `result.passkeyOptions`
89
+ to the page. Social sign-in already does: `SocialSecondFactor` carries
90
+ `methods: [String!]!` and `passkeyOptions: String` (JSON text, null without a
91
+ passkey). The page then calls:
92
+
93
+ ```graphql
94
+ mutation($c: String!, $a: String!) {
95
+ confirmSecondFactorPasskey(challenge: $c, assertion: $a) { userId expiresAt newDevice user { email } }
96
+ }
97
+ ```
98
+
99
+ - **The session** is set as a cookie through `useJanus()`'s `onResponse`, as
100
+ `socialSignInComplete` does. With `passkeyResolvers({ auth, answerToken: true })` no
101
+ cookie is set and `PasskeySignedIn.token` answers the session token, for a
102
+ BFF that forwards it as `Authorization: Bearer`. A response that answers the
103
+ token carries `Cache-Control: no-store` (through `useJanus()`'s `onResponse`,
104
+ over HTTP), so no cache keeps it.
105
+ - **The device** is tracked only with `passkeyResolvers({ auth, device: true })`
106
+ (or the device cookie's attributes), and needs `janus({ devices })`: a visitor
107
+ without the cookie is a new device (`newDevice`, `user.newDeviceSignedIn`) and gets
108
+ the cookie. Without `device` nothing is tracked, as `socialSignInComplete`.
109
+ - **Attempts**: the challenge's five are shared with the TOTP code. A wrong
110
+ assertion is `CODE_INVALID`, 401, with `attemptsLeft`; the fifth spends the
111
+ challenge (a later call is `TOKEN_SPENT` or `TOKEN_UNKNOWN`).
112
+
113
+ Several user types: pass `type` (`passkeyResolvers({ auth, type: 'staff' })`),
114
+ which reads `auth.staff.passkeys` and limits every field to that type's users.
115
+
116
+ ## Passkey as the first factor
117
+
118
+ With `janus({ passkeys: { firstFactor: true } })` (a `secondFactor` is optional then), a user registers a passkey without a TOTP and signs in with it alone: no password, no code. The core's rules are in [its passkeys guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/passkeys.md). Here it is the schema:
119
+
120
+ ```ts
121
+ createSchema({
122
+ typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, janusPasskeySignInTypeDefs, typeDefs],
123
+ resolvers: {
124
+ ...passkeyResolvers({ auth, firstFactor: true }),
125
+ PasskeySignedIn: { user: (signedIn) => signedIn.user },
126
+ },
127
+ });
128
+ ```
129
+
130
+ `janusPasskeySignInTypeDefs` (also `graphql/janus-passkey-sign-in.graphqls`) goes beside `janusPasskeyTypeDefs`, whose `PasskeySignedIn` it answers. `passkeyResolvers({ firstFactor: true })` throws a `TypeError` at wiring when `auth` has no `passkeys`. With `firstFactor: true` the returned map types `Query.passkeySignInOptions` and `Mutation.passkeySignIn` as defined, so they are callable without a guard; without it they stay optional (`PasskeyResolvers<F>`, `F` defaulting to `boolean`). It needs no `secondFactor` on the instance (only `confirmSecondFactorPasskey` does, and it fails on the call without one); an instance whose `passkeys` has no `firstFactor: true` is refused by the core on the call (a `TypeError` naming `passkeys.firstFactor`).
131
+
132
+ | Field | Guard | Answers |
133
+ | --- | --- | --- |
134
+ | `passkeySignInOptions` (on `Query`) | none | `JanusPasskeySignInChallenge!`: `options` (JSON text for `navigator.credentials.get`, no credential named), `challenge`, `expiresAt`. It stores a token, though it is a query; its response carries `Cache-Control: no-store`. **Rate-limit it** where requests enter |
135
+ | `passkeySignIn(challenge: String!, assertion: String!)` | none | `PasskeySignedIn!`: `token`, `userId`, `expiresAt`, `newDevice` |
136
+
137
+ ```ts
138
+ const { options, challenge } = (await gql(`{ passkeySignInOptions { options challenge } }`)).passkeySignInOptions;
139
+ const assertion = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(JSON.parse(options)) });
140
+ await gql(
141
+ `mutation($c: String!, $a: String!) { passkeySignIn(challenge: $c, assertion: $a) { userId expiresAt } }`,
142
+ { c: challenge, a: JSON.stringify(assertion.toJSON()) },
143
+ );
144
+ ```
145
+
146
+ The session cookie, `answerToken` and `device` work as for `confirmSecondFactorPasskey` above. One attempt per challenge: an assertion the core refuses is `CREDENTIALS_INVALID`, 401, and a missing, spent or lapsed challenge is `TOKEN_UNKNOWN`, `TOKEN_SPENT` or `TOKEN_EXPIRED`; ask for new options each time. A user whose account is inactive is `USER_INACTIVE`, and `EMAIL_UNVERIFIED` follows `password.requireVerifiedEmail`.
147
+
148
+ ## One auth instance per request
149
+
150
+ `auth` may be a function of the GraphQL context, as `useJanus({ auth })` allows, for a server that builds one `janus()` instance per tenant:
151
+
152
+ ```ts
153
+ const authFor = (ctx: { host: string }) => instances.get(ctx.host);
154
+
155
+ createYoga({
156
+ schema: createSchema({
157
+ typeDefs,
158
+ resolvers: passkeyResolvers({ auth: authFor, firstFactor: true }),
159
+ }),
160
+ plugins: [useJanus({ auth: authFor, types: ['user'] })],
161
+ context: ({ request }) => ({ host: new URL(request.url).host }),
162
+ });
163
+ ```
164
+
165
+ - The function runs on every passkey field, may return a promise, and its answer is bound once per instance. `null` or `undefined` (no tenant for this host) is `UNAUTHENTICATED`, 401.
166
+ - An instance is checked when it is chosen: one with no `passkeys` (or no `firstFactor` with that option) is a `TypeError` on that request, not at wiring.
167
+ - Give `useJanus()` the same function, so `@authenticated`, `ctx.janus` and the field resolvers agree on the instance. Registration challenges and sign-in challenges live in the chosen instance's store.
168
+ - `type`, `answerToken` and `device` apply to every instance the function answers.
169
+
170
+ ## Step-up with a passkey
171
+
172
+ `@softistx/janus-graphql` declares no step-up mutations: [yours](step-up.md)
173
+ call the core's two methods, with the same `rethrown` handling:
174
+
175
+ ```ts
176
+ // StepUpByPasskey: { via: 'passkey', challenge, options, expiresAt, user }
177
+ const issued = await auth.stepUp.request(user, { via: 'passkey' });
178
+ // answer { challenge: issued.challenge, options: JSON.stringify(issued.options) }
179
+
180
+ // the page sends back the challenge and the assertion as a JSON string
181
+ const session = await auth.stepUp.confirmPasskey(
182
+ request, // the request that presents the session
183
+ challenge,
184
+ JSON.parse(assertion), // what navigator.credentials.get produced
185
+ );
186
+ ```
187
+
188
+ ## Errors
189
+
190
+ Every refusal of the core goes through `janusMaskError()`:
191
+
192
+ | `extensions.code` | Status | When |
193
+ | --- | --- | --- |
194
+ | `PASSKEY_INVALID` | 400 | the response does not verify, or the name is not 1 to 100 characters (`extensions.field: 'name'`). The challenge of a failed verification stays spent |
195
+ | `PASSKEY_TAKEN` | 409 | the credential is already registered |
196
+ | `PASSKEY_LIMIT` | 409 | the user holds the maximum (`extensions.maxActive`) |
197
+ | `EMAIL_UNVERIFIED` | 403 | registration options or `registerPasskey` while the account's e-mail is not proved |
198
+ | `SECOND_FACTOR_NOT_ENROLLED` | 409 | options asked for a user whose TOTP is not active |
199
+ | `STEP_UP_REQUIRED` | 403 | `registerPasskey` or `removePasskey` on a stale session |
200
+ | `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED` | 4xx | the registration or sign-in challenge |
201
+ | `CODE_INVALID` | 401 | a sign-in assertion that does not verify (`attemptsLeft`) |
202
+ | `CREDENTIALS_INVALID` | 401 | a first-factor assertion the core refuses |
203
+ | `BAD_USER_INPUT` | 400 | `response` or `assertion` is not JSON |
204
+
205
+ The verifier's `reason` never reaches the client.
206
+
207
+ Related: [social sign-in](social.md), [the step-up over GraphQL](step-up.md), [errors](errors.md).