@nlabs/reaktor 1.19.2 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ # Lean hosted database
2
+
3
+ The additive `@nlabs/reaktor/database` entry exposes `createHostedDatabase`, `createManagedSessionPersistence`, the web factories below, and their public option/port types. It imports arangojs, the lean Rip-Hunter HTTP entry and owned web scope/hash validation, never Config, schema defaults, JWT issuance, media or AWS providers. Legacy root `useDb` is unchanged.
4
+
5
+ Configure a full HTTPS server origin, designated existing database name, non-root service username, private password and positive `timeoutMs`. Missing/invalid settings fail before the injected `DatabaseFactory` runs. No environment lookup, defaults, credentials discovery or database/collection/index creation occurs. The returned object is the actual arangojs `Database`; its public query, collection, beginTransaction and close APIs remain available. The optional constructor binding accepts the public arangojs `ConfigOptions` and returns its actual `Database` type.
6
+
7
+ Both factories require explicit `timeoutMs`, with the persistence adapter passing it in every public QueryOptions. arangojs10.5.0 query() passes its own undefined timeout and can override the constructor common timeout: raw driver query/transaction callers must provide their own explicit supported timeout options. The adapter’s `timeoutMs` maps to arangojs 10.5.0's per-request Fetch timeout (AbortSignal on the driver's request). The driver clears this timer when Fetch resolves its response headers; it does not guarantee a response-body deadline. Zero is rejected (no disable mode); the largest permitted integer is 2,147,483,647 milliseconds, preventing timer overflow. This is neither a Node socket-idle timeout nor an absolute deadline spanning multiple queries/cursor requests/whole auth operations. Callers needing whole-operation deadlines must provide a separately reviewed orchestration policy. Redirects fail, transport retries and conflict retries are disabled; mutations are never replayed by this adapter. TLS certificate verification retains driver defaults; private trust installation is external infrastructure.
8
+
9
+ `createManagedSessionPersistence({database, accountsCollection, familiesCollection, environment, timeoutMs})` returns the concrete `accounts`/`families` ports expected by `ManagedSessionOptions`. Use separate existing collections and least-privilege service access. Collections and environment are explicit configuration. Query text is fixed; names and all ids/data use AQL bind variables. Account reads use exact email matching (managed auth already normalizes email). Documents must have `_key === userId`, an explicit environment matching the configured stage, explicit boolean active, and nonempty username/password/salt strings. Password/salt are preserved unchanged. Unstaged legacy users, absent active fields and malformed records fail closed; this is not an implicit migration or proof that existing accounts are compatible. Authoritative enrollment/migration must establish this schema independently.
10
+
11
+ Session families require `_key === sid`, safe key-format sid/userId, exact environment, boolean revoked, nonnegative integer created and integer absoluteExpires greater than created with duration at most 86,400,000 milliseconds (24 hours, matching managed auth). Create accepts only unrevoked records. The built-in unique primary `_key` index provides atomic unique sid insertion; `INSERT ... overwriteMode: conflict` never updates prior rows, including revoked ones. Reads strictly validate records and requested identity. Revoke executes one AQL statement whose update predicate includes sid/userId/environment and revoked=false. Missing, wrong-owner, wrong-stage and already-revoked rows cause no update. Concurrent write conflicts return a sanitized error, never automatic replay. Isolated tests prove actual driver serialization and synthetic conflict handling; database server transactional execution and collection permissions require separate real-service acceptance.
12
+
13
+ Database errors become `database_unavailable`; malformed rows/ids become `invalid_database_record`; configuration errors become `invalid_database_configuration`, without raw driver/credential details. Game repositories, ownership/revision/idempotency/replay policy remain application domain work. This additive source requires fresh review and frozen package/archive verification before consumer adoption. No hosted service, credentials or native acceptance is implied.
14
+
15
+ ## Additive body deadline profile
16
+
17
+ `createManagedSessionHttpPersistence` accepts the explicit hosted database fields, distinct existing accounts/families collections, environment, positive safe-integer timeoutMs and maxResponseBytes (1..1,048,576). Its optional requestImplementation is the installed public Rip-Hunter RequestImplementation; optional signal can bind a caller scope. Configuration is captured before any I/O. This profile does not use arangojs query promises or change the existing driver factories. It reuses the same private account/family validations and fixed parameterized AQL commands.
18
+
19
+ The trusted HTTPS origin is extended only with /_db/<configured-name>/_api/cursor. Basic credentials are explicit private configuration; root and colon-containing usernames are rejected. Rip-Hunter owns JSON encoding, Fetch transport and the absolute deadline across request and consumer callback. No redirects or automatic retries occur. Exact final response URL and status 201 precede bounded streamed bytes, fatal UTF8 decoding, JSON and envelope validation. Errors/provider bodies are never included in messages. DatabaseRequestError distinguishes abort, timeout, limit, status, response and unavailable; only caller cancellation cause is retained exactly. Managed auth's existing I/O boundary continues to sanitize persistence failures.
20
+
21
+ Requests use batchSize2, cachefalse, ttl 1 and server maxRuntime matching the configured duration in seconds. Dirty-read opt-in is absent, matching the installed driver's allowDirtyReadfalse wire behavior. Only the fixed email query can return two rows (managed auth detects duplicates); keyed reads and mutations accept at most one row. hasMore and retained cursor ids are rejected; pagination is never followed. A rejected unexpected server cursor is bounded by the requested one-second TTL rather than an unbounded client pagination/cleanup chain. Server enforcement, actual atomic AQL execution and least-privilege access remain live acceptance gates.
22
+
23
+ The deadline now bounds post-header slow/hanging bodies for these per-query ports. Timers and caller listeners are cleaned by the installed public Rip-Hunter lifecycle, including finite durations above the platform timer maximum; zero remains rejected in this hosted profile. Native Fetch aborts its stream on cancellation; injected implementations must honor the supplied AbortSignal to release their underlying resources, although Rip-Hunter still bounds caller completion for noncooperative implementations. No whole-auth/KMS-signing deadline or Node socket-idle guarantee follows. A caller may supply a shared signal, but signing and overall operation orchestration remain separate required work. The consumer uses published Rip-Hunter 3.3.0 HTTP and deadline entry points rather than a private archive. Reaktor's own release and production qualification remain separate gates.
24
+
25
+ Managed auth ports now accept an optional `ManagedAuthPortContext`. HTTP ports use its operation signal (combined with the optional adapter signal) and the minimum remaining auth budget/per-request timeout, including streamed response consumption. Exhaustion rejects before dispatch instead of passing zero to disable transport deadlines. The old driver ports remain compatible and do not claim cooperative abort support. Neither adapter claims that cancellation rolls back an already-submitted mutation or establishes noncommit; no automatic replay occurs.
26
+
27
+ ## Bounded application AQL
28
+
29
+ `createBoundedAqlExecutor(options)` adds a public single-page executor to this entry. The trusted options require an existing HTTPS server origin, databaseName, non-root username, private password, positive safe-integer timeoutMs, and explicit maxRequestBytes/maxResponseBytes (1..16,777,216 each). Optional requestImplementation uses Rip-Hunter's public Fetch callback type; optional signal binds adapter shutdown. Construction reads each configuration field once before validating the captured values and performs no I/O/provisioning. Throwing configuration getters fail as invalid_database_configuration without retaining their cause. The managed-session HTTP profile retains its existing 1 MiB cap, fixed AQL and status behavior.
30
+
31
+ `executor.execute({query, bindVars, maxRows}, {signal?, remainingMs?}?)` accepts trusted caller-owned AQL and bind variables. maxRows is a required integer from 1..10,000. It sets batchSize and bounds accepted result rows; it does not rewrite/parse AQL or bound database work. The caller must author its query LIMIT, ownership predicates and mutation/transaction policy. Requests use cache:false, ttl:1 and options.maxRuntime in seconds. No redirects, retries, pagination, retained-cursor cleanup requests or environment defaults occur. Oversized results are rejected and any unexpected retained cursor expires under the requested one-second TTL. Server behavior needs separate acceptance.
32
+
33
+ Byte caps count UTF-8 bytes of the complete serialized JSON request and entire response envelope, including error envelopes, rather than just a document or Content-Length. An 8 MiB aggregate therefore needs envelope headroom: 9 MiB (9,437,184 bytes) is an example explicit bound for one aggregate, provided the caller separately ensures all query/bind/envelope fields fit; it is not a production default. Each statement field is read once before validation; its captured query, row bound and bind variables supply the bounded serializable JSON snapshot. The parsed snapshot must preserve the validated query and batch size and contain nonnull, non-array object bindVars, including when toJSON is present. Throwing statement/context getters and malformed serialized snapshots fail as invalid_database_statement before dispatch. Rip-Hunter encodes the wire payload. Failed serialization is sanitized as invalid_database_statement. Bind-variable schema, canonical JSON and untrusted input validation remain caller policy.
34
+
35
+ Only exact final endpoint responses with status 201 return data, with error:false, hasMore:false, an array within maxRows and no cursor id. An optional success code must match 201. Fatal UTF-8 and JSON parsing reject malformed data. Non-success statuses400..599 consume only bounded bodies within the full request deadline; they expose a DatabaseRequestError of kind status only when error:true, code matches the HTTP status, no cursor fields occur, and errorNum is an integer1..2,147,483,647. Only status/errorNum are retained; server errorMessage/body/query/credential details are discarded. Malformed error envelopes are response failures, excess bytes are limit failures. Other statuses and redirected endpoints are refused before JSON decode.
36
+
37
+ remainingMs, when supplied, must return a finite number; zero/negative rejects as timeout before dispatch, never a disabled timeout. Each request uses the smaller configured/remaining budget, rechecked after request snapshotting. Rip-Hunter bounds both headers and body consumption and handles finite durations above the platform timer maximum with bounded scheduling. Caller and adapter cancellation preserve the exact caller signal reason in DatabaseRequestError.cause; other error causes remain sanitized. Rip owns timer/listener cleanup. Injected transports must honor the supplied signal to release underlying resources. Cancellation or rejection after submitting a mutation does not establish rollback/noncommit. No mutation is replayed automatically.
38
+
39
+ Official [cursor API](https://docs.arango.ai/arangodb/stable/develop/http-api/queries/aql-queries/) describes single-roundtrip batchSize/hasMore/id behavior. Official [core errors](https://docs.arango.ai/arangodb/stable/develop/error-codes/) define 1200 as detected document conflict and 1210 as unique-constraint violation. These are raw sanitized database numbers, not an application CAS/idempotency interpretation. Product repository atomicity, database TLS/permissions/durability, live concurrency, artifact release and consumer adoption remain separate gates.
40
+
41
+ ## Owner web-session persistence and limiter
42
+
43
+ `createManagedWebSessionPersistence` adds explicit `accountsCollection`, `sessionsCollection`, server-owned `scope`, and `topology: 'single-server' | 'one-shard'` to the bounded HTTP configuration. The distinct existing collections are never provisioned on import. Account records retain the managed canonical `_key === userId`, environment and active contract. Session primary `_key` is the credential SHA256 digest; sid uniqueness is checked inside the exclusive transaction before insert. Stored fields are digest, sid, userId, app/environment/owner scope, createdAt, lastActivityAt, idleExpiresAt, revoked and optional revocation/Arango revision metadata. No graph edges are created because these are standalone session/counter documents, not graph relationships.
44
+
45
+ Create, touch and revoke use the supported [Stream Transaction HTTP API](https://docs.arango.ai/arangodb/stable/develop/http-api/transactions/stream-transactions/): begin with explicitly exclusive declared collections and `allowImplicit:false`, execute fixed bound AQL under the validated `x-arango-trx-id`, then require an exact committed acknowledgment. Create/touch exclusively lock accounts plus sessions; revoke locks sessions. The database observation uses one `DATE_NOW()` value. Create rechecks the active owner and never overwrites a prior digest/sid. Touch predicates include exact digest/scope/owner, unrevoked status, consistent existing activity times and strict `now < idleExpiresAt`. Revoke includes expired records and never clears revocation. ReadLive sends one pure read with the same live predicates and returns the current account username; every returned complete record is validated again before exposure. The database clock supplies the response `observedAt`.
46
+
47
+ The internal transport reuses bounded response parsing and public Rip-Hunter HTTP deadlines. One monotonic budget spans begin, query, validation and commit. Known precommit failures attempt abort only within the remaining budget. Lost/malformed begin acknowledgments can leave an unknown transaction until the server cleans it up. Once commit is submitted, a failed response is an unknown outcome: no automatic retry, abort-as-proof, successful grant, or durable logout claim follows. Transport cancellation is not rollback. Configure and qualify server streaming transaction idle cleanup, lock contention, permissions and size limits. `waitForSync:true` requests durable acknowledgment; it is not evidence of real deployment durability.
48
+
49
+ Cross-collection guarantees require a qualified single-server or OneShard deployment and authoritative account disable/revoke paths. The topology value is an explicit caller assertion, not discovery or production proof. Exclusive locks trade concurrency for this bounded owner-only policy; live server lock ordering, two-touch/touch-vs-revoke/account-disable races and actual AQL execution remain acceptance gates. JavaScript transactions are not used.
50
+
51
+ `createWebSignInLimiter` takes the same bounded HTTP/topology fields plus `scope`, `countersCollection`, and required positive safe-integer `identityLimit`, `identityWindowMs`, `sourceLimit`, `sourceWindowMs` (strictly below MAX_SAFE_INTEGER). There are no unlimited defaults. It hashes scoped normalized email and separately scoped trusted source into two counter keys, retaining neither raw identity nor raw source in the database request/documents. One exclusive counter transaction consumes both buckets, using database time and capped counters; failed admissions and exhausted requests retain their consumed attempts. Exhaustion is reported only after commit acknowledgment. Invalid counter records, transport failures and unknown commits fail closed. Deployment limits/windows, collection isolation/least privilege and housekeeping remain explicit operational policy.
@@ -0,0 +1,47 @@
1
+ # Managed authentication source capability
2
+
3
+ The additive `@nlabs/reaktor/auth` entry owns an asynchronous, database-backed session protocol. It is an unpublished source capability pending independent review and exact compatible artifact qualification; it is not installed in Kurupt or evidence of live service acceptance. Existing root user actions, admin policy and synchronous SESSION_SECRET functions remain unchanged.
4
+
5
+ `createManagedSessionService(options)` requires account and session-family persistence ports, an explicit issuer, audience, environment, signing binding and configured public-key trust. No provider or database client is created on import or by default. `signIn({user:{email,password}})`, `renew(token)`, `verify(token)` and `revoke(token)` are asynchronous. Sign-in uses the existing owned parsePassword/createPassword format factored into `matchesAccountPassword`, with no admin password override. An account must be explicitly active. Passwords and hashes never reach responses or JWTs. Enrollment/password migration and rate limits remain separate domain requirements.
6
+
7
+ Bearer tokens last at most 900 seconds. Every sign-in creates a unique session-family record with a fixed 86,400-second absolute limit; renewal retains sid and clamps expiration to that limit. Expired bearers require sign-in. This protocol has no refresh token, automatic mutation replay or immediate revocation of an earlier bearer on ordinary renewal. The client refresh window is 300 seconds and belongs to the frontend policy owner. Response `issued`/`expires` and family timestamps are milliseconds; JWT iat/exp are integer seconds. Responses include schemaVersion=1, environment, userId, username, sid, token, issued and expires only.
8
+
9
+ Every verify/renew/revoke reads the active account and family, including ownership and environment; revoked/missing families fail closed. Issuance rechecks them after managed signing, so account disable or revocation during signing cannot publish successful credentials. Persistence failures are `auth_unavailable`, with no provider/database error text. Adapters must atomically create unique sid records, never resurrect or overwrite revoked families, and atomically/idempotently mark the matching sid/userId revoked. Repeated revoke of an already revoked family rejects as revoked_session. Failed sign-in after family creation may leave an unusable family until its absolute expiry; housekeeping must not grant it a credential.
10
+
11
+ Family schema is `{sid,userId,environment,created,absoluteExpires,revoked}`. Account bindings must return canonical database-owned identity and explicit active status, salt and stored hash. The lean `/database` entry supplies the driver and bounded HTTP session-family adapters described in `LEAN_DATABASE.md`; no in-memory production adapter or implicit account migration is supplied. Account repository implementations must enforce exact normalized email lookup and database authorization. Synthetic ports in owner tests are test fixtures only.
12
+
13
+ Trust uses RSA public keys of at least 2048 bits. Only RS256 JWTs with known kid and typ=JWT are accepted, with exact configured iss/aud, nonempty bounded sub/userId agreement, sid/jti and integer iat/exp. Tokens are limited to 8192 bytes, lifetime to 900 seconds and future-iat tolerance to a configured 0–30 seconds. Expiration remains strict even with skew. Token-supplied discovery/header fields are rejected. Trust allows exactly one nonretiring current signing kid and at most three explicitly retiring keys; retiring deadlines must be future and at most 900+skew seconds from configuration. Keys are captured at service creation and never discovered remotely. Rotation requires replacing the explicitly approved service configuration before deadlines; no ambient cache or URL discovery exists.
14
+
15
+ `createKmsSigner(kmsClient, SignCommand, {keyArn,kid})` binds the real AWS SDK KMSClient/SignCommand through their public structural contracts. The configured key ARN must identify a key, never an alias or JWT secret. It sends RAW JWT signing input (1–4096 bytes) with RSASSA_PKCS1_V1_5_SHA_256, validates returned key/algorithm/signature, and redacts provider errors. Signer output is verified against current configured public trust before credentials are returned. The owner does not add SDK construction or a provider default; the trusted runtime composition must install a compatible `@aws-sdk/client-kms`, supply credentials/IAM privately and disable mutation retry as appropriate. An isolated fixture qualifies 3.1138.0's actual client/command declarations and request serialization with denied network; this does not prove key capabilities, IAM or cloud acceptance.
16
+
17
+ Public declarations require Node crypto/Buffer and this entry is server-only. Native auth composition belongs to Metropolis; do not import it into a React Native bundle. The owner package still includes repository-relative analytics/transport dependencies and broad legacy root APIs. Scoped auth compilation does not certify a portable archive or the complete owner build. Exact artifact members/dependency closure, consumer adoption, a concrete database composition, GraphQL authorization, independent review, external signing key/current-retiring trust provision and real account/network/revocation acceptance remain open.
18
+
19
+ ## Optional whole-operation deadline and cancellation
20
+
21
+ `operationTimeoutMs` optionally configures the service default. Each `signIn`, `renew`, `verify` and `revoke` accepts a final `{timeoutMs?, signal?}` argument. Omitted timeouts preserve unlimited legacy timing; configured values must be finite positive safe integer milliseconds. An explicit per-call duration replaces the default. The operation owns one monotonic absolute budget across every read, insert, signer and post-sign verification, using the public Rip-Hunter `/deadline` scheduler for bounded intervals above the platform timer limit. Calls reject with `ManagedAuthOperationError` (`kind: timeout | abort`, sanitized `auth_timeout` / `auth_abort` message). For aborts its `cause` is the caller's exact reason; callers must not log that potentially sensitive value.
22
+
23
+ Account/family/signer ports accept an optional `ManagedAuthPortContext` containing `signal` and `remainingMs()`. Existing ports may ignore the additive argument. The service guards before/after each await and before starting subsequent work; it races cancellation so an uncooperative pending binding cannot indefinitely delay caller rejection. Later resolutions/rejections remain observed and cannot publish credentials or initiate a subsequent mutation. Synchronous password/signature work cannot be preempted on the JavaScript thread; the next guard rejects before continuing.
24
+
25
+ `createKmsSigner` forwards this signal via the actual AWS SDK `send(command, {abortSignal})` contract and checks cancellation before/after signing. Provider bindings must honor the signal to release their resources. The HTTP persistence adapter composes the operation signal with its optional adapter shutdown signal and caps each request/body deadline at the smaller remaining operation budget. Exhausted budget rejects before dispatch and is never passed as zero (which disables generic HTTP deadlines). The older arangojs persistence binding cannot cancel through its supported public API; it retains its per-query timeout and can ignore the optional context, while the service still bounds completion and further work.
26
+
27
+ Cancellation is not rollback. Already-submitted INSERT/revoke/KMS work may have executed or committed before cancellation, including when a provider ignores the signal. No mutation is replayed automatically, and a timeout/rejection does not establish noncommit. Live SDK/DB cancellation, cursor TTL/atomicity and compatible frozen artifact adoption remain separate acceptance gates. The newly public Rip-Hunter scheduler export must be adopted from an exact compatible artifact; physical file presence alone is insufficient.
28
+
29
+ An ordinary terminal operation failure also aborts its signal before timer/listener cleanup, so cooperative pending sibling ports (for example the parallel account/family reads) can release resources promptly. The signal reason is the original outward sanitized failure; the caller still receives that identical error, rather than a replacement cancellation error. Successful completion clears timer/listener controls without aborting its signal. Later caller cancellation cannot change the failed terminal reason or restart work. Bindings should not log signal reasons.
30
+
31
+ ## Opaque owner web sessions
32
+
33
+ The additive `/auth` entry exports `createWebSessionService({accounts, limiter, persistence, scope, operationTimeoutMs?})`. Scope is a captured server-owned `{appId, environment, ownerUserId}`. Accounts use the existing `ManagedSessionOptions['accounts']` contract. `limiter` is mandatory. Credential parsing and password matching reuse the private admission helper; native candidate selection and 15-minute bearer / 24-hour family behavior remain unchanged. Web admission requires exactly one active canonical owner, consumes the normalized email/trusted-source budget before account lookup/password evaluation, and returns generic invalid credentials for wrong, unknown, disabled, nonowner, or ambiguous accounts. No signup, enrollment, password override, JWT or KMS issuance is introduced.
34
+
35
+ `signIn({email,password,sourceKey}, operation?)` returns a server-only `{credential,identity}` grant. Every grant has a fresh random sid and 32-byte opaque credential. Only the SHA256 credential digest reaches persistence. `restore(credential, operation?)` reads without updating activity. `activity(...)` alone renews the idle deadline; `revoke(...)` revokes independently of idle expiry. All ports receive the shared operation context; configure an explicit operation timeout when a total sign-in budget is required. Failures are sanitized and ambiguous mutations are never replayed.
36
+
37
+ Identity is exactly `{idleExpiresAt,observedAt,sid,userId,username}`. Both timestamps are safe integer milliseconds from the same database observation. The idle interval is exactly 3,600,000 ms; at `observedAt >= idleExpiresAt`, admission fails. There is no inherited web absolute maximum. `observedAt` is response metadata, not persisted activity on restore. The server-only grant must never be logged, serialized as browser JSON, stored in Flux/preferences, or returned as a bearer.
38
+
39
+ `createWebSessionHttpAdapter({allowedOrigin,cookieName,service,sourceKey})` returns `signIn`, `restore`, `activity`, and `signOut` handlers. A thin server wrapper maps its structural `{method,headers,body?,cookies?}` request and `{statusCode,headers,body,cookies?}` response to the platform. Preserve duplicate headers as array values when the platform exposes them; duplicate/conflicting sensitive headers fail closed. `sourceKey(request)` must obtain source identity from trusted platform metadata, never arbitrary forwarding headers. Gateway cookie arrays and Cookie headers are supported individually; supplying both is rejected.
40
+
41
+ POSTs require an exact HTTPS configured Origin, `Content-Type: application/json` (optional UTF-8 charset), `X-Reaktor-CSRF: 1`, and an object JSON body of at most 4096 UTF-8 bytes. Sign-in accepts only email/password properties; activity/logout can send `{}`. Restore requires GET and exact Origin, or browser `Sec-Fetch-Site: same-origin` plus a Referer with the exact approved origin and no URL credentials. Host and forwarded headers grant no authority. Cookies are capped at 8192 UTF-8 bytes, malformed encoding and duplicate target cookies are rejected, and credentials have the existing exact 43-character opaque format. The cookie name is a validated `__Host-` name; attributes are fixed `Path=/; Secure; HttpOnly; SameSite=Strict`, without Domain. Sign-in and accepted activity set `Max-Age=3600`; restore emits no renewal. Signout and invalid-session responses clear with `Max-Age=0`. Existing cookie cleanup precedes replacement admission, so failed/unknown revocation cannot publish a replacement grant.
42
+
43
+ Success sign-in/restore/activity returns the flat nonsecret identity JSON. Successful signout returns `{authenticated:false}`. Invalid credentials/session returns 401 `{error:"unauthorized"}`; exhaustion returns 429 `{error:"rate_limited"}`; unavailable/timeout returns 503 `{error:"unavailable"}`. Boundary failures return 400/403/405 with `{error:"unauthorized"}`. Every response is `Cache-Control: no-store` and JSON. Signout always clears its local cookie, but a failed server revoke returns 503 and does not claim durable logout. No wildcard CORS is emitted. Private routes can call `service.restore` and use the verified owner identity directly; they still need their own route-specific origin and authorization boundary.
44
+
45
+ The same adapter exposes `authorize(request)` for thin private-route wrappers, returning `{authorized:true,identity}` or `{authorized:false,response}`. It reuses strict cookie/origin/CSRF policy and calls only `service.restore`; it never touches idle state, emits a renewed cookie or consumes the domain payload. GET is safe; POST/PUT/PATCH/DELETE require the exact Origin and JSON/CSRF headers. Other methods are denied. This boundary deliberately leaves chapter/asset body size and parsing to the route, so the auth endpoint's 4096-byte JSON limit does not apply to private-route payloads. The application must separately enforce its private route allowlist and business permissions.
46
+
47
+ The legacy console cookie/traffic renewal flow is unchanged. Metropolis lifecycle integration, Vault routes, owner enrollment, deployment topology/permissions, live concurrency, immutable artifact qualification, publication and consumer adoption remain separate work.
@@ -0,0 +1,10 @@
1
+ import type { ManagedAccount } from './managedSession.js';
2
+ export declare const parseManagedCredentials: (input: {
3
+ readonly email: string;
4
+ readonly password: string;
5
+ }) => {
6
+ email: string;
7
+ password: string;
8
+ };
9
+ /** Private shared admission; native preserves candidate selection, web requires one canonical owner. */
10
+ export declare const admitManagedAccount: (candidates: readonly ManagedAccount[], password: string, ownerUserId?: string) => ManagedAccount;
@@ -0,0 +1,24 @@
1
+ import { parseEmail, parsePassword } from '@nlabs/utils/parsers/strings';
2
+ import { matchesAccountPassword } from './credentials.js';
3
+ export const parseManagedCredentials = (input)=>{
4
+ const email = parseEmail(input?.email);
5
+ if (!email || typeof input?.password !== 'string') {
6
+ throw new Error('invalid_credentials');
7
+ }
8
+ return {
9
+ email,
10
+ password: input.password
11
+ };
12
+ };
13
+ /** Private shared admission; native preserves candidate selection, web requires one canonical owner. */ export const admitManagedAccount = (candidates, password, ownerUserId)=>{
14
+ if (!Array.isArray(candidates) || ownerUserId !== undefined && candidates.length !== 1) {
15
+ throw new Error('invalid_credentials');
16
+ }
17
+ const account = candidates.find((candidate)=>candidate?.active === true && (ownerUserId === undefined || candidate.userId === ownerUserId) && matchesAccountPassword(parsePassword(password), candidate.password, candidate.salt));
18
+ if (!account || typeof account.userId !== 'string' || account.userId.length < 1 || account.userId.length > 256 || typeof account.username !== 'string' || account.username.length < 1 || account.username.length > 256) {
19
+ throw new Error('invalid_credentials');
20
+ }
21
+ return account;
22
+ };
23
+
24
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9uaXRyb2c3Ly5jb2RleC93b3JrdHJlZXMvdmF1bHQtczMtcmVsZWFzZS9yZWFrdG9yL3BhY2thZ2VzL3JlYWt0b3Ivc3JjL2F1dGgvYWRtaXNzaW9uLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7cGFyc2VFbWFpbCwgcGFyc2VQYXNzd29yZH0gZnJvbSAnQG5sYWJzL3V0aWxzL3BhcnNlcnMvc3RyaW5ncyc7XG5cbmltcG9ydCB7bWF0Y2hlc0FjY291bnRQYXNzd29yZH0gZnJvbSAnLi9jcmVkZW50aWFscy5qcyc7XG5cbmltcG9ydCB0eXBlIHtNYW5hZ2VkQWNjb3VudH0gZnJvbSAnLi9tYW5hZ2VkU2Vzc2lvbi5qcyc7XG5cbmV4cG9ydCBjb25zdCBwYXJzZU1hbmFnZWRDcmVkZW50aWFscyA9IChcbiAgaW5wdXQ6IHtyZWFkb25seSBlbWFpbDogc3RyaW5nOyByZWFkb25seSBwYXNzd29yZDogc3RyaW5nfVxuKToge2VtYWlsOiBzdHJpbmc7IHBhc3N3b3JkOiBzdHJpbmd9ID0+IHtcbiAgY29uc3QgZW1haWwgPSBwYXJzZUVtYWlsKGlucHV0Py5lbWFpbCk7XG4gIGlmKCFlbWFpbCB8fCB0eXBlb2YgaW5wdXQ/LnBhc3N3b3JkICE9PSAnc3RyaW5nJykge1xuICAgIHRocm93IG5ldyBFcnJvcignaW52YWxpZF9jcmVkZW50aWFscycpO1xuICB9XG4gIHJldHVybiB7ZW1haWwsIHBhc3N3b3JkOiBpbnB1dC5wYXNzd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xhQUFhSixXQUFXSyxNQUFNLEtBQUssR0FBSTtRQUN2RixNQUFNLElBQUlQLE1BQU07SUFDbEI7SUFDQSxNQUFNUSxVQUFVTixXQUFXTyxJQUFJLENBQUMsQ0FBQ0MsWUFBY0EsV0FBV0MsV0FBVyxRQUMvRFIsQ0FBQUEsZ0JBQWdCRyxhQUFhSSxVQUFVRSxNQUFNLEtBQUtULFdBQVUsS0FDN0RSLHVCQUF1QkQsY0FBY0ssV0FBV1csVUFBVVgsUUFBUSxFQUFFVyxVQUFVRyxJQUFJO0lBQ3ZGLElBQUcsQ0FBQ0wsV0FBVyxPQUFPQSxRQUFRSSxNQUFNLEtBQUssWUFBWUosUUFBUUksTUFBTSxDQUFDTCxNQUFNLEdBQUcsS0FBS0MsUUFBUUksTUFBTSxDQUFDTCxNQUFNLEdBQUcsT0FDckcsT0FBT0MsUUFBUU0sUUFBUSxLQUFLLFlBQVlOLFFBQVFNLFFBQVEsQ0FBQ1AsTUFBTSxHQUFHLEtBQUtDLFFBQVFNLFFBQVEsQ0FBQ1AsTUFBTSxHQUFHLEtBQUs7UUFDekcsTUFBTSxJQUFJUCxNQUFNO0lBQ2xCO0lBQ0EsT0FBT1E7QUFDVCxFQUFFIn0=
@@ -0,0 +1,2 @@
1
+ /** Accept the already-normalized password, preserving the existing owned hash policy exactly. */
2
+ export declare const matchesAccountPassword: (password: string, storedPassword: string, salt: string) => boolean;
@@ -0,0 +1,4 @@
1
+ import { createPassword } from '@nlabs/utils/parsers/strings';
2
+ /** Accept the already-normalized password, preserving the existing owned hash policy exactly. */ export const matchesAccountPassword = (password, storedPassword, salt)=>Boolean(storedPassword && salt && storedPassword === createPassword(password, salt));
3
+
4
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9uaXRyb2c3Ly5jb2RleC93b3JrdHJlZXMvdmF1bHQtczMtcmVsZWFzZS9yZWFrdG9yL3BhY2thZ2VzL3JlYWt0b3Ivc3JjL2F1dGgvY3JlZGVudGlhbHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtjcmVhdGVQYXNzd29yZH0gZnJvbSAnQG5sYWJzL3V0aWxzL3BhcnNlcnMvc3RyaW5ncyc7XG5cbi8qKiBBY2NlcHQgdGhlIGFscmVhZHktbm9ybWFsaXplZCBwYXNzd29yZCwgcHJlc2VydmluZyB0aGUgZXhpc3Rpbmcgb3duZWQgaGFzaCBwb2xpY3kgZXhhY3RseS4gKi9cbmV4cG9ydCBjb25zdCBtYXRjaGVzQWNjb3VudFBhc3N3b3JkID0gKHBhc3N3b3JkOiBzdHJpbmcsIHN0b3JlZFBhc3N3b3JkOiBzdHJpbmcsIHNhbHQ6IHN0cmluZyk6IGJvb2xlYW4gPT5cbiAgQm9vbGVhbihzdG9yZWRQYXNzd29yZCAmJiBzYWx0ICYmIHN0b3JlZFBhc3N3b3JkID09PSBjcmVhdGVQYXNzd29yZChwYXNzd29yZCwgc2FsdCkpO1xuIl0sIm5hbWVzIjpbImNyZWF0ZVBhc3N3b3JkIiwibWF0Y2hlc0FjY291bnRQYXNzd29yZCIsInBhc3N3b3JkIiwic3RvcmVkUGFzc3dvcmQiLCJzYWx0IiwiQm9vbGVhbiJdLCJtYXBwaW5ncyI6IkFBQUEsU0FBUUEsY0FBYyxRQUFPLCtCQUErQjtBQUU1RCwrRkFBK0YsR0FDL0YsT0FBTyxNQUFNQyx5QkFBeUIsQ0FBQ0MsVUFBa0JDLGdCQUF3QkMsT0FDL0VDLFFBQVFGLGtCQUFrQkMsUUFBUUQsbUJBQW1CSCxlQUFlRSxVQUFVRSxPQUFPIn0=
@@ -0,0 +1,12 @@
1
+ export { matchesAccountPassword } from './credentials.js';
2
+ export { createKmsSigner } from './kmsSigner.js';
3
+ export type { KmsSignInput, KmsSignOutput } from './kmsSigner.js';
4
+ export { createManagedSessionService } from './managedSession.js';
5
+ export type { ManagedAccount, ManagedCredentialEnvelope, ManagedSessionOptions, ManagedSessionService, SessionFamily, VerifiedManagedIdentity } from './managedSession.js';
6
+ export { ManagedAuthOperationError } from './operation.js';
7
+ export type { ManagedAuthOperationOptions, ManagedAuthPortContext } from './operation.js';
8
+ export { createWebSessionService, WebSignInLimitError } from './webSession.js';
9
+ export type { ManagedWebSessionPersistence, WebSessionGrant, WebSessionIdentity, WebSessionLookup, WebSessionOptions, WebSessionScope, WebSessionService, WebSignInLimiter } from './webSession.js';
10
+ export { createWebSessionHttpAdapter } from './webSessionHttp.js';
11
+ export type { WebSessionAuthorization, WebSessionHttpAdapter, WebSessionHttpOptions, WebSessionHttpResponse } from './webSessionHttp.js';
12
+ export type { WebSessionHttpRequest } from './webSessionCookies.js';
@@ -0,0 +1,8 @@
1
+ export { matchesAccountPassword } from './credentials.js';
2
+ export { createKmsSigner } from './kmsSigner.js';
3
+ export { createManagedSessionService } from './managedSession.js';
4
+ export { ManagedAuthOperationError } from './operation.js';
5
+ export { createWebSessionService, WebSignInLimitError } from './webSession.js';
6
+ export { createWebSessionHttpAdapter } from './webSessionHttp.js';
7
+
8
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9uaXRyb2c3Ly5jb2RleC93b3JrdHJlZXMvdmF1bHQtczMtcmVsZWFzZS9yZWFrdG9yL3BhY2thZ2VzL3JlYWt0b3Ivc3JjL2F1dGgvaW5kZXgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHttYXRjaGVzQWNjb3VudFBhc3N3b3JkfSBmcm9tICcuL2NyZWRlbnRpYWxzLmpzJztcbmV4cG9ydCB7Y3JlYXRlS21zU2lnbmVyfSBmcm9tICcuL2ttc1NpZ25lci5qcyc7XG5leHBvcnQgdHlwZSB7S21zU2lnbklucHV0LCBLbXNTaWduT3V0cHV0fSBmcm9tICcuL2ttc1NpZ25lci5qcyc7XG5leHBvcnQge2NyZWF0ZU1hbmFnZWRTZXNzaW9uU2VydmljZX0gZnJvbSAn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Jlc3BvbnNlfSBmcm9tICcuL3dlYlNlc3Npb25IdHRwLmpzJztcbmV4cG9ydCB0eXBlIHtXZWJTZXNzaW9uSHR0cFJlcXVlc3R9IGZyb20gJy4vd2ViU2Vzc2lvbkNvb2tpZXMuanMnO1xuIl0sIm5hbWVzIjpbIm1hdGNoZXNBY2NvdW50UGFzc3dvcmQiLCJjcmVhdGVLbXNTaWduZXIiLCJjcmVhdGVNYW5hZ2VkU2Vzc2lvblNlcnZpY2UiLCJNYW5hZ2VkQXV0aE9wZXJhdGlvbkVycm9yIiwiY3JlYXRlV2ViU2Vzc2lvblNlcnZpY2UiLCJXZWJTaWduSW5MaW1pdEVycm9yIiwiY3JlYXRlV2ViU2Vzc2lvbkh0dHBBZGFwdGVyIl0sIm1hcHBpbmdzIjoiQUFBQSxTQUFRQSxzQkFBc0IsUUFBTyxtQkFBbUI7QUFDeEQsU0FBUUMsZUFBZSxRQUFPLGlCQUFpQjtBQUUvQyxTQUFRQywyQkFBMkIsUUFBTyxzQkFBc0I7QUFHaEUsU0FBUUMseUJBQXlCLFFBQU8saUJBQWlCO0FBRXpELFNBQVFDLHVCQUF1QixFQUFFQyxtQkFBbUIsUUFBTyxrQkFBa0I7QUFFN0UsU0FBUUMsMkJBQTJCLFFBQU8sc0JBQXNCIn0=
@@ -0,0 +1,24 @@
1
+ import type { ManagedAuthPortContext } from './operation.js';
2
+ export interface KmsSignInput {
3
+ readonly KeyId: string;
4
+ readonly Message: Uint8Array;
5
+ readonly MessageType: 'RAW';
6
+ readonly SigningAlgorithm: 'RSASSA_PKCS1_V1_5_SHA_256';
7
+ }
8
+ export interface KmsSignOutput {
9
+ readonly KeyId?: string;
10
+ readonly Signature?: Uint8Array;
11
+ readonly SigningAlgorithm?: string;
12
+ }
13
+ /** Inject the actual AWS SDK KMSClient and SignCommand. No ambient client is created. */
14
+ export declare const createKmsSigner: <Command>(client: {
15
+ readonly send: (command: NoInfer<Command>, options?: {
16
+ readonly abortSignal?: AbortSignal;
17
+ }) => Promise<KmsSignOutput>;
18
+ }, SignCommand: new (input: KmsSignInput) => Command, options: {
19
+ readonly keyArn: string;
20
+ readonly kid: string;
21
+ }) => {
22
+ readonly kid: string;
23
+ readonly sign: (input: Uint8Array, context?: ManagedAuthPortContext) => Promise<Uint8Array>;
24
+ };
@@ -0,0 +1,36 @@
1
+ import { assertAuthOperation } from './operation.js';
2
+ /** Inject the actual AWS SDK KMSClient and SignCommand. No ambient client is created. */ export const createKmsSigner = (client, SignCommand, options)=>{
3
+ if (!/^arn:aws(?:-us-gov|-cn)?:kms:[a-z0-9-]+:[0-9]{12}:key\/[a-zA-Z0-9-]+$/.test(options.keyArn) || !options.kid || options.kid.length > 256) {
4
+ throw new Error('invalid_auth_configuration');
5
+ }
6
+ const { keyArn, kid } = options;
7
+ return {
8
+ kid,
9
+ sign: async (input, context)=>{
10
+ assertAuthOperation(context);
11
+ if (input.byteLength < 1 || input.byteLength > 4096) {
12
+ throw new Error('invalid_signing_input');
13
+ }
14
+ try {
15
+ const output = await client.send(new SignCommand({
16
+ KeyId: keyArn,
17
+ Message: input,
18
+ MessageType: 'RAW',
19
+ SigningAlgorithm: 'RSASSA_PKCS1_V1_5_SHA_256'
20
+ }), context === undefined ? undefined : {
21
+ abortSignal: context.signal
22
+ });
23
+ assertAuthOperation(context);
24
+ if (output.KeyId !== keyArn || output.SigningAlgorithm !== 'RSASSA_PKCS1_V1_5_SHA_256' || !output.Signature || output.Signature.byteLength < 256) {
25
+ throw new Error('invalid_signing_output');
26
+ }
27
+ return output.Signature;
28
+ } catch {
29
+ assertAuthOperation(context);
30
+ throw new Error('auth_unavailable');
31
+ }
32
+ }
33
+ };
34
+ };
35
+
36
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9uaXRyb2c3Ly5jb2RleC93b3JrdHJlZXMvdmF1bHQtczMtcmVsZWFzZS9yZWFrdG9yL3BhY2thZ2VzL3JlYWt0b3Ivc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ZCLG9CQUFvQlk7Z0JBQ3BCLE1BQU0sSUFBSUgsTUFBTTtZQUNsQjtRQUNGO0lBQ0Y7QUFDRixFQUFFIn0=
@@ -0,0 +1,72 @@
1
+ import type { ManagedAuthOperationOptions, ManagedAuthPortContext } from './operation.js';
2
+ export interface ManagedAccount {
3
+ readonly active: boolean;
4
+ readonly password: string;
5
+ readonly salt: string;
6
+ readonly userId: string;
7
+ readonly username: string;
8
+ }
9
+ export interface SessionFamily {
10
+ readonly absoluteExpires: number;
11
+ readonly created: number;
12
+ readonly environment: string;
13
+ readonly revoked: boolean;
14
+ readonly sid: string;
15
+ readonly userId: string;
16
+ }
17
+ export interface ManagedSessionOptions {
18
+ readonly accounts: {
19
+ readonly findByEmail: (email: string, context?: ManagedAuthPortContext) => Promise<readonly ManagedAccount[]>;
20
+ readonly read: (userId: string, context?: ManagedAuthPortContext) => Promise<ManagedAccount | null>;
21
+ };
22
+ readonly audience: string;
23
+ readonly clock?: () => number;
24
+ readonly clockSkewSeconds?: number;
25
+ readonly environment: string;
26
+ readonly families: {
27
+ /** Must atomically insert a unique sid; never overwrite a revoked family. */
28
+ readonly create: (family: SessionFamily, context?: ManagedAuthPortContext) => Promise<void>;
29
+ readonly read: (sid: string, context?: ManagedAuthPortContext) => Promise<SessionFamily | null>;
30
+ /** Atomically revoke only this sid/userId, idempotently. */
31
+ readonly revoke: (sid: string, userId: string, context?: ManagedAuthPortContext) => Promise<void>;
32
+ };
33
+ readonly operationTimeoutMs?: number;
34
+ readonly issuer: string;
35
+ readonly signer: {
36
+ readonly kid: string;
37
+ readonly sign: (input: Uint8Array, context?: ManagedAuthPortContext) => Promise<Uint8Array>;
38
+ };
39
+ readonly trust: readonly {
40
+ readonly kid: string;
41
+ readonly publicKey: string;
42
+ readonly retireAt?: number;
43
+ }[];
44
+ }
45
+ export interface ManagedCredentialEnvelope {
46
+ readonly environment: string;
47
+ readonly expires: number;
48
+ readonly issued: number;
49
+ readonly schemaVersion: 1;
50
+ readonly sid: string;
51
+ readonly token: string;
52
+ readonly userId: string;
53
+ readonly username: string;
54
+ }
55
+ export interface VerifiedManagedIdentity {
56
+ readonly sid: string;
57
+ readonly userId: string;
58
+ readonly username: string;
59
+ }
60
+ export interface ManagedSessionService {
61
+ readonly renew: (token: string, operation?: ManagedAuthOperationOptions) => Promise<ManagedCredentialEnvelope>;
62
+ readonly revoke: (token: string, operation?: ManagedAuthOperationOptions) => Promise<void>;
63
+ readonly signIn: (input: {
64
+ readonly user: {
65
+ readonly email: string;
66
+ readonly password: string;
67
+ };
68
+ }, operation?: ManagedAuthOperationOptions) => Promise<ManagedCredentialEnvelope>;
69
+ readonly verify: (token: string, operation?: ManagedAuthOperationOptions) => Promise<VerifiedManagedIdentity>;
70
+ }
71
+ /** No provider construction, ambient configuration, discovery or secret fallback. */
72
+ export declare const createManagedSessionService: (options: ManagedSessionOptions) => ManagedSessionService;