saaslayer 0.0.7 → 0.2.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 (48) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +318 -66
  3. package/package.json +4 -3
  4. package/src/api-client.js +48 -28
  5. package/src/aws-sigv4.js +1 -1
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +32 -3
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +55 -6
  10. package/src/commands/catalog.js +30 -29
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +79 -10
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +456 -0
  15. package/src/commands/integration-credentials.js +66 -0
  16. package/src/commands/lifecycle.js +77 -40
  17. package/src/commands/login.js +200 -26
  18. package/src/commands/machine-trust.js +96 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +29 -4
  21. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  22. package/src/commands/release-manifest.js +138 -0
  23. package/src/commands/service-principals.js +81 -0
  24. package/src/commands/settings.js +140 -0
  25. package/src/commands/stacks.js +12 -7
  26. package/src/commands/users-management.js +401 -0
  27. package/src/commands/users.js +192 -4
  28. package/src/config.js +20 -7
  29. package/src/credentials.js +221 -34
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +12 -13
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/iam-session.js +4 -30
  36. package/src/module-catalog.js +66 -0
  37. package/src/permissions-request.js +43 -0
  38. package/src/release-manifest.js +334 -0
  39. package/src/scope.js +114 -0
  40. package/src/settings.js +272 -0
  41. package/src/users-api.js +165 -0
  42. package/src/users-import/import.js +10 -10
  43. package/templates/saaslayer-foundation-region.yml +37 -1
  44. package/templates/saaslayer-foundation.yml +63 -10
  45. package/src/commands/iam-principals.js +0 -53
  46. package/src/rbac-auth.js +0 -25
  47. package/vendor/ids/index.d.ts +0 -21
  48. package/vendor/ids/index.js +0 -237
@@ -15,7 +15,8 @@
15
15
  # 1. SaaSLayerDeploymentRole — the only cross-account WRITE entry point. Assumable solely by the
16
16
  # SaaSLayer control-plane account (ControlPlaneAccountId parameter) and only with the shared
17
17
  # ExternalId. It can drive the CloudFormation lifecycle of stacks whose names start with
18
- # StackNamePrefix (default "sl-"), read/write the deployment artifact buckets, and pass exactly
18
+ # StackNamePrefix (default "sl-"), read/write the deployment artifact buckets, update the
19
+ # configuration of StackNamePrefix functions (credential hot-swap), and pass exactly
19
20
  # one role (SaaSLayerCloudFormationExecutionRole) to CloudFormation. It cannot create IAM
20
21
  # resources or touch anything outside the managed stack namespace directly. Its only
21
22
  # sts:AssumeRole grant is into a module stack's own data-migration role
@@ -34,7 +35,8 @@
34
35
  # It carries only Get/List/Describe verbs, is tag-scoped to resources carrying
35
36
  # managed-by=saaslayer-deployer where IAM supports resource-tag conditions, and deliberately
36
37
  # excludes all data-plane reads (no S3 object reads, no DynamoDB item reads, no SSM parameter
37
- # values, no Secrets Manager secret values).
38
+ # values, no Secrets Manager secret values, no function code downloads). An explicit Deny
39
+ # (DenySecretValueReads) covers the /saaslayer/deployment/* SecureStrings and their KMS decrypt.
38
40
  #
39
41
  # SaaSLayerManagedResourceBoundary is a permissions boundary attached to every IAM role that
40
42
  # SaaSLayer module templates create: whatever a module role's own policy says, its effective
@@ -113,7 +115,7 @@ Mappings:
113
115
  # patch = comments/docs/no behavior change
114
116
  Meta:
115
117
  Foundation:
116
- Version: '5.9.0'
118
+ Version: '6.0.0'
117
119
 
118
120
  Resources:
119
121
  # The shared deployment-artifact bucket moved OUT of this account-global stack into the per-region
@@ -570,12 +572,17 @@ Resources:
570
572
  - cognito-idp:AdminDeleteUser
571
573
  - cognito-idp:AdminDeleteUserAttributes
572
574
  - cognito-idp:AdminDisableProviderForUser
575
+ # User lifecycle operations by suid (user-service API: disable/enable after global sign-out, reset-password).
576
+ - cognito-idp:AdminDisableUser
577
+ - cognito-idp:AdminEnableUser
573
578
  - cognito-idp:AdminGetUser
574
579
  - cognito-idp:AdminLinkProviderForUser
575
580
  - cognito-idp:AdminListGroupsForUser
581
+ - cognito-idp:AdminResetUserPassword
576
582
  - cognito-idp:AdminSetUserMFAPreference
577
583
  - cognito-idp:AdminSetUserPassword
578
584
  - cognito-idp:AdminUpdateUserAttributes
585
+ - cognito-idp:AdminUserGlobalSignOut
579
586
  # Social login + identity stitching (epic monorepo-24667): the idpResource custom-resource
580
587
  # Lambda manages the federated IdPs; the PreSignUp/stitching + account Lambdas link/disable
581
588
  # providers, set passwords, and delete users. The boundary is the ceiling, so it must allow
@@ -635,6 +642,12 @@ Resources:
635
642
  # secret from an SSM SecureString (/saaslayer/deployment/*); kms:Decrypt above covers the
636
643
  # SecureString's aws/ssm key.
637
644
  - ssm:GetParameter
645
+ # ssm SecretDelivery: user-service reads its create-only integration-credential generations by path
646
+ # (/saaslayer/deployment/<dep>/<inst>/users/integration-credentials); its role scopes the path.
647
+ - ssm:GetParametersByPath
648
+ # ssm SecretDelivery: user-service reads its permissions handoff parameters in one batch call; its role
649
+ # names the exact parameters.
650
+ - ssm:GetParameters
638
651
  Resource: '*'
639
652
  # PITR check + opt-in on-demand backup for per-service migrate roles (@saaslayer/migrations).
640
653
  # Managed-prefix tables only. The boundary is account-global and the role policies do the
@@ -647,6 +660,12 @@ Resources:
647
660
  Resource:
648
661
  - !Sub arn:${AWS::Partition}:dynamodb:*:${AWS::AccountId}:table/${StackNamePrefix}*
649
662
  - !Sub arn:${AWS::Partition}:dynamodb:*:${AWS::AccountId}:table/${StackNamePrefix}*/backup/*
663
+ # rbac's machine-trust API renders its own IAM-principals document under the deployment's SSM namespace.
664
+ - Effect: Allow
665
+ Action:
666
+ - ssm:PutParameter
667
+ Resource:
668
+ - !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
650
669
  # Transactional email from this account's own SES identities (user-service registration codes).
651
670
  - Effect: Allow
652
671
  Action:
@@ -768,12 +787,21 @@ Resources:
768
787
  - lambda:ListTags
769
788
  - lambda:ListVersionsByFunction
770
789
  Resource: '*'
790
+ # Env-mode credential hot-swap: revoke/rotate updates a managed function's environment directly
791
+ # (UpdateFunctionConfiguration with RevisionId, read back with GetFunctionConfiguration above) instead
792
+ # of a stack deploy. Managed-prefix functions only.
793
+ - Sid: HotSwapFunctionConfiguration
794
+ Effect: Allow
795
+ Action:
796
+ - lambda:UpdateFunctionConfiguration
797
+ Resource: !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackNamePrefix}*
771
798
  # Post-deploy SEED data-plane: after a module deploys, the deployer runs its seed
772
- # script under this role to make the deployment usable — create the initial admin
773
- # user in the just-created Cognito pool (user-service seed) and bootstrap the tenant,
774
- # admin role, and trust policy in the rbac tables (rbac-core seed). Cognito admin
775
- # actions cannot be resource-scoped to a pool that does not exist at bootstrap time;
776
- # DynamoDB is scoped to the rbac-* managed tables.
799
+ # script under this role to make the deployment usable — bootstrap the tenant, the
800
+ # designated first admin's deployment-administrator binding (and an explicit recovery's
801
+ # rebinding) and the trust policy in the rbac tables (rbac-core seed), then create and
802
+ # deliver the first admin in the just-created Cognito pool with its core-table records
803
+ # (user-service seed). Cognito admin actions cannot be resource-scoped to a pool that does
804
+ # not exist at bootstrap time; DynamoDB is scoped to the managed-prefix tables.
777
805
  - Effect: Allow
778
806
  Action:
779
807
  - cognito-idp:AdminCreateUser
@@ -793,12 +821,17 @@ Resources:
793
821
  - dynamodb:GetItem
794
822
  - dynamodb:PutItem
795
823
  - dynamodb:UpdateItem
824
+ # rbac unbinds a role with DeleteItem (first-admin recovery, legacy admin retirement).
825
+ - dynamodb:DeleteItem
796
826
  - dynamodb:Query
797
827
  - dynamodb:BatchWriteItem
798
828
  # Teardown cleanup: a table with DeletionPolicy:Retain survives `serverless remove`, so the
799
829
  # deployer's module-runner deletes those retained sl-* tables directly after the stack is gone
800
830
  # (deleteStackOwnedTables) — else a same-named recreate collides. Scoped to sl-* tables only.
801
831
  - dynamodb:DeleteTable
832
+ # Protected-environment tables carry deletion protection; a delete-custody teardown turns it off
833
+ # (UpdateTable DeletionProtectionEnabled=false) before DeleteTable. Same sl-* scope.
834
+ - dynamodb:UpdateTable
802
835
  Resource:
803
836
  - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${StackNamePrefix}*
804
837
  - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${StackNamePrefix}*/index/*
@@ -920,7 +953,11 @@ Resources:
920
953
  # account + external ID) and additionally pins the session name to saaslayer-support-* so each
921
954
  # assumption is attributable in CloudTrail. Grants carry only Get/List/Describe verbs — enforced
922
955
  # by tests/bootstrap.test.js — and exclude all data-plane reads: no S3 object reads, no DynamoDB
923
- # item reads, no SSM parameter values, no Secrets Manager secret values.
956
+ # item reads, no SSM parameter values, no Secrets Manager secret values, no function code downloads.
957
+ # Function configuration and stack templates stay readable: with SecretDelivery=env (the default) they
958
+ # carry the deployment's generated secrets (an accepted risk; this role trusts the same principals as the
959
+ # deployment role). With SecretDelivery=ssm they carry only parameter paths, and DenySecretValueReads
960
+ # blocks the values.
924
961
  SaaSLayerSupportReadOnlyRole:
925
962
  Type: AWS::IAM::Role
926
963
  Properties:
@@ -976,8 +1013,8 @@ Resources:
976
1013
  - dynamodb:ListTagsOfResource
977
1014
  - events:DescribeEventBus
978
1015
  - events:ListTagsForResource
1016
+ # No lambda:GetFunction: it returns a presigned code download URL. Configuration reads stay.
979
1017
  - lambda:GetAlias
980
- - lambda:GetFunction
981
1018
  - lambda:GetFunctionConfiguration
982
1019
  - lambda:GetFunctionEventInvokeConfig
983
1020
  - lambda:GetPolicy
@@ -1014,6 +1051,22 @@ Resources:
1014
1051
  - cloudwatch:GetDashboard
1015
1052
  - cloudwatch:ListDashboards
1016
1053
  Resource: '*'
1054
+ # DenySecretValueReads: deployments with SecretDelivery=ssm keep generated secrets as SecureStrings
1055
+ # under /saaslayer/deployment/*. The role has no Allow for them; these Denies make that explicit, in
1056
+ # every region, so no later Allow (here or attached out of band) can read a secret value.
1057
+ - Sid: DenySecretValueReads
1058
+ Effect: Deny
1059
+ Action:
1060
+ - ssm:GetParameter*
1061
+ Resource: !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
1062
+ - Effect: Deny
1063
+ Action:
1064
+ - kms:Decrypt
1065
+ Resource: '*'
1066
+ Condition:
1067
+ StringLike:
1068
+ kms:ViaService: ssm.*.amazonaws.com
1069
+ kms:EncryptionContext:PARAMETER_ARN: !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
1017
1070
 
1018
1071
  Outputs:
1019
1072
  DeploymentRoleArn:
@@ -1,53 +0,0 @@
1
- // `saaslayer rbac iam-principals set|get`: declare which of your AWS IAM roles are trusted SaaSLayer principals (and
2
- // their credential scopes) by writing the deployment's SSM parameter in your own account with your AWS credentials.
3
- 'use strict'
4
- const fs = require('fs')
5
- const path = require('path')
6
- const { execFileSync } = require('child_process')
7
- const { iamPrincipalsParam, validatePrincipalsFile } = require('../iam-session')
8
-
9
- /** @param {string} cmd @param {string[]} args */
10
- const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8' })
11
-
12
- /**
13
- * @param {{ deployment?: string, 'service-instance'?: string, region?: string, profile?: string }} flags
14
- * @returns {{ name: string, awsArgs: string[] }}
15
- */
16
- function target(flags) {
17
- if (!flags.deployment) throw new Error('rbac iam-principals: --deployment <dep_id> is required')
18
- const region = flags.region || process.env.AWS_REGION
19
- if (!region) throw new Error('rbac iam-principals: --region (or $AWS_REGION) is required')
20
- return {
21
- name: iamPrincipalsParam(flags.deployment, flags['service-instance'] || '_'),
22
- awsArgs: ['--region', region, ...(flags.profile ? ['--profile', flags.profile] : [])],
23
- }
24
- }
25
-
26
- /**
27
- * Validate the principals file and write it to the deployment's SSM parameter.
28
- * @param {string[]} positional [file]
29
- * @param {object} flags
30
- * @param {{ exec?: typeof defaultExec }} [deps]
31
- */
32
- function iamPrincipalsSet(positional, flags, { exec = defaultExec } = {}) {
33
- if (!positional[0]) throw new Error('rbac iam-principals set: a principals file is required')
34
- const config = JSON.parse(fs.readFileSync(path.resolve(positional[0]), 'utf8'))
35
- const errors = validatePrincipalsFile(config)
36
- if (errors.length) throw new Error(`rbac iam-principals set: ${errors.join('; ')}`)
37
- const { name, awsArgs } = target(flags)
38
- exec('aws', ['ssm', 'put-parameter', '--name', name, '--type', 'String', '--overwrite', '--value', JSON.stringify(config), ...awsArgs])
39
- return name
40
- }
41
-
42
- /**
43
- * Read the deployment's current IAM principals.
44
- * @param {string[]} positional
45
- * @param {object} flags
46
- * @param {{ exec?: typeof defaultExec }} [deps]
47
- */
48
- function iamPrincipalsGet(positional, flags, { exec = defaultExec } = {}) {
49
- const { name, awsArgs } = target(flags)
50
- return JSON.parse(exec('aws', ['ssm', 'get-parameter', '--name', name, '--query', 'Parameter.Value', '--output', 'text', ...awsArgs]))
51
- }
52
-
53
- module.exports = { iamPrincipalsSet, iamPrincipalsGet }
package/src/rbac-auth.js DELETED
@@ -1,25 +0,0 @@
1
- // Auth headers for calls to a deployment's rbac API from the CLI: an IAM principal token (--iam, exchanged from your
2
- // AWS identity) or an API key (--token). Shared by the catalog and users commands.
3
- 'use strict'
4
-
5
- /**
6
- * Request auth headers: an IAM principal token (--iam, exchanged from your AWS identity) as a bearer only, or a
7
- * --token sent as both api key and bearer.
8
- * @param {string} apiBase
9
- * @param {{ token?: string, iam?: string, region?: string, profile?: string }} flags
10
- * @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
11
- * @returns {Promise<Record<string, string>>}
12
- */
13
- async function authHeaders(apiBase, flags, { exchange }) {
14
- if (flags.iam) {
15
- const region = flags.region || process.env.AWS_REGION || 'us-west-2'
16
- const token = await exchange({ apiBase, principalId: flags.iam, region, profile: flags.profile })
17
- return { authorization: `Bearer ${token}` }
18
- }
19
- const token = flags.token || process.env.SAASLAYER_TOKEN
20
- if (!token) throw new Error('--iam <principalId> or --token (or $SAASLAYER_TOKEN) is required')
21
- return { 'x-api-key': token, authorization: `Bearer ${token}` }
22
- }
23
-
24
-
25
- module.exports = { authHeaders }
@@ -1,21 +0,0 @@
1
- // Kept in lockstep with @revenue-engine/typeid — same API, same byte format.
2
- export const TYPEID_ALPHABET: string
3
- export const TYPEID_SUFFIX_LENGTH: 26
4
- export const MAX_CALLER_ID_LENGTH: 255
5
-
6
- export type ParsedTypeId = {
7
- prefix: string
8
- suffix: string
9
- }
10
-
11
- export function uuidV7BytesFromEntropy(timestampMs: number, entropy: Uint8Array): Buffer
12
- export function encodeTypeIdSuffix(bytes: Uint8Array): string
13
- export function isValidTypeIdSuffix(value: unknown): boolean
14
- export function generateTypeId(prefix: string, approvedPrefixes?: Iterable<string> | Set<string>): string
15
- export function generateTypeIdSuffix(): string
16
- export function typeIdFromBytes(prefix: string, bytes: Uint8Array, approvedPrefixes?: Iterable<string> | Set<string>): string
17
- export function parseTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): ParsedTypeId | null
18
- export function isTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): boolean
19
- export function assertTypeIdPrefix(id: string, expectedPrefix: string, approvedPrefixes?: Iterable<string> | Set<string>): void
20
- export function validateCallerId(id: unknown): string
21
- export function validateRefId(fieldName: string, value: unknown): unknown
@@ -1,237 +0,0 @@
1
- // The platform's single id generator — a verbatim port of @revenue-engine/typeid (byte-identical ids:
2
- // monotonic UUIDv7 encoded as a 26-char TypeID base32 suffix, lowercase). CommonJS for the saaslayer
3
- // service runtime. generateTypeIdSuffix() -> the BARE k-sortable body (custom:suid); generateTypeId(prefix,
4
- // approvedPrefixes) -> "<prefix>_<body>". Keep this in lockstep with @revenue-engine/typeid.
5
- const { randomBytes } = require('node:crypto')
6
-
7
- const TYPEID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'
8
- const TYPEID_SUFFIX_LENGTH = 26
9
- const MAX_CALLER_ID_LENGTH = 255
10
-
11
- const TYPEID_ALPHABET_SET = new Set(TYPEID_ALPHABET)
12
- const PREFIX_PATTERN = /^[a-z][a-z0-9_]{0,62}$/
13
-
14
- let lastTs = 0
15
- let seq = 0
16
-
17
- function assertPrefix(prefix) {
18
- if (typeof prefix !== 'string' || !PREFIX_PATTERN.test(prefix)) {
19
- throw new Error(`Invalid TypeID prefix: "${prefix}"`)
20
- }
21
- }
22
-
23
- function normalizeApprovedPrefixes(prefixes) {
24
- if (!prefixes) return null
25
- return prefixes instanceof Set ? prefixes : new Set(prefixes)
26
- }
27
-
28
- function assertApprovedPrefix(prefix, approvedPrefixes) {
29
- const set = normalizeApprovedPrefixes(approvedPrefixes)
30
- assertPrefix(prefix)
31
- if (set && !set.has(prefix)) {
32
- throw new Error(`Unknown TypeID prefix: "${prefix}"`)
33
- }
34
- }
35
-
36
- function uuidV7Bytes() {
37
- const now = Date.now()
38
- if (now > lastTs) {
39
- lastTs = now
40
- seq = 0
41
- } else {
42
- seq += 1
43
- if (seq > 0xfff) {
44
- while (Date.now() <= lastTs) { /* spin to the next ms */ }
45
- lastTs = Date.now()
46
- seq = 0
47
- }
48
- }
49
-
50
- const buf = Buffer.alloc(16)
51
- writeTimestamp(buf, lastTs)
52
- buf[6] = 0x70 | ((seq >> 8) & 0x0f)
53
- buf[7] = seq & 0xff
54
-
55
- const rand = randomBytes(8)
56
- buf[8] = 0x80 | (rand[0] & 0x3f)
57
- buf[9] = rand[1]
58
- buf[10] = rand[2]
59
- buf[11] = rand[3]
60
- buf[12] = rand[4]
61
- buf[13] = rand[5]
62
- buf[14] = rand[6]
63
- buf[15] = rand[7]
64
- return buf
65
- }
66
-
67
- function writeTimestamp(buf, timestampMs) {
68
- const hi = Math.floor(timestampMs / 0x100000000)
69
- const lo = timestampMs - hi * 0x100000000
70
- buf.writeUInt16BE(hi, 0)
71
- buf.writeUInt32BE(lo, 2)
72
- }
73
-
74
- function uuidV7BytesFromEntropy(timestampMs, entropy) {
75
- if (!Number.isSafeInteger(timestampMs) || timestampMs < 0 || timestampMs > 0xffffffffffff) {
76
- throw new Error(`Invalid UUIDv7 timestamp: ${timestampMs}`)
77
- }
78
- if (!(entropy instanceof Uint8Array) || entropy.length < 10) {
79
- throw new Error('UUIDv7 entropy must be at least 10 bytes')
80
- }
81
-
82
- const buf = Buffer.alloc(16)
83
- writeTimestamp(buf, timestampMs)
84
- buf[6] = 0x70 | (entropy[0] & 0x0f)
85
- buf[7] = entropy[1]
86
- buf[8] = 0x80 | (entropy[2] & 0x3f)
87
- buf[9] = entropy[3]
88
- buf[10] = entropy[4]
89
- buf[11] = entropy[5]
90
- buf[12] = entropy[6]
91
- buf[13] = entropy[7]
92
- buf[14] = entropy[8]
93
- buf[15] = entropy[9]
94
- return buf
95
- }
96
-
97
- function encodeTypeIdSuffix(bytes) {
98
- if (!(bytes instanceof Uint8Array) || bytes.length !== 16) {
99
- throw new Error('TypeID suffix encoding requires exactly 16 bytes')
100
- }
101
-
102
- let n = 0n
103
- for (let i = 0; i < 16; i += 1) {
104
- n = (n << 8n) | BigInt(bytes[i])
105
- }
106
-
107
- const chars = new Array(TYPEID_SUFFIX_LENGTH)
108
- for (let i = TYPEID_SUFFIX_LENGTH - 1; i >= 0; i -= 1) {
109
- chars[i] = TYPEID_ALPHABET[Number(n & 0x1fn)]
110
- n >>= 5n
111
- }
112
- return chars.join('')
113
- }
114
-
115
- function isValidTypeIdSuffix(value) {
116
- if (typeof value !== 'string' || value.length !== TYPEID_SUFFIX_LENGTH) return false
117
- if (!'01234567'.includes(value[0].toLowerCase())) return false
118
- for (let i = 0; i < value.length; i += 1) {
119
- if (!TYPEID_ALPHABET_SET.has(value[i].toLowerCase())) return false
120
- }
121
- return true
122
- }
123
-
124
- function generateTypeId(prefix, approvedPrefixes) {
125
- assertApprovedPrefix(prefix, approvedPrefixes)
126
- return `${prefix}_${encodeTypeIdSuffix(uuidV7Bytes())}`
127
- }
128
-
129
- function generateTypeIdSuffix() {
130
- return encodeTypeIdSuffix(uuidV7Bytes())
131
- }
132
-
133
- function typeIdFromBytes(prefix, bytes, approvedPrefixes) {
134
- assertApprovedPrefix(prefix, approvedPrefixes)
135
- return `${prefix}_${encodeTypeIdSuffix(bytes)}`
136
- }
137
-
138
- function parseTypeId(id, approvedPrefixes) {
139
- if (typeof id !== 'string' || id.length === 0) return null
140
- const idx = id.lastIndexOf('_')
141
- if (idx < 1) return null
142
-
143
- const prefix = id.slice(0, idx).toLowerCase()
144
- const suffix = id.slice(idx + 1).toLowerCase()
145
- if (!PREFIX_PATTERN.test(prefix)) return null
146
- const set = normalizeApprovedPrefixes(approvedPrefixes)
147
- if (set && !set.has(prefix)) return null
148
- if (!isValidTypeIdSuffix(suffix)) return null
149
- return { prefix, suffix }
150
- }
151
-
152
- function isTypeId(id, approvedPrefixes) {
153
- return parseTypeId(id, approvedPrefixes) !== null
154
- }
155
-
156
- function assertTypeIdPrefix(id, expectedPrefix, approvedPrefixes) {
157
- const parsed = parseTypeId(id, approvedPrefixes)
158
- if (!parsed) {
159
- throw new Error(`Value is not a TypeID: "${id}"`)
160
- }
161
- if (parsed.prefix !== expectedPrefix) {
162
- throw new Error(`Expected TypeID prefix "${expectedPrefix}" but got "${parsed.prefix}"`)
163
- }
164
- }
165
-
166
- /**
167
- * Shape checks shared by caller-chosen ids and references: string, non-empty after trim, bounded, no control
168
- * characters, no "#" key delimiter.
169
- * @param {unknown} id
170
- * @returns {string} trimmed id
171
- */
172
- function validateIdShape(id) {
173
- if (typeof id !== 'string') {
174
- throw new TypeError('Caller ID must be a string')
175
- }
176
-
177
- const trimmed = id.trim()
178
- if (!trimmed) {
179
- throw new Error('Caller ID must not be empty after trimming')
180
- }
181
- if (trimmed.length > MAX_CALLER_ID_LENGTH) {
182
- throw new Error(`Caller ID exceeds max length of ${MAX_CALLER_ID_LENGTH}`)
183
- }
184
- if (/[\x00-\x1f\x7f]/.test(trimmed)) {
185
- throw new Error('Caller ID must not contain ASCII control characters')
186
- }
187
- if (trimmed.includes('#')) {
188
- throw new Error('Caller ID must not contain "#" (DynamoDB key delimiter)')
189
- }
190
- return trimmed
191
- }
192
-
193
- /**
194
- * Validate a caller-chosen id for a new entity. Rejects "*" so an id can never act as a wildcard when substituted
195
- * into a pattern (F18: `like` + `${subject.id}`).
196
- * @param {unknown} id
197
- * @returns {string} trimmed id
198
- */
199
- function validateCallerId(id) {
200
- const trimmed = validateIdShape(id)
201
- if (trimmed.includes('*')) {
202
- throw new Error('Caller ID must not contain "*" (pattern wildcard)')
203
- }
204
- return trimmed
205
- }
206
-
207
- /**
208
- * Validate a reference field (an existing id, or a scope where "*" keeps its catch-all meaning).
209
- * @param {string} fieldName
210
- * @param {unknown} value
211
- */
212
- function validateRefId(fieldName, value) {
213
- if (value == null) return value
214
- try {
215
- return validateIdShape(value)
216
- } catch (err) {
217
- const message = err instanceof Error ? err.message : String(err)
218
- throw new Error(`${fieldName}: ${message}`)
219
- }
220
- }
221
-
222
- module.exports = {
223
- TYPEID_ALPHABET,
224
- TYPEID_SUFFIX_LENGTH,
225
- MAX_CALLER_ID_LENGTH,
226
- uuidV7BytesFromEntropy,
227
- encodeTypeIdSuffix,
228
- isValidTypeIdSuffix,
229
- generateTypeId,
230
- generateTypeIdSuffix,
231
- typeIdFromBytes,
232
- parseTypeId,
233
- isTypeId,
234
- assertTypeIdPrefix,
235
- validateCallerId,
236
- validateRefId,
237
- }