@sssb/tools 0.4.0 → 0.6.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.
- package/package.json +1 -1
- package/src/assembly-checks.d.ts +10 -2
- package/src/assembly-checks.js +136 -10
- package/src/commands/check-e2e.js +37 -23
- package/src/commands/ci.js +5 -1
- package/src/commands/doctor.js +11 -1
- package/src/commands/remove-items.js +3 -2
- package/src/commands/serve-standalone.js +15 -2
- package/src/ports.d.ts +5 -4
- package/src/ports.js +37 -6
- package/src/remove-items/code.patch +199 -30
- package/src/tick/tick.js +5 -2
- package/src/tick/ticker.d.ts +4 -1
- package/src/tick/ticker.js +8 -2
package/package.json
CHANGED
package/src/assembly-checks.d.ts
CHANGED
|
@@ -44,8 +44,16 @@ export declare function failClosedEnvironmentProblems(env: Record<string, unknow
|
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
46
|
* Problems with Secrets Manager and managed-policy grants: every Secrets Manager grant names only the
|
|
47
|
-
* cluster's own secret,
|
|
48
|
-
* `AWS::
|
|
47
|
+
* cluster's own secret, no role, user or group attaches an AWS-managed policy the check cannot read, and no
|
|
48
|
+
* `AWS::IAM::*` resource is of a type the check does not read. Grants are read from `AWS::IAM::Policy`,
|
|
49
|
+
* `ManagedPolicy`, `RolePolicy`, `UserPolicy` and `GroupPolicy`, and from a `Role`'s, `User`'s or `Group`'s inline
|
|
50
|
+
* `Policies`; the IAM types that grant nothing (an instance profile, an identity provider, a service-linked role,
|
|
51
|
+
* an access key, a certificate, an MFA device, a user-to-group addition) pass. A `*` or `?` in a granted resource
|
|
52
|
+
* is a wildcard. An `AWS::SecretsManager::ResourcePolicy` on the cluster's secret (or on a secret the check cannot
|
|
53
|
+
* tell is another) may let in only the roles the stack's own Lambda functions run as, each named as
|
|
54
|
+
* `{ AWS: { Fn::GetAtt: [<role>, Arn] } }`: any other principal (`*`, an account, a service, a `NotPrincipal`), or a
|
|
55
|
+
* policy the check cannot read, is a problem. Needs the one `AWS::RDS::DBCluster` in the template; runs on every
|
|
56
|
+
* database shape.
|
|
49
57
|
*/
|
|
50
58
|
export declare function secretGrantProblems(resources: Resources): string[]
|
|
51
59
|
|
package/src/assembly-checks.js
CHANGED
|
@@ -78,22 +78,63 @@ export function failClosedEnvironmentProblems(env) {
|
|
|
78
78
|
return problems
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
// THE IAM TYPES THE CHECKS READ, and the ones that grant nothing. A grant is read from a policy resource's own
|
|
82
|
+
// document (a policy, a managed policy, a role's, user's or group's policy), from a principal's inline policies, and,
|
|
83
|
+
// for an AWS-managed policy a principal attaches, judged by name (unreadablePolicies). Any other `AWS::IAM::*` type
|
|
84
|
+
// fails closed (unreadTypes): one this file does not know could carry a grant it cannot see.
|
|
85
|
+
const POLICY_TYPES = new Set([
|
|
86
|
+
'AWS::IAM::Policy',
|
|
87
|
+
'AWS::IAM::ManagedPolicy',
|
|
88
|
+
'AWS::IAM::RolePolicy',
|
|
89
|
+
'AWS::IAM::UserPolicy',
|
|
90
|
+
'AWS::IAM::GroupPolicy',
|
|
91
|
+
])
|
|
92
|
+
const PRINCIPAL_TYPES = new Set(['AWS::IAM::Role', 'AWS::IAM::User', 'AWS::IAM::Group'])
|
|
93
|
+
// Each grants nothing of its own: a role's carrier for EC2, identity providers, a service-linked role (whose policy
|
|
94
|
+
// is the service's, fixed by AWS), credentials and certificates, and a user put in a group (the group's grants are
|
|
95
|
+
// read where the group is).
|
|
96
|
+
const GRANTS_NOTHING = new Set([
|
|
97
|
+
'AWS::IAM::InstanceProfile',
|
|
98
|
+
'AWS::IAM::OIDCProvider',
|
|
99
|
+
'AWS::IAM::SAMLProvider',
|
|
100
|
+
'AWS::IAM::ServiceLinkedRole',
|
|
101
|
+
'AWS::IAM::ServerCertificate',
|
|
102
|
+
'AWS::IAM::VirtualMFADevice',
|
|
103
|
+
'AWS::IAM::AccessKey',
|
|
104
|
+
'AWS::IAM::UserToGroupAddition',
|
|
105
|
+
])
|
|
106
|
+
|
|
81
107
|
/**
|
|
82
|
-
* The permission documents a resource carries: a policy's, a
|
|
108
|
+
* The permission documents a resource carries: a policy resource's own, or a role's, user's or group's inline ones.
|
|
83
109
|
* @param {Resource} resource
|
|
84
110
|
* @returns {unknown[]}
|
|
85
111
|
*/
|
|
86
112
|
function policyDocuments(resource) {
|
|
87
|
-
if (resource.Type
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
if (resource.Type === 'AWS::IAM::Role') {
|
|
113
|
+
if (POLICY_TYPES.has(resource.Type)) return [resource.Properties?.PolicyDocument]
|
|
114
|
+
if (PRINCIPAL_TYPES.has(resource.Type)) {
|
|
91
115
|
const inline = /** @type {{ PolicyDocument?: unknown }[] | undefined} */ (resource.Properties?.Policies) ?? []
|
|
92
116
|
return inline.map((policy) => policy.PolicyDocument)
|
|
93
117
|
}
|
|
94
118
|
return []
|
|
95
119
|
}
|
|
96
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Each `AWS::IAM::*` resource of a type the checks neither read nor know to grant nothing, as `<id> (<type>)`.
|
|
123
|
+
* @param {Resources} all
|
|
124
|
+
* @returns {string[]}
|
|
125
|
+
*/
|
|
126
|
+
function unreadTypes(all) {
|
|
127
|
+
return Object.entries(all)
|
|
128
|
+
.filter(
|
|
129
|
+
([, r]) =>
|
|
130
|
+
r.Type.startsWith('AWS::IAM::') &&
|
|
131
|
+
!POLICY_TYPES.has(r.Type) &&
|
|
132
|
+
!PRINCIPAL_TYPES.has(r.Type) &&
|
|
133
|
+
!GRANTS_NOTHING.has(r.Type),
|
|
134
|
+
)
|
|
135
|
+
.map(([id, r]) => `${id} (${r.Type})`)
|
|
136
|
+
}
|
|
137
|
+
|
|
97
138
|
/**
|
|
98
139
|
* Whether an IAM action pattern can name one of `service`'s actions. IAM matches `*` and `?` anywhere in
|
|
99
140
|
* an action, so `*`, `rds-data:*` and `rds*:Execute*` all reach `rds-data:ExecuteStatement`.
|
|
@@ -110,7 +151,7 @@ function reaches(action, service) {
|
|
|
110
151
|
}
|
|
111
152
|
|
|
112
153
|
/**
|
|
113
|
-
* Every Allow statement in the stack's IAM
|
|
154
|
+
* Every Allow statement in the stack's IAM policy resources and its roles', users' and groups' inline policies that can
|
|
114
155
|
* grant one of `service`'s actions (`rds-data`, `secretsmanager`): by naming one, by a wildcard that
|
|
115
156
|
* reaches one (`*` reaches every service), or by `NotAction`, which grants everything it does not name.
|
|
116
157
|
* Roles' trust policies grant nothing and are not read.
|
|
@@ -153,7 +194,7 @@ function unreadablePolicies(all) {
|
|
|
153
194
|
.map(([id]) => id),
|
|
154
195
|
)
|
|
155
196
|
return Object.entries(all)
|
|
156
|
-
.filter(([, r]) => r.Type
|
|
197
|
+
.filter(([, r]) => PRINCIPAL_TYPES.has(r.Type))
|
|
157
198
|
.flatMap(([id, r]) =>
|
|
158
199
|
/** @type {unknown[] | undefined} */ (r.Properties?.ManagedPolicyArns ?? [])
|
|
159
200
|
.filter((arn) => {
|
|
@@ -188,7 +229,80 @@ function databaseSecretIds(all, clusterId) {
|
|
|
188
229
|
}
|
|
189
230
|
|
|
190
231
|
/**
|
|
191
|
-
*
|
|
232
|
+
* The roles the stack's Lambda functions run as, by logical id: the only principals a resource policy on the cluster's
|
|
233
|
+
* secret may name (the server's and the migrator's are among them).
|
|
234
|
+
* @param {Resources} all
|
|
235
|
+
* @returns {Set<string>}
|
|
236
|
+
*/
|
|
237
|
+
function functionRoles(all) {
|
|
238
|
+
return new Set(
|
|
239
|
+
Object.values(all)
|
|
240
|
+
.filter((r) => r.Type === 'AWS::Lambda::Function')
|
|
241
|
+
.map((r) => /** @type {{ 'Fn::GetAtt'?: unknown[] } | undefined} */ (r.Properties?.Role)?.['Fn::GetAtt'])
|
|
242
|
+
.filter((att) => Array.isArray(att) && att[1] === 'Arn' && typeof att[0] === 'string')
|
|
243
|
+
.map((att) => /** @type {string} */ (/** @type {unknown[]} */ (att)[0]))
|
|
244
|
+
.filter((id) => all[id]?.Type === 'AWS::IAM::Role'),
|
|
245
|
+
)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Each resource policy on the cluster's secret that lets in a principal other than a role one of the stack's own
|
|
250
|
+
* functions runs as, as `<id>`. A resource policy grants with no IAM resource at all (`Principal: "*"` and
|
|
251
|
+
* `GetSecretValue` is the secret for anyone), so it is read here. Fails closed: a policy whose secret is not a `Ref` to
|
|
252
|
+
* another secret of the stack counts as on the cluster's, and a principal that is not exactly
|
|
253
|
+
* `{ AWS: { Fn::GetAtt: [<role>, Arn] } }` (or a list of those), a `NotPrincipal`, or a document the check cannot
|
|
254
|
+
* read, is a problem.
|
|
255
|
+
* @param {Resources} all
|
|
256
|
+
* @param {readonly string[]} secretIds
|
|
257
|
+
* @returns {string[]}
|
|
258
|
+
*/
|
|
259
|
+
function secretResourcePolicies(all, secretIds) {
|
|
260
|
+
const roles = functionRoles(all)
|
|
261
|
+
/** @param {unknown} principal */
|
|
262
|
+
const isOwnRole = (principal) => {
|
|
263
|
+
if (principal === null || typeof principal !== 'object' || Object.keys(principal).length !== 1) return false
|
|
264
|
+
const att = /** @type {{ 'Fn::GetAtt'?: unknown[] }} */ (principal)['Fn::GetAtt']
|
|
265
|
+
return (
|
|
266
|
+
Array.isArray(att) &&
|
|
267
|
+
att.length === 2 &&
|
|
268
|
+
att[1] === 'Arn' &&
|
|
269
|
+
typeof att[0] === 'string' &&
|
|
270
|
+
roles.has(att[0])
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
/** @param {unknown} principal */
|
|
274
|
+
const onlyOwnRoles = (principal) => {
|
|
275
|
+
if (principal === null || typeof principal !== 'object' || Array.isArray(principal)) return false
|
|
276
|
+
const keys = Object.keys(principal)
|
|
277
|
+
if (keys.length !== 1 || keys[0] !== 'AWS') return false
|
|
278
|
+
const aws = /** @type {{ AWS: unknown }} */ (principal).AWS
|
|
279
|
+
const list = Array.isArray(aws) ? aws : [aws]
|
|
280
|
+
return list.length > 0 && list.every(isOwnRole)
|
|
281
|
+
}
|
|
282
|
+
return Object.entries(all)
|
|
283
|
+
.filter(([, r]) => r.Type === 'AWS::SecretsManager::ResourcePolicy')
|
|
284
|
+
.filter(([, r]) => {
|
|
285
|
+
const ref = /** @type {{ Ref?: unknown } | undefined} */ (r.Properties?.SecretId)?.Ref
|
|
286
|
+
const another =
|
|
287
|
+
typeof ref === 'string' && !secretIds.includes(ref) && all[ref]?.Type === 'AWS::SecretsManager::Secret'
|
|
288
|
+
return !another
|
|
289
|
+
})
|
|
290
|
+
.filter(([, r]) => {
|
|
291
|
+
const statements = /** @type {{ Statement?: unknown } | undefined} */ (r.Properties?.ResourcePolicy)
|
|
292
|
+
?.Statement
|
|
293
|
+
if (!Array.isArray(statements)) return true
|
|
294
|
+
return statements.some((statement) => {
|
|
295
|
+
const st = /** @type {Statement & { Principal?: unknown, NotPrincipal?: unknown }} */ (statement)
|
|
296
|
+
if (st.Effect === 'Deny') return false
|
|
297
|
+
return st.NotPrincipal !== undefined || !onlyOwnRoles(st.Principal)
|
|
298
|
+
})
|
|
299
|
+
})
|
|
300
|
+
.map(([id]) => id)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Whether every resource `statement` grants refers to one of `ids`, and none is a wildcard (`*` or `?`, which IAM
|
|
305
|
+
* matches anywhere in a resource).
|
|
192
306
|
* @param {Statement} statement
|
|
193
307
|
* @param {readonly string[]} ids
|
|
194
308
|
*/
|
|
@@ -196,7 +310,7 @@ function namesOnly(statement, ids) {
|
|
|
196
310
|
const granted = Array.isArray(statement.Resource) ? statement.Resource : [statement.Resource ?? '*']
|
|
197
311
|
return granted.every((resource) => {
|
|
198
312
|
const text = JSON.stringify(resource)
|
|
199
|
-
return
|
|
313
|
+
return !/[*?]/.test(text) && ids.some((id) => text.includes(`"Ref":"${id}"`))
|
|
200
314
|
})
|
|
201
315
|
}
|
|
202
316
|
|
|
@@ -225,7 +339,19 @@ export function secretGrantProblems(resources) {
|
|
|
225
339
|
}
|
|
226
340
|
const unreadable = unreadablePolicies(resources)
|
|
227
341
|
if (unreadable.length > 0) {
|
|
228
|
-
problems.push(
|
|
342
|
+
problems.push(
|
|
343
|
+
`no role, user or group attaches an AWS-managed policy the check cannot read: ${unreadable.join('; ')}`,
|
|
344
|
+
)
|
|
345
|
+
}
|
|
346
|
+
const open = secretResourcePolicies(resources, secretIds)
|
|
347
|
+
if (open.length > 0) {
|
|
348
|
+
problems.push(
|
|
349
|
+
`no resource policy on the cluster’s secret lets in any principal but the stack’s own functions’ roles: ${open.join('; ')}`,
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
const unread = unreadTypes(resources)
|
|
353
|
+
if (unread.length > 0) {
|
|
354
|
+
problems.push(`no IAM resource is of a type this check does not read: ${unread.join('; ')}`)
|
|
229
355
|
}
|
|
230
356
|
return problems
|
|
231
357
|
}
|
|
@@ -14,11 +14,12 @@
|
|
|
14
14
|
// it to Node. So a bare specifier is FOLLOWED when its real path is outside node_modules (the app's own files, its `@/`
|
|
15
15
|
// alias, a sibling workspace package and whatever that imports) or is framework source in any copy (its nearest named
|
|
16
16
|
// package.json is `@sssb/kit`'s), and the seam always; every other package stays external. A `require()` esbuild can
|
|
17
|
-
// see is followed like an import. A function made by `createRequire(...)
|
|
18
|
-
//
|
|
19
|
-
// specifier esbuild did not resolve (other than the entry and
|
|
20
|
-
//
|
|
21
|
-
//
|
|
17
|
+
// see is followed like an import. A loader it cannot see through (a function made by `createRequire(...)`, a plain
|
|
18
|
+
// `require` handed a variable that holds the specifier) is not, so a followed file outside the kit that writes, as a
|
|
19
|
+
// string literal in its code, an `@sssb/kit` specifier esbuild did not resolve (other than the entry and a `.md` or
|
|
20
|
+
// `.json` file of the kit, such as the guide or its `package.json`, other than a property name, and other than an import or export declaration's or a type `import('…')`'s, which esbuild reads or
|
|
21
|
+
// which load nothing) fails too; the file is read by the app's own TypeScript parser, so a comment is not code. A
|
|
22
|
+
// computed specifier stays out of reach of any static check.
|
|
22
23
|
//
|
|
23
24
|
// WHICH FILES: Playwright is asked. Each Playwright config of the app (`playwright.config.*`,
|
|
24
25
|
// `playwright.<name>.config.*` in its directory), plus each `--config <file>` given (repeatable, relative to the
|
|
@@ -54,8 +55,10 @@ import { isInRepoKit, seamOfKit } from './doctor-checks.js'
|
|
|
54
55
|
|
|
55
56
|
const KIT = '@sssb/kit'
|
|
56
57
|
const ENTRY = `${KIT}/testing/e2e`
|
|
57
|
-
/** Kit specifiers
|
|
58
|
+
/** Kit specifiers written in code that load no framework code: the entry, and a data file (the guide, a manifest). */
|
|
58
59
|
const NOT_FRAMEWORK = new Set([ENTRY, `${KIT}/package.json`])
|
|
60
|
+
/** @param {string} specifier */
|
|
61
|
+
const loadsNoFramework = (specifier) => NOT_FRAMEWORK.has(specifier) || /\.(md|json)$/.test(specifier)
|
|
59
62
|
const KEEP = /^@sssb\/(kit|app-config)(\/|$)/
|
|
60
63
|
const PROBE = 'sssbCheckE2eProbe'
|
|
61
64
|
const CONFIG = /^playwright(\.[\w-]+)?\.config\.(c|m)?[jt]s$/
|
|
@@ -369,20 +372,22 @@ function chain(metafile, from, to) {
|
|
|
369
372
|
const typescripts = new Map()
|
|
370
373
|
|
|
371
374
|
/**
|
|
372
|
-
* The `@sssb/kit` specifiers `file` writes as string literals in its CODE,
|
|
373
|
-
*
|
|
375
|
+
* The `@sssb/kit` specifiers `file` writes as string literals in its CODE, outside the module specifier of an import or
|
|
376
|
+
* export declaration and a type `import('…')` (esbuild follows the first, and neither a type-only declaration nor a type
|
|
377
|
+
* import loads anything) and a `declare module` name. Read by the app's own TypeScript parser, as doctor reads the
|
|
378
|
+
* app's tsconfig: comments are not code.
|
|
374
379
|
* @param {string} app
|
|
375
380
|
* @param {string} file
|
|
376
381
|
* @param {string} text
|
|
377
382
|
* @returns {string[]}
|
|
378
383
|
*/
|
|
379
|
-
function
|
|
384
|
+
function kitLiteralsInCode(app, file, text) {
|
|
380
385
|
let ts = typescripts.get(app)
|
|
381
386
|
if (ts === undefined) {
|
|
382
387
|
const resolved = resolveFromApp(
|
|
383
388
|
app,
|
|
384
389
|
'typescript',
|
|
385
|
-
'sssb check-e2e reads the files
|
|
390
|
+
'sssb check-e2e reads the files it follows for a kit specifier esbuild cannot see with',
|
|
386
391
|
)
|
|
387
392
|
ts = /** @type {typeof import('typescript')} */ (createRequire(import.meta.url)(resolved))
|
|
388
393
|
typescripts.set(app, ts)
|
|
@@ -396,29 +401,36 @@ function kitLiteralsBesideCreateRequire(app, file, text) {
|
|
|
396
401
|
: /^\.[cm]?ts$/.test(ext)
|
|
397
402
|
? ts.ScriptKind.TS
|
|
398
403
|
: ts.ScriptKind.JS
|
|
399
|
-
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest,
|
|
400
|
-
let creates = false
|
|
404
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind)
|
|
401
405
|
/** @type {string[]} */
|
|
402
406
|
const literals = []
|
|
403
407
|
/** @param {import('typescript').Node} node */
|
|
404
408
|
const visit = (node) => {
|
|
405
|
-
if (
|
|
406
|
-
else if (
|
|
409
|
+
if (
|
|
407
410
|
(ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) &&
|
|
408
411
|
/^@sssb\/kit(\/|$)/.test(node.text)
|
|
409
|
-
)
|
|
410
|
-
|
|
412
|
+
) {
|
|
413
|
+
const parent = node.parent
|
|
414
|
+
const named =
|
|
415
|
+
((ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) &&
|
|
416
|
+
parent.moduleSpecifier === node) ||
|
|
417
|
+
// a string-literal TYPE (`type S = '@sssb/kit/…'`, an import('…') type's argument): a type loads nothing
|
|
418
|
+
ts.isLiteralTypeNode(parent) ||
|
|
419
|
+
// a NAME (an object-literal or class key, an interface member, a `declare module`): never a specifier
|
|
420
|
+
('name' in parent && parent.name === node)
|
|
421
|
+
if (!named) literals.push(node.text)
|
|
422
|
+
}
|
|
411
423
|
ts.forEachChild(node, visit)
|
|
412
424
|
}
|
|
413
425
|
visit(source)
|
|
414
|
-
return
|
|
426
|
+
return literals
|
|
415
427
|
}
|
|
416
428
|
|
|
417
429
|
/**
|
|
418
430
|
* @typedef {{ file: string, error?: string, reached: { kitFile: string, via: string[] }[], count: number,
|
|
419
431
|
* unfollowed: string[], throughEntry: boolean }} SpecReach
|
|
420
432
|
* `reached`: the kit files outside the entry that the file enters the kit through (each with its import chain);
|
|
421
|
-
* `count`: every kit file outside the entry it reaches; `unfollowed`: a kit specifier named
|
|
433
|
+
* `count`: every kit file outside the entry it reaches; `unfollowed`: a kit specifier named where esbuild cannot follow it
|
|
422
434
|
* that esbuild could not follow; `throughEntry`: whether it reaches the allowed entry at all
|
|
423
435
|
*/
|
|
424
436
|
|
|
@@ -511,18 +523,20 @@ export async function e2eReach(appDir, extraConfigs = []) {
|
|
|
511
523
|
input.imports.some((i) => i.path === key && !i.external),
|
|
512
524
|
),
|
|
513
525
|
)
|
|
514
|
-
// What esbuild cannot see: a kit specifier
|
|
526
|
+
// What esbuild cannot see: a kit specifier written in the code of a followed file outside the kit, which it did not
|
|
527
|
+
// resolve as an import (a `createRequire(...)` function, a `require` of a variable).
|
|
515
528
|
/** @type {string[]} */
|
|
516
529
|
const unfollowed = []
|
|
517
530
|
for (const [key, input] of Object.entries(result.metafile.inputs)) {
|
|
518
531
|
const source = realOf.get(key) ?? key
|
|
519
532
|
if (!path.isAbsolute(source) || isKit(source) || underNodeModules(source)) continue
|
|
520
533
|
const text = readFileSync(source, 'utf8')
|
|
521
|
-
if (!/\bcreateRequire\b/.test(text)) continue
|
|
522
534
|
const seen = new Set(input.imports.map((i) => i.original))
|
|
523
|
-
for (const specifier of
|
|
524
|
-
if (!
|
|
525
|
-
unfollowed.push(
|
|
535
|
+
for (const specifier of kitLiteralsInCode(app, source, text)) {
|
|
536
|
+
if (!loadsNoFramework(specifier) && !seen.has(specifier))
|
|
537
|
+
unfollowed.push(
|
|
538
|
+
`${show(source)} names '${specifier}' where esbuild cannot follow it: reach the kit through ${ENTRY}, or keep the specifier out of code a spec loads`,
|
|
539
|
+
)
|
|
526
540
|
}
|
|
527
541
|
}
|
|
528
542
|
reach.push({
|
package/src/commands/ci.js
CHANGED
|
@@ -278,7 +278,11 @@ export async function run(args) {
|
|
|
278
278
|
// checks under the config a bare `vitest` loads for each app. It runs for the first app, not the root, because
|
|
279
279
|
// an adopter's root need not resolve @sssb/kit. Then, in each app, no e2e spec reaching the kit other than
|
|
280
280
|
// through @sssb/kit/testing/e2e.
|
|
281
|
-
|
|
281
|
+
// The walk is held to every app the job fans out over, as a bare `sssb doctor` at the root holds it to every app
|
|
282
|
+
// the workspace names: an app the workspace's packages do not reach fails here, with doctor's own line.
|
|
283
|
+
const { doctorFor } = await import('./doctor.js')
|
|
284
|
+
const named = apps.map((app) => path.join(root, app))
|
|
285
|
+
const doctor = async () => doctorFor({ dir: path.join(root, apps[0] ?? '.'), defaulted: false, named })
|
|
282
286
|
checks.push(['doctor', doctor, ['--app', path.join(root, apps[0] ?? '.')]])
|
|
283
287
|
const { run: checkE2e } = await import('./check-e2e.js')
|
|
284
288
|
for (const app of apps) checks.push(['check-e2e', checkE2e, ['--app', path.join(root, app)]])
|
package/src/commands/doctor.js
CHANGED
|
@@ -141,8 +141,18 @@ export function doctorApp(args, cwd = process.cwd()) {
|
|
|
141
141
|
/** @param {string[]} args */
|
|
142
142
|
export async function run(args) {
|
|
143
143
|
const chosen = doctorApp(args)
|
|
144
|
-
const appDir = realpathSync(chosen.dir)
|
|
145
144
|
if (args.length > 0) throw new UsageError(`sssb doctor: unknown argument ${args[0]} (usage: doctor [--app <dir>])`)
|
|
145
|
+
return doctorFor(chosen)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* One doctor run, from `dir`, holding the walk to reach every app in `named` (absolute directories). `sssb ci` calls it
|
|
150
|
+
* with the apps it fans out over, so CI's doctor makes the same check as a bare `sssb doctor` at the root.
|
|
151
|
+
* @param {{ dir: string, defaulted: boolean, named: string[] }} chosen
|
|
152
|
+
* @returns {Promise<number>}
|
|
153
|
+
*/
|
|
154
|
+
export async function doctorFor(chosen) {
|
|
155
|
+
const appDir = realpathSync(chosen.dir)
|
|
146
156
|
const root = realpathSync(workspaceRootOf(appDir))
|
|
147
157
|
const rel = relativeTo(root)
|
|
148
158
|
// Said before anything can fail on the app it chose, so a failure there is read with the reason it was picked.
|
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
// against the starter without Items, applied EXACTLY by ./exact-patch.js). The code half removes everything an app's
|
|
9
9
|
// code says about Items: the card, the route, the query, the ability, the catalog namespace, the dashboard's glue, the
|
|
10
10
|
// static demo's card, the specs that name Items, and the proofs of paging. It writes nothing of its own: the starter's
|
|
11
|
-
//
|
|
12
|
-
// RLS proofs, and only runs with
|
|
11
|
+
// e2e specs that do not name Items (the Simulator's among them) stay, so the app still has some for `sssb check-e2e`.
|
|
12
|
+
// The database half removes the migrations, the table's type and its RLS proofs, and only runs with
|
|
13
|
+
// `--drop-migrations`.
|
|
13
14
|
//
|
|
14
15
|
// THE RULE FOR MIGRATIONS. A database that ran `1001_items` records it, and the migrator refuses to start when a migration
|
|
15
16
|
// it recorded is gone from the code (Kysely: "previously executed migration ... is missing"). So this command never
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// The port: PORT when set, else the named port service, else the app's declared one (`"sssb": { "port": … }`).
|
|
11
11
|
import { spawn } from 'node:child_process'
|
|
12
12
|
import { cpSync, existsSync, readdirSync } from 'node:fs'
|
|
13
|
+
import { constants } from 'node:os'
|
|
13
14
|
import path from 'node:path'
|
|
14
15
|
import { appPortService, serviceNamed, servicesKnownTo } from '../app-port.js'
|
|
15
16
|
import { takeAppDir, UsageError } from '../app.js'
|
|
@@ -68,11 +69,23 @@ export async function run(args) {
|
|
|
68
69
|
env: { ...process.env, PORT: port, HOSTNAME: '127.0.0.1', APP_DATA_DIR: dataDir },
|
|
69
70
|
cwd: serverDir,
|
|
70
71
|
})
|
|
72
|
+
// A signal sent to this process alone (`kill <pid>`, a supervisor, a CI cancel) is forwarded, so the server does not
|
|
73
|
+
// outlive the wrapper holding the app's port, where the next run's `reuseExistingServer` would adopt a stale
|
|
74
|
+
// build. A server that dies on a signal is a failure (128 + the signal's number), never a success.
|
|
75
|
+
/** @type {NodeJS.Signals[]} */
|
|
76
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP']
|
|
77
|
+
const forwards = signals.map((signal) => /** @type {const} */ ([signal, () => child.kill(signal)]))
|
|
78
|
+
for (const [signal, forward] of forwards) process.on(signal, forward)
|
|
71
79
|
return await new Promise((resolve) => {
|
|
80
|
+
/** @param {number} status */
|
|
81
|
+
const done = (status) => {
|
|
82
|
+
for (const [signal, forward] of forwards) process.off(signal, forward)
|
|
83
|
+
resolve(status)
|
|
84
|
+
}
|
|
72
85
|
child.on('error', (error) => {
|
|
73
86
|
console.error(`Could not start the standalone server: ${error.message}`)
|
|
74
|
-
|
|
87
|
+
done(1)
|
|
75
88
|
})
|
|
76
|
-
child.on('exit', (code) =>
|
|
89
|
+
child.on('exit', (code, signal) => done(code ?? 128 + (signal ? constants.signals[signal] : 1)))
|
|
77
90
|
})
|
|
78
91
|
}
|
package/src/ports.d.ts
CHANGED
|
@@ -32,10 +32,11 @@ export declare function readPortDeclaration(appDir: string): PortDeclaration | u
|
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
34
|
* What port a checkout at `root` should use for a service, given an environment: the service's env var
|
|
35
|
-
* (`STARTER_PORT`, `LEDGER_PORT`) when set, a port derived from the path in a linked worktree
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
35
|
+
* (`STARTER_PORT`, `LEDGER_PORT`) when set, a port derived from the path in a linked git worktree (a checkout whose
|
|
36
|
+
* `.git` is a file pointing into a repository's `.git/worktrees/`, or any path under `.claude/worktrees/`), and the
|
|
37
|
+
* documented default otherwise. A built-in's derived port is keyed on the checkout alone; a custom slot's also on its
|
|
38
|
+
* name, so two slots of one worktree differ, and comes from a band no built-in uses (20000-29999). It reads nothing but
|
|
39
|
+
* that `.git`, so it can be tested against checkouts that do not exist.
|
|
39
40
|
*/
|
|
40
41
|
export declare function portForRoot(
|
|
41
42
|
root: string,
|
package/src/ports.js
CHANGED
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
// * STABLE ACROSS PROCESSES. The package script that starts the server and the Playwright config that points
|
|
16
16
|
// at it compute it independently: they agree only because neither one guesses.
|
|
17
17
|
// * NOT applied to a main checkout. It keeps the documented defaults, so every runbook that names :3000 or
|
|
18
|
-
// :3100 stays true for the person reading it. Only linked
|
|
18
|
+
// :3100 stays true for the person reading it. Only a linked git worktree derives: one whose `.git` (at the
|
|
19
|
+
// checkout's root or the nearest above it) is a FILE pointing into the main repository's `.git/worktrees/`,
|
|
20
|
+
// which is what `git worktree add` writes wherever the worktree is, and, read from the path alone, any checkout
|
|
21
|
+
// under `.claude/worktrees/` (Claude Code's own, and a checkout that does not exist yet). A submodule's `.git` is
|
|
22
|
+
// a file too, pointing into `.git/modules/`, and keeps the defaults.
|
|
19
23
|
//
|
|
20
24
|
// An explicit env var always wins, which is what makes an isolated one-off run possible without editing
|
|
21
25
|
// anything: `SHOWCASE_PORT=3210 pnpm dev`.
|
|
@@ -33,7 +37,7 @@
|
|
|
33
37
|
// repository this package is a workspace link, so its real path is outside node_modules and Playwright compiles
|
|
34
38
|
// it. Walking up from the working directory is the portable option.
|
|
35
39
|
import { createHash } from 'node:crypto'
|
|
36
|
-
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
40
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
37
41
|
import path from 'node:path'
|
|
38
42
|
|
|
39
43
|
/**
|
|
@@ -68,7 +72,7 @@ const SLOTS = 200
|
|
|
68
72
|
const SERVICES = {
|
|
69
73
|
showcase: { env: 'SHOWCASE_PORT', fallback: 3000, derive: (slot) => 3200 + slot * 2 },
|
|
70
74
|
starter: { env: 'STARTER_PORT', fallback: 3100, derive: (slot) => 3201 + slot * 2 },
|
|
71
|
-
ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) =>
|
|
75
|
+
ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) => 61001 + slot },
|
|
72
76
|
contractPg: { env: 'CONTRACT_PG_PORT', fallback: 5439, derive: (slot) => 5440 + slot },
|
|
73
77
|
}
|
|
74
78
|
|
|
@@ -91,7 +95,7 @@ const slotFor = (root) => hashOf(root) % SLOTS
|
|
|
91
95
|
/**
|
|
92
96
|
* The band a custom slot's derived port comes from in a linked worktree: 10000 ports, so two custom slots of one
|
|
93
97
|
* worktree collide about once in ten thousand (a loud EADDRINUSE, never a silent adoption). Clear of every built-in
|
|
94
|
-
* default and derived band (3000, 3100, 3200-3599, 5439-5639, 61000-
|
|
98
|
+
* default and derived band (3000, 3100, 3200-3599, 5439-5639, 61000-61200), and below Linux's ephemeral range (32768)
|
|
95
99
|
* and macOS's (49152), so the OS never hands one of these to an outbound connection.
|
|
96
100
|
*/
|
|
97
101
|
const CUSTOM_BAND = { start: 20000, size: 10000 }
|
|
@@ -221,8 +225,35 @@ export function portForRoot(root, service, env = process.env) {
|
|
|
221
225
|
return parsed
|
|
222
226
|
}
|
|
223
227
|
|
|
224
|
-
|
|
225
|
-
|
|
228
|
+
return isLinkedWorktree(root) ? spec.derive(root) : spec.fallback
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// The `gitdir:` line `git worktree add` writes into a linked worktree's `.git` file: a directory under the main
|
|
232
|
+
// repository's `.git/worktrees/`.
|
|
233
|
+
const LINKED_GITDIR = /^gitdir:\s*(.+?)\s*$/m
|
|
234
|
+
const WORKTREES_ENTRY = /[\\/]worktrees[\\/][^\\/]+[\\/]?$/
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Whether `root` is a linked git worktree: under `.claude/worktrees/` by its path alone, or with a `.git` FILE at it or
|
|
238
|
+
* the nearest above it that points into a repository's `.git/worktrees/`. A main checkout's `.git` is a directory; a
|
|
239
|
+
* submodule's is a file pointing into `.git/modules/`.
|
|
240
|
+
* @param {string} root
|
|
241
|
+
*/
|
|
242
|
+
function isLinkedWorktree(root) {
|
|
243
|
+
if (root.includes(`${path.sep}.claude${path.sep}worktrees${path.sep}`)) return true
|
|
244
|
+
for (let dir = path.resolve(root); ; dir = path.dirname(dir)) {
|
|
245
|
+
const git = path.join(dir, '.git')
|
|
246
|
+
if (existsSync(git)) {
|
|
247
|
+
if (!statSync(git).isFile()) return false
|
|
248
|
+
try {
|
|
249
|
+
const gitdir = LINKED_GITDIR.exec(readFileSync(git, 'utf8'))?.[1]
|
|
250
|
+
return gitdir !== undefined && WORKTREES_ENTRY.test(gitdir)
|
|
251
|
+
} catch {
|
|
252
|
+
return false
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (path.dirname(dir) === dir) return false
|
|
256
|
+
}
|
|
226
257
|
}
|
|
227
258
|
|
|
228
259
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
diff --git a/messages/en.json b/messages/en.json
|
|
2
|
-
index
|
|
2
|
+
index 63e30fc..15cd515 100644
|
|
3
3
|
--- a/messages/en.json
|
|
4
4
|
+++ b/messages/en.json
|
|
5
|
-
@@ -8,
|
|
5
|
+
@@ -8,15 +8,5 @@
|
|
6
6
|
"dashboard": {
|
|
7
7
|
"title": "Dashboard",
|
|
8
8
|
"signedInAs": "Signed in as {name} ({role})."
|
|
@@ -12,16 +12,17 @@ index 43e5945..15cd515 100644
|
|
|
12
12
|
- "hint": "Items belong to the team you're working in — and never leave your tenant.",
|
|
13
13
|
- "empty": "No items in this team yet.",
|
|
14
14
|
- "addLabel": "New item",
|
|
15
|
+
- "addError": "That item could not be added. Your text is still here: try again.",
|
|
15
16
|
- "addButton": "Add item",
|
|
16
17
|
- "readOnlyHint": "You have read-only access to items in this team.",
|
|
17
18
|
- "loadMore": "Show older items"
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
21
|
diff --git a/messages/es.json b/messages/es.json
|
|
21
|
-
index
|
|
22
|
+
index b6428fd..7a7ecf8 100644
|
|
22
23
|
--- a/messages/es.json
|
|
23
24
|
+++ b/messages/es.json
|
|
24
|
-
@@ -8,
|
|
25
|
+
@@ -8,15 +8,5 @@
|
|
25
26
|
"dashboard": {
|
|
26
27
|
"title": "Panel",
|
|
27
28
|
"signedInAs": "Sesión iniciada como {name} ({role})."
|
|
@@ -31,34 +32,25 @@ index 07b6b29..7a7ecf8 100644
|
|
|
31
32
|
- "hint": "Los elementos pertenecen al equipo en el que trabajas y nunca salen de tu organización.",
|
|
32
33
|
- "empty": "Aún no hay elementos en este equipo.",
|
|
33
34
|
- "addLabel": "Nuevo elemento",
|
|
35
|
+
- "addError": "No se pudo añadir el elemento. Tu texto sigue aquí: inténtalo de nuevo.",
|
|
34
36
|
- "addButton": "Añadir elemento",
|
|
35
37
|
- "readOnlyHint": "Tienes acceso de solo lectura a los elementos de este equipo.",
|
|
36
38
|
- "loadMore": "Ver elementos anteriores"
|
|
37
39
|
}
|
|
38
40
|
}
|
|
39
41
|
diff --git a/playwright.config.ts b/playwright.config.ts
|
|
40
|
-
index
|
|
42
|
+
index 9317684..106ccfc 100644
|
|
41
43
|
--- a/playwright.config.ts
|
|
42
44
|
+++ b/playwright.config.ts
|
|
43
|
-
@@ -
|
|
44
|
-
export default defineConfig({
|
|
45
|
+
@@ -21,7 +21,7 @@ export default defineConfig({
|
|
45
46
|
testDir: './tests/e2e',
|
|
46
47
|
fullyParallel: true,
|
|
47
|
-
|
|
48
|
+
// This app's whole suite is a few short specs, so the first always starts against a cold dev server and pays a
|
|
48
49
|
- // full Next compile on every route it touches — sign-in, dashboard, the items route, the Simulator's. The default
|
|
49
|
-
+ // This app's whole suite is one short spec, so it always starts against a cold dev server and pays a
|
|
50
50
|
+ // full Next compile on every route it touches — sign-in, dashboard, the Simulator's. The default
|
|
51
51
|
// 30s is marginal for that (it timed out on the first run and passed on retry), and there is no
|
|
52
52
|
// warm-up pass to inherit, so the budget is raised rather than left to flake.
|
|
53
53
|
timeout: 60_000,
|
|
54
|
-
expect: { timeout: 15_000 },
|
|
55
|
-
forbidOnly: !!process.env['CI'],
|
|
56
|
-
retries: process.env['CI'] ? 2 : 1,
|
|
57
|
-
- // One worker, on CI too — this app's whole suite is two short specs, so parallelism buys little here,
|
|
58
|
-
+ // One worker, on CI too — this app's whole suite is one short spec, so parallelism buys little here,
|
|
59
|
-
// and more workers against one shared world (one `.data` behind one dev server) cost reliability rather than
|
|
60
|
-
// saving time.
|
|
61
|
-
workers: 1,
|
|
62
54
|
diff --git a/src/app-config/abilities.ts b/src/app-config/abilities.ts
|
|
63
55
|
index c69a9ec..851160c 100644
|
|
64
56
|
--- a/src/app-config/abilities.ts
|
|
@@ -256,7 +248,7 @@ index 117cbdc..6539ae5 100644
|
|
|
256
248
|
/**
|
|
257
249
|
* The app's catalog for one locale. Framework code (the next-intl request config, the parity tests)
|
|
258
250
|
diff --git a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
259
|
-
index
|
|
251
|
+
index 1aa84a0..874f935 100644
|
|
260
252
|
--- a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
261
253
|
+++ b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
262
254
|
@@ -1,61 +1,7 @@
|
|
@@ -312,10 +304,10 @@ index 5fdea5a..874f935 100644
|
|
|
312
304
|
- headers: { 'content-type': 'application/json' },
|
|
313
305
|
- body: JSON.stringify({ title }),
|
|
314
306
|
- })
|
|
315
|
-
-
|
|
316
|
-
-
|
|
317
|
-
-
|
|
318
|
-
-
|
|
307
|
+
- // A refusal rejects, so the card keeps the draft and shows its error.
|
|
308
|
+
- if (!response.ok) throw new Error(`POST /api/items answered ${response.status}`)
|
|
309
|
+
- const { item } = (await response.json()) as { item: Item }
|
|
310
|
+
- setItems((prev) => [item, ...prev])
|
|
319
311
|
- }}
|
|
320
312
|
- />
|
|
321
313
|
- </DashboardScreen>
|
|
@@ -352,12 +344,111 @@ index 1794523..9fba9eb 100644
|
|
|
352
344
|
+ // from @sssb/kit/authz/authorize, and re-check with `authorize()` in every route that writes.
|
|
353
345
|
+ return <DashboardGlue user={{ name: user.name, role: user.role }} />
|
|
354
346
|
}
|
|
347
|
+
diff --git a/src/app/api/items/route.test.ts b/src/app/api/items/route.test.ts
|
|
348
|
+
deleted file mode 100644
|
|
349
|
+
index 30c1f3b..0000000
|
|
350
|
+
--- a/src/app/api/items/route.test.ts
|
|
351
|
+
+++ /dev/null
|
|
352
|
+
@@ -1,93 +0,0 @@
|
|
353
|
+
-import { beforeEach, describe, expect, test, vi } from 'vitest'
|
|
354
|
+
-import type { AuthUser } from '@sssb/kit/ports/auth'
|
|
355
|
+
-import { GET, POST } from './route'
|
|
356
|
+
-
|
|
357
|
+
-// Real authorize (pure abilities) runs — only the adapters and data modules are faked. Low-entropy
|
|
358
|
+
-// fixture ids/slugs (gitleaks): no hex, no UUIDs.
|
|
359
|
+
-const h = vi.hoisted(() => ({
|
|
360
|
+
- requireUser: vi.fn(),
|
|
361
|
+
- tenantIdForSlug: vi.fn(),
|
|
362
|
+
- orgIdForSlug: vi.fn(),
|
|
363
|
+
- listItems: vi.fn(),
|
|
364
|
+
- withTenant: vi.fn(),
|
|
365
|
+
-}))
|
|
366
|
+
-vi.mock('@sssb/kit/adapters/index', () => ({ auth: { requireUser: h.requireUser }, db: { withTenant: h.withTenant } }))
|
|
367
|
+
-vi.mock('@sssb/kit/db/tenant-lookup', () => ({ tenantIdForSlug: h.tenantIdForSlug }))
|
|
368
|
+
-vi.mock('@sssb/kit/db/org-lookup', () => ({ orgIdForSlug: h.orgIdForSlug }))
|
|
369
|
+
-vi.mock('@/domain/db/items', () => ({ listItems: h.listItems }))
|
|
370
|
+
-
|
|
371
|
+
-function user(overrides: Partial<AuthUser> = {}): AuthUser {
|
|
372
|
+
- return {
|
|
373
|
+
- id: 'user-ada',
|
|
374
|
+
- name: 'Dana Okoye',
|
|
375
|
+
- email: 'dana.okoye@example.test',
|
|
376
|
+
- role: 'member',
|
|
377
|
+
- locale: 'en',
|
|
378
|
+
- tenantSlug: 'northwind',
|
|
379
|
+
- orgSlug: 'frontline',
|
|
380
|
+
- restricted: false,
|
|
381
|
+
- ...overrides,
|
|
382
|
+
- }
|
|
383
|
+
-}
|
|
384
|
+
-
|
|
385
|
+
-const listRequest = (query = '') => new Request(`http://localhost/api/items${query}`)
|
|
386
|
+
-
|
|
387
|
+
-function post(body: string): Promise<Response> {
|
|
388
|
+
- return POST(new Request('http://localhost/api/items', { method: 'POST', body }))
|
|
389
|
+
-}
|
|
390
|
+
-
|
|
391
|
+
-beforeEach(() => {
|
|
392
|
+
- for (const fn of Object.values(h)) fn.mockReset()
|
|
393
|
+
- h.requireUser.mockResolvedValue(user())
|
|
394
|
+
- h.tenantIdForSlug.mockResolvedValue('tenant-northwind')
|
|
395
|
+
- h.orgIdForSlug.mockResolvedValue('org-frontline')
|
|
396
|
+
- h.listItems.mockResolvedValue({ items: [], nextCursor: null })
|
|
397
|
+
-})
|
|
398
|
+
-
|
|
399
|
+
-describe('GET /api/items (list)', () => {
|
|
400
|
+
- test('returns one page of the active org items, tenant- and org-scoped', async () => {
|
|
401
|
+
- h.listItems.mockResolvedValue({ items: [{ id: 'item-1', title: 'First' }], nextCursor: null })
|
|
402
|
+
-
|
|
403
|
+
- const response = await GET(listRequest())
|
|
404
|
+
-
|
|
405
|
+
- expect(response.status).toBe(200)
|
|
406
|
+
- expect(await response.json()).toEqual({ items: [{ id: 'item-1', title: 'First' }], nextCursor: null })
|
|
407
|
+
- expect(h.listItems).toHaveBeenCalledWith(expect.anything(), 'tenant-northwind', 'org-frontline', {
|
|
408
|
+
- after: null,
|
|
409
|
+
- limit: expect.any(Number),
|
|
410
|
+
- })
|
|
411
|
+
- })
|
|
412
|
+
-
|
|
413
|
+
- test('a restricted member may still READ the list (Item read = sameOrg; only writes need !restricted)', async () => {
|
|
414
|
+
- h.requireUser.mockResolvedValue(user({ role: 'restricted', restricted: true }))
|
|
415
|
+
-
|
|
416
|
+
- const response = await GET(listRequest())
|
|
417
|
+
-
|
|
418
|
+
- expect(response.status).toBe(200)
|
|
419
|
+
- expect(await response.json()).toEqual({ items: [], nextCursor: null })
|
|
420
|
+
- })
|
|
421
|
+
-
|
|
422
|
+
- test('403 for a person with the role none: no standing in the org, so no org-scoped read', async () => {
|
|
423
|
+
- h.requireUser.mockResolvedValue(user({ role: 'none', restricted: true }))
|
|
424
|
+
-
|
|
425
|
+
- expect((await GET(listRequest())).status).toBe(403)
|
|
426
|
+
- expect(h.listItems).not.toHaveBeenCalled()
|
|
427
|
+
- })
|
|
428
|
+
-})
|
|
429
|
+
-
|
|
430
|
+
-describe('POST /api/items: a malformed body is a 400, never a 500', () => {
|
|
431
|
+
- test.each([['{'], ['null'], ['[]']])('a body %s that is not an object', async (body) => {
|
|
432
|
+
- expect((await post(body)).status).toBe(400)
|
|
433
|
+
- expect(h.withTenant).not.toHaveBeenCalled()
|
|
434
|
+
- })
|
|
435
|
+
-
|
|
436
|
+
- test.each([[JSON.stringify({ title: 5 })], [JSON.stringify({ title: ' ' })], [JSON.stringify({})]])(
|
|
437
|
+
- 'a title that is not a non-empty string: %s',
|
|
438
|
+
- async (body) => {
|
|
439
|
+
- const response = await post(body)
|
|
440
|
+
- expect(response.status).toBe(400)
|
|
441
|
+
- expect(await response.json()).toEqual({ error: 'empty item' })
|
|
442
|
+
- expect(h.withTenant).not.toHaveBeenCalled()
|
|
443
|
+
- },
|
|
444
|
+
- )
|
|
445
|
+
-})
|
|
355
446
|
diff --git a/src/app/api/items/route.ts b/src/app/api/items/route.ts
|
|
356
447
|
deleted file mode 100644
|
|
357
|
-
index
|
|
448
|
+
index b540297..0000000
|
|
358
449
|
--- a/src/app/api/items/route.ts
|
|
359
450
|
+++ /dev/null
|
|
360
|
-
@@ -1,
|
|
451
|
+
@@ -1,62 +0,0 @@
|
|
361
452
|
-import { auth, db } from '@sssb/kit/adapters/index'
|
|
362
453
|
-import { authorize } from '@sssb/kit/authz/authorize'
|
|
363
454
|
-import { clampKeysetLimit } from '@sssb/kit/core/keyset'
|
|
@@ -365,7 +456,7 @@ index cb2d480..0000000
|
|
|
365
456
|
-import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
|
|
366
457
|
-import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
|
|
367
458
|
-import { listItems } from '@/domain/db/items'
|
|
368
|
-
-import { withPortErrors } from '../respond'
|
|
459
|
+
-import { readJsonObject, withPortErrors } from '../respond'
|
|
369
460
|
-
|
|
370
461
|
-/**
|
|
371
462
|
- * The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
|
|
@@ -387,6 +478,9 @@ index cb2d480..0000000
|
|
|
387
478
|
- if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
388
479
|
- const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
389
480
|
- if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
|
|
481
|
+
- // A read is authorized as a write is: being placed in an org is not membership of it (a signed-in person with
|
|
482
|
+
- // the role `none` has no standing there), so the session's org alone never decides what it may read.
|
|
483
|
+
- authorize(user, orgId, 'read', { type: 'Item', orgId })
|
|
390
484
|
- const { items, nextCursor } = await listItems(db, tenantId, orgId, {
|
|
391
485
|
- after: cursor.position ?? null,
|
|
392
486
|
- limit: clampKeysetLimit(params.get('limit')),
|
|
@@ -398,8 +492,8 @@ index cb2d480..0000000
|
|
|
398
492
|
-export async function POST(request: Request): Promise<Response> {
|
|
399
493
|
- return withPortErrors(async () => {
|
|
400
494
|
- const user = await auth.requireUser()
|
|
401
|
-
- const { title } =
|
|
402
|
-
- if (!title
|
|
495
|
+
- const { title } = await readJsonObject(request)
|
|
496
|
+
- if (typeof title !== 'string' || !title.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
|
|
403
497
|
- const tenantId = await tenantIdForSlug(db, user.tenantSlug)
|
|
404
498
|
- if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
405
499
|
- const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
@@ -432,12 +526,76 @@ index 42b10b7..20ada9e 100644
|
|
|
432
526
|
const t = useTranslations('dashboard')
|
|
433
527
|
return (
|
|
434
528
|
<Container component="main" size="sm" py="xl">
|
|
529
|
+
diff --git a/src/components/items-card.test.tsx b/src/components/items-card.test.tsx
|
|
530
|
+
deleted file mode 100644
|
|
531
|
+
index 2380455..0000000
|
|
532
|
+
--- a/src/components/items-card.test.tsx
|
|
533
|
+
+++ /dev/null
|
|
534
|
+
@@ -1,58 +0,0 @@
|
|
535
|
+
-import { MantineProvider } from '@mantine/core'
|
|
536
|
+
-import { NextIntlClientProvider } from 'next-intl'
|
|
537
|
+
-import { act } from 'react'
|
|
538
|
+
-import { createRoot } from 'react-dom/client'
|
|
539
|
+
-import { afterEach, describe, expect, it } from 'vitest'
|
|
540
|
+
-import en from '../../messages/en.json'
|
|
541
|
+
-import { ItemsCard } from './items-card'
|
|
542
|
+
-
|
|
543
|
+
-/** A create that fails keeps what the person typed and says so; one that succeeds clears the box. */
|
|
544
|
+
-
|
|
545
|
+
-const unmounts: Array<() => void> = []
|
|
546
|
+
-afterEach(() => {
|
|
547
|
+
- for (const unmount of unmounts.splice(0)) act(unmount)
|
|
548
|
+
-})
|
|
549
|
+
-
|
|
550
|
+
-async function addWith(onAdd: (title: string) => Promise<void>): Promise<HTMLElement> {
|
|
551
|
+
- ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
|
552
|
+
- const container = document.createElement('div')
|
|
553
|
+
- document.body.append(container)
|
|
554
|
+
- const root = createRoot(container)
|
|
555
|
+
- await act(async () => {
|
|
556
|
+
- root.render(
|
|
557
|
+
- <NextIntlClientProvider locale="en" messages={en}>
|
|
558
|
+
- <MantineProvider>
|
|
559
|
+
- <ItemsCard items={[]} onAdd={onAdd} />
|
|
560
|
+
- </MantineProvider>
|
|
561
|
+
- </NextIntlClientProvider>,
|
|
562
|
+
- )
|
|
563
|
+
- })
|
|
564
|
+
- unmounts.push(() => root.unmount())
|
|
565
|
+
- const input = container.querySelector<HTMLInputElement>('[data-testid="item-input"]')!
|
|
566
|
+
- await act(async () => {
|
|
567
|
+
- // React tracks a controlled input's value; set it through the native setter so onChange sees the change.
|
|
568
|
+
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'my important draft')
|
|
569
|
+
- input.dispatchEvent(new Event('input', { bubbles: true }))
|
|
570
|
+
- })
|
|
571
|
+
- await act(async () => {
|
|
572
|
+
- container.querySelector<HTMLButtonElement>('[data-testid="item-add"]')!.click()
|
|
573
|
+
- })
|
|
574
|
+
- return container
|
|
575
|
+
-}
|
|
576
|
+
-
|
|
577
|
+
-const inputValue = (container: HTMLElement) =>
|
|
578
|
+
- container.querySelector<HTMLInputElement>('[data-testid="item-input"]')!.value
|
|
579
|
+
-
|
|
580
|
+
-describe('ItemsCard', () => {
|
|
581
|
+
- it('keeps the draft and shows an alert when the create fails', async () => {
|
|
582
|
+
- const container = await addWith(() => Promise.reject(new Error('403')))
|
|
583
|
+
- expect(inputValue(container)).toBe('my important draft')
|
|
584
|
+
- expect(container.querySelector('[role="alert"]')?.textContent).toBe(en.items.addError)
|
|
585
|
+
- })
|
|
586
|
+
-
|
|
587
|
+
- it('clears the draft, with no alert, when the create succeeds', async () => {
|
|
588
|
+
- const container = await addWith(() => Promise.resolve())
|
|
589
|
+
- expect(inputValue(container)).toBe('')
|
|
590
|
+
- expect(container.querySelector('[role="alert"]')).toBeNull()
|
|
591
|
+
- })
|
|
592
|
+
-})
|
|
435
593
|
diff --git a/src/components/items-card.tsx b/src/components/items-card.tsx
|
|
436
594
|
deleted file mode 100644
|
|
437
|
-
index
|
|
595
|
+
index a36ed54..0000000
|
|
438
596
|
--- a/src/components/items-card.tsx
|
|
439
597
|
+++ /dev/null
|
|
440
|
-
@@ -1,
|
|
598
|
+
@@ -1,117 +0,0 @@
|
|
441
599
|
-'use client'
|
|
442
600
|
-
|
|
443
601
|
-import { Button, Card, Group, Stack, Text, TextInput, Title } from '@mantine/core'
|
|
@@ -462,6 +620,7 @@ index 9a501ae..0000000
|
|
|
462
620
|
- onLoadMore,
|
|
463
621
|
-}: {
|
|
464
622
|
- items: Item[]
|
|
623
|
+
- /** Rejects when the item was not created: the card then keeps the draft and says so. */
|
|
465
624
|
- onAdd: (title: string) => Promise<void>
|
|
466
625
|
- /** When false (restricted members), the add affordance is disabled and a read-only hint shows. */
|
|
467
626
|
- canCreate?: boolean
|
|
@@ -473,6 +632,7 @@ index 9a501ae..0000000
|
|
|
473
632
|
- const t = useTranslations('items')
|
|
474
633
|
- const [draft, setDraft] = useState('')
|
|
475
634
|
- const [busy, setBusy] = useState(false)
|
|
635
|
+
- const [addFailed, setAddFailed] = useState(false)
|
|
476
636
|
- const [loadingMore, setLoadingMore] = useState(false)
|
|
477
637
|
-
|
|
478
638
|
- return (
|
|
@@ -527,14 +687,23 @@ index 9a501ae..0000000
|
|
|
527
687
|
- data-testid="item-add"
|
|
528
688
|
- onClick={() => {
|
|
529
689
|
- setBusy(true)
|
|
690
|
+
- setAddFailed(false)
|
|
530
691
|
- onAdd(draft.trim())
|
|
531
|
-
- .then(
|
|
692
|
+
- .then(
|
|
693
|
+
- () => setDraft(''),
|
|
694
|
+
- () => setAddFailed(true),
|
|
695
|
+
- )
|
|
532
696
|
- .finally(() => setBusy(false))
|
|
533
697
|
- }}
|
|
534
698
|
- >
|
|
535
699
|
- {t('addButton')}
|
|
536
700
|
- </Button>
|
|
537
701
|
- </Group>
|
|
702
|
+
- {addFailed ? (
|
|
703
|
+
- <Text size="sm" c="red.8" role="alert" data-testid="items-add-error">
|
|
704
|
+
- {t('addError')}
|
|
705
|
+
- </Text>
|
|
706
|
+
- ) : null}
|
|
538
707
|
- {!canCreate ? (
|
|
539
708
|
- <Text size="sm" c="gray.7" data-testid="items-readonly-hint">
|
|
540
709
|
- {t('readOnlyHint')}
|
package/src/tick/tick.js
CHANGED
|
@@ -267,8 +267,11 @@ function count(value) {
|
|
|
267
267
|
}
|
|
268
268
|
|
|
269
269
|
/**
|
|
270
|
-
* What a tick did, in one line. `failed` is a schedule whose spawn failed
|
|
271
|
-
*
|
|
270
|
+
* What a tick did, in one line. `failed` is a schedule whose spawn failed, and a delivery that failed or died: shown,
|
|
271
|
+
* but it is the tick reporting work that went wrong, not the tick failing. A failed schedule is retried by the next tick
|
|
272
|
+
* only when the failure was inside the spawn transaction (it rolled back); after that transaction commits, the job is
|
|
273
|
+
* left queued and the schedule has moved on (the in-process runner's sweep fails the job after five minutes; see
|
|
274
|
+
* `@sssb/kit/db/schedules`).
|
|
272
275
|
*
|
|
273
276
|
* @param {Record<string, unknown>} body the route's JSON: `{ ok, spawned, failed, deliveries: { delivered, failed, dead } }`
|
|
274
277
|
*/
|
package/src/tick/ticker.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface TickerStatus {
|
|
|
16
16
|
export interface Ticker {
|
|
17
17
|
/** Starts ticking every `seconds`, or does nothing if it already is (an interval change is a stop then a start). */
|
|
18
18
|
start(seconds: number): TickerStatus
|
|
19
|
-
/** Stops ticking
|
|
19
|
+
/** Stops ticking, waits for a tick in flight to end, and resolves to the status then (`running: false`). */
|
|
20
20
|
stop(): Promise<TickerStatus>
|
|
21
21
|
status(): TickerStatus
|
|
22
22
|
}
|
|
@@ -32,5 +32,8 @@ export interface TickerOptions {
|
|
|
32
32
|
now?: () => Date
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/** A sleep that ends early, and quietly, when `signal` aborts: the ticker's default `sleep`. */
|
|
36
|
+
export declare function abortableSleep(ms: number, signal: AbortSignal): Promise<void>
|
|
37
|
+
|
|
35
38
|
/** The dev ticker: one object that owns start, stop, the interval and whether it is running. */
|
|
36
39
|
export declare function createTicker(options: TickerOptions): Ticker
|
package/src/tick/ticker.js
CHANGED
|
@@ -123,15 +123,21 @@ export function createTicker({
|
|
|
123
123
|
return { ...state }
|
|
124
124
|
},
|
|
125
125
|
|
|
126
|
-
/**
|
|
126
|
+
/**
|
|
127
|
+
* Stops it, cancels a tick in flight, and resolves to the status once the loop has ended. Safe to call when not
|
|
128
|
+
* running.
|
|
129
|
+
*
|
|
130
|
+
* @returns {Promise<TickerStatus>}
|
|
131
|
+
*/
|
|
127
132
|
async stop() {
|
|
128
133
|
const stopping = controller
|
|
129
134
|
controller = null
|
|
130
|
-
if (!stopping) return
|
|
135
|
+
if (!stopping) return { ...state }
|
|
131
136
|
stopping.abort()
|
|
132
137
|
if (markerFile) removeTickerMarker(markerFile)
|
|
133
138
|
state = { ...state, running: false }
|
|
134
139
|
await loop
|
|
140
|
+
return { ...state }
|
|
135
141
|
},
|
|
136
142
|
|
|
137
143
|
/** @returns {TickerStatus} */
|