@astram/core 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/authentication/index.d.ts +1 -0
  2. package/dist/authentication/index.d.ts.map +1 -1
  3. package/dist/authentication/index.js +2 -0
  4. package/dist/authentication/index.js.map +1 -1
  5. package/dist/authentication/service-account-authenticator.d.ts +82 -0
  6. package/dist/authentication/service-account-authenticator.d.ts.map +1 -0
  7. package/dist/authentication/service-account-authenticator.js +74 -0
  8. package/dist/authentication/service-account-authenticator.js.map +1 -0
  9. package/dist/encryption/encryption-service.d.ts +63 -0
  10. package/dist/encryption/encryption-service.d.ts.map +1 -0
  11. package/dist/encryption/encryption-service.js +184 -0
  12. package/dist/encryption/encryption-service.js.map +1 -0
  13. package/dist/encryption/index.d.ts +17 -0
  14. package/dist/encryption/index.d.ts.map +1 -0
  15. package/dist/encryption/index.js +15 -0
  16. package/dist/encryption/index.js.map +1 -0
  17. package/dist/encryption/ports.d.ts +84 -0
  18. package/dist/encryption/ports.d.ts.map +1 -0
  19. package/dist/encryption/ports.js +18 -0
  20. package/dist/encryption/ports.js.map +1 -0
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/secrets/index.d.ts +15 -0
  26. package/dist/secrets/index.d.ts.map +1 -0
  27. package/dist/secrets/index.js +14 -0
  28. package/dist/secrets/index.js.map +1 -0
  29. package/dist/secrets/ports.d.ts +45 -0
  30. package/dist/secrets/ports.d.ts.map +1 -0
  31. package/dist/secrets/ports.js +26 -0
  32. package/dist/secrets/ports.js.map +1 -0
  33. package/dist/secrets/resolve.d.ts +29 -0
  34. package/dist/secrets/resolve.d.ts.map +1 -0
  35. package/dist/secrets/resolve.js +49 -0
  36. package/dist/secrets/resolve.js.map +1 -0
  37. package/dist-cjs/authentication/index.js +2 -0
  38. package/dist-cjs/authentication/service-account-authenticator.js +78 -0
  39. package/dist-cjs/encryption/encryption-service.js +189 -0
  40. package/dist-cjs/encryption/index.js +20 -0
  41. package/dist-cjs/encryption/ports.js +18 -0
  42. package/dist-cjs/index.js +2 -0
  43. package/dist-cjs/secrets/index.js +21 -0
  44. package/dist-cjs/secrets/ports.js +29 -0
  45. package/dist-cjs/secrets/resolve.js +54 -0
  46. package/package.json +1 -1
@@ -49,4 +49,5 @@ export * from './password-hasher.js';
49
49
  export * from './credential-resolver.js';
50
50
  export * from './totp.js';
51
51
  export * from './authenticator.js';
52
+ export * from './service-account-authenticator.js';
52
53
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEtD,yEAAyE;AACzE,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,MAAM,GAAG,UAAU,GAAG,eAAe,CAAC;AAE5E,0EAA0E;AAC1E,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACrD;AAED,4CAA4C;AAC5C,MAAM,MAAM,qBAAqB,GAAG,eAAe,GAAG,cAAc,GAAG,UAAU,CAAC;AAElF,mDAAmD;AACnD,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,OAAO,EAAE,qBAAqB,CAAC;IACxC,uDAAuD;IACvD,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;IAC/B,yEAAyE;IACzE,QAAQ,CAAC,gBAAgB,EAAE,SAAS,UAAU,EAAE,CAAC;IACjD,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,CAAC,EAAE,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UAAU,EAAE,GACjC,OAAO,CAAC,oBAAoB,CAAC,CAAC;CAClC;AAKD,cAAc,sBAAsB,CAAC;AAGrC,cAAc,0BAA0B,CAAC;AAEzC,cAAc,WAAW,CAAC;AAE1B,cAAc,oBAAoB,CAAC;AAEnC,cAAc,oCAAoC,CAAC"}
@@ -24,4 +24,6 @@ export * from './credential-resolver.js';
24
24
  export * from './totp.js';
25
25
  // The Authentication engine + the `createAuthenticator` factory:
26
26
  export * from './authenticator.js';
27
+ // Service-account API-key authentication (ADR-0033) — the machine/agent/MCP auth path:
28
+ export * from './service-account-authenticator.js';
27
29
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA2CH,iFAAiF;AACjF,iFAAiF;AACjF,aAAa;AACb,cAAc,sBAAsB,CAAC;AACrC,kFAAkF;AAClF,qBAAqB;AACrB,cAAc,0BAA0B,CAAC;AACzC,qFAAqF;AACrF,cAAc,WAAW,CAAC;AAC1B,iEAAiE;AACjE,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA2CH,iFAAiF;AACjF,iFAAiF;AACjF,aAAa;AACb,cAAc,sBAAsB,CAAC;AACrC,kFAAkF;AAClF,qBAAqB;AACrB,cAAc,0BAA0B,CAAC;AACzC,qFAAqF;AACrF,cAAc,WAAW,CAAC;AAC1B,iEAAiE;AACjE,cAAc,oBAAoB,CAAC;AACnC,uFAAuF;AACvF,cAAc,oCAAoC,CAAC"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Service-account API-key authentication (ADR-0033) — the machine auth path. An agent / MCP server /
3
+ * script presents an API key (`ask_<accountId>_<secret>`); this engine verifies it and produces a
4
+ * tenant-bound `service_account` {@link Principal} that then flows through the SAME `decide()` as a
5
+ * human (ADR-0001 — no agent-special enforcement path).
6
+ *
7
+ * SECURITY (ADR-0033):
8
+ * - HASH-ONLY: the store holds only the Argon2id hash of the secret (reuses {@link PasswordHasher},
9
+ * the same bar as passwords/refresh-tokens) — a store breach yields no usable key.
10
+ * - CONSTANT-TIME verify (via PasswordHasher.verify); a malformed/unknown/expired/revoked key ⇒ a
11
+ * UNIFORM authentication failure (no enumeration of which accounts exist).
12
+ * - FAIL-CLOSED: expired, revoked, or a store/hasher outage ⇒ deny (never allow, never a partial
13
+ * principal). The secret is NEVER logged / returned / audited (only the account id/label/version).
14
+ * - LEAST PRIVILEGE + tenant-bound: the resolved Principal carries ONLY the account's own scope and
15
+ * tenant — a hijacked (prompt-injected) agent is bounded by scope + tenant + attribution, not by
16
+ * trusting the agent.
17
+ *
18
+ * Pure + zero-dep (ADR-0003): the hasher + store are injected ports; `@astram/guard` ships adapters.
19
+ */
20
+ import type { Principal } from '../identity/index.js';
21
+ import type { PasswordHasher } from './password-hasher.js';
22
+ /** The API-key prefix that identifies a service-account credential. */
23
+ export declare const API_KEY_PREFIX = "ask_";
24
+ /**
25
+ * A stored API-key record — HASH ONLY, never the secret. Looked up by `accountId` (parsed from the
26
+ * presented key). Carries the fields the engine needs to build the Principal + enforce lifecycle.
27
+ */
28
+ export interface ApiKeyRecord {
29
+ readonly accountId: string;
30
+ readonly tenantId: string;
31
+ /** The account's scope subtree (ADR-0027) — the reachable tenant nodes for its Principal. */
32
+ readonly scopeSubtreeNodeIds: readonly string[];
33
+ /** Role ids the service account holds (drive its object-type grants). */
34
+ readonly roleIds: readonly string[];
35
+ /** Argon2id hash of the key's secret (from PasswordHasher.hash). NEVER the plaintext. */
36
+ readonly secretHash: string;
37
+ /** Monotonic key version (rotation increments it). */
38
+ readonly version: number;
39
+ /** Absolute expiry (epoch-ms); `undefined` = non-expiring (discouraged; opt-in at issue). */
40
+ readonly expiresAtMs?: number;
41
+ /** Set when the key has been revoked (epoch-ms); a revoked key fails closed. */
42
+ readonly revokedAtMs?: number;
43
+ }
44
+ /**
45
+ * Loads an API-key record by the account id parsed from the presented key. Fail-closed: a store
46
+ * OUTAGE must THROW (the engine maps it to an authentication failure) — it must NOT return `null`
47
+ * to mask an outage (that would be indistinguishable from "unknown account", which is fine for
48
+ * enumeration but the throw lets the engine log the outage distinctly server-side).
49
+ */
50
+ export interface ApiKeyStore {
51
+ /** The current key record for an account, or `null` if the account/key is unknown. */
52
+ getByAccountId(accountId: string): Promise<ApiKeyRecord | null>;
53
+ }
54
+ /** The result of an API-key authentication attempt. Success carries the resolved Principal. */
55
+ export type ServiceAuthResult = {
56
+ readonly ok: true;
57
+ readonly principal: Principal;
58
+ } | {
59
+ readonly ok: false;
60
+ readonly reason: 'invalid_key';
61
+ };
62
+ export interface ServiceAuthenticatorDeps {
63
+ readonly store: ApiKeyStore;
64
+ readonly hasher: PasswordHasher;
65
+ /** Injectable clock (epoch-ms) for expiry/revocation checks; defaults to Date.now. */
66
+ readonly now?: () => number;
67
+ }
68
+ /** Parse `ask_<accountId>_<secret>`. Returns null on ANY malformation (→ uniform deny). */
69
+ export declare function parseApiKey(key: string): {
70
+ accountId: string;
71
+ secret: string;
72
+ } | null;
73
+ export interface ServiceAuthenticator {
74
+ /**
75
+ * Authenticate a presented API key → a `service_account` Principal, or a uniform failure. NEVER
76
+ * throws on a bad key (returns `{ok:false}`); NEVER logs/returns the secret. Fail-closed on
77
+ * expiry/revocation/outage.
78
+ */
79
+ authenticateApiKey(presentedKey: string): Promise<ServiceAuthResult>;
80
+ }
81
+ export declare function createServiceAuthenticator(deps: ServiceAuthenticatorDeps): ServiceAuthenticator;
82
+ //# sourceMappingURL=service-account-authenticator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-account-authenticator.d.ts","sourceRoot":"","sources":["../../src/authentication/service-account-authenticator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,C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;AAC3F,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CASrF;AAED,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACtE;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,wBAAwB,GAAG,oBAAoB,CAuD/F"}
@@ -0,0 +1,74 @@
1
+ /** The API-key prefix that identifies a service-account credential. */
2
+ export const API_KEY_PREFIX = 'ask_';
3
+ /** Parse `ask_<accountId>_<secret>`. Returns null on ANY malformation (→ uniform deny). */
4
+ export function parseApiKey(key) {
5
+ if (typeof key !== 'string' || !key.startsWith(API_KEY_PREFIX))
6
+ return null;
7
+ const rest = key.slice(API_KEY_PREFIX.length);
8
+ const sep = rest.indexOf('_');
9
+ if (sep <= 0)
10
+ return null; // must have a non-empty accountId AND a secret
11
+ const accountId = rest.slice(0, sep);
12
+ const secret = rest.slice(sep + 1);
13
+ if (accountId === '' || secret === '')
14
+ return null;
15
+ return { accountId, secret };
16
+ }
17
+ export function createServiceAuthenticator(deps) {
18
+ const now = deps.now ?? (() => Date.now());
19
+ const fail = () => ({ ok: false, reason: 'invalid_key' });
20
+ return {
21
+ async authenticateApiKey(presentedKey) {
22
+ const parsed = parseApiKey(presentedKey);
23
+ if (parsed === null)
24
+ return fail(); // malformed → uniform deny (no enumeration)
25
+ let record;
26
+ try {
27
+ record = await deps.store.getByAccountId(parsed.accountId);
28
+ }
29
+ catch {
30
+ // Store outage → fail closed (authentication failure). Distinct from "unknown" only in
31
+ // the server log; the caller sees the same uniform failure.
32
+ return fail();
33
+ }
34
+ if (record === null) {
35
+ // Unknown account. Still spend a verify against a decoy? PasswordHasher.verify already runs
36
+ // near-constant-time; we simply deny. (Timing parity with the argon path is acceptable —
37
+ // the account id is not itself a secret.)
38
+ return fail();
39
+ }
40
+ // Verify the secret against the stored hash (constant-time). A malformed/mismatched hash →
41
+ // the hasher returns false or rejects; either way we deny (fail-closed).
42
+ let matches = false;
43
+ try {
44
+ matches = await deps.hasher.verify(record.secretHash, parsed.secret);
45
+ }
46
+ catch {
47
+ return fail();
48
+ }
49
+ if (matches !== true)
50
+ return fail(); // strict === true
51
+ // Lifecycle: revoked or expired → deny (fail-closed), even on a correct secret.
52
+ const t = now();
53
+ if (record.revokedAtMs !== undefined && record.revokedAtMs <= t)
54
+ return fail();
55
+ if (record.expiresAtMs !== undefined && record.expiresAtMs <= t)
56
+ return fail();
57
+ // Build the tenant-bound service_account Principal — the SAME shape the broker produces, so it
58
+ // flows through decide() unchanged. NEVER root; scope is the account's own (least privilege).
59
+ const principal = {
60
+ kind: 'service_account',
61
+ id: record.accountId,
62
+ activeScopeNodeId: record.tenantId,
63
+ scopeSubtreeNodeIds: record.scopeSubtreeNodeIds.length > 0
64
+ ? record.scopeSubtreeNodeIds
65
+ : [record.tenantId],
66
+ tenantId: record.tenantId,
67
+ roleIds: record.roleIds,
68
+ isRoot: false,
69
+ };
70
+ return { ok: true, principal };
71
+ },
72
+ };
73
+ }
74
+ //# sourceMappingURL=service-account-authenticator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-account-authenticator.js","sourceRoot":"","sources":["../../src/authentication/service-account-authenticator.ts"],"names":[],"mappings":"AAsBA,uEAAuE;AACvE,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC;AA8CrC,2FAA2F;AAC3F,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,cAAc,CAAC;QAAE,OAAO,IAAI,CAAC;IAC5E,MAAM,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,C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crypto, dekStore, dekCache })` returns the ONE service the platform
5
+ * uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
6
+ * crypto, KMS, and persistence are injected ports (ADR-0003). The service:
7
+ * • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
8
+ * → cache it (so the hot path unwraps at most once per tenant per TTL);
9
+ * • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
10
+ * • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
11
+ * (survives key rotation);
12
+ * • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
13
+ * re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
14
+ *
15
+ * FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
16
+ * returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
17
+ * plaintext is NEVER written unencrypted as a fallback.
18
+ *
19
+ * THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
20
+ * NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
21
+ */
22
+ import type { CryptoPort, DekStore, DekCache, Ciphertext } from './ports.js';
23
+ /** The dependencies the engine composes (all injected — ADR-0003 zero-dep). */
24
+ export interface EncryptionServiceDeps {
25
+ readonly crypto: CryptoPort;
26
+ readonly dekStore: DekStore;
27
+ /** Optional hot-path DEK cache. Absent ⇒ every op unwraps (correct, just slower). */
28
+ readonly dekCache?: DekCache;
29
+ }
30
+ /**
31
+ * A stored, encrypted value — the versioned envelope. Persist THIS (not the raw ciphertext): the
32
+ * `version` tells a later decrypt which DEK the data was written under, so rotation never orphans
33
+ * old data. `tenantId` is stored for defence-in-depth (the caller must also pass it to decrypt).
34
+ */
35
+ export interface Envelope {
36
+ readonly tenantId: string;
37
+ readonly version: number;
38
+ readonly ciphertext: Ciphertext;
39
+ }
40
+ export interface EncryptionService {
41
+ /** Encrypt `plaintext` for `tenantId` (provisioning the tenant's DEK on first use). */
42
+ encryptFor(tenantId: string, plaintext: Uint8Array): Promise<Envelope>;
43
+ /** Decrypt an {@link Envelope} for `tenantId`. Throws (fail-closed) on any failure. */
44
+ decryptFor(tenantId: string, envelope: Envelope): Promise<Uint8Array>;
45
+ /** Rotate a tenant's DEK: mint + persist a new version. Returns the new version number. */
46
+ rotateDek(tenantId: string): Promise<number>;
47
+ /** Crypto-shred a tenant (destroy all its DEKs) — its at-rest data becomes unrecoverable. */
48
+ destroyTenantKeys(tenantId: string): Promise<void>;
49
+ }
50
+ /** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
51
+ export declare class DecryptionError extends Error {
52
+ /** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
53
+ readonly cause?: unknown;
54
+ constructor(message: string, cause?: unknown);
55
+ }
56
+ /** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
57
+ export declare class EncryptionError extends Error {
58
+ /** Underlying cause — for admin logging; never surfaced/leaked. */
59
+ readonly cause?: unknown;
60
+ constructor(message: string, cause?: unknown);
61
+ }
62
+ export declare function createEncryptionService(deps: EncryptionServiceDeps): EncryptionService;
63
+ //# sourceMappingURL=encryption-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-service.d.ts","sourceRoot":"","sources":["../../src/encryption/encryption-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EACV,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,UAAU,EAEX,MAAM,YAAY,CAAC;AAEpB,+EAA+E;AAC/E,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,qFAAqF;IACrF,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;CAC9B;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;CACjC;AAED,MAAM,WAAW,iBAAiB;IAChC,uFAAuF;IACvF,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvE,uFAAuF;IACvF,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACtE,2FAA2F;IAC3F,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7C,6FAA6F;IAC7F,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD;AAED,iGAAiG;AACjG,qBAAa,eAAgB,SAAQ,KAAK;IACxC,mGAAmG;IACnG,SAAkB,KAAK,CAAC,EAAE,OAAO,CAAC;gBACtB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAK7C;AAED,oGAAoG;AACpG,qBAAa,eAAgB,SAAQ,KAAK;IACxC,mEAAmE;IACnE,SAAkB,KAAK,CAAC,EAAE,OAAO,CAAC;gBACtB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAK7C;AAQD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,qBAAqB,GAAG,iBAAiB,CAoItF"}
@@ -0,0 +1,184 @@
1
+ /**
2
+ * The **Encryption engine** (ADR-0031) — per-tenant envelope encryption for data at rest.
3
+ *
4
+ * `createEncryptionService({ crypto, dekStore, dekCache })` returns the ONE service the platform
5
+ * uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
6
+ * crypto, KMS, and persistence are injected ports (ADR-0003). The service:
7
+ * • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
8
+ * → cache it (so the hot path unwraps at most once per tenant per TTL);
9
+ * • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
10
+ * • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
11
+ * (survives key rotation);
12
+ * • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
13
+ * re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
14
+ *
15
+ * FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
16
+ * returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
17
+ * plaintext is NEVER written unencrypted as a fallback.
18
+ *
19
+ * THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
20
+ * NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
21
+ */
22
+ /** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
23
+ export class DecryptionError extends Error {
24
+ /** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
25
+ cause;
26
+ constructor(message, cause) {
27
+ super(message);
28
+ this.name = 'DecryptionError';
29
+ this.cause = cause;
30
+ }
31
+ }
32
+ /** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
33
+ export class EncryptionError extends Error {
34
+ /** Underlying cause — for admin logging; never surfaced/leaked. */
35
+ cause;
36
+ constructor(message, cause) {
37
+ super(message);
38
+ this.name = 'EncryptionError';
39
+ this.cause = cause;
40
+ }
41
+ }
42
+ function requireTenant(tenantId) {
43
+ if (typeof tenantId !== 'string' || tenantId.trim() === '') {
44
+ throw new EncryptionError('tenantId is required (non-empty).');
45
+ }
46
+ }
47
+ export function createEncryptionService(deps) {
48
+ const { crypto, dekStore, dekCache } = deps;
49
+ /** Resolve a tenant's CURRENT DEK: cache → store(current) → unwrap → cache. Provisions on absence. */
50
+ async function currentDek(tenantId) {
51
+ // The cache holds the CURRENT dek only; a version bump evicts it (see rotateDek).
52
+ const cached = dekCache?.get(tenantId);
53
+ let record;
54
+ try {
55
+ record = await dekStore.getCurrent(tenantId);
56
+ }
57
+ catch (cause) {
58
+ // Store outage is NOT "no key" — fail closed loudly, never provision-over-an-outage.
59
+ throw new EncryptionError('DEK store unavailable', cause);
60
+ }
61
+ if (record === null) {
62
+ // First use for this tenant: provision a DEK (generate → wrap → persist v1).
63
+ return provisionDek(tenantId);
64
+ }
65
+ if (cached !== undefined)
66
+ return { dek: cached, version: record.version };
67
+ let dek;
68
+ try {
69
+ dek = await crypto.unwrapDek(record.wrapped, tenantId);
70
+ }
71
+ catch (cause) {
72
+ throw new EncryptionError('could not unwrap the current DEK', cause);
73
+ }
74
+ dekCache?.put(tenantId, dek);
75
+ return { dek, version: record.version };
76
+ }
77
+ /** Resolve a SPECIFIC version's DEK (for decrypting data under an older key). No provisioning. */
78
+ async function dekForVersion(tenantId, version) {
79
+ let record;
80
+ try {
81
+ record = await dekStore.getVersion(tenantId, version);
82
+ }
83
+ catch (cause) {
84
+ throw new DecryptionError('DEK store unavailable', cause);
85
+ }
86
+ if (record === null) {
87
+ throw new DecryptionError(`no DEK version ${version} for tenant '${tenantId}'`);
88
+ }
89
+ try {
90
+ return await crypto.unwrapDek(record.wrapped, tenantId);
91
+ }
92
+ catch (cause) {
93
+ throw new DecryptionError('could not unwrap the DEK', cause);
94
+ }
95
+ }
96
+ async function provisionDek(tenantId) {
97
+ let dek;
98
+ let wrapped;
99
+ try {
100
+ dek = await crypto.generateDek();
101
+ wrapped = await crypto.wrapDek(dek, tenantId);
102
+ }
103
+ catch (cause) {
104
+ throw new EncryptionError('could not generate/wrap a new DEK', cause);
105
+ }
106
+ const version = 1;
107
+ try {
108
+ await dekStore.put({ tenantId, version, wrapped });
109
+ }
110
+ catch (cause) {
111
+ // A concurrent provision may have created v1 first — re-read the current and use it (idempotent-ish).
112
+ const existing = await dekStore.getCurrent(tenantId).catch(() => null);
113
+ if (existing) {
114
+ const existingDek = await crypto.unwrapDek(existing.wrapped, tenantId);
115
+ dekCache?.put(tenantId, existingDek);
116
+ return { dek: existingDek, version: existing.version };
117
+ }
118
+ throw new EncryptionError('could not persist the new DEK', cause);
119
+ }
120
+ dekCache?.put(tenantId, dek);
121
+ return { dek, version };
122
+ }
123
+ return {
124
+ async encryptFor(tenantId, plaintext) {
125
+ requireTenant(tenantId);
126
+ const { dek, version } = await currentDek(tenantId);
127
+ let ciphertext;
128
+ try {
129
+ ciphertext = await crypto.encrypt(plaintext, dek, tenantId);
130
+ }
131
+ catch (cause) {
132
+ throw new EncryptionError('encryption failed', cause);
133
+ }
134
+ return { tenantId, version, ciphertext };
135
+ },
136
+ async decryptFor(tenantId, envelope) {
137
+ requireTenant(tenantId);
138
+ // Defence in depth: the caller-supplied tenant MUST match the envelope's stamp.
139
+ if (envelope.tenantId !== tenantId) {
140
+ throw new DecryptionError('tenant mismatch between caller and envelope (cross-tenant guard)');
141
+ }
142
+ // Prefer the cached current DEK when the envelope is at the current version; else load by version.
143
+ const dek = await dekForVersion(tenantId, envelope.version);
144
+ try {
145
+ return await crypto.decrypt(envelope.ciphertext, dek, tenantId);
146
+ }
147
+ catch (cause) {
148
+ // A tag/AAD mismatch or malformed ciphertext → fail closed. Never leak plaintext/ciphertext.
149
+ throw new DecryptionError('decryption failed (tag mismatch or malformed ciphertext)', cause);
150
+ }
151
+ },
152
+ async rotateDek(tenantId) {
153
+ requireTenant(tenantId);
154
+ let current;
155
+ try {
156
+ current = await dekStore.getCurrent(tenantId);
157
+ }
158
+ catch (cause) {
159
+ throw new EncryptionError('DEK store unavailable', cause);
160
+ }
161
+ const nextVersion = (current?.version ?? 0) + 1;
162
+ let dek;
163
+ let wrapped;
164
+ try {
165
+ dek = await crypto.generateDek();
166
+ wrapped = await crypto.wrapDek(dek, tenantId);
167
+ await dekStore.put({ tenantId, version: nextVersion, wrapped });
168
+ }
169
+ catch (cause) {
170
+ throw new EncryptionError('could not rotate the DEK', cause);
171
+ }
172
+ // The new DEK is now current; drop the stale cached one so the next op unwraps the new one.
173
+ dekCache?.evict(tenantId);
174
+ dekCache?.put(tenantId, dek);
175
+ return nextVersion;
176
+ },
177
+ async destroyTenantKeys(tenantId) {
178
+ requireTenant(tenantId);
179
+ dekCache?.evict(tenantId);
180
+ await dekStore.destroy(tenantId);
181
+ },
182
+ };
183
+ }
184
+ //# sourceMappingURL=encryption-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-service.js","sourceRoot":"","sources":["../../src/encryption/encryption-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAwCH,iGAAiG;AACjG,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,mGAAmG;IACjF,KAAK,CAAW;IAClC,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAED,oGAAoG;AACpG,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,mEAAmE;IACjD,KAAK,CAAW;IAClC,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAED,SAAS,aAAa,CAAC,QAAgB;IACrC,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QAC3D,MAAM,IAAI,eAAe,CAAC,mCAAmC,CAAC,CAAC;IACjE,CAAC;AACH,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,IAA2B;IACjE,MAAM,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,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,KAAK,CAAC,iBAAiB,CAAC,QAAQ;YAC9B,aAAa,CAAC,QAAQ,CAAC,CAAC;YACxB,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC1B,MAAM,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Engine seam: **Encryption** — per-tenant envelope encryption for data at rest (ADR-0031).
3
+ *
4
+ * `createEncryptionService` encrypts/decrypts a tenant's data with that tenant's own DEK; DEKs are
5
+ * wrapped by a KMS-held KEK and only wrapped DEKs are ever persisted. Pure + zero-dep (ADR-0003):
6
+ * crypto/KMS/persistence are injected ports, shipped as adapters in `@astram/guard`.
7
+ *
8
+ * THREAT MODEL (ADR-0031, stated honestly): defends the STORAGE boundary (stolen disk / DB dump /
9
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). Does NOT defend a compromised app host
10
+ * or a compromised KMS. See `docs/Shield/140_Security_Hardening` + ADR-0031.
11
+ *
12
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
13
+ */
14
+ export type { Dek, WrappedDek, Ciphertext, CryptoPort, DekStore, DekCache, WrappedDekRecord, } from './ports.js';
15
+ export { createEncryptionService, DecryptionError, EncryptionError, } from './encryption-service.js';
16
+ export type { EncryptionService, EncryptionServiceDeps, Envelope, } from './encryption-service.js';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/encryption/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,YAAY,EACV,GAAG,EACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,gBAAgB,GACjB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAEjC,YAAY,EACV,iBAAiB,EACjB,qBAAqB,EACrB,QAAQ,GACT,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Engine seam: **Encryption** — per-tenant envelope encryption for data at rest (ADR-0031).
3
+ *
4
+ * `createEncryptionService` encrypts/decrypts a tenant's data with that tenant's own DEK; DEKs are
5
+ * wrapped by a KMS-held KEK and only wrapped DEKs are ever persisted. Pure + zero-dep (ADR-0003):
6
+ * crypto/KMS/persistence are injected ports, shipped as adapters in `@astram/guard`.
7
+ *
8
+ * THREAT MODEL (ADR-0031, stated honestly): defends the STORAGE boundary (stolen disk / DB dump /
9
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). Does NOT defend a compromised app host
10
+ * or a compromised KMS. See `docs/Shield/140_Security_Hardening` + ADR-0031.
11
+ *
12
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
13
+ */
14
+ export { createEncryptionService, DecryptionError, EncryptionError, } from './encryption-service.js';
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/encryption/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAYH,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,eAAe,GAChB,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Encryption engine PORTS — the framework-agnostic contracts the {@link EncryptionService} uses,
3
+ * WITHOUT the engine ever knowing the algorithm, the KMS, or where wrapped DEKs are stored.
4
+ *
5
+ * ADR-0031 (envelope encryption / per-tenant DEKs) + ADR-0003 (zero-dep core): real crypto needs a
6
+ * library + native bindings and a KMS needs network/SDK — neither can live in `@astram/core`. The
7
+ * core defines only these interfaces; `@astram/guard` ships the concrete AEAD + KMS + DEK-store
8
+ * adapters and INJECTS them into `createEncryptionService`. Core stays at ZERO runtime deps.
9
+ *
10
+ * THREAT MODEL (ADR-0031, honest): this defends the STORAGE boundary (stolen disk / DB dump /
11
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). It does NOT defend a compromised app
12
+ * host (the app must hold a tenant's DEK in memory to serve it) or a compromised KMS.
13
+ *
14
+ * SECURITY: no port implementation may log a plaintext, a DEK, or a plaintext key. DEKs and
15
+ * plaintext are transient inputs; they are never surfaced in a result, a reason, or a log.
16
+ */
17
+ /** An opaque data-encryption key (raw bytes). NEVER persisted in plaintext; NEVER logged. */
18
+ export type Dek = Uint8Array;
19
+ /** A DEK wrapped (encrypted) by the KEK — the ONLY form of a DEK that may be persisted. */
20
+ export type WrappedDek = Uint8Array;
21
+ /** Self-describing AEAD ciphertext (algorithm + nonce + tag + body). Opaque to the engine. */
22
+ export type Ciphertext = Uint8Array;
23
+ /**
24
+ * The cryptographic primitives, delegated to the adapter (AEAD in-process; KEK ops to a KMS). The
25
+ * engine composes these; it never sees the KEK and never picks an algorithm.
26
+ */
27
+ export interface CryptoPort {
28
+ /** A fresh, cryptographically-random DEK. */
29
+ generateDek(): Promise<Dek>;
30
+ /**
31
+ * Wrap (encrypt) a DEK with the tenant's KEK — a KMS operation in production. `tenantId` scopes
32
+ * the KEK / is bound so a wrapped DEK is meaningful only for that tenant.
33
+ */
34
+ wrapDek(dek: Dek, tenantId: string): Promise<WrappedDek>;
35
+ /** Unwrap (decrypt) a wrapped DEK with the tenant's KEK. Throws if the KEK can't unwrap it. */
36
+ unwrapDek(wrapped: WrappedDek, tenantId: string): Promise<Dek>;
37
+ /**
38
+ * Authenticated encryption of `plaintext` under `dek`. The `tenantId` MUST be bound as AAD so a
39
+ * ciphertext produced for one tenant cannot be decrypted as another (cross-tenant replay guard).
40
+ * Output is self-describing (algorithm + nonce + tag).
41
+ */
42
+ encrypt(plaintext: Uint8Array, dek: Dek, tenantId: string): Promise<Ciphertext>;
43
+ /**
44
+ * Authenticated decryption. MUST verify the AEAD tag AND the bound `tenantId` (AAD). A tag or
45
+ * AAD mismatch MUST throw — never return partial/garbage plaintext (fail-closed). Throws on any
46
+ * malformed ciphertext.
47
+ */
48
+ decrypt(ciphertext: Ciphertext, dek: Dek, tenantId: string): Promise<Uint8Array>;
49
+ }
50
+ /** A persisted wrapped-DEK record — ONLY the wrapped key + metadata; never a plaintext DEK. */
51
+ export interface WrappedDekRecord {
52
+ readonly tenantId: string;
53
+ /** Monotonic key version for the tenant (rotation increments it; highest is current). */
54
+ readonly version: number;
55
+ readonly wrapped: WrappedDek;
56
+ }
57
+ /**
58
+ * Persists wrapped DEKs (guard adapter → a dedicated table). The store NEVER holds a plaintext
59
+ * DEK. Unique on `(tenantId, version)`. Fail-closed: a load failure throws (never returns "no key"
60
+ * to mask an outage — the engine must distinguish "tenant has no DEK yet" from "store is down").
61
+ */
62
+ export interface DekStore {
63
+ /** The CURRENT (highest-version) wrapped DEK for a tenant, or `null` if the tenant has none. */
64
+ getCurrent(tenantId: string): Promise<WrappedDekRecord | null>;
65
+ /** A specific version's wrapped DEK (for decrypting data written under an older key), or `null`. */
66
+ getVersion(tenantId: string, version: number): Promise<WrappedDekRecord | null>;
67
+ /** Persist a new wrapped DEK at `version` for a tenant (atomic; unique per (tenant,version)). */
68
+ put(record: WrappedDekRecord): Promise<void>;
69
+ /**
70
+ * Permanently destroy ALL wrapped DEKs for a tenant (crypto-shred on offboard — the tenant's
71
+ * at-rest data becomes unrecoverable). Idempotent.
72
+ */
73
+ destroy(tenantId: string): Promise<void>;
74
+ }
75
+ /**
76
+ * A short-lived, memory-only cache of UNWRAPPED DEKs so the hot path unwraps at most once per
77
+ * tenant per TTL. NEVER persisted, NEVER logged. TTL-bounded. A miss is not an error.
78
+ */
79
+ export interface DekCache {
80
+ get(tenantId: string): Dek | undefined;
81
+ put(tenantId: string, dek: Dek): void;
82
+ evict(tenantId: string): void;
83
+ }
84
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ports.d.ts","sourceRoot":"","sources":["../../src/encryption/ports.ts"],"names":[],"mappings":"AAA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AO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC;IAEhF,iGAAiG;IACjG,GAAG,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7C;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACvB,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;IACvC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC;IACtC,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Encryption engine PORTS — the framework-agnostic contracts the {@link EncryptionService} uses,
3
+ * WITHOUT the engine ever knowing the algorithm, the KMS, or where wrapped DEKs are stored.
4
+ *
5
+ * ADR-0031 (envelope encryption / per-tenant DEKs) + ADR-0003 (zero-dep core): real crypto needs a
6
+ * library + native bindings and a KMS needs network/SDK — neither can live in `@astram/core`. The
7
+ * core defines only these interfaces; `@astram/guard` ships the concrete AEAD + KMS + DEK-store
8
+ * adapters and INJECTS them into `createEncryptionService`. Core stays at ZERO runtime deps.
9
+ *
10
+ * THREAT MODEL (ADR-0031, honest): this defends the STORAGE boundary (stolen disk / DB dump /
11
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). It does NOT defend a compromised app
12
+ * host (the app must hold a tenant's DEK in memory to serve it) or a compromised KMS.
13
+ *
14
+ * SECURITY: no port implementation may log a plaintext, a DEK, or a plaintext key. DEKs and
15
+ * plaintext are transient inputs; they are never surfaced in a result, a reason, or a log.
16
+ */
17
+ export {};
18
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ports.js","sourceRoot":"","sources":["../../src/encryption/ports.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG"}
package/dist/index.d.ts CHANGED
@@ -38,6 +38,8 @@ export * from './session/index.js';
38
38
  export * from './risk/index.js';
39
39
  export * from './authorization/index.js';
40
40
  export * from './audit/index.js';
41
+ export * from './encryption/index.js';
42
+ export * from './secrets/index.js';
41
43
  export * from './metadata/index.js';
42
44
  export * from './admin/index.js';
43
45
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAGH,cAAc,qBAAqB,CAAC;AACpC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AAGjC,cAAc,qBAAqB,CAAC;AAKpC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAGH,cAAc,qBAAqB,CAAC;AACpC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AAGnC,cAAc,qBAAqB,CAAC;AAKpC,cAAc,kBAAkB,CAAC"}