@owlmeans/auth 0.1.18-rc.9 → 0.1.18

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 (84) hide show
  1. package/README.md +289 -45
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/auth/SKILL.md +29 -23
  4. package/agent-meta/skills/auth-protocol/SKILL.md +111 -91
  5. package/build/allowance/index.d.ts +1 -1
  6. package/build/allowance/index.d.ts.map +1 -1
  7. package/build/allowance/index.js +1 -1
  8. package/build/allowance/index.js.map +1 -1
  9. package/build/allowance/schemas.d.ts +7 -0
  10. package/build/allowance/schemas.d.ts.map +1 -0
  11. package/build/allowance/schemas.js +62 -0
  12. package/build/allowance/schemas.js.map +1 -0
  13. package/build/auth/index.d.ts +1 -1
  14. package/build/auth/index.d.ts.map +1 -1
  15. package/build/auth/index.js +1 -1
  16. package/build/auth/index.js.map +1 -1
  17. package/build/auth/schemas.d.ts +8 -0
  18. package/build/auth/schemas.d.ts.map +1 -0
  19. package/build/auth/schemas.js +55 -0
  20. package/build/auth/schemas.js.map +1 -0
  21. package/build/consts.d.ts +5 -0
  22. package/build/consts.d.ts.map +1 -1
  23. package/build/consts.js +5 -0
  24. package/build/consts.js.map +1 -1
  25. package/build/entity/index.d.ts +1 -1
  26. package/build/entity/index.js +1 -1
  27. package/build/entity/schemas.d.ts +4 -0
  28. package/build/entity/schemas.d.ts.map +1 -0
  29. package/build/entity/schemas.js +21 -0
  30. package/build/entity/schemas.js.map +1 -0
  31. package/build/errors.d.ts +15 -0
  32. package/build/errors.d.ts.map +1 -1
  33. package/build/errors.js +19 -0
  34. package/build/errors.js.map +1 -1
  35. package/build/helper/types.d.ts +22 -0
  36. package/build/helper/types.d.ts.map +1 -0
  37. package/build/helper/types.js +2 -0
  38. package/build/helper/types.js.map +1 -0
  39. package/build/helper.d.ts +7 -11
  40. package/build/helper.d.ts.map +1 -1
  41. package/build/helper.js +30 -27
  42. package/build/helper.js.map +1 -1
  43. package/build/index.d.ts +1 -0
  44. package/build/index.d.ts.map +1 -1
  45. package/build/index.js.map +1 -1
  46. package/build/permission/index.d.ts +1 -1
  47. package/build/permission/index.d.ts.map +1 -1
  48. package/build/permission/index.js +1 -1
  49. package/build/permission/index.js.map +1 -1
  50. package/build/permission/schemas.d.ts +6 -0
  51. package/build/permission/schemas.d.ts.map +1 -0
  52. package/build/permission/schemas.js +27 -0
  53. package/build/permission/schemas.js.map +1 -0
  54. package/build/rely/index.d.ts +1 -1
  55. package/build/rely/index.d.ts.map +1 -1
  56. package/build/rely/index.js +1 -1
  57. package/build/rely/index.js.map +1 -1
  58. package/build/rely/schemas.d.ts +4 -0
  59. package/build/rely/schemas.d.ts.map +1 -0
  60. package/build/rely/schemas.js +12 -0
  61. package/build/rely/schemas.js.map +1 -0
  62. package/build/supervisor.d.ts +0 -8
  63. package/build/supervisor.d.ts.map +1 -1
  64. package/build/types.d.ts +12 -0
  65. package/build/types.d.ts.map +1 -1
  66. package/package.json +4 -4
  67. package/src/allowance/index.ts +1 -1
  68. package/src/allowance/{model.ts → schemas.ts} +4 -2
  69. package/src/auth/index.ts +1 -1
  70. package/src/auth/{model.ts → schemas.ts} +1 -1
  71. package/src/consts.ts +6 -0
  72. package/src/entity/index.ts +1 -1
  73. package/src/entity/{profile.ts → schemas.ts} +1 -1
  74. package/src/errors.ts +22 -1
  75. package/src/helper/types.ts +22 -0
  76. package/src/helper.ts +44 -33
  77. package/src/index.ts +1 -0
  78. package/src/permission/index.ts +1 -1
  79. package/src/rely/index.ts +1 -1
  80. package/src/supervisor.ts +0 -8
  81. package/src/types.ts +13 -0
  82. package/tests/errors.spec.ts +19 -0
  83. /package/src/permission/{model.ts → schemas.ts} +0 -0
  84. /package/src/rely/{model.ts → schemas.ts} +0 -0
package/README.md CHANGED
@@ -1,84 +1,328 @@
1
1
  # @owlmeans/auth
2
2
 
3
- Core authentication types, schemas, and constants for OwlMeans fullstack applications.
4
-
5
- ## Overview
6
-
7
- - Defines the shared `Auth`, `AuthCredentials`, `AuthPayload`, and `AuthToken` types used by all auth-related packages
8
- - Provides AJV schemas for validating auth requests (`AuthCredentialsSchema`, `AllowanceRequestSchema`, etc.)
9
- - Defines the `AuthRole` and `AuthenticationStage` enums used across server and client
10
- - Used in request handlers to access `req.auth` and throw typed auth errors
3
+ The core authentication and authorization vocabulary shared by server and client: the `Auth` /
4
+ `AuthPayload` / `AuthCredentials` types, the `AuthRole` and `AuthenticationType` enums, the auth
5
+ error hierarchy, AJV schemas for request bodies and record fields, the auth entrypoint aliases, and
6
+ `authHelper.entitySlugOf()` for reading the organization entity off a token. An app imports it whenever code
7
+ on either side of the wire needs to name an identity, throw an auth error, or reuse a scalar schema
8
+ (`IdValueSchema`, `DateSchema`). It contains no services and no wiring: guards, the Ed25519 guard,
9
+ shared auth protocols and organization-entity resolution (`makeEntityScope(req)` —
10
+ `entityKeyOf`, `requireEntityKey`, `attachEntity`) live in [`@owlmeans/auth-common`](../auth-common); the server auth service in
11
+ [`@owlmeans/server-auth`](../server-auth); the browser auth service in
12
+ [`@owlmeans/client-auth`](../client-auth).
11
13
 
12
14
  ## Installation
13
15
 
14
16
  ```bash
15
- bun add @owlmeans/auth@^0.1.18-rc.8
17
+ bun add @owlmeans/auth@^0.1.18
16
18
  ```
17
19
 
20
+ `ajv` is a **peer** dependency — install it alongside, or `authHelper.verifyAuth` /
21
+ `authHelper.verifyAuthCredentials` fail to resolve.
22
+
23
+ ## Concepts
24
+
25
+ - **Authorization** — the RBAC base every identity shape extends: `entitySlug?`, `scopes`,
26
+ `permissions?` (`PermissionSet[]`), `attributes?`, `permissioned?`, `denormalized?`.
27
+ - **AuthPayload / Auth** — `AuthPayload` adds `type`, `role`, `userId`, `profileId?`,
28
+ `expiresAt?`; `Auth` is the resolved identity a guard puts on `request.auth` (adds `token`,
29
+ `isUser`, `createdAt`).
30
+ - **Allowance / credentials** — the two-step handshake: a client posts an `AllowanceRequest` to get
31
+ a `challenge`, then posts `AuthCredentials` (`challenge` + `credential`) to authenticate.
32
+ - **Organization entity** — `entitySlug` is the renameable organization name and the only
33
+ organization value on the wire. Read it with `authHelper.entitySlugOf(payload)`. The stable `entityId` is
34
+ never on the wire and is not declared here; server handlers get it from
35
+ `makeEntityScope(req).requireEntityKey()` / `.requireEntity()` in `@owlmeans/auth-common`.
36
+ - **Error hierarchy** — `AuthError` is the root of i18n-aware `ResilientError` subclasses that
37
+ survive marshalling across a service boundary: `AuthUnknown` (no identity), `AuthenFailed`
38
+ (credential rejected), `AuthForbidden` (authenticated, not allowed).
39
+ - **Authentication stage** — `AuthenticationStage` tracks a client or socket flow from `Init` to
40
+ `Authenticated` (or `Error`).
41
+
18
42
  ## Usage
19
43
 
20
- Throw a typed auth error when a request lacks an entity:
44
+ ### Reuse scalar schemas in shared contracts
45
+
46
+ Field schemas keep ids, dates and scopes consistent across every app model.
47
+
48
+ ```ts
49
+ import type { JSONSchemaType } from 'ajv'
50
+ import { DateSchema, IdValueSchema } from '@owlmeans/auth'
51
+
52
+ export interface Invoice {
53
+ id?: string
54
+ projectId: string
55
+ total: number
56
+ createdAt: Date
57
+ }
58
+
59
+ export const InvoiceSchema: JSONSchemaType<Invoice> = {
60
+ type: 'object',
61
+ properties: {
62
+ id: { ...IdValueSchema, nullable: true },
63
+ projectId: IdValueSchema,
64
+ total: { type: 'number', minimum: 0 },
65
+ createdAt: DateSchema,
66
+ },
67
+ required: ['projectId', 'total', 'createdAt'],
68
+ additionalProperties: false,
69
+ }
70
+ ```
71
+
72
+ ### Throw typed errors from a handler
21
73
 
22
- ```typescript
23
- import { AuthUnknown } from '@owlmeans/auth'
74
+ A handler that finds no identity throws `AuthUnknown`; one that finds an identity without the right
75
+ to act throws `AuthForbidden`. Organization-scoped records are keyed by the resolved id from
76
+ `makeEntityScope(req).requireEntityKey()`, never by the slug on the token.
24
77
 
25
- export const create = handleBody(async (body, context, request) => {
26
- if (request.auth?.entityId == null) {
27
- throw new AuthUnknown('entity')
78
+ ```ts
79
+ import { AuthForbidden, AuthUnknown } from '@owlmeans/auth'
80
+ import { makeEntityScope } from '@owlmeans/auth-common'
81
+ import { handlers } from '@owlmeans/server-api'
82
+ import { invoiceProtocols } from 'my-app-common'
83
+ import type { AppContext } from '../types.js'
84
+
85
+ const api = handlers<AppContext>()
86
+
87
+ export const listInvoices = api.request(invoiceProtocols.list, async (req, context) => {
88
+ if (req.auth?.profileId == null) {
89
+ throw new AuthUnknown('profile')
90
+ }
91
+ const entityId = makeEntityScope(req).requireEntityKey() // stable record id, never from the token
92
+
93
+ return await loadInvoices(context, entityId, req.params.projectId)
94
+ })
95
+
96
+ export const archiveInvoice = api.request(invoiceProtocols.archive, async (req, context) => {
97
+ const entityId = makeEntityScope(req).requireEntityKey()
98
+ if (!req.auth!.scopes.includes('invoice-admin')) {
99
+ throw new AuthForbidden('permission')
28
100
  }
29
- // ...
101
+
102
+ return await archive(context, entityId, req.params.id)
30
103
  })
31
104
  ```
32
105
 
33
- Check authentication stage in a WebSocket connection:
106
+ ### Deny access in a gate
107
+
108
+ A gate service declared on a protocol (`gate: { alias, params }`) asserts scopes and throws
109
+ `AuthForbidden` on denial.
110
+
111
+ ```ts
112
+ import { createLazyService } from '@owlmeans/context'
113
+ import type { GateService } from '@owlmeans/entrypoint'
114
+ import { ALL_SCOPES, AuthForbidden } from '@owlmeans/auth'
115
+ import { makeEntityScope } from '@owlmeans/auth-common'
34
116
 
35
- ```typescript
36
- import { AuthenticationStage } from '@owlmeans/auth'
117
+ export const makeProjectGate = (alias: string = 'my-app:project-gate'): GateService =>
118
+ createLazyService<GateService>(alias, {
119
+ assert: async (req, _, params) => {
120
+ if (req.auth == null) throw new AuthForbidden('auth')
121
+
122
+ const entityId = makeEntityScope(req).entityKeyOf()
123
+ if (entityId == null) throw new AuthForbidden('entity')
124
+
125
+ // Params name the organization by its stable id, matching how grants are stored.
126
+ const required = params.map(p => p.replace(/\{entity\}/g, entityId))
127
+ const scopes = req.auth.scopes ?? []
128
+ if (!required.every(p => scopes.includes(ALL_SCOPES) || scopes.includes(p))) {
129
+ throw new AuthForbidden('permission')
130
+ }
131
+ },
132
+ })
133
+ ```
37
134
 
38
- if (connection.stage !== AuthenticationStage.Authenticated) {
39
- throw new AuthUnknown('not-authenticated')
135
+ ### Authenticate a socket connection
136
+
137
+ A socket authenticates after its connection is open, so it moves through `AuthenticationStage`
138
+ itself, sets the bearer token under `AUTH_HEADER`, and must call `makeEntityScope(req).attachEntity(context)`.
139
+
140
+ ```ts
141
+ import type { Auth, AuthToken } from '@owlmeans/auth'
142
+ import { AUTH_HEADER, AuthenFailed, AuthenticationStage, AuthUnknown } from '@owlmeans/auth'
143
+ import { DEFAULT_GUARD, makeEntityScope } from '@owlmeans/auth-common'
144
+ import type { AbstractRequest, AbstractResponse, GuardService } from '@owlmeans/entrypoint'
145
+ import { provideResponse } from '@owlmeans/entrypoint'
146
+ import type { AppContext } from '../types.js'
147
+
148
+ export const authenticateSocket = (context: AppContext, req: AbstractRequest) =>
149
+ async (stage: AuthenticationStage, token: AuthToken) => {
150
+ if (stage !== AuthenticationStage.Authenticate) throw new AuthUnknown('stage')
151
+
152
+ req.headers ??= {}
153
+ req.headers[AUTH_HEADER] ??= token.token
154
+
155
+ const res: AbstractResponse<Auth> = provideResponse({ header: () => void 0 })
156
+ if (!await context.service<GuardService>(DEFAULT_GUARD).handle(req, res) || res.value == null) {
157
+ throw new AuthenFailed('guard')
158
+ }
159
+
160
+ req.auth = res.value
161
+ await makeEntityScope(req).attachEntity(context)
162
+
163
+ return [AuthenticationStage.Authenticated, true]
164
+ }
165
+ ```
166
+
167
+ ### Build payloads, read the organization, widen a token schema
168
+
169
+ `AuthRole` is a string enum, `authHelper.entitySlugOf` is the only supported way to read the organization off a
170
+ payload, and `AuthTokenSchema` caps `token` at 1024 characters — a route carrying a wrapped
171
+ credential envelope declares its own wider schema.
172
+
173
+ ```ts
174
+ import type { JSONSchemaType } from 'ajv'
175
+ import type { AuthPayload, AuthToken } from '@owlmeans/auth'
176
+ import { AuthRole, AuthenticationType, authHelper } from '@owlmeans/auth'
177
+
178
+ const payload: AuthPayload = {
179
+ type: AuthenticationType.OneTimeToken,
180
+ role: AuthRole.User,
181
+ userId: 'account-1',
182
+ profileId: 'profile-1',
183
+ entitySlug: 'acme-studio',
184
+ scopes: ['my-app-project'],
185
+ }
186
+
187
+ const orgLabel = authHelper.entitySlugOf(payload) // string | undefined — opaque, never a database key
188
+
189
+ export const WrappedTokenSchema: JSONSchemaType<AuthToken> = {
190
+ type: 'object',
191
+ properties: { token: { type: 'string', minLength: 32, maxLength: 8192 } },
192
+ required: ['token'],
193
+ additionalProperties: false,
40
194
  }
195
+
196
+ export const tokenOf = (body: unknown): string | undefined =>
197
+ authHelper.isAuthToken(body) ? body.token : undefined
41
198
  ```
42
199
 
43
200
  ## API
44
201
 
202
+ All symbols are exported from the package root (`@owlmeans/auth`); there are no subpath exports.
203
+
45
204
  ### Types
46
205
 
47
- - `Auth` — the auth object attached to `request.auth`; contains `userId`, `entityId`, `role`, `scopes`
48
- - `AuthCredentials` — signed credential payload with `challenge`, `credential`, `publicKey`
49
- - `AuthPayload` — base payload with `type`, `role`, `userId`, `profileId`, `expiresAt`
50
- - `AuthToken` — JWT-like token structure
206
+ | Symbol | Kind | Purpose |
207
+ |--------|------|---------|
208
+ | `Authorization` | interface | RBAC base: `entitySlug?`, `scopes`, `permissions?`, `attributes?`, `permissioned?`, `denormalized?` |
209
+ | `ProfilePayload` | interface | `Authorization` + `groups?` |
210
+ | `AuthPayload` | interface | `ProfilePayload` + `type`, `role`, `userId`, `source?`, `profileId?`, `expiresAt?` |
211
+ | `AuthCredentials` | interface | `AuthPayload` + `challenge`, `credential`, `publicKey?` — the authenticate body |
212
+ | `Auth` | interface | `AuthPayload` + `token`, `isUser`, `createdAt` — the identity on `request.auth` |
213
+ | `Profile` | interface | `ProfilePayload` + `id`, `name`, `credential?`, `secret?` — a stored identity record |
214
+ | `Group` | interface | `Authorization` + `id`, `name` |
215
+ | `AllowanceRequest` | interface | `Partial<AuthPayload>` with required `type` — asks for a challenge |
216
+ | `AllowanceResponse` | interface | `{ challenge }` |
217
+ | `AuthToken` | interface | `{ token }` — the bearer envelope on the wire |
218
+ | `PermissionSet` | interface | `scope`, `title?`, `permissions: Capabilties`, `resources?` |
219
+ | `Capabilties` | interface | Map of capability name to `boolean \| number \| null` |
220
+ | `AttributeSet` | interface | `scope`, `attributes: string[]` |
221
+ | `RelyToken` | interface | Rely-handshake token: `nonce`, `pin?`, `token?`, `check?` |
222
+ | `SupervisorCredentialPayload` | interface | `{ salt, signature }` packed into a supervisor credential |
51
223
 
52
224
  ### Enums
53
225
 
54
- ```typescript
55
- enum AuthRole { User, Guest, Service, System, Admin, Superuser, Blocked }
56
- enum AuthenticationType { BasicEd25519, OneTimeToken, ReCaptcha }
57
- enum AuthenticationStage { /* connection auth lifecycle */ }
58
- ```
226
+ | Symbol | Kind | Purpose |
227
+ |--------|------|---------|
228
+ | `AuthRole` | string enum | `User`, `Guest`, `Service`, `System`, `Admin`, `Superuser`, `Blocked` |
229
+ | `AuthenticationType` | string enum | How identity is proven: `BasicEd25519`, `OneTimeToken`, `ReCaptcha`, `WalletDid`, `RelyHandshake`, `WalletConsumer`, `WalletProvider`, `Google` (`'google-oauth'`), `Supervisor` (`'pk-supervisor'`) |
230
+ | `AuthroizationType` (sic) | string enum | How a request carries authorization: `AuthToken`, `Ed25519BasicToken`, `Ed25519BasicSignature` |
231
+ | `AuthenticationStage` | string enum | Flow stage: `Error`, `Init`, `Allowence`, `Authenticate`, `Authentication`, `Authenticated` |
232
+
233
+ ### Constants
234
+
235
+ | Symbol | Kind | Purpose |
236
+ |--------|------|---------|
237
+ | `AUTH_HEADER` / `AUTH_QUERY` | const | `'authorization'` / `'token'` |
238
+ | `ENTITY_QUERY` / `PROFILE_QUERY` | const | `'entitySlug'` / `'profile'` query parameter names |
239
+ | `ALL_SCOPES` / `AUTH_SCOPE` | const | `'*'` / `'__auth'` |
240
+ | `INCLUDE`, `EXCLUDE`, `WILDCARD`, `DELIMITER` | const | Permission-string grammar: `'+'`, `'-'`, `'*'`, `':'` |
241
+ | `GUEST_ID`, `RELY_3RD` | const | Reserved ids: `'__guest'`, `'rely'` |
242
+ | `AUTHEN`, `AUTHEN_INIT`, `AUTHEN_AUTHEN`, `AUTHEN_RELY` | const | Backend authentication entrypoint aliases |
243
+ | `CAUTHEN`, `CAUTHEN_AUTHEN`, `CAUTHEN_AUTHEN_DEFAULT`, `CAUTHEN_AUTHEN_TYPED`, `CAUTHEN_FLOW_ENTER` | const | Front-end authentication entrypoint aliases |
244
+ | `DISPATCHER`, `DISPATCHER_AUTHEN`, `DISPATCHER_SURROGATE` | const | Dispatcher and surrogate login-window entrypoint aliases |
245
+ | `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | const | reCAPTCHA plugin-record ids (server secret + policy, browser site key) |
246
+ | `RECAPTCHA_GUARD` | const | `'guard:re-captcha'` — the guard alias of a route a reCAPTCHA-proven guest calls once |
59
247
 
60
248
  ### Errors
61
249
 
62
- - `AuthUnknown` — thrown when a request is missing or has invalid auth
250
+ Every class extends `ResilientError` (`@owlmeans/error`), is registered for marshalling, and takes
251
+ an optional message suffix (default `'error'`).
252
+
253
+ | Symbol | Kind | Purpose |
254
+ |--------|------|---------|
255
+ | `AuthError` | class | Root of the hierarchy |
256
+ | `AuthUnknown` | class | The subject is not known — missing auth state, unregistered plugin type |
257
+ | `AuthManagerError` | class | The auth manager itself failed |
258
+ | `AuthManagerUnsupported` | class | The manager cannot serve this request shape |
259
+ | `AuthenFailed` | class | Authentication attempted and rejected (bad challenge, code, signature) |
260
+ | `AuthenExists` | class | The identity being registered already exists |
261
+ | `AuthenPayloadError` | class | A required credential field is missing |
262
+ | `AuthPluginError` | class | An auth plugin misbehaved |
263
+ | `TypeMissmatchError` | class | A plugin was handed the wrong authentication type |
264
+ | `AuthorizationError` | class | Authenticated, but no usable authorization |
265
+ | `AuthForbidden` | class | Authenticated and understood — and not allowed |
266
+ | `ProfileError` / `ProfileConsistencyError` | class | A profile is missing / internally inconsistent |
267
+
268
+ ### Schemas
269
+
270
+ | Symbol | Kind | Purpose |
271
+ |--------|------|---------|
272
+ | `AuthorizationSchema`, `ProfilePayloadSchema`, `AuthPayloadSchema` | JSON schema | Payload validation; `AuthPayloadSchema` requires `scopes`, `role`, `type` |
273
+ | `PartialAuthPayloadSchema`, `AllowanceRequestSchema` | JSON schema | The `authentication:init` body |
274
+ | `AuthCredentialsSchema` | JSON schema | The `authentication:authenticate` body; requires `challenge`, `credential`, `scopes`, `role`, `type` |
275
+ | `AuthSchema` | JSON schema | A resolved `Auth` |
276
+ | `AuthTokenSchema`, `OptionalAuthTokenSchema` | JSON schema | Bearer-token bodies; `token` is 32–1024 characters |
277
+ | `ProfileSchema` | JSON schema | A stored `Profile` |
278
+ | `PermissionSetSchema`, `AttributeSetSchema`, `CapabiltiesSchema` | JSON schema | Permission and attribute shapes |
279
+ | `RelyChallengeSchema` | JSON schema | A `RelyToken` |
280
+ | `ScopeValueSchema`, `PermissionValueSchema`, `ResourceValueSchema`, `AttributeValueSchema`, `GroupValueSchema`, `TypeNameSchema`, `EnumValueSchema`, `IdValueSchema` | JSON schema | Reusable string field schemas with length bounds |
281
+ | `EntitySlugValueSchema` | JSON schema | Organization slug field (3–256 characters) |
282
+ | `EntityValueSchema` | JSON schema | Deprecated alias of `EntitySlugValueSchema` |
283
+ | `DateSchema` | JSON schema | `date-time` formatted `Date` field |
284
+ | `AuthRoleSchema` | JSON schema | Enum of `AuthRole` values |
63
285
 
64
- ## Product-Viable Integration Notes
286
+ ### Helpers
65
287
 
66
- - Manager API handlers use `AuthUnknown('entity')` when `request.auth?.entityId` is missing.
67
- - WebSocket helpers use `Auth`, `AuthToken`, and `AuthenticationStage` to authenticate token-bearing connections.
68
- - Google/OIDC login is normalized into an `AuthPayload` with `userId`, `profileId`, `entityId`, and `scopes`; the local identity store lives in `@owlmeans/server-auth-identity`.
69
- - Gate denial should use `AuthForbidden`; product ownership checks should stay in entrypoint gates or handlers, not in this core package.
288
+ | Symbol | Kind | Purpose |
289
+ |--------|------|---------|
290
+ | `authHelper.entitySlugOf(payload?)` | method | The organization carried by a payload: `entitySlug`, falling back to a legacy `entityId` |
291
+ | `authHelper.verifyAuth(auth)` | method | Validate against `AuthSchema` (AJV with formats) |
292
+ | `authHelper.verifyAuthCredentials(auth)` | method | Validate against `AuthCredentialsSchema` |
293
+ | `authHelper.isAuth(value)` | type guard | Has `token` and `isUser` |
294
+ | `authHelper.isAuthCredentials(value)` | type guard | Has `challenge` and `credential` |
295
+ | `authHelper.isAuthToken(value)` | type guard | Has a string `token` |
296
+ | `buildSupervisorPayload(challenge, userId, salt)` | function | The canonical payload the PK supervisor login signs and verifies |
70
297
 
71
- ### AJV Schemas (for entrypoint filter definitions)
298
+ ## Common pitfalls
72
299
 
73
- - `AuthCredentialsSchema` — validates an auth credential request body
74
- - `AllowanceRequestSchema` — validates an allowance/init request body
75
- - `AuthTokenSchema` — validates query params containing an auth token
300
+ - `AuthRole` is a **string** enum — use the members; numeric literals do not compile.
301
+ - Read the organization with `authHelper.entitySlugOf()`, never `payload.entitySlug` directly. Its result may
302
+ be a legacy `entityId`, so treat it as an opaque key: never compose names from it and never write
303
+ it as a database key — use `makeEntityScope(req).requireEntityKey()` / `.requireEntity()` from
304
+ `@owlmeans/auth-common`.
305
+ - Never put `entityId` on the wire (tokens, URLs, query params, forms) — only `entitySlug`.
306
+ - Any code path that establishes authentication outside the HTTP boundary (sockets) must call
307
+ `makeEntityScope(request).attachEntity(context)`, or `request.entity` stays empty.
308
+ - Pick the right error: a gate denial is `AuthForbidden`, a missing identity is `AuthUnknown`, a
309
+ failed credential check is `AuthenFailed`.
310
+ - `AuthCredentialsSchema` requires `type`, `role` and `scopes` on every authenticate call.
311
+ - `AuthTokenSchema` caps `token` at 1024 characters; a route accepting a wrapped credential envelope
312
+ needs its own wider schema.
313
+ - Keep ownership and permission rules out of this package — compose them in entrypoint gates or
314
+ handlers around these types.
315
+ - `ajv` is a peer dependency; without it the `verify*` helpers fail to resolve.
76
316
 
77
- ## Related Packages
317
+ ## Related packages
78
318
 
79
- - [`@owlmeans/auth-common`](../auth-common) — auth entrypoints, guards, and middleware
80
- - [`@owlmeans/server-auth`](../server-auth) — server-side auth service implementation
81
- - [`@owlmeans/client-auth`](../client-auth) — client-side auth service
319
+ - [`@owlmeans/auth-common`](../auth-common) — guards, shared auth protocols, organization-entity resolution
320
+ - [`@owlmeans/server-auth`](../server-auth) — server-side auth service and plugins
321
+ - [`@owlmeans/server-auth-identity`](../server-auth-identity) — local identity store behind provider logins
322
+ - [`@owlmeans/client-auth`](../client-auth) — browser auth service and login hooks
323
+ - [`@owlmeans/entrypoint`](../entrypoint) — protocols, guards and gates that consume these types
324
+ - [`@owlmeans/error`](../error) — `ResilientError`, the base of every auth error
325
+ - [`@owlmeans/socket`](../socket) — socket connections that authenticate through `AuthenticationStage`
82
326
 
83
327
  <!-- owlmeans:agent-guidance:start -->
84
328
  ## Agent guidance
@@ -88,7 +332,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
88
332
  your project's skill store (`.agents/skills/`):
89
333
 
90
334
  ```sh
91
- npx @owlmeans/agent-skills@^0.1.18-rc.12
335
+ npx @owlmeans/agent-skills@^0.1.18
92
336
  ```
93
337
 
94
338
  The embedded files are version-matched to this package release. Do not edit them
@@ -1,8 +1,8 @@
1
1
  {
2
- "schemaVersion": 2,
2
+ "schemaVersion": 3,
3
3
  "package": "@owlmeans/auth",
4
- "version": "0.1.18-rc.9",
5
- "generatedAt": "2026-09-04T22:43:25.434Z",
4
+ "version": "0.1.18",
5
+ "generatedAt": "2026-10-28T00:31:34.705Z",
6
6
  "canonicalRepo": "https://github.com/owlmeans/common",
7
7
  "entries": [
8
8
  {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: auth
3
- description: How to use @owlmeans/auth — the core authentication and authorization vocabulary shared by server and client, covering the Auth / AuthPayload / AuthCredentials types, the AuthRole and AuthenticationType enums, the error hierarchy (AuthUnknown, AuthenFailed, AuthForbidden …), the request JSON schemas, the entrypoint aliases, and entitySlugOf for reading the organization entity off a token. Auto-invoked when importing auth types, errors, schemas or constants, or when working with request authentication.
3
+ description: How to use @owlmeans/auth — the core authentication and authorization vocabulary shared by server and client, covering the Auth / AuthPayload / AuthCredentials types, the AuthRole and AuthenticationType enums, the error hierarchy (AuthUnknown, AuthenFailed, AuthForbidden …), the request JSON schemas, the entrypoint aliases, and authHelper.entitySlugOf for reading the organization entity off a token. Auto-invoked when importing auth types, errors, schemas or constants, or when working with request authentication.
4
4
  user-invocable: false
5
5
  ---
6
6
  <!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
@@ -8,7 +8,7 @@ user-invocable: false
8
8
  # @owlmeans/auth
9
9
 
10
10
  **Layer:** Core
11
- **Install:** `"@owlmeans/auth": "^0.1.18-rc.9"` in `dependencies`
11
+ **Install:** `"@owlmeans/auth": "^0.1.18"` in `dependencies`
12
12
 
13
13
  Types, enums, errors and schemas only — no services, no wiring. Every other auth package builds on
14
14
  this vocabulary, so a symbol belongs here exactly when both a server and a browser need to agree on
@@ -49,7 +49,8 @@ it.
49
49
  | `AUTHEN`, `AUTHEN_INIT`, `AUTHEN_AUTHEN`, `AUTHEN_RELY` | Backend entrypoint aliases |
50
50
  | `CAUTHEN`, `CAUTHEN_AUTHEN`, `CAUTHEN_AUTHEN_DEFAULT`, `CAUTHEN_AUTHEN_TYPED`, `CAUTHEN_FLOW_ENTER` | Front-end entrypoint aliases |
51
51
  | `DISPATCHER`, `DISPATCHER_AUTHEN`, `DISPATCHER_SURROGATE` | Dispatcher and surrogate-window entrypoint aliases |
52
- | `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | reCAPTCHA entrypoint aliases |
52
+ | `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | reCAPTCHA plugin-record ids: the server's (secret + policy, a Backend record never advertised) and the browser's (site key, a Frontend record) |
53
+ | `RECAPTCHA_GUARD` | `'guard:re-captcha'` — the guard alias of a route a reCAPTCHA-proven guest may call once (`makeReCaptchaGuard` in `@owlmeans/server-auth`) |
53
54
 
54
55
  ### Errors
55
56
 
@@ -58,7 +59,7 @@ it.
58
59
 
59
60
  | Error | Raise it when |
60
61
  |-------|---------------|
61
- | `AuthUnknown` | The thing being authenticated is not known at all — an unregistered plugin type, a request whose auth state is missing |
62
+ | `AuthUnknown` | The thing being authenticated is not known at all — an unregistered plugin type, a method a gate refuses, a request whose auth state is missing. Declares `httpStatus = 400`: the caller's request, never a 500 |
62
63
  | `AuthManagerError` | The auth manager itself failed |
63
64
  | `AuthManagerUnsupported` | The manager cannot serve this request shape |
64
65
  | `AuthenFailed` | Authentication was attempted and rejected (bad challenge, bad code, bad signature) |
@@ -79,9 +80,9 @@ it.
79
80
  | `AuthSchema`, `AuthTokenSchema`, `OptionalAuthTokenSchema` | Resolved auth and bearer-token bodies |
80
81
  | `ProfileSchema`, `RelyChallengeSchema`, `PermissionSetSchema`, `AttributeSetSchema`, `CapabiltiesSchema` | Record and permission schemas |
81
82
  | `ScopeValueSchema`, `PermissionValueSchema`, `ResourceValueSchema`, `AttributeValueSchema`, `EntitySlugValueSchema`, `GroupValueSchema`, `TypeNameSchema`, `EnumValueSchema`, `IdValueSchema`, `DateSchema`, `AuthRoleSchema` | Reusable scalar schemas |
82
- | `entitySlugOf(payload)` | The organization entity carried by an auth payload — its `entitySlug`, falling back to an `entityId` the payload may carry instead — see below |
83
- | `verifyAuth`, `verifyAuthCredentials` | Validate against `AuthSchema` / `AuthCredentialsSchema` |
84
- | `isAuth`, `isAuthCredentials`, `isAuthToken` | Type guards |
83
+ | `authHelper.entitySlugOf(payload)` | The organization entity carried by an auth payload — its `entitySlug`, falling back to an `entityId` the payload may carry instead — see below |
84
+ | `authHelper.verifyAuth`, `authHelper.verifyAuthCredentials` | Validate against `AuthSchema` / `AuthCredentialsSchema` |
85
+ | `authHelper.isAuth`, `authHelper.isAuthCredentials`, `authHelper.isAuthToken` | Type guards |
85
86
  | `buildSupervisorPayload`, `SupervisorCredentialPayload` | The payload the PK supervisor login signs — see the `supervisor-auth` skill |
86
87
 
87
88
  `AuthTokenSchema` caps `token` at 1024 characters. A route that accepts a token wrapping a full
@@ -95,23 +96,23 @@ query params and request bodies. No `entityId` is declared on any type here —
95
96
  an implementation stores its rows against belongs to whichever package owns the organization
96
97
  registry, and is resolved from the slug at the server boundary.
97
98
 
98
- Read the value through `entitySlugOf()` rather than off the field. A token is signed once and then
99
- read for as long as it lives, across deployments, and the helper absorbs that spread: when
99
+ Read the value through `authHelper.entitySlugOf()` rather than off the field. A token is signed once
100
+ and then read for as long as it lives, across deployments, and the helper absorbs that spread: when
100
101
  `entitySlug` is absent it returns an `entityId` the payload carries instead, so a payload that names
101
102
  the organization under either field resolves through one code path. That fallback is why the helper
102
103
  is the only supported way to get the value out of a payload:
103
104
 
104
105
  ```typescript
105
- import { entitySlugOf } from '@owlmeans/auth'
106
+ import { authHelper } from '@owlmeans/auth'
106
107
 
107
- const slug = entitySlugOf(req.auth) // string | undefined
108
+ const slug = authHelper.entitySlugOf(req.auth) // string | undefined
108
109
  ```
109
110
 
110
111
  Because of that fallback the result is not guaranteed to be a slug: a payload carrying only
111
112
  `entityId` yields that id. Treat it as an opaque organization key, never as a name to compose from
112
- and never as a database key written directly — `@owlmeans/auth-common` exports `entityKeyOf` /
113
- `requireEntityKey` for storage keys, and they prefer the resolved id; a user-facing name wants the
114
- resolved entity's current slug.
113
+ and never as a database key written directly — `@owlmeans/auth-common`'s
114
+ `makeEntityScope(req).entityKeyOf()` / `.requireEntityKey()` give storage keys, and they prefer the
115
+ resolved id; a user-facing name wants the resolved entity's current slug.
115
116
 
116
117
  ## AuthRole is a string enum
117
118
 
@@ -129,11 +130,11 @@ const creds: AuthCredentials = { role: AuthRole.User, /* … */ } as AuthCredent
129
130
  Throw from a handler when the request is missing the identity it needs:
130
131
 
131
132
  ```typescript
132
- import { AuthUnknown, entitySlugOf } from '@owlmeans/auth'
133
- import { handleRequest } from '@owlmeans/server-app'
133
+ import { AuthUnknown, authHelper } from '@owlmeans/auth'
134
+ import { handlers } from '@owlmeans/server-app'
134
135
 
135
- export const list = handleRequest(async (req, context) => {
136
- const slug = entitySlugOf(req.auth)
136
+ export const list = handlers<Context>().request(projectProtocols.list, async (req, context) => {
137
+ const slug = authHelper.entitySlugOf(req.auth)
137
138
  if (slug == null) throw new AuthUnknown('entity')
138
139
 
139
140
  return await listProjects(context, slug)
@@ -142,12 +143,17 @@ export const list = handleRequest(async (req, context) => {
142
143
 
143
144
  Rules of thumb:
144
145
 
145
- - A gate that decides "not allowed" throws `AuthForbidden`; a handler that finds no identity to act
146
- on throws `AuthUnknown`; a failed credential check throws `AuthenFailed`.
146
+ - A gate that decides "not allowed" throws `AuthForbidden` (403); a handler that finds no identity
147
+ to act on, or a sign-in naming a method nobody serves, throws `AuthUnknown` (400); a failed
148
+ credential check throws `AuthenFailed`. `@owlmeans/server-api` maps the authorization family to
149
+ 401/403 before reading a class's declared `httpStatus`, so `AuthUnknown`'s 400 never masks them.
147
150
  - Keep ownership rules out of this package. Downstream apps compose `@owlmeans/entrypoint` gates or
148
151
  handler-level checks around these types.
149
152
  - WebSocket wiring uses `Auth`, `AuthToken` and `AuthenticationStage` to move a token-bearing
150
153
  connection into an authenticated state.
154
+ - `AuthenticationType.ReCaptcha` proves a solved challenge, never a person: its token is a guest
155
+ (`GUEST_ID`, `AuthRole.Guest`, `[AUTH_SCOPE]`), travels as `Authorization: RE-CAPTCHA <token>`,
156
+ is accepted only by a route guarded with `RECAPTCHA_GUARD`, and never becomes a session.
151
157
  - A provider login (Google/OIDC, OTP, supervisor) ultimately produces an ordinary `AuthPayload` with
152
158
  `userId`, `profileId`, `entitySlug` and `scopes`; `@owlmeans/server-auth-identity` stores the local
153
159
  identity behind it and returns that payload.
@@ -157,6 +163,6 @@ Rules of thumb:
157
163
  - `@owlmeans/error` — every error class extends `ResilientError`, which is what makes the messages
158
164
  translatable and re-throwable across the wire
159
165
  - `ajv-formats` — date/time formats for the `verify*` helpers
160
- - `ajv` — a **peer** dependency (`"*"`), not a direct one: `verifyAuth` / `verifyAuthCredentials`
161
- construct `new Ajv({ strict: false })`. Install it alongside this package, or those two helpers
162
- fail to resolve.
166
+ - `ajv` — a **peer** dependency (`"*"`), not a direct one: `authHelper.verifyAuth` /
167
+ `authHelper.verifyAuthCredentials` construct `new Ajv({ strict: false })`. Install it alongside
168
+ this package, or those two helpers fail to resolve.